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    #[must_use]
993    pub fn identity(&self) -> ContratoIdentity<'_> {
994        (
995            self.source(),
996            self.destination(),
997            self.world_ref(),
998            self.endpoint(),
999            self.subject(),
1000            self.slot(),
1001        )
1002    }
1003
1004    /// True when this contract targets an HTTP-shaped WIT world.
1005    ///
1006    /// Declared `pub const fn` — routes through the paired `pub const
1007    /// fn` [`Self::world_ref`] scalar accessor and the substrate's
1008    /// `pub const fn` free-function classifier [`wit_shape_is_http`]
1009    /// (d46420c). Sibling in `const`-eval posture to the peer
1010    /// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
1011    /// [`Self::is_capability`] WIT-shape-predicate family; the closed
1012    /// 4-arm partition on the raw `:contratos :wit` axis now carries
1013    /// the same `const`-eval-surface posture as the free-function
1014    /// classifier family it composes through. Pinned load-bearing by
1015    /// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
1016    /// test (a future accidental downgrade to non-`const` fires E0015
1017    /// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
1018    /// build time).
1019    #[must_use]
1020    pub const fn is_http(&self) -> bool {
1021        wit_shape_is_http(self.world_ref())
1022    }
1023
1024    /// True when this contract targets a pub-sub-shaped WIT world.
1025    ///
1026    /// Declared `pub const fn` — sibling in `const`-eval posture to
1027    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
1028    /// [`Self::is_capability`] WIT-shape-predicate family. See
1029    /// [`Self::is_http`] for the family-closure rationale.
1030    #[must_use]
1031    pub const fn is_pubsub(&self) -> bool {
1032        wit_shape_is_pubsub(self.world_ref())
1033    }
1034
1035    /// True when this contract targets a key/value-shaped WIT world.
1036    ///
1037    /// Declared `pub const fn` — sibling in `const`-eval posture to
1038    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
1039    /// [`Self::is_capability`] WIT-shape-predicate family. See
1040    /// [`Self::is_http`] for the family-closure rationale.
1041    #[must_use]
1042    pub const fn is_store(&self) -> bool {
1043        wit_shape_is_store(self.world_ref())
1044    }
1045
1046    /// True when this contract targets *none* of the three known payload-
1047    /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
1048    /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1049    /// open on the [`WitContract`] surface. Returns the exact-inverse
1050    /// disjunction of the peer trio — `true` when none of the three
1051    /// prefix-set predicates matches the raw `:contratos :wit` value; the
1052    /// author-declared WIT world is a pure typed capability edge with no
1053    /// payload selector (the shape [`WitContract::target`] projects onto
1054    /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
1055    /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
1056    ///
1057    /// The `:contratos :wit` shape-space is closed at four arms
1058    /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
1059    /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
1060    /// everything else on the payload-less capability arm), and every
1061    /// downstream consumer that must filter contratos by shape-class
1062    /// keys off the four sibling predicates (the [`WitContract::target`]
1063    /// dispatch's implicit `else` after the three payload-shape arm
1064    /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
1065    /// every future substrate-side capability-shape-only emitter — the
1066    /// M4 per-Aplicacao WIT-registry capability-import materializer, the
1067    /// future `feira app graph --capability` per-Aplicacao capability-
1068    /// column filter, the future per-cluster capability-scope reconciler
1069    /// that skips L4/L7 emission for payload-less edges since Cilium
1070    /// can't introspect WASI capability calls, the future
1071    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
1072    /// shape shape-count histogram). Every such consumer reaches for one
1073    /// typed dispatch on the substrate primitive so the "which arm
1074    /// carries the capability-only shape?" answer lives at one caixa-core
1075    /// edit rather than open-coded across per-consumer
1076    /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
1077    /// negations, each of which would silently drop a future fourth
1078    /// payload-arm addition without a compile-time signal at the
1079    /// consumer site.
1080    ///
1081    /// Prior to this lift the "not one of the three known payload
1082    /// shapes" classification sat inline at [`WitContract::target`]'s
1083    /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
1084    /// [`WitTarget::Capability`] admission arm after the three `if
1085    /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
1086    /// { … }` guards) with no named accessor for downstream consumers
1087    /// to reach through. A future substrate-side capability-only
1088    /// filter or a future capability-scope reconciler would have had to
1089    /// re-inline the same triplet negation at every emit site with no
1090    /// compile-time link back to the sibling trio, and a future arm
1091    /// addition (a hypothetical fourth payload-shape prefix set — a
1092    /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
1093    /// import carrier per the sibling [`wit_shape_matches`] docstring's
1094    /// trajectory bullet) would land the new predicate on the payload-
1095    /// carrying trio and silently misclassify the new shape as
1096    /// capability at every triplet-negation consumer site, propagating
1097    /// the drift far from the caixa-core prefix-set commit.
1098    ///
1099    /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
1100    /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
1101    /// trio into a 4-way partition witness on the raw `:contratos :wit`
1102    /// axis, mirroring the paired post-projection [`WitTarget`]
1103    /// `gen_platform::IsVariant`-derived 4-way predicate set
1104    /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
1105    /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
1106    /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
1107    /// arm-set). The two typed axes — pre-projection on the raw
1108    /// `:contratos :wit` string, post-projection on the validated typed
1109    /// view — now carry a matched 4-arm predicate discipline: every
1110    /// arm on the closed [`WitTarget`] set has a peer pre-projection
1111    /// predicate on the [`WitContract`] surface, and any future
1112    /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
1113    /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
1114    /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
1115    /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
1116    /// pre-projection axis through a matching peer prefix-set + peer
1117    /// predicate lift by construction — the compile-time exhaustiveness
1118    /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
1119    /// the post-projection accessor family stays in sync, and the sibling
1120    /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
1121    /// partition-witness pin locks the pre-projection classification in
1122    /// load-bearing so a peer prefix-set addition that widened one arm's
1123    /// accept-set without shrinking the [`Self::is_capability`] accept-set
1124    /// surfaces as a test failure at caixa-core build time rather than a
1125    /// silent per-consumer split at renderer emit time.
1126    ///
1127    /// Composes byte-for-byte through the lifted peer trio
1128    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
1129    /// any future rebrand of any prefix-set const flows through this
1130    /// method by construction without a coordinated per-consumer rewrite
1131    /// (pinned by the sibling
1132    /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
1133    /// composition-witness).
1134    ///
1135    /// Note: purely syntactic classification on the `:wit` prefix-set —
1136    /// unlike [`Self::target`], which additionally rejects value-shape-
1137    /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
1138    /// package) via [`crate::render::is_wit_world_ref`] and payload-
1139    /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
1140    /// structurally malformed returns `true` from `is_capability()` (the
1141    /// prefix set matches nothing), and the surrounding
1142    /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
1143    /// is where the [`AplicacaoError::EmptyWit`] /
1144    /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
1145    /// predicate is the classifier, not the validator.
1146    ///
1147    /// Declared `pub const fn` — closes the WIT-shape-predicate
1148    /// family's `const`-eval-surface pass at the fourth (payload-less)
1149    /// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
1150    /// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
1151    /// See [`Self::is_http`] for the family-closure rationale.
1152    #[must_use]
1153    pub const fn is_capability(&self) -> bool {
1154        wit_shape_is_capability(self.world_ref())
1155    }
1156
1157    /// True when this contract's caller equals its callee — a
1158    /// structurally degenerate typed edge that no `:contratos` entry can
1159    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
1160    /// Servico B" is an *inter*-Servico contract between two distinct
1161    /// graph nodes). A Servico contracting with itself resolves to an
1162    /// in-process call the wasm-engine never routes through the mesh at
1163    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
1164    /// per-edge policy can express the intended shape — the pub-sub
1165    /// path silently rendered a self-allow rule that is a no-op (intra-
1166    /// pod traffic bypasses the mesh entirely), and the synchronous
1167    /// paths surfaced as a misleading `ContratoCycle` whose path was
1168    /// `["cart", "cart"]` — framing a self-edge as a multi-node
1169    /// deadlock. Every downstream consumer that must reject the shape
1170    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
1171    /// gate at caixa-core/src/aplicacao.rs:5559, every future
1172    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
1173    /// axis, every future adjacency-graph builder that must skip self-
1174    /// edges rather than fold them into an incidental cycle) now keys
1175    /// off exactly one typed dispatch on the substrate primitive, so
1176    /// any future rebrand on the axis (an M4-typed-caller enum whose
1177    /// identity comparison rule the accessor could route through, an
1178    /// operator-side per-cluster caller/callee-alias table the
1179    /// materializer resolves per-CR before the equality probe, a
1180    /// promotion of the pointwise `==` to a set-membership check once
1181    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
1182    /// so a per-replica self-edge is rejected under the same predicate)
1183    /// migrates as a single caixa-core edit rather than a coordinated
1184    /// rewrite of every downstream self-edge consumer. Composes
1185    /// byte-for-byte through the lifted [`Self::source`] /
1186    /// [`Self::destination`] scalar accessors — the accessor pair every
1187    /// per-`:contratos` scalar-value axis already routes through — so
1188    /// any future rebrand of the underlying `:de` / `:para` storage
1189    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1190    /// a per-Aplicacao interning arena the M4 CR materializer authors,
1191    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1192    /// same one body without a coordinated per-consumer rewrite.
1193    ///
1194    /// Sibling in shape to the peer per-`:contratos` shape-predicate
1195    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1196    /// on the `:wit` world-ref axis — extended onto the per-edge
1197    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1198    /// partition the WIT-shape-space; `is_self_loop` partitions the
1199    /// caller-callee identity-space. Named `is_self_loop()` to reflect
1200    /// the graph-theoretic identity of the shape (a loop from a graph
1201    /// node to itself, distinct from the sibling multi-node
1202    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1203    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1204    /// variant already carrying the term.
1205    #[must_use]
1206    pub fn is_self_loop(&self) -> bool {
1207        self.source() == self.destination()
1208    }
1209
1210    /// Typed view of the contract's payload target. Enforces that the
1211    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1212    /// fields agree, and that each carried value is itself
1213    /// value-shape valid:
1214    ///
1215    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1216    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1217    ///     `PathPrefix` invariant — same shape required of `:entrada
1218    ///     :paths`)
1219    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1220    ///     non-empty (NATS / Kafka publish without a subject is a
1221    ///     no-op subscribe, never the author's intent)
1222    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1223    ///     non-empty (an empty slot template addresses the bucket
1224    ///     root, defeating the per-key isolation the slot exists for)
1225    ///   - Anything else ⇒ none of the three; the contract is a pure
1226    ///     typed capability edge with no payload selector.
1227    ///
1228    /// Translates the Apollo Federation discipline ("conflicts are
1229    /// errors at compile time, not warnings at runtime";
1230    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1231    /// a contract whose WIT shape disagrees with its target field, or
1232    /// whose target field carries a value-shape-invalid string, is a
1233    /// build error — not a silent renderer drop. The returned
1234    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1235    /// non-empty (and absolute, for `Http`); every downstream consumer
1236    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1237    /// the M4 per-edge policy resolver) can rely on that without
1238    /// re-checking.
1239    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1240        // Route the HTTP-shaped payload-target extraction through the
1241        // lifted [`WitContract::endpoint`] accessor rather than the raw
1242        // `self.endpoint.as_deref()` field access — the two production
1243        // consumers of the per-`:contratos :endpoint` HTTP-shaped
1244        // payload-carrier scalar (this method's Http-arm payload
1245        // extraction, the [`AplicacaoSpec::validate`] duplicate-
1246        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1247        // off exactly one typed dispatch on the substrate primitive, so
1248        // any future rebrand on the axis (an M4 per-cluster endpoint-
1249        // alias rewrite, a per-CR fully-qualified path prefix the M4
1250        // materializer applies per-tenant, an M4 promotion from
1251        // `Option<String>` to a typed HTTP path-template enum) migrates
1252        // as a single caixa-core edit rather than a coordinated rewrite
1253        // of the two call sites — peer of the sibling M3 per-`:placement`
1254        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1255        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1256        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1257        let endpoint = self.endpoint();
1258        let subject = self.subject();
1259        // Route the store-arm payload-carrier scalar through the
1260        // lifted [`WitContract::slot`] accessor rather than the raw
1261        // `self.slot.as_deref()` field access — the two production
1262        // consumers of the per-`:contratos :slot` key/value-store-
1263        // shaped payload-carrier scalar (this method's Store-arm
1264        // payload extraction, the [`AplicacaoSpec::validate`]
1265        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1266        // arm) now key off exactly one typed dispatch on the substrate
1267        // primitive. Closes the last unlifted per-`:contratos`
1268        // `Option<String>` axis, completing the payload-carrier
1269        // accessor family peer of the sibling per-`:contratos`
1270        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1271        // (90de675) lifts across the HTTP / pub-sub arms.
1272        let slot = self.slot();
1273        // Route the local `(de, para, wit)` triple-projection closure
1274        // through the lifted [`WitContract::edge_triple`] typed accessor
1275        // rather than re-inlining `(self.de.clone(), self.para.clone(),
1276        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1277        // triple-carrying diagnostic constructors below (wrong-target /
1278        // missing-target on all three payload arms + capability-with-
1279        // payload + invalid-wit) now key off exactly one typed dispatch
1280        // on the substrate-primitive composite projection, sibling to
1281        // the peer [`WitContract::edge_pair`]-routed
1282        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1283        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1284        // diagnostic constructors on the same per-`:contratos`
1285        // diagnostic-construction surface.
1286        let edge = || self.edge_triple();
1287
1288        // The `:wit` value drives every downstream dispatch — the
1289        // is_http/is_pubsub/is_store prefix matchers below, the
1290        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1291        // exclusion. Until this gate landed `target()` accepted any
1292        // non-empty string and silently demoted unrecognized shapes to
1293        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1294        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1295        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1296        // package, the paste-from-binary footgun a multi-line blob
1297        // accidentally landing in the slot, the un-percent-encoded
1298        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1299        // routing, got L4-only" footgun. Empty is still pre-checked at
1300        // the [`AplicacaoSpec::validate`] call site via the narrower
1301        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1302        // validate layer); the value-shape gate here picks up the
1303        // structurally-invalid non-empty cases the empty check misses,
1304        // and remains correct under direct `target()` calls outside
1305        // validate (the predicate's defensive empty arm returns a
1306        // parser-shaped reason rather than silently falling through to
1307        // the Capability arm). Same trajectory as c4213a4 (WitContract
1308        // endpoint/subject/slot value-shape gates lifted into
1309        // `target()`) on the peer payload axes.
1310        if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
1311            let (de, para, wit) = edge();
1312            return Err(AplicacaoError::ContratoWitInvalid {
1313                de,
1314                para,
1315                wit,
1316                reason,
1317            });
1318        }
1319
1320        if self.is_http() {
1321            if subject.is_some() || slot.is_some() {
1322                let (de, para, wit) = edge();
1323                return Err(AplicacaoError::ContratoWrongTarget {
1324                    de,
1325                    para,
1326                    wit,
1327                    expected: WitTarget::HTTP_FIELD_NAME,
1328                });
1329            }
1330            let ep = endpoint.ok_or_else(|| {
1331                let (de, para, wit) = edge();
1332                AplicacaoError::ContratoMissingTarget {
1333                    de,
1334                    para,
1335                    wit,
1336                    expected: WitTarget::HTTP_FIELD_NAME,
1337                }
1338            })?;
1339            if ep.is_empty() {
1340                let (de, para) = self.edge_pair();
1341                return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
1342            }
1343            if !ep.starts_with('/') {
1344                let (de, para) = self.edge_pair();
1345                return Err(AplicacaoError::ContratoEndpointNotAbsolute {
1346                    de,
1347                    para,
1348                    endpoint: ep.to_string(),
1349                });
1350            }
1351            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1352            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1353            // API v1 HTTPPathMatch.value admission grammar with the
1354            // sibling `:entrada :paths` axis. Until this gate landed
1355            // `target()` only refused the empty string + the missing-
1356            // leading-`/` form; a structurally invalid endpoint
1357            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1358            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1359            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1360            // path-traversal segment, the >1024-byte slug) silently
1361            // passed validate and the failure surfaced at apply time
1362            // as a Cilium policy rejection / silent traffic drop, far
1363            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1364            // grammar `:entrada :paths` already gates (55410e4), now
1365            // shared with `:contratos :endpoint` through the lifted
1366            // `crate::render::is_gateway_api_http_path` predicate.
1367            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1368                let (de, para) = self.edge_pair();
1369                return Err(AplicacaoError::ContratoEndpointInvalid {
1370                    de,
1371                    para,
1372                    endpoint: ep.to_string(),
1373                    reason,
1374                });
1375            }
1376            return Ok(WitTarget::Http { endpoint: ep });
1377        }
1378        if self.is_pubsub() {
1379            if endpoint.is_some() || slot.is_some() {
1380                let (de, para, wit) = edge();
1381                return Err(AplicacaoError::ContratoWrongTarget {
1382                    de,
1383                    para,
1384                    wit,
1385                    expected: WitTarget::PUBSUB_FIELD_NAME,
1386                });
1387            }
1388            let s = subject.ok_or_else(|| {
1389                let (de, para, wit) = edge();
1390                AplicacaoError::ContratoMissingTarget {
1391                    de,
1392                    para,
1393                    wit,
1394                    expected: WitTarget::PUBSUB_FIELD_NAME,
1395                }
1396            })?;
1397            if s.is_empty() {
1398                let (de, para) = self.edge_pair();
1399                return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1400            }
1401            // The `:subject` lands at runtime as the NATS subject the
1402            // producer publishes to and the consumer subscribes from.
1403            // Until this gate landed `target()` only refused the
1404            // empty string; a structurally invalid subject
1405            // (`"foo..bar"` — empty token between separators,
1406            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1407            // server's subject parser rejects, `"foo bar"` —
1408            // un-percent-encoded whitespace, `"foo.café"` —
1409            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1410            // empty leading/trailing tokens, the >256-byte
1411            // paste-from-binary slug) silently passed validate and
1412            // the failure surfaced at runtime as a NATS server-side
1413            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1414            // a silent message drop, far from the source caixa.lisp.
1415            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1416            // trajectory `:contratos :endpoint` (4f0390b) and
1417            // `:contratos :wit` (6226bf4) already gate, now shared
1418            // with `:contratos :subject` through the lifted
1419            // `crate::render::is_nats_subject` predicate.
1420            if let Err(reason) = crate::render::is_nats_subject(s) {
1421                let (de, para) = self.edge_pair();
1422                return Err(AplicacaoError::ContratoSubjectInvalid {
1423                    de,
1424                    para,
1425                    subject: s.to_string(),
1426                    reason,
1427                });
1428            }
1429            return Ok(WitTarget::PubSub { subject: s });
1430        }
1431        if self.is_store() {
1432            if endpoint.is_some() || subject.is_some() {
1433                let (de, para, wit) = edge();
1434                return Err(AplicacaoError::ContratoWrongTarget {
1435                    de,
1436                    para,
1437                    wit,
1438                    expected: WitTarget::STORE_FIELD_NAME,
1439                });
1440            }
1441            let sl = slot.ok_or_else(|| {
1442                let (de, para, wit) = edge();
1443                AplicacaoError::ContratoMissingTarget {
1444                    de,
1445                    para,
1446                    wit,
1447                    expected: WitTarget::STORE_FIELD_NAME,
1448                }
1449            })?;
1450            if sl.is_empty() {
1451                let (de, para) = self.edge_pair();
1452                return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1453            }
1454            // Value-shape gate on the third (and last) typed payload
1455            // axis the `WitContract::target` dispatch carries — the
1456            // peer of [`crate::render::is_gateway_api_http_path`] for
1457            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1458            // for `:subject` (63e18a0). Until this gate landed
1459            // `target()` only refused the empty string; a structurally
1460            // invalid slot (`"check out/$order"` — un-percent-encoded
1461            // whitespace whose runtime behavior varies unpredictably
1462            // across kv backends, `"checkout/\x01order"` — control
1463            // character that Redis admits but corrupts on next read
1464            // and DynamoDB rejects outright, `"chéckout/$order"` —
1465            // un-percent-encoded non-ASCII byte each backend re-encodes
1466            // differently, `"checkout\n/$order"` — embedded newline,
1467            // the 513-byte paste-from-binary slug) silently passed
1468            // validate and surfaced at runtime as a per-backend kv
1469            // write rejection (DynamoDB / etcd) or as a silent
1470            // next-read corruption (Redis-via-RESP3), far from the
1471            // source caixa.lisp with no field naming which `:contratos`
1472            // edge carried the typo. The lifted predicate makes the
1473            // kv-backend intersection-floor a substrate-level
1474            // invariant at validate time, not a runtime "this passed
1475            // validate but the kv backend rejected on first write"
1476            // surprise — closes the typed payload-axis value-shape
1477            // trajectory across all three legs of the four
1478            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1479            // that caixa-mesh + the future kv emitters land in.
1480            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1481                let (de, para) = self.edge_pair();
1482                return Err(AplicacaoError::ContratoSlotInvalid {
1483                    de,
1484                    para,
1485                    slot: sl.to_string(),
1486                    reason,
1487                });
1488            }
1489            return Ok(WitTarget::Store { slot: sl });
1490        }
1491
1492        // Unrecognized WIT world — must not carry any payload target.
1493        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1494            let (de, para, wit) = edge();
1495            return Err(AplicacaoError::ContratoWrongTarget {
1496                de,
1497                para,
1498                wit,
1499                expected: WitTarget::CAPABILITY_EXPECTED,
1500            });
1501        }
1502        Ok(WitTarget::Capability)
1503    }
1504
1505    /// Substrate-canonical post-validation projection of the typed
1506    /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
1507    /// downstream of an [`AplicacaoSpec`] that has already crossed the
1508    /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
1509    /// [`typed_view`]-shaped entry point that composes `validate` into
1510    /// the projection) reaches through when it needs the typed
1511    /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
1512    /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
1513    /// coherence for every `:contratos` entry. The peer accessor to the
1514    /// [`Self::target`] `Result`-returning validator on the same
1515    /// per-`:contratos` typed-projection axis — [`Self::target`] is the
1516    /// pre-validation validator that computes the projection *and* raises
1517    /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
1518    /// (`:wit`, payload) mismatch; this method is the post-validation
1519    /// projection every downstream consumer reaches through once the
1520    /// pre-validation gate has succeeded.
1521    ///
1522    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1523    ///
1524    /// Prior to this lift the "call `.target()` then `.expect(…)` with
1525    /// the same message" pattern sat inline at two production sites with
1526    /// no compile-time link between them: the
1527    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
1528    /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
1529    /// (`c.target().expect("validated by typed_view").http_endpoint()`)
1530    /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
1531    /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
1532    /// (`c.target().expect("validated by typed_view").graph_label()`),
1533    /// each open-coding the same `.target().expect("validated by
1534    /// typed_view")` pair with the message spelled twice. A future
1535    /// vocabulary shift on the panic-message axis (a tightening from
1536    /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
1537    /// validate"` as the substrate's validator entry-point vocabulary
1538    /// sharpens, a per-consumer disambiguation, an M4 promotion of the
1539    /// panic to a `debug_assert` under a `--release` build profile) would
1540    /// have had to be threaded through both open-coded call sites in
1541    /// lockstep or one consumer would silently disagree with the peer on
1542    /// which invariant the panic message names. Same "same shape written
1543    /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
1544    /// discipline the sibling [`Self::edge_pair`] /
1545    /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
1546    /// lifts already establish on the paired composite-projection axis;
1547    /// this lift extends it onto the post-validation typed-view axis.
1548    ///
1549    /// Every future downstream consumer of the projected typed view
1550    /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
1551    /// CR materializer's per-edge admission webhook, the future
1552    /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
1553    /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
1554    /// resolver, the future `feira app graph --l7` / `--pubsub` /
1555    /// `--kv` per-shape column emitters) reaches through this one typed
1556    /// dispatch on the substrate primitive rather than an open-coded
1557    /// per-consumer `.target().expect(…)` pair with the message
1558    /// re-inlined. The invariant the accessor's panic path pins — "this
1559    /// call is only reachable after [`AplicacaoSpec::validate`] has
1560    /// succeeded on the containing spec" — is the substrate's answer to
1561    /// give exactly once, at the primitive, not once per consumer.
1562    ///
1563    /// # Panics
1564    ///
1565    /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
1566    /// would return an `Err` — i.e. if this contract's
1567    /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
1568    /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
1569    /// this accessor only from a code path that has already reached the
1570    /// containing [`AplicacaoSpec`] through a validating entry-point
1571    /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
1572    /// [`typed_view`] compose, the future M4 CR admission webhook's
1573    /// per-CR validate). Use [`Self::target`] instead on any pre-
1574    /// validation code path.
1575    ///
1576    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1577    #[must_use]
1578    pub fn target_projected(&self) -> WitTarget<'_> {
1579        self.target().expect(Self::PROJECTED_INVARIANT_MSG)
1580    }
1581
1582    /// Canonical panic message the [`Self::target_projected`]
1583    /// post-validation projection accessor threads through when the
1584    /// caller has violated the "call only after [`AplicacaoSpec::validate`]
1585    /// has succeeded" precondition. Lifted as a `pub const` on the
1586    /// [`WitContract`] surface so the byte-string lives in one place
1587    /// across the substrate — the [`Self::target_projected`] method
1588    /// body, the two prior production call sites' comments now naming
1589    /// the const, and every future consumer that must format-match the
1590    /// panic-message shape (a future test suite that asserts the panic-
1591    /// message byte-string across a fuzzed invalid-contract corpus,
1592    /// a future custom-panic hook in `caixa-operator` that surfaces the
1593    /// message with per-`:contratos` telemetry, the future admission
1594    /// webhook's per-CR validate-error report) reaches through the same
1595    /// canonical `&'static str`. A future rebrand on the panic-message
1596    /// axis (a tightening from `"validated by typed_view"` to `"validated
1597    /// by AplicacaoSpec::validate"` as the substrate's validator
1598    /// entry-point vocabulary sharpens once caixa-core grows a
1599    /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
1600    /// [`typed_view`]) lands at one caixa-core edit rather than a
1601    /// coordinated per-consumer sweep — same "one canonical declaration
1602    /// per axis, next to the accessor that reads it" discipline the peer
1603    /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
1604    /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
1605    /// const family already establishes on the paired per-consumer-axis
1606    /// diagnostic-scalar surface.
1607    pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
1608}
1609
1610/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1611/// gate (see [`AplicacaoSpec::validate`]): every field that
1612/// distinguishes one contract from another, in declaration order
1613/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1614/// with equal [`ContratoIdentity`]s are the same typed edge declared
1615/// twice — the graph-edge analogue of duplicate `:membros` /
1616/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1617/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1618/// clippy's `type_complexity` lint (and so a future axis added to
1619/// `WitContract` is one alias edit, not a coordinated rewrite of
1620/// every set instantiation).
1621pub type ContratoIdentity<'a> = (
1622    &'a str,
1623    &'a str,
1624    &'a str,
1625    Option<&'a str>,
1626    Option<&'a str>,
1627    Option<&'a str>,
1628);
1629
1630/// Typed view of a [`WitContract`]'s payload target. Each variant
1631/// carries the field its WIT shape requires; constructing a `Http`
1632/// view without an endpoint is impossible by the type system.
1633///
1634/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1635/// instead of probing `Option<String>` fields one by one — the
1636/// "which payload field is set?" question is answered once, at
1637/// validation time.
1638#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1639pub enum WitTarget<'a> {
1640    /// HTTP-shaped WIT world. Carries the configured request path.
1641    Http { endpoint: &'a str },
1642    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1643    ///
1644    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1645    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1646    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1647    /// method name byte-identical to the sibling
1648    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1649    /// arm-discriminator that routes through
1650    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1651    /// through `matches!` on the variant), so the two arm-discriminator
1652    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1653    /// every downstream consumer through the same `is_pubsub()` name.
1654    #[is_variant(name = "pubsub")]
1655    PubSub { subject: &'a str },
1656    /// Key-value-shaped WIT world. Carries the slot template.
1657    Store { slot: &'a str },
1658    /// A typed capability edge with no payload selector — the WIT
1659    /// world stands on its own (rare; reserved for plain capability
1660    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1661    Capability,
1662}
1663
1664impl<'a> WitTarget<'a> {
1665    /// Canonical author-facing `:contratos` payload field name for the
1666    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1667    /// [`AplicacaoError::ContratoMissingTarget`] /
1668    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1669    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1670    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1671    /// the `feira app graph` verb prints. Peer of
1672    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1673    /// on the payload-field-name axis; declared as a peer const next
1674    /// to the [`WitTarget::Http`] variant so a future rename on the
1675    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1676    /// :endpoint …)))` field lands in exactly one place, not scattered
1677    /// across the [`WitContract::target`] gate's six `expected:`
1678    /// literals, the label template, and every downstream consumer
1679    /// that prints a per-arm prefix. Same trajectory as the peer
1680    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1681    /// for the arm's shape, next to the variant declaration.
1682    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1683    /// Canonical author-facing `:contratos` payload field name for the
1684    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1685    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1686    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1687    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1688    /// Canonical author-facing `:contratos` payload field name for the
1689    /// key/value-store-shaped arm. Peer of
1690    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1691    /// on the payload-field-name axis; see
1692    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1693    pub const STORE_FIELD_NAME: &'static str = "slot";
1694
1695    /// Canonical stable human-readable label the payload-less
1696    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1697    /// the byte-string every consumer that formats a payload-less
1698    /// typed capability edge as text lands on (the
1699    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1700    /// naming which identical edge was declared twice, the future
1701    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1702    /// policy resolver's audit view, the operator's mesh-graph audit).
1703    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1704    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1705    /// author-facing label-scalar consts — the same
1706    /// "one canonical declaration per arm, next to the variant, so a
1707    /// future rename lands in one place" discipline extended to the
1708    /// payload-less arm. Until this lift landed the byte-string sat
1709    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1710    /// match arm, once in the pin test asserting the label's
1711    /// [`WitTarget::Capability`] output — with no compile-time link
1712    /// between the two: a rebrand on either side (an operator-facing
1713    /// vocabulary shift, a per-consumer disambiguation like
1714    /// `"(capability — no payload; typed edge only)"`) would silently
1715    /// desynchronize until a downstream consumer surfaced the drift at
1716    /// runtime.
1717    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1718
1719    /// Canonical `expected:` scalar the
1720    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1721    /// through for the payload-less [`WitTarget::Capability`] arm — the
1722    /// byte-string authors read as "this WIT world's shape is not one
1723    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1724    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1725    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1726    /// [`Self::STORE_FIELD_NAME`] consts on the
1727    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1728    /// same "which payload field name goes in the diagnostic" dispatch
1729    /// the three payload-arm consts cover, extended to the payload-less
1730    /// arm. Until this lift landed the byte-string sat twice — once
1731    /// inline in the [`Self::target`] Capability-arm rejection at the
1732    /// production dispatch, once in the pin test asserting the
1733    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1734    /// no compile-time link between the two: a rebrand on either side
1735    /// (an author-facing vocabulary shift to `"capability"` /
1736    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1737    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1738    /// [`WitTarget::Capability`] into per-shape peers) would silently
1739    /// desynchronize until a downstream consumer surfaced the drift at
1740    /// runtime. Same "one canonical declaration per arm, next to the
1741    /// variant, so a future rename lands in one place" discipline the
1742    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1743    /// established for the payload-less arm's human-readable label
1744    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1745    /// so both halves of the "how does the Capability arm surface at
1746    /// its two consumer axes (human-readable label, wrong-target
1747    /// diagnostic)" pipeline route through peer consts declared next
1748    /// to the variant.
1749    ///
1750    /// Pairwise-distinctness against the three payload-arm scalars
1751    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1752    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1753    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1754    /// test — the 4-way closure of the 3-way
1755    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1756    /// the `ContratoWrongTarget::expected` axis, matching the peer
1757    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1758    /// scalar-value distinctness discipline the sibling M3 typed-enum
1759    /// discriminator axis already carries.
1760    pub const CAPABILITY_EXPECTED: &'static str = "none";
1761
1762    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1763    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1764    /// as under [`Self::graph_label`] — the sibling
1765    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1766    /// payload-column axis (the graph verb spells payload-less as
1767    /// `(capability-only)`, distinct from the duplicate-`:contratos`
1768    /// diagnostic's `(capability — no payload)` on the human-readable
1769    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1770    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1771    /// family — extends the "one canonical declaration per arm, next to
1772    /// the variant, so a future rename lands in one place" discipline
1773    /// onto the third payload-less-arm consumer axis (`feira app graph`
1774    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1775    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1776    /// axis).
1777    ///
1778    /// Until this lift landed the byte-string sat inline in
1779    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1780    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1781    /// `"(capability-only)".to_string()` literal, with no compile-time link
1782    /// back to the [`WitTarget::Capability`] variant declaration nor to
1783    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1784    /// peer consts already carrying the "one canonical declaration per
1785    /// payload-less-arm consumer axis" discipline. A rebrand on either
1786    /// side (the graph verb's operator-facing vocabulary tightening from
1787    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1788    /// the WIT registry vocabulary sharpens, an M4 split of
1789    /// [`Self::Capability`] into per-shape peers) would silently
1790    /// desynchronize the graph-verb byte-string from the paired
1791    /// per-arm-adjacent const and land two spellings of the same axis in
1792    /// two spots.
1793    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1794
1795    /// The `(author-facing field name, payload)` pair this typed target
1796    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1797    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1798    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1799    /// [`Self::Store`], `None` for the payload-less
1800    /// [`Self::Capability`] arm.
1801    ///
1802    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1803    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1804    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1805    /// (returns the first component) route through, so a future
1806    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1807    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1808    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1809    /// exactly one new match-arm here (a compile-time exhaustiveness
1810    /// error otherwise), not a coordinated three-way rewrite of the
1811    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1812    /// + every downstream consumer that reaches for the pair.
1813    ///
1814    /// Until this lift landed the three payload arms sat in
1815    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1816    /// invocations (one per variant, each hand-quoting the paired
1817    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1818    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1819    /// "same shape, written N times" duplication THEORY.md §I.3.5
1820    /// ("Generation first, composition second, hand-authoring last;
1821    /// the duplication budget is zero") promotes to a build-time
1822    /// concern, with each per-arm site paired to its own const with no
1823    /// compile-time link between the format template and the arm's
1824    /// payload extraction.
1825    #[must_use]
1826    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1827        match *self {
1828            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1829            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1830            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1831            WitTarget::Capability => None,
1832        }
1833    }
1834
1835    /// The canonical author-facing `:contratos` payload field name
1836    /// this typed target arm carries (`Http` → `Some("endpoint")`,
1837    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1838    /// `None` for the payload-less `Capability` arm.
1839    ///
1840    /// Routes through [`Self::payload_pair`] — the single 4-arm
1841    /// dispatch [`Self::label`] also reads — so a future variant
1842    /// addition is one match-arm edit at [`Self::payload_pair`], not a
1843    /// per-consumer rewrite. Same "exhaustive-match at one canonical
1844    /// dispatch, thin projections at each consumer" trajectory the
1845    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1846    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1847    #[must_use]
1848    pub const fn field_name(&self) -> Option<&'static str> {
1849        match self.payload_pair() {
1850            Some((f, _)) => Some(f),
1851            None => None,
1852        }
1853    }
1854
1855    /// The underlying scalar the payload-carrying arm carries — the
1856    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
1857    /// subject ([`Self::PubSub`] `:subject`), or slot template
1858    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
1859    /// `&'a str` storage — or `None` on the payload-less
1860    /// [`Self::Capability`] arm.
1861    ///
1862    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
1863    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
1864    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
1865    /// the paired sub-selector axis. Both per-half accessors read from
1866    /// one authoritative match, so a future [`WitTarget`] variant
1867    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
1868    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
1869    /// on [`Self::payload_pair`] and both per-half projections + every
1870    /// downstream consumer picks the new arm up by construction — no
1871    /// coordinated N-way rewrite across the paired accessor dispatches,
1872    /// the [`Self::label`] / [`Self::graph_label`] format templates,
1873    /// and every future WIT-registry-shaped consumer.
1874    ///
1875    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
1876    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
1877    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
1878    /// both per-half projections as thin readers, every downstream
1879    /// consumer through the same match" discipline extended onto the
1880    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
1881    /// gap between the two paired-dispatch surfaces: the peer
1882    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
1883    /// the first-component projection until this lift; the second-
1884    /// component sibling now sits alongside so both halves reach every
1885    /// future consumer through the same substrate-primitive dispatch.
1886    ///
1887    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
1888    #[must_use]
1889    pub const fn payload(&self) -> Option<&'a str> {
1890        match self.payload_pair() {
1891            Some((_, p)) => Some(p),
1892            None => None,
1893        }
1894    }
1895
1896    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
1897    /// consumer that fans on the L7-HTTP-shaped payload keys off —
1898    /// returns the [`Self::Http`]-arm's author-declared request path
1899    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
1900    /// projected target is [`Self::Http { endpoint }`], `None` on the
1901    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
1902    /// [`Self::Capability`], each of which carries no HTTP endpoint by
1903    /// definition).
1904    ///
1905    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
1906    /// `path:` rule payload every substrate-side L7-introspecting
1907    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
1908    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
1909    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
1910    /// on the L7 introspection branch; every peer WIT shape stays
1911    /// L4-only because Cilium can't introspect NATS / key-value / plain
1912    /// capability edges), and every future L7-introspecting consumer
1913    /// of the projected target's HTTP endpoint (the future M4
1914    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
1915    /// materializer's per-edge L7 admission-webhook overlay, the
1916    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
1917    /// path bucket-key resolver, the future per-`:contratos`-edge
1918    /// mTLS-required overlay's HTTP-shape scope filter, the future
1919    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
1920    /// through the same typed dispatch.
1921    ///
1922    /// Prior to this lift the sole production consumer of the projected-
1923    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
1924    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
1925    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
1926    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
1927    /// }`) — reached the payload through a raw per-arm `if let` pattern-
1928    /// match that expressed no compile-time link back to the substrate
1929    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
1930    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
1931    /// scalar accessor on the peer per-`:contratos` raw-field axis but
1932    /// with no post-projection peer on the typed-view surface. A future
1933    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
1934    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
1935    /// gRPC-shaped worlds per this enum's own docstring at
1936    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
1937    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
1938    /// would have had to be threaded through the caixa-mesh L7 emit
1939    /// branch's raw `if let` in lockstep — either coalescing the two
1940    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
1941    /// emit path per-arm — with no substrate-primitive dispatch making
1942    /// the "which arms count as L7-HTTP-shaped for path-emission
1943    /// purposes" question the substrate's answer to give. Lifting the
1944    /// resolution to a typed method on the substrate primitive means
1945    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
1946    /// projected-target HTTP endpoint reaches for exactly one typed
1947    /// dispatch — the resolver's accept-set migrates as a unit on any
1948    /// future arm-family widening, and the caixa-mesh L7 emit branch
1949    /// reads through the same substrate primitive.
1950    ///
1951    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
1952    /// (7020470) `Option<&str>` scalar accessor on the raw
1953    /// `:contratos :endpoint` field-access axis — same "one typed
1954    /// dispatch on the substrate primitive, thin projections at each
1955    /// consumer" discipline extended onto the peer post-projection typed-
1956    /// view surface (the [`WitContract::endpoint`] pre-projection
1957    /// accessor returns `Some` for any author-declared `:endpoint`
1958    /// value regardless of the paired `:wit` world's HTTP-shape
1959    /// classification — the raw slot before validation crosses it —
1960    /// while this post-projection [`Self::http_endpoint`] accessor
1961    /// returns `Some` iff the target has been projected onto the
1962    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
1963    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
1964    /// coherence; the two accessors close the pre-projection /
1965    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
1966    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
1967    /// the three payload-carrying arms) — extends the per-arm
1968    /// projection family onto the [`Self::Http`] specialization axis
1969    /// that the pan-arm accessor's shape blends into a single arm-
1970    /// agnostic view; paired with [`Self::pubsub_subject`] /
1971    /// [`Self::store_slot`] on the sibling per-arm axes so every
1972    /// per-payload-arm shape carries a named post-projection accessor
1973    /// on the same shape as `http_endpoint`, closing the per-arm-shape
1974    /// accept-set the substrate primitive owns.
1975    #[must_use]
1976    pub const fn http_endpoint(&self) -> Option<&'a str> {
1977        match *self {
1978            WitTarget::Http { endpoint } => Some(endpoint),
1979            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1980        }
1981    }
1982
1983    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
1984    /// consumer that fans on the pub-sub-shaped payload keys off —
1985    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
1986    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
1987    /// the projected target is [`Self::PubSub { subject }`], `None` on
1988    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
1989    /// [`Self::Capability`], each of which carries no NATS-shaped
1990    /// subject by definition).
1991    ///
1992    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
1993    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
1994    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
1995    /// CR materializer's `spec.subjects[]` projection, the future
1996    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
1997    /// bucket-key resolver, the future `feira app graph --pubsub`
1998    /// per-Aplicacao subject column, any future substrate-lifted
1999    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
2000    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
2001    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
2002    /// future pub-sub-shape consumer reaches for the same typed
2003    /// dispatch this accessor exposes so the "which arm carries the
2004    /// subject scalar?" answer lives at one caixa-core edit rather
2005    /// than open-coded across per-consumer `if let WitTarget::PubSub
2006    /// { subject } = c.target()…` pattern-matches.
2007    ///
2008    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2009    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2010    /// the pre-projection [`WitContract::subject`] scalar accessor on
2011    /// the raw `:contratos :subject` field-access axis — same "one
2012    /// typed dispatch on the substrate primitive, thin projections at
2013    /// each consumer" discipline extended onto the per-arm pub-sub
2014    /// post-projection axis. The pre-projection accessor returns
2015    /// `Some` for any author-declared `:subject` value regardless of
2016    /// the paired `:wit` world's pub-sub-shape classification (the raw
2017    /// slot before validation crosses it); this post-projection
2018    /// accessor returns `Some` iff the target has been projected onto
2019    /// the [`Self::PubSub`] arm, i.e. only after the
2020    /// [`WitContract::target`] gate has admitted the
2021    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2022    /// the pre-/post-projection pair on the pub-sub-subject axis to
2023    /// match the pair the [`WitContract::endpoint`] +
2024    /// [`Self::http_endpoint`] surfaces already close on the peer
2025    /// HTTP-endpoint axis.
2026    ///
2027    /// Sibling of the unified pan-arm [`Self::payload`]
2028    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2029    /// extends the per-arm projection family onto the [`Self::PubSub`]
2030    /// specialization axis that the pan-arm accessor's shape blends
2031    /// into a single arm-agnostic view; the pair
2032    /// (`pubsub_subject`, `store_slot`) closes the trio
2033    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2034    /// payload arm now carries its own per-arm-shape post-projection
2035    /// accessor.
2036    #[must_use]
2037    pub const fn pubsub_subject(&self) -> Option<&'a str> {
2038        match *self {
2039            WitTarget::PubSub { subject } => Some(subject),
2040            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2041        }
2042    }
2043
2044    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2045    /// every consumer that fans on the store-shaped payload keys off —
2046    /// returns the [`Self::Store`]-arm's author-declared slot template
2047    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2048    /// projected target is [`Self::Store { slot }`], `None` on the
2049    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2050    /// [`Self::Capability`], each of which carries no
2051    /// key/value-store slot by definition).
2052    ///
2053    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2054    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2055    /// every future substrate-side store-introspecting per-`(:de,
2056    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2057    /// namespace / prefix reconciler's per-slot projection, the future
2058    /// per-store-backend routing overlay's slot-shape gate, the future
2059    /// `feira app graph --store` per-Aplicacao slot column, any future
2060    /// substrate-lifted store-shape emitter that reads a projected
2061    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2062    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2063    /// Every future store-shape consumer reaches for the same typed
2064    /// dispatch this accessor exposes so the "which arm carries the
2065    /// slot scalar?" answer lives at one caixa-core edit rather than
2066    /// open-coded across per-consumer
2067    /// `if let WitTarget::Store { slot } = c.target()…`
2068    /// pattern-matches.
2069    ///
2070    /// Peer of the sibling [`Self::http_endpoint`] +
2071    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2072    /// axes and of the pre-projection [`WitContract::slot`] scalar
2073    /// accessor on the raw `:contratos :slot` field-access axis — same
2074    /// "one typed dispatch on the substrate primitive, thin projections
2075    /// at each consumer" discipline extended onto the per-arm store
2076    /// post-projection axis. Closes the pre-/post-projection pair on
2077    /// the store-slot axis to match the pairs the
2078    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2079    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2080    /// already close on the peer HTTP-endpoint and pub-sub-subject
2081    /// axes; the substrate-side pre-/post-projection accessor family
2082    /// now spans all three payload arms as a matched trio, so any
2083    /// future arm-shape widening (a `Rest`/`Grpc` split of
2084    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2085    /// lands one accessor without threading through the sibling
2086    /// pre-projection or the peer per-arm post-projection surfaces a
2087    /// compile-time exhaustiveness error at the substrate primitive,
2088    /// not a silent per-consumer split at renderer emit time.
2089    ///
2090    /// Sibling of the unified pan-arm [`Self::payload`]
2091    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2092    /// closes the per-arm projection family onto the [`Self::Store`]
2093    /// specialization axis that the pan-arm accessor's shape blends
2094    /// into a single arm-agnostic view. The trio
2095    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2096    /// pan-arm accept-set on every payload-carrying arm: exactly one
2097    /// per-arm accessor returns `Some(payload)` and the two peers
2098    /// return `None`, and every payload-less [`Self::Capability`]
2099    /// input returns `None` on all three — the partition the sibling
2100    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2101    /// pin locks in load-bearing.
2102    #[must_use]
2103    pub const fn store_slot(&self) -> Option<&'a str> {
2104        match *self {
2105            WitTarget::Store { slot } => Some(slot),
2106            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2107        }
2108    }
2109
2110    /// Render this typed target as a stable human-readable label
2111    /// (`:endpoint "/charge"`, `:subject "events.x"`,
2112    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2113    /// the WIT world is a pure capability edge).
2114    ///
2115    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2116    /// gate so the diagnostic names *which* identical edge was
2117    /// declared twice (not just which `(de, para, wit)` triple).
2118    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2119    /// on the payload-carrying arms (`Some((field, payload)) →
2120    /// format!(":{field} {payload:?}")`) and through the lifted
2121    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2122    /// [`Self::Capability`] arm — so a future variant addition (the
2123    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2124    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2125    /// `Queue`-shaped peer) becomes a single new match-arm on
2126    /// [`Self::payload_pair`] rather than a rewrite of this template
2127    /// (and every downstream consumer that reaches for the label
2128    /// shape: the per-edge policy resolver in M4, the `feira app
2129    /// graph` view, the operator's mesh-graph audit). Until this
2130    /// lift landed the three payload arms carried three near-identical
2131    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2132    /// [`Self::Capability`] arm carried the payload-less byte-string
2133    /// twice (once inline here, once in the pin test) — closing the
2134    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2135    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2136    /// / 4a1e490) peer-const lifts already established for the
2137    /// payload-carrying arms.
2138    #[must_use]
2139    pub fn label(&self) -> String {
2140        match self.payload_pair() {
2141            Some((field, payload)) => format!(":{field} {payload:?}"),
2142            None => Self::CAPABILITY_LABEL.to_string(),
2143        }
2144    }
2145
2146    /// Render this typed target as the `feira app graph` per-`:contratos`
2147    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2148    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2149    /// payload-less arm).
2150    ///
2151    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2152    /// on the payload-carrying arms (`Some((field, payload)) →
2153    /// format!("{field}={payload}")`) and through the lifted
2154    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2155    /// [`Self::Capability`] arm — so a future variant addition
2156    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2157    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2158    /// `Queue`-shaped peer) becomes one match-arm edit at
2159    /// [`Self::payload_pair`], propagating through this graph-verb
2160    /// projection at zero call-site cost, sibling to the peer
2161    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2162    /// same 4-arm dispatch.
2163    ///
2164    /// Until this lift landed the [`caixa-feira`]
2165    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2166    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2167    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2168    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2169    /// `format!("{}={endpoint}", ...)` template and hard-coding
2170    /// `"(capability-only)"` as a fifth payload-less scalar with no link
2171    /// back to the paired [`WitTarget::Capability`] variant declaration.
2172    /// A future variant addition would have had to be threaded through
2173    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2174    /// verb's inline match in lockstep or the two projections would
2175    /// silently disagree on the arm-set the graph verb prints — the
2176    /// duplicate-`:contratos` diagnostic reading one shape while the
2177    /// graph verb's payload column silently dropped the new arm to
2178    /// `(capability-only)`. Lifting the graph-verb projection onto the
2179    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2180    /// the axis: both projections migrate as a unit.
2181    ///
2182    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2183    /// quoting) shape is graph-verb-canonical — distinct from the
2184    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2185    /// duplicate-`:contratos` diagnostic seeds (see
2186    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2187    /// on the payload-less axis for the paired distinction).
2188    #[must_use]
2189    pub fn graph_label(&self) -> String {
2190        match self.payload_pair() {
2191            Some((field, payload)) => format!("{field}={payload}"),
2192            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2193        }
2194    }
2195}
2196
2197/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2198/// pretty-printed byte-string every consumer that formats a typed
2199/// payload target as user-facing text lands on (the
2200/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2201/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2202/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2203/// graph` per-`:contratos`-edge payload column that reaches the graph
2204/// verb through `format!("{target}")`, the future M4 per-edge policy
2205/// resolver's per-edge audit-log line, the operator's mesh-graph
2206/// per-edge inspection view) reaches for the same lifted
2207/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2208/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2209/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2210/// routes through — extending the three-path-convergence
2211/// (`Debug` for structural inspection, `Display` for user-facing text,
2212/// per-arm typed accessor for the canonical byte-string) discipline the
2213/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2214/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2215/// onto the fourth (and only remaining) typed-shape-discriminator axis
2216/// on the caixa surface.
2217///
2218/// Pre-lift the two paths were structurally independent — every consumer
2219/// reaching for a payload byte-string past the [`WitTarget::label`]
2220/// helper had to pick between three paths ([`WitTarget::label`],
2221/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2222/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2223/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2224/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2225/// that reached for `format!("{target}")` — the canonical shape every
2226/// user-facing pretty-print site on the sibling typed-enum axes already
2227/// uses — would silently land on the `Debug` derive's structural output
2228/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2229/// than the `label()` helper's stable byte-string (`:endpoint
2230/// "/charge"` — the author-facing `:contratos` keyword form) the
2231/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2232/// already threads through. The two spellings would diverge silently in
2233/// every downstream diagnostic / graph / audit line reached through
2234/// `format!` rather than through the `label()` helper. Routing
2235/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2236/// path: every `format!("{v}")` call reaches the same
2237/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2238/// and the duplicate-`:contratos` gate already route through, so a
2239/// future variant addition (the M4-and-later per-edge WIT registry may
2240/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2241/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2242/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2243/// match — rather than fanning out through hand-rolled per-arm
2244/// [`std::fmt::Display`] arms.
2245///
2246/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2247/// is the typed view returned by [`WitContract::target`], not a
2248/// closed-set discriminator enum with a gen-platform Discriminant
2249/// registration, so the `Debug` derive's structural output (which every
2250/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2251/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2252/// shape for structural inspection; `Display` (via `label`) reveals the
2253/// stable author-facing payload projection.
2254///
2255/// Pin tests
2256/// [`tests::wit_target_display_routes_through_label_helper`] and
2257/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2258/// assert the two paths agree byte-for-byte on every variant, so a
2259/// future variant addition or `label()` reimplementation that hand-rolls
2260/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2261/// build error visible at caixa-core test time, not a silent
2262/// per-consumer dispatch miss at diagnostic / audit / graph time.
2263impl std::fmt::Display for WitTarget<'_> {
2264    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2265        f.write_str(&self.label())
2266    }
2267}
2268
2269// ── one Aplicacao member ─────────────────────────────────────────────
2270
2271/// A Servico participating in the Aplicacao. Same shape as
2272/// `crate::supervisor::ChildSpec` but without a restart policy —
2273/// supervision is per-Servico (each member has its own
2274/// `:supervisor`), the Aplicacao orchestrates *placement*.
2275#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2276#[serde(rename_all = "camelCase")]
2277pub struct Membro {
2278    /// Member caixa's `:nome`. Resolves through the same dep
2279    /// resolution path as `crate::dep::Dep`.
2280    pub caixa: String,
2281
2282    /// Semver constraint.
2283    pub versao: String,
2284}
2285
2286impl Membro {
2287    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2288    /// accessor every consumer that reads the member's Servico identity
2289    /// keys off — returns the author-declared `:membros :caixa`
2290    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2291    /// own [`String`] storage.
2292    ///
2293    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2294    /// participating in the Aplicacao — validated by
2295    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2296    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2297    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2298    /// [`validate_no_self_membership`]) — and every downstream consumer
2299    /// that fans on the member's identity keys off this scalar (the
2300    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2301    /// lookup, the per-`:membros` duplicate gate's dedup key, the
2302    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2303    /// identity, the self-membership gate, the
2304    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2305    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2306    /// CR materializer's per-member resolver).
2307    ///
2308    /// Prior to this lift the `.caixa` byte-string was read inline at
2309    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2310    /// set collector at
2311    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2312    /// [`validate_membros`] validation-side member-caixa gate at
2313    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2314    /// per-member duplicate-gate dedup key at
2315    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2316    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2317    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2318    /// [`validate_no_self_membership`] self-loop gate at
2319    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2320    /// expressed no compile-time link back to the typed slot. Every
2321    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2322    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2323    /// `name:` axis, so a future extension of the `:membros :caixa`
2324    /// axis to a richer author surface — a per-cluster alias table the
2325    /// operator pins through a future `:placement`-scoped slot, a
2326    /// namespace-qualified rewrite the M4 CR materializer applies
2327    /// per-CR, a per-member overlay from the future `:membros
2328    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2329    /// acknowledges — would have had to be threaded through every
2330    /// open-coded copy in lockstep or one consumer would silently
2331    /// disagree with the peers on which caixa a given member resolves
2332    /// to. A member-set lookup that treated the name as `"cart"` while
2333    /// the peer adjacency map treated it as `"tenant-a/cart"` would
2334    /// silently split the `:contratos` membership-lookup diagnostic from
2335    /// the cycle-detector's node identity — a two-consumer split at the
2336    /// validator far from the source `caixa.lisp` with no field naming
2337    /// the identity-drift root cause. Lifting the resolution rule to a
2338    /// typed method on the substrate primitive means every downstream
2339    /// consumer of the Aplicacao's per-`:membros` identity surface
2340    /// reaches for exactly one typed dispatch — the resolver's
2341    /// accept-set migrates as a unit on any future axis addition.
2342    ///
2343    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2344    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2345    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2346    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2347    /// destination-Servico scalar accessors — same "one typed dispatch
2348    /// on the substrate primitive, thin projections at each consumer"
2349    /// discipline extended onto the per-`:membros` member-caixa `:nome`
2350    /// byte-string axis. Named `nome()` to match the tatara-lisp
2351    /// author-surface term the field's docstring already reaches for
2352    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2353    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2354    /// already carries — the accessor's name maps directly onto the
2355    /// canonical caixa-identity vocabulary rather than shadowing the
2356    /// field's storage-side `caixa` label.
2357    #[must_use]
2358    pub const fn nome(&self) -> &str {
2359        self.caixa.as_str()
2360    }
2361
2362    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2363    /// requirement scalar accessor every consumer that reads the
2364    /// member's version pin keys off — returns the author-declared
2365    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2366    /// from the typed slot's own [`String`] storage.
2367    ///
2368    /// The `:membros :versao` slot carries the Cargo-shaped semver
2369    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2370    /// pins which release of the member-caixa the Aplicacao composes
2371    /// against — the same requirement grammar the peer `:deps :versao`
2372    /// / `:children :versao` axes carry, resolved through the shared
2373    /// [`crate::render::require_valid_versao_requirement`] cascade and
2374    /// the shared [`crate::version::parse_requirement`] parser. Every
2375    /// downstream consumer that fans on the member's version pin keys
2376    /// off this scalar (the [`validate_membros`] per-member requirement
2377    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2378    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
2379    /// m.nome(), m.versao_requirement())` line, every future per-cluster
2380    /// version-lock overlay the operator pins through a future
2381    /// `:placement`-scoped slot, the future
2382    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2383    /// version resolver, the future `feira app deploy` pipeline's
2384    /// per-member lacre BLAKE3-closure lookup).
2385    ///
2386    /// Prior to this lift the `.versao` byte-string was accessed inline
2387    /// at two `&str`-shaped sites — the [`validate_membros`]
2388    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2389    /// …)` and the `feira app graph` per-member printer's `println!(
2390    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2391    /// prior to this lift) — two open-coded field-accesses that expressed
2392    /// no compile-time link back to the typed slot. A future extension of
2393    /// the `:membros :versao` axis to a richer author surface (a
2394    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2395    /// flow, a lacre-projected concrete-version rewrite the operator
2396    /// materializes at CR-admission time, a future `:membros :versao-lock`
2397    /// per-cluster override slot) would have had to be threaded through
2398    /// every open-coded copy in lockstep or one consumer would silently
2399    /// disagree with the peers on which release constraint a given
2400    /// member resolves to. Lifting the resolution rule to a typed method
2401    /// on the substrate primitive means every downstream requirement-
2402    /// facing consumer reaches for exactly one typed dispatch — the
2403    /// resolver's accept-set migrates as a unit on any future axis
2404    /// addition.
2405    ///
2406    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2407    /// member-caixa `:nome` scalar accessor — the pair
2408    /// `(nome(), versao_requirement())` jointly projects the
2409    /// `(caixa, versao)` field pair every renderer that fans on
2410    /// per-member identity + version pin keys off, closing the last
2411    /// unlifted per-`:membros` scalar axis so every downstream
2412    /// per-`:membros` reader now routes through a typed dispatch on the
2413    /// substrate primitive. Named `versao_requirement()` rather than
2414    /// `versao()` because the field's storage-side `.versao` label is
2415    /// already the author-surface term (`:versao`); the accessor's name
2416    /// carries the semantic role — the semver *requirement* string the
2417    /// shared [`crate::version::parse_requirement`] entry-point consumes
2418    /// — so a raw field access and a typed dispatch read differently at
2419    /// every consumer site.
2420    ///
2421    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2422    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2423    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2424    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2425    /// destination-Servico scalar accessors — same "one typed dispatch
2426    /// on the substrate primitive, thin projections at each consumer"
2427    /// discipline extended onto the per-`:membros` member-`:versao`
2428    /// semver-requirement byte-string axis.
2429    #[must_use]
2430    pub const fn versao_requirement(&self) -> &str {
2431        self.versao.as_str()
2432    }
2433}
2434
2435// ── mesh-level policies ──────────────────────────────────────────────
2436
2437/// Mesh policies that apply to every `:contratos` edge unless
2438/// overridden per-edge in M4. V0 is a single global policy block.
2439#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2440#[serde(rename_all = "camelCase")]
2441pub struct MeshPolicy {
2442    /// Per-call timeout. Authored as a duration string (`"30s"`).
2443    #[serde(
2444        default,
2445        skip_serializing_if = "Option::is_none",
2446        with = "supervisor::duration_codec"
2447    )]
2448    pub timeout: Option<Duration>,
2449
2450    /// Number of retries on transient failure. None = no retries.
2451    #[serde(default, skip_serializing_if = "Option::is_none")]
2452    pub retries: Option<u32>,
2453
2454    /// Circuit breaker config. Trips after N failures within W
2455    /// duration; closes after a cooldown.
2456    #[serde(default, skip_serializing_if = "Option::is_none")]
2457    pub circuit_breaker: Option<CircuitBreaker>,
2458
2459    /// Whether mTLS is required for every contrato. Default: true
2460    /// (sandboxing-by-default; explicit opt-out only).
2461    #[serde(default, skip_serializing_if = "Option::is_none")]
2462    pub mtls_required: Option<bool>,
2463
2464    /// Token-bucket rate limit. Authored as `"100/s"` or
2465    /// `"5000/m"`; stored as `(rate, window)`.
2466    #[serde(
2467        default,
2468        skip_serializing_if = "Option::is_none",
2469        with = "rate_limit_codec"
2470    )]
2471    pub rate_limit: Option<RateLimit>,
2472}
2473
2474impl MeshPolicy {
2475    /// True when no `:politicas` axis carries a value — every field is
2476    /// `None`. The same emptiness contract every other M2/M3 typed
2477    /// surface carries ([`crate::LimitsSpec::is_empty`],
2478    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2479    /// typed slot onto a cluster artifact key off this predicate to
2480    /// decide "emit the slot" vs "skip the slot entirely", so an
2481    /// authored-but-unset `:politicas (())` round-trips to a rendered
2482    /// artifact that's structurally identical to one that omits the
2483    /// slot. Lifted as a typed predicate (rather than per-renderer
2484    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2485    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2486    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2487    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2488    /// not a coordinated rewrite of every consumer that's reaching
2489    /// for the emptiness semantic.
2490    #[must_use]
2491    pub const fn is_empty(&self) -> bool {
2492        self.timeout().is_none()
2493            && self.retries().is_none()
2494            && self.circuit_breaker().is_none()
2495            && self.mtls_required().is_none()
2496            && self.rate_limit().is_none()
2497    }
2498
2499    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
2500    /// per-call-deadline scalar accessor every consumer of the
2501    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
2502    /// returns the author-declared `:politicas :timeout` typed
2503    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
2504    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
2505    /// is `Copy`, so the accessor returns by value; no borrow of
2506    /// `&self` past the call). `None` when the slot is absent (the
2507    /// "cluster default applies — typically the gateway class's
2508    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
2509    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
2510    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
2511    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
2512    /// round-trips to a rendered `HTTPRoute` structurally identical to
2513    /// one that omits the slot).
2514    ///
2515    /// The `:politicas :timeout` slot carries the "no infinite blocking"
2516    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
2517    /// the typed slot's `Option<Duration>` accept-set (zero-floor
2518    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
2519    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
2520    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
2521    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
2522    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
2523    /// Every downstream consumer that reads the per-call cap keys off
2524    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2525    /// renderers key off to decide "emit :politicas overlay" vs "skip
2526    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2527    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
2528    /// fans the deadline into every rule via
2529    /// [`crate::render::single_field_overlay`], the future M4 per-
2530    /// Aplicacao Gateway API reconciler materialization pass, the
2531    /// future per-`:contratos`-edge timeout-override overlay the
2532    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
2533    ///
2534    /// Prior to this lift the `.timeout` field was accessed inline at
2535    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
2536    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
2537    /// …)` call — two open-coded field-accesses that expressed no
2538    /// compile-time link back to the typed slot. A future extension of
2539    /// the `:politicas :timeout` axis to a richer author surface — a
2540    /// per-`:contratos`-edge timeout override the operator pins through
2541    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
2542    /// roadmap acknowledges, a per-cluster timeout-default overlay the
2543    /// M4 CR materializer resolves per-CR, a split of the single
2544    /// per-call `Duration` into a richer `{request, backendRequest}`
2545    /// pair once the Gateway API's per-rule `timeouts` block grows the
2546    /// upstream-facing backendRequest arm alongside the client-facing
2547    /// request arm — would have had to be threaded through both open-
2548    /// coded copies in lockstep or the emptiness predicate and the
2549    /// caixa-mesh emit path would silently disagree on which per-call
2550    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
2551    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
2552    /// == false` while the renderer's overlay-emit path silently read
2553    /// a drifted other value, or vice versa: an author's `:timeout
2554    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
2555    /// the emptiness predicate still classified the policy as non-
2556    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
2557    /// | grep -A2 timeouts` audit would land on a route whose author's
2558    /// typed slot value silently vanished at the renderer layer).
2559    /// Lifting the resolution to a typed method on the substrate
2560    /// primitive means every downstream consumer of the Aplicacao's
2561    /// per-`:politicas` deadline surface reaches for exactly one typed
2562    /// dispatch — the resolver's accept-set migrates as a unit on any
2563    /// future axis addition.
2564    ///
2565    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
2566    /// family (sibling of the peer per-`:politicas`
2567    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
2568    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
2569    /// `Option<bool>` accessor — same "one typed dispatch on the
2570    /// substrate primitive, thin projections at each consumer"
2571    /// discipline extended onto the peer per-`:politicas` typed-
2572    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
2573    /// numeric-Copy-T scalar" projection pattern the sibling
2574    /// `Option<u32>` / `Option<bool>` lifts opened, since every
2575    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
2576    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
2577    /// than a scalar). Named `timeout()` to match the storage field's
2578    /// name; the accessor's identity maps onto the canonical MESH-
2579    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
2580    #[must_use]
2581    pub const fn timeout(&self) -> Option<Duration> {
2582        self.timeout
2583    }
2584
2585    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
2586    /// retry-budget scalar accessor every consumer of the Aplicacao's
2587    /// Gateway API v1.x per-rule retry-cap keys off — returns the
2588    /// author-declared `:politicas :retries` typed `u32` verbatim as an
2589    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
2590    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
2591    /// value; no borrow of `&self` past the call). `None` when the slot
2592    /// is absent (the "cluster default applies — typically 'no retries
2593    /// beyond a single dispatch attempt'" arm the caixa-mesh
2594    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
2595    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
2596    /// this predicate too, so an authored-but-unset `:politicas
2597    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
2598    /// identical to one that omits the slot).
2599    ///
2600    /// The `:politicas :retries` slot carries the "transient failure
2601    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
2602    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
2603    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2604    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
2605    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
2606    /// count scalar the caixa-mesh `retry_overlay` builder writes.
2607    /// Every downstream consumer that reads the retry cap keys off this
2608    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2609    /// renderers key off to decide "emit :politicas overlay" vs "skip
2610    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2611    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
2612    /// the value into every rule via [`crate::render::single_field_overlay`],
2613    /// the future M4 per-Aplicacao Gateway API reconciler
2614    /// materialization pass, the future per-`:contratos`-edge retry-
2615    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
2616    /// acknowledges).
2617    ///
2618    /// Prior to this lift the `.retries` field was accessed inline at
2619    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
2620    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
2621    /// …)` call — two open-coded field-accesses that expressed no
2622    /// compile-time link back to the typed slot. A future extension of
2623    /// the `:politicas :retries` axis to a richer author surface — a
2624    /// per-`:contratos`-edge retry override the operator pins through a
2625    /// future `:contratos :retries` slot, a per-cluster retry-default
2626    /// overlay the M4 CR materializer resolves per-CR, a promotion of
2627    /// the plain `u32` attempt-count to a richer `{attempts, codes,
2628    /// backoff}` sub-block once the Gateway API grows the peer
2629    /// `retry.codes` / `retry.backoff` axes — would have had to be
2630    /// threaded through both open-coded copies in lockstep or the
2631    /// emptiness predicate and the caixa-mesh emit path would silently
2632    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
2633    /// (a `:politicas` block whose only axis is a `Some :retries` would
2634    /// satisfy `is_empty() == false` while the renderer's overlay-emit
2635    /// path silently read a drifted other value, or vice versa: an
2636    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
2637    /// block while the emptiness predicate still classified the policy
2638    /// as non-empty). Lifting the resolution to a typed method on the
2639    /// substrate primitive means every downstream consumer of the
2640    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
2641    /// one typed dispatch — the resolver's accept-set migrates as a
2642    /// unit on any future axis addition.
2643    ///
2644    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
2645    /// family (sibling of the peer per-`:politicas`
2646    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
2647    /// same "one typed dispatch on the substrate primitive, thin
2648    /// projections at each consumer" discipline extended onto the
2649    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
2650    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
2651    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
2652    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
2653    /// fold on). Named `retries()` to match the storage field's name;
2654    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
2655    /// §III.2 vocabulary the slot's docstring already carries.
2656    #[must_use]
2657    pub const fn retries(&self) -> Option<u32> {
2658        self.retries
2659    }
2660
2661    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
2662    /// enforcement-toggle scalar accessor every consumer of the
2663    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
2664    /// — returns the author-declared `:politicas :mtls-required` typed
2665    /// bool verbatim as an `Option<bool>`, copied out of the typed
2666    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
2667    /// the accessor returns by value; no borrow of `&self` past the
2668    /// call). `None` when the slot is absent (the "cluster default
2669    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
2670    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
2671    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
2672    /// this predicate too, so an authored-but-unset `:politicas
2673    /// (:mtls-required ())` round-trips to a rendered
2674    /// `CiliumNetworkPolicy` structurally identical to one that omits
2675    /// the slot).
2676    ///
2677    /// The `:politicas :mtls-required` slot carries the "explicit opt-
2678    /// out only, sandboxing-by-default" mTLS-enforcement toggle
2679    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
2680    /// `{None, Some(true), Some(false)}` accept-set maps onto the
2681    /// Cilium `authentication.mode` bijection through
2682    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
2683    /// handshake enforced), `Some(false) → "disabled"` (handshake
2684    /// skipped — the debug-edge opt-out), `None` → omit the block
2685    /// (cluster default applies). Every downstream consumer that
2686    /// reads the toggle keys off this scalar (the
2687    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2688    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2689    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
2690    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
2691    /// ingress rule via [`crate::render::single_field_overlay`], the
2692    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
2693    /// materialization pass, the future per-`:contratos`-edge mTLS
2694    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2695    ///
2696    /// Prior to this lift the `.mtls_required` field was accessed
2697    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2698    /// `self.mtls_required.is_none()` arm and caixa-mesh's
2699    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
2700    /// two open-coded field-accesses that expressed no compile-time
2701    /// link back to the typed slot. A future extension of the
2702    /// `:politicas :mtls-required` axis to a richer author surface —
2703    /// a per-`:contratos`-edge mTLS override the operator pins through
2704    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
2705    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
2706    /// M4 CR materializer resolves per-CR, a three-valued
2707    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
2708    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
2709    /// would have had to be threaded through both open-coded copies in
2710    /// lockstep or the emptiness predicate and the caixa-mesh emit
2711    /// path would silently disagree on which toggle a given
2712    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
2713    /// axis is a `Some`
2714    /// `:mtls-required` would satisfy `is_empty() == false` while the
2715    /// renderer's overlay-emit path silently read a drifted other
2716    /// value, or vice versa). Lifting the resolution to a typed method
2717    /// on the substrate primitive means every downstream consumer of
2718    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
2719    /// for exactly one typed dispatch — the resolver's accept-set
2720    /// migrates as a unit on any future axis addition.
2721    ///
2722    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2723    /// family (peer of the sibling per-`:placement`
2724    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2725    /// same "one typed dispatch on the substrate primitive, thin
2726    /// projections at each consumer" discipline extended onto the
2727    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2728    /// the "optional per-slot Copy-T scalar" projection pattern the
2729    /// sibling per-`:politicas` `:retries` (Option<u32>) /
2730    /// `:timeout` (Option<Duration>) future lifts fold on). Named
2731    /// `mtls_required()` to match the storage field's name; the
2732    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2733    /// §III.2 vocabulary the slot's docstring already carries.
2734    #[must_use]
2735    pub const fn mtls_required(&self) -> Option<bool> {
2736        self.mtls_required
2737    }
2738
2739    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2740    /// `local_rate_limit`-mesh token-bucket-declaration scalar
2741    /// accessor every consumer of the Aplicacao's per-`:politicas`
2742    /// per-`(rate, window)` rate-limit surface keys off — returns the
2743    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2744    /// verbatim as an `Option<RateLimit>`, copied out of the typed
2745    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2746    /// `Copy`, so the accessor returns by value; no borrow of `&self`
2747    /// past the call). `None` when the slot is absent (the "cluster
2748    /// default applies — typically 'no per-Aplicacao rate declaration,
2749    /// gateway-class per-listener default applies'" arm the future
2750    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2751    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2752    /// `rate_limit().is_none()` arm reads this predicate too, so an
2753    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2754    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2755    /// identical to one that omits the slot).
2756    ///
2757    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2758    /// token-bucket rate declaration" contract (MESH-COMPOSITION
2759    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2760    /// (rate lower-bounded by 1 through
2761    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2762    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2763    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2764    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2765    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2766    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2767    /// `:politicas` overlay emits. Every downstream consumer that
2768    /// reads the rate declaration keys off this scalar (the
2769    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2770    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2771    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2772    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2773    /// `rl.window` against [`is_canonical_rate_limit_window`], the
2774    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2775    /// the future per-`:contratos`-edge rate-limit override the
2776    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2777    ///
2778    /// Prior to this lift the `.rate_limit` field was accessed inline
2779    /// at two sites — [`MeshPolicy::is_empty`]'s
2780    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2781    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2782    /// field-accesses that expressed no compile-time link back to the
2783    /// typed slot. A future extension of the `:politicas :rate-limit`
2784    /// axis to a richer author surface — a per-`:contratos`-edge
2785    /// rate-limit override the operator pins through a future
2786    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2787    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2788    /// the M4 CR materializer resolves per-CR, a promotion of the
2789    /// plain `(rate, window)` scalar pair to a richer
2790    /// `{rate, window, burst, key}` sub-block once Envoy's
2791    /// `local_rate_limit` grows the peer `burst_size` /
2792    /// `descriptor_key` axes — would have had to be threaded through
2793    /// both open-coded copies in lockstep or the emptiness predicate
2794    /// and the validate gate would silently disagree on which rate
2795    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2796    /// block whose only axis is a `Some :rate-limit` would satisfy
2797    /// `is_empty() == false` while the validate path silently read a
2798    /// drifted other value, or vice versa: an author's
2799    /// `:rate-limit "100/s"` would omit the value-shape gate while the
2800    /// emptiness predicate still classified the policy as non-empty).
2801    /// Lifting the resolution to a typed method on the substrate
2802    /// primitive means every downstream consumer of the Aplicacao's
2803    /// per-`:politicas` rate-limit surface reaches for exactly one
2804    /// typed dispatch — the resolver's accept-set migrates as a unit
2805    /// on any future axis addition.
2806    ///
2807    /// First `Option<Copy-composite-T>`-return accessor on the M3
2808    /// mesh-slot family — closes the last un-lifted per-`:politicas`
2809    /// scalar-value axis. Peer of the sibling per-`:politicas`
2810    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2811    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2812    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2813    /// "one typed dispatch on the substrate primitive, thin
2814    /// projections at each consumer" discipline extended onto the
2815    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2816    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2817    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2818    /// sub-accessors rather than a top-level accessor because
2819    /// consumers reach for the axes not the aggregate). Named
2820    /// `rate_limit()` to match the storage field's name; the
2821    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2822    /// §III.2 vocabulary the slot's docstring already carries.
2823    #[must_use]
2824    pub const fn rate_limit(&self) -> Option<RateLimit> {
2825        self.rate_limit
2826    }
2827
2828    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2829    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2830    /// declaration scalar accessor every consumer of the Aplicacao's
2831    /// per-`:politicas` breaker declaration keys off — returns the
2832    /// author-declared `:politicas :circuit-breaker` typed
2833    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2834    /// copied out of the typed slot's own `Option<CircuitBreaker>`
2835    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2836    /// by value; no borrow of `&self` past the call). `None` when the
2837    /// slot is absent (the "cluster default applies — typically 'no
2838    /// per-Aplicacao breaker declaration, gateway-class per-listener
2839    /// default applies'" arm the future caixa-mesh
2840    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2841    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2842    /// arm reads this predicate too, so an authored-but-unset
2843    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2844    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2845    /// that omits the slot).
2846    ///
2847    /// The `:politicas :circuit-breaker` slot carries the
2848    /// "per-Aplicacao consecutive-transient-failure trip declaration"
2849    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2850    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2851    /// zero-floor rejected through
2852    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2853    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2854    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2855    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2856    /// canonical-form pinned through
2857    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2858    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2859    /// bijection the future `CiliumClusterwideEnvoyConfig`
2860    /// per-`:politicas` overlay emits. Every downstream consumer that
2861    /// reads the breaker declaration keys off this scalar (the
2862    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2863    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2864    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2865    /// that brackets `cb.max_failures()` against
2866    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2867    /// [`POLICY_BREAKER_WINDOW_MAX`] via
2868    /// [`crate::render::require_positive_canonical_bounded_duration`],
2869    /// the future M4 per-Aplicacao Envoy reconciler materialization
2870    /// pass, the future per-`:contratos`-edge breaker override the
2871    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2872    ///
2873    /// Prior to this lift the `.circuit_breaker` field was accessed
2874    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2875    /// `self.circuit_breaker.is_none()` arm and the
2876    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2877    /// bind — two open-coded field-accesses that expressed no
2878    /// compile-time link back to the typed slot. A future extension of
2879    /// the `:politicas :circuit-breaker` axis to a richer author
2880    /// surface — a per-`:contratos`-edge breaker override the operator
2881    /// pins through a future `:contratos :circuit-breaker` slot the
2882    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2883    /// breaker-default overlay the M4 CR materializer resolves per-CR,
2884    /// a promotion of the plain `(max_failures, window)` scalar pair to
2885    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2886    /// sub-block once Envoy's `outlier_detection` grows the peer
2887    /// ejection-percentage / ejection-time axes — would have had to be
2888    /// threaded through both open-coded copies in lockstep or the
2889    /// emptiness predicate and the validate gate would silently
2890    /// disagree on which breaker declaration a given [`MeshPolicy`]
2891    /// resolves to (a `:politicas` block whose only axis is a
2892    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2893    /// the validate path silently read a drifted other value, or vice
2894    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2895    /// "60s"))` would omit the value-shape gate while the emptiness
2896    /// predicate still classified the policy as non-empty). Lifting
2897    /// the resolution to a typed method on the substrate primitive
2898    /// means every downstream consumer of the Aplicacao's
2899    /// per-`:politicas` breaker surface reaches for exactly one typed
2900    /// dispatch — the resolver's accept-set migrates as a unit on any
2901    /// future axis addition.
2902    ///
2903    /// Second `Option<Copy-composite-T>`-return accessor on the M3
2904    /// mesh-slot family (sibling of the peer per-`:politicas`
2905    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2906    /// on the same composite-Copy shape, and of the sibling per-
2907    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2908    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2909    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2910    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2911    /// same "one typed dispatch on the substrate primitive, thin
2912    /// projections at each consumer" discipline extended onto the last
2913    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2914    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2915    /// match the storage field's name; the accessor's identity maps
2916    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2917    /// docstring already carries. Closes the last unlifted
2918    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2919    /// reader now routes through a typed dispatch on the substrate
2920    /// primitive.
2921    #[must_use]
2922    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2923        self.circuit_breaker
2924    }
2925}
2926
2927#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2928#[serde(rename_all = "camelCase")]
2929pub struct CircuitBreaker {
2930    pub max_failures: u32,
2931    #[serde(with = "supervisor::duration_codec_required")]
2932    pub window: Duration,
2933}
2934
2935impl CircuitBreaker {
2936    /// Substrate-canonical per-`:politicas :circuit-breaker`
2937    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2938    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2939    /// breaker trip-count keys off — returns the author-declared
2940    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2941    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2942    /// so the accessor returns by value; no borrow of `&self` past the
2943    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2944    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2945    /// axis; a `CircuitBreaker` past pattern-match is definitionally
2946    /// present, and its `:max-failures` field carries the trip count as a
2947    /// required-axis scalar).
2948    ///
2949    /// The `:politicas :circuit-breaker :max-failures` axis carries the
2950    /// "consecutive-transient-failure trip threshold" contract
2951    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2952    /// (zero-floor rejected through
2953    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2954    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2955    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2956    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2957    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2958    /// Every downstream consumer that reads the trip threshold keys off
2959    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2960    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2961    /// canonical `require_positive_bounded_u32` helper, the future M4
2962    /// per-Aplicacao Envoy config reconciler materialization pass, the
2963    /// future per-`:contratos`-edge breaker-override overlay the
2964    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2965    ///
2966    /// Prior to this lift the `.max_failures` field was accessed inline
2967    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2968    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2969    /// open-coded field-access that expressed no compile-time link back
2970    /// to the typed sub-struct axis. A future extension of the
2971    /// `:max-failures` axis to a richer author surface — a
2972    /// per-`:contratos`-edge breaker override the operator pins through a
2973    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2974    /// #3 roadmap acknowledges, a per-cluster max-failures-default
2975    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2976    /// plain `u32` trip count to a richer
2977    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2978    /// tuple once Envoy's `outlier_detection` block's peer axes come into
2979    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2980    /// count arms — would have had to be threaded through every open-
2981    /// coded copy in lockstep or the validate gate and the future M4
2982    /// emit path would silently disagree on which trip threshold a given
2983    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2984    /// would satisfy validate while the emit path silently read a drifted
2985    /// other value, or vice versa: a validated typed slot would land at
2986    /// the emit boundary as a no-op breaker whose trip threshold is
2987    /// structurally never reached). Lifting the resolution to a typed
2988    /// method on the substrate primitive means every downstream consumer
2989    /// of the Aplicacao's per-`:politicas :circuit-breaker`
2990    /// trip-threshold surface reaches for exactly one typed dispatch —
2991    /// the resolver's accept-set migrates as a unit on any future axis
2992    /// addition.
2993    ///
2994    /// First sub-struct scalar accessor on the M3 mesh-slot family
2995    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2996    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2997    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2998    /// closes the last unlifted per-`:politicas` scalar-value axis after
2999    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
3000    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
3001    /// Same "one typed dispatch on the substrate primitive, thin
3002    /// projections at each consumer" discipline the peer
3003    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3004    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3005    /// [`Membro::versao_requirement`] (a40b0e3),
3006    /// [`Entrada::destination`] (6db982c) accessors carry on their
3007    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
3008    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
3009    /// match the storage field's name; the accessor's identity maps onto
3010    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3011    /// docstring already carries.
3012    #[must_use]
3013    pub const fn max_failures(&self) -> u32 {
3014        self.max_failures
3015    }
3016
3017    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
3018    /// Envoy-outlier-detection rolling-observation-interval scalar
3019    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3020    /// breaker rolling-window duration keys off — returns the
3021    /// author-declared `:politicas :circuit-breaker :window` typed
3022    /// `Duration` verbatim, copied out of the typed slot's own
3023    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
3024    /// by value; no borrow of `&self` past the call). Non-optional (the
3025    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
3026    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
3027    /// `CircuitBreaker` past pattern-match is definitionally present,
3028    /// and its `:window` field carries the rolling-observation interval
3029    /// as a required-axis scalar).
3030    ///
3031    /// The `:politicas :circuit-breaker :window` axis carries the
3032    /// "consecutive-transient-failure rolling-observation interval"
3033    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3034    /// `Duration` accept-set (zero-floor rejected through
3035    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
3036    /// residue rejected through
3037    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
3038    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
3039    /// Envoy `outlier_detection.interval` per-cluster
3040    /// ejection-observation-interval scalar (equivalently the future
3041    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3042    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3043    /// consumer that reads the rolling-observation interval keys off
3044    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3045    /// integer-millisecond canonical-form + cap bracket at
3046    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
3047    /// [`crate::render::require_positive_canonical_bounded_duration`]
3048    /// helper, the future M4 per-Aplicacao Envoy config reconciler
3049    /// materialization pass, the future per-`:contratos`-edge
3050    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3051    /// acknowledges).
3052    ///
3053    /// Prior to this lift the `.window` field was accessed inline at
3054    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
3055    /// `require_positive_canonical_bounded_duration(cb.window, …)`
3056    /// call — one open-coded field-access that expressed no compile-
3057    /// time link back to the typed sub-struct axis. A future extension
3058    /// of the `:window` axis to a richer author surface — a
3059    /// per-`:contratos`-edge window override the operator pins through
3060    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
3061    /// #3 roadmap acknowledges, a per-cluster window-default overlay
3062    /// the M4 CR materializer resolves per-CR, a promotion of the plain
3063    /// `Duration` observation interval to a richer
3064    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
3065    /// once Envoy's `outlier_detection` block's peer axes come into
3066    /// scope, a per-Envoy-cluster minimum-request-volume gate before
3067    /// the window arms — would have had to be threaded through every
3068    /// open-coded copy in lockstep or the validate gate and the future
3069    /// M4 emit path would silently disagree on which observation
3070    /// interval a given [`CircuitBreaker`] resolves to (an author's
3071    /// `:window "60s"` would satisfy validate while the emit path
3072    /// silently read a drifted other value, or vice versa: a validated
3073    /// typed slot would land at the emit boundary as a breaker whose
3074    /// observation window is structurally so wide that no realistic
3075    /// failure-rate shape can trip it). Lifting the resolution to a
3076    /// typed method on the substrate primitive means every downstream
3077    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
3078    /// observation-window surface reaches for exactly one typed
3079    /// dispatch — the resolver's accept-set migrates as a unit on any
3080    /// future axis addition.
3081    ///
3082    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
3083    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
3084    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
3085    /// required-axis, extended onto the per-sub-struct required-`Duration`
3086    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
3087    /// axis. Same "one typed dispatch on the substrate primitive, thin
3088    /// projections at each consumer" discipline the peer
3089    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3090    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3091    /// [`Membro::versao_requirement`] (a40b0e3),
3092    /// [`Entrada::destination`] (6db982c) accessors carry on their
3093    /// respective per-mesh-slot-atom scalar-value axes, extended onto
3094    /// the per-sub-struct required-`Duration` axis. Named `window()` to
3095    /// match the storage field's name; the accessor's identity maps onto
3096    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3097    /// docstring already carries.
3098    #[must_use]
3099    pub const fn window(&self) -> Duration {
3100        self.window
3101    }
3102}
3103
3104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3105pub struct RateLimit {
3106    /// Requests per window.
3107    pub rate: u32,
3108    /// Window duration.
3109    pub window: Duration,
3110}
3111
3112impl RateLimit {
3113    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
3114    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
3115    /// every consumer of the Aplicacao's per-`:contratos`-edge
3116    /// rate-limit-bucket capacity keys off — returns the author-declared
3117    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
3118    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
3119    /// returns by value; no borrow of `&self` past the call). Non-optional
3120    /// (the surrounding `Option<RateLimit>` is the "slot present?"
3121    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
3122    /// `RateLimit` past pattern-match is definitionally present, and its
3123    /// `:rate` field carries the token-bucket capacity as a required-axis
3124    /// scalar).
3125    ///
3126    /// The `:politicas :rate-limit` `:rate` axis carries the
3127    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
3128    /// the typed slot's `u32` accept-set (zero-floor rejected through
3129    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
3130    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
3131    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
3132    /// token-bucket-capacity scalar (equivalently the future
3133    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3134    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3135    /// consumer that reads the token-bucket capacity keys off this
3136    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3137    /// cap bracket that gates on the canonical
3138    /// [`crate::render::require_positive_bounded_u32`] helper, the
3139    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3140    /// emits the `<n>/<s|m|h>` author surface, the future M4
3141    /// per-Aplicacao Envoy config reconciler materialization pass, the
3142    /// future per-`:contratos`-edge rate-limit-override overlay the
3143    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3144    ///
3145    /// Prior to this lift the `.rate` field was accessed inline at three
3146    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
3147    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
3148    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
3149    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
3150    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
3151    /// field-accesses that expressed no compile-time link back to the
3152    /// typed sub-struct axis. A future extension of the `:rate` axis
3153    /// to a richer author surface — a per-`:contratos`-edge rate
3154    /// override the operator pins through a future `:contratos :rate`
3155    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
3156    /// per-cluster rate-default overlay the M4 CR materializer resolves
3157    /// per-CR, a promotion of the plain `u32` token capacity to a
3158    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
3159    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3160    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
3161    /// before the token arms — would have had to be threaded through
3162    /// every open-coded copy in lockstep or the validate gate, the
3163    /// codec's render path, and the future M4 emit path would silently
3164    /// disagree on which token capacity a given [`RateLimit`] resolves
3165    /// to (an author's `:rate-limit "100/s"` would satisfy validate
3166    /// while the render / emit paths silently read a drifted other
3167    /// value, or vice versa: a validated typed slot would land at the
3168    /// emit boundary as a no-op limiter whose token capacity is
3169    /// structurally so high that no realistic per-edge traffic shape
3170    /// can drain it). Lifting the resolution to a typed method on the
3171    /// substrate primitive means every downstream consumer of the
3172    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
3173    /// reaches for exactly one typed dispatch — the resolver's
3174    /// accept-set migrates as a unit on any future axis addition.
3175    ///
3176    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
3177    /// in shape to the peer per-`CircuitBreaker`
3178    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
3179    /// on the peer per-sub-struct required-axis, extended onto the
3180    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
3181    /// required-axis scalar" projection pattern the sibling
3182    /// [`RateLimit::window`] future lift folds on. Same "one typed
3183    /// dispatch on the substrate primitive, thin projections at each
3184    /// consumer" discipline the peer [`WitContract::source`] /
3185    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
3186    /// (0804823), [`Membro::nome`] (4a32abf),
3187    /// [`Membro::versao_requirement`] (a40b0e3),
3188    /// [`Entrada::destination`] (6db982c),
3189    /// [`CircuitBreaker::max_failures`] (3a74062),
3190    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
3191    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
3192    /// to match the storage field's name; the accessor's identity maps
3193    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3194    /// docstring already carries.
3195    #[must_use]
3196    pub const fn rate(&self) -> u32 {
3197        self.rate
3198    }
3199
3200    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
3201    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
3202    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3203    /// rate-limit-bucket refill period keys off — returns the
3204    /// author-declared `:politicas :rate-limit` typed `Duration`
3205    /// verbatim, copied out of the typed slot's own `Duration` storage
3206    /// (`Duration` is `Copy`, so the accessor returns by value; no
3207    /// borrow of `&self` past the call). Non-optional (the surrounding
3208    /// `Option<RateLimit>` is the "slot present?" projection at the
3209    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
3210    /// pattern-match is definitionally present, and its `:window`
3211    /// field carries the token-bucket refill period as a required-axis
3212    /// scalar).
3213    ///
3214    /// The `:politicas :rate-limit` `:window` axis carries the
3215    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
3216    /// — the typed slot's `Duration` accept-set (constrained to the
3217    /// three canonical windows `{1s, 60s, 3600s}` the
3218    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
3219    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
3220    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
3221    /// per-cluster token-bucket-refill-period scalar (equivalently the
3222    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3223    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3224    /// consumer that reads the token-bucket refill period keys off
3225    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
3226    /// canonical-window gate that keys off
3227    /// [`is_canonical_rate_limit_window`], the
3228    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3229    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
3230    /// [`rate_limit_window_unit`] and non-canonical fallback via
3231    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
3232    /// reconciler materialization pass, the future per-`:contratos`-
3233    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
3234    /// roadmap acknowledges).
3235    ///
3236    /// Prior to this lift the `.window` field was accessed inline at
3237    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
3238    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
3239    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
3240    /// error-payload construction on refusal, and the two
3241    /// [`rate_limit_codec::render`] arms
3242    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
3243    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
3244    /// open-coded field-accesses that expressed no compile-time link
3245    /// back to the typed sub-struct axis. A future extension of the
3246    /// `:window` axis to a richer author surface — a per-`:contratos`-
3247    /// edge window override the operator pins through a future
3248    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
3249    /// acknowledges, a per-cluster window-default overlay the M4 CR
3250    /// materializer resolves per-CR, a promotion of the plain
3251    /// `Duration` refill period to a richer
3252    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
3253    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3254    /// axis comes into scope, an addition of a `"d"` day suffix once
3255    /// Envoy's `rate_limit_action` grows daily-bucket support — would
3256    /// have had to be threaded through every open-coded copy in
3257    /// lockstep or the validate gate, the codec's render path, and
3258    /// the future M4 emit path would silently disagree on which
3259    /// refill period a given [`RateLimit`] resolves to (an author's
3260    /// `:rate-limit "100/s"` would satisfy validate while the render
3261    /// / emit paths silently read a drifted other value, or vice
3262    /// versa: a validated typed slot would land at the emit boundary
3263    /// as a limiter whose refill period is structurally so long that
3264    /// no realistic per-edge traffic shape stays inside the token
3265    /// budget). Lifting the resolution to a typed method on the
3266    /// substrate primitive means every downstream consumer of the
3267    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
3268    /// reaches for exactly one typed dispatch — the resolver's
3269    /// accept-set migrates as a unit on any future axis addition.
3270    ///
3271    /// Second sub-struct scalar accessor on the `RateLimit` axis —
3272    /// sibling in shape to the just-landed [`RateLimit::rate`]
3273    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
3274    /// required-axis, extended onto the per-sub-struct
3275    /// required-`Duration` axis; closes the last unlifted
3276    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
3277    /// per-sub-struct accessor coverage is now complete across both
3278    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
3279    /// the substrate primitive, thin projections at each consumer"
3280    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
3281    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
3282    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
3283    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
3284    /// [`Membro::nome`] (4a32abf),
3285    /// [`Membro::versao_requirement`] (a40b0e3),
3286    /// [`Entrada::destination`] (6db982c) accessors carry on their
3287    /// respective per-mesh-slot-atom scalar-value axes. Named
3288    /// `window()` to match the storage field's name; the accessor's
3289    /// identity maps onto the canonical MESH-COMPOSITION §III.2
3290    /// vocabulary the slot's docstring already carries.
3291    #[must_use]
3292    pub const fn window(&self) -> Duration {
3293        self.window
3294    }
3295
3296    /// Recognize this rate-limit's `:window` as a canonical
3297    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
3298    /// exactly matches one of the three closed-set arm-Durations
3299    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
3300    /// non-canonical magnitude the codec's round-trip would break on
3301    /// (sub-second residue, or a second-magnitude outside the set
3302    /// [`RateLimitUnit::ALL`] enumerates).
3303    ///
3304    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
3305    /// returns `Some` here — the validate gate's
3306    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
3307    /// rejects every window this accessor returns `None` on. Downstream
3308    /// consumers past validate (the codec's [`rate_limit_codec::render`]
3309    /// path, the future M4 per-Aplicacao Envoy config reconciler's
3310    /// materialization pass, the future per-`:contratos`-edge rate-limit-
3311    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3312    /// acknowledges) that read the typed unit off a validated slot can
3313    /// pattern-match on the returned `Some` without re-checking
3314    /// canonicality at the consumer layer — the typed enum surface is
3315    /// the load-bearing carrier of the canonicality invariant.
3316    ///
3317    /// Preferred over the free [`is_canonical_rate_limit_window`]
3318    /// module-private helper at any call site that has the typed
3319    /// [`RateLimit`] in hand (the codec's `render` arm at
3320    /// [`rate_limit_codec::render`], the validate gate's canonical-form
3321    /// arm in [`AplicacaoSpec::validate_politicas`], any future
3322    /// per-`:contratos` edge-override overlay resolver): those consumers
3323    /// reach for the typed enum without going through the
3324    /// `.window()` scalar-projection layer, and get the enum value
3325    /// directly (which the codec's render arm can then format via
3326    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
3327    /// "typed sub-struct scalar accessor, one dispatch on the substrate
3328    /// primitive" discipline the sibling [`RateLimit::rate`] and
3329    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
3330    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
3331    /// projection axis (the third scalar accessor on the [`RateLimit`]
3332    /// axis, first typed-enum-return projection).
3333    ///
3334    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
3335    /// the canonical [`RateLimitUnit`] arm now carries the same
3336    /// `const`-eval-surface posture the sibling `pub const fn`
3337    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
3338    /// this typed sub-struct already carry, composing through the
3339    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
3340    /// reverse-resolver in `const` context. Any downstream substrate-
3341    /// side `const`-context consumer of the typed unit (a module-scope
3342    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
3343    /// invariant pin on a typed fixture, a future M4 admission-webhook
3344    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
3345    /// resolver over a typed [`RateLimit`], any future `const fn`
3346    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3347    /// the substrate primitive) now reaches the same typed dispatch on
3348    /// the substrate primitive at const-eval time as at runtime.
3349    ///
3350    /// Pinned load-bearing at the substrate-primitive level by
3351    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
3352    /// eval-surface pin via `const fn` wrapper).
3353    #[must_use]
3354    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
3355        RateLimitUnit::from_window(self.window)
3356    }
3357}
3358
3359/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
3360/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
3361/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
3362///
3363/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
3364/// the `:politicas :rate-limit` unit surface reads from
3365/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
3366/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
3367/// [`is_canonical_rate_limit_window`] predicate the
3368/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
3369/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
3370/// projection) now lives inside this typed enum's `match self` arms — a
3371/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
3372/// `rate_limit_action` grows daily-bucket support) is one new variant
3373/// plus the exhaustiveness arms on the four methods, so every consumer
3374/// picks it up by compile-time construction rather than a runtime
3375/// table-scan miss.
3376///
3377/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
3378/// scanned via `find_map` at every projection call — an untyped runtime
3379/// walk that carried no compile-time link between the parse arm's
3380/// accepted suffixes, the render arm's emitted suffixes, and the
3381/// validate gate's accepted windows. A future rate-limit-unit addition
3382/// that landed one row without threading through the other consumers
3383/// (or a copy-paste flip that collapsed two rows onto one suffix) would
3384/// silently split the accepted-set across the three consumers — the
3385/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
3386/// for a 24h window that parse can't round-trip, the validate gate
3387/// misses one canonical window. Lifting the pairs onto a typed
3388/// closed-set enum with exhaustive `match` arms makes any such
3389/// half-landed extension a caixa-core build error (the compiler enforces
3390/// arm coverage on every method), not a silent per-consumer drift
3391/// surfacing at apply time. Same "closed-set typed-enum discriminator"
3392/// discipline the sibling [`PlacementStrategy`] (cc8f749),
3393/// [`crate::supervisor::RestartStrategy`],
3394/// [`crate::supervisor::RestartPolicy`],
3395/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
3396/// closed-set typed enums carry on their respective closed-set axes —
3397/// extended onto the seventh closed-set typed-enum discriminator axis
3398/// on the caixa typed surface (the `:politicas :rate-limit :window`
3399/// canonical-unit axis).
3400#[derive(
3401    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3402)]
3403pub enum RateLimitUnit {
3404    /// 1-second window — canonical author-surface suffix `"s"`
3405    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3406    /// with a 1s magnitude.
3407    Second,
3408    /// 1-minute window — canonical author-surface suffix `"m"`
3409    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3410    /// with a 60s magnitude.
3411    Minute,
3412    /// 1-hour window — canonical author-surface suffix `"h"`
3413    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3414    /// with a 3600s magnitude.
3415    Hour,
3416}
3417
3418impl RateLimitUnit {
3419    /// Exhaustive iteration surface for every consumer that reads the
3420    /// full canonical-unit set (the byte-parity witness against the
3421    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
3422    /// webhook's accepted-suffix listing in its rejection body, any
3423    /// future round-trip fuzz harness). A future variant addition to
3424    /// [`RateLimitUnit`] extends this slice as a single edit and every
3425    /// consumer picks up the new entry by construction — the compiler-
3426    /// checked exhaustiveness on the sibling method `match` arms is the
3427    /// build-time guarantee that no arm forgets to grow.
3428    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
3429
3430    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
3431    /// string every `<n>/<unit>` rate-limit shape carries after its
3432    /// `/` separator. The single source of truth the codec's parse and
3433    /// render arms both dispatch on: the parse arm matches an incoming
3434    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
3435    /// output; the render arm emits the entry's `as_suffix` verbatim
3436    /// after the rate magnitude.
3437    #[must_use]
3438    pub const fn as_suffix(self) -> &'static str {
3439        match self {
3440            Self::Second => "s",
3441            Self::Minute => "m",
3442            Self::Hour => "h",
3443        }
3444    }
3445
3446    /// Canonical `Duration` for this unit — the token-bucket refill
3447    /// period the [`RateLimit::window`] axis carries when the surrounding
3448    /// slot's `:rate-limit` author surface named this unit.
3449    #[must_use]
3450    pub const fn window(self) -> Duration {
3451        Duration::from_secs(match self {
3452            Self::Second => 1,
3453            Self::Minute => 60,
3454            Self::Hour => 3_600,
3455        })
3456    }
3457
3458    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
3459    /// `None` when `suffix` is outside the closed-set arm-string set
3460    /// [`Self::as_suffix`] emits. The single `str → Self` projection
3461    /// [`rate_limit_codec::parse`] consumes.
3462    #[must_use]
3463    pub fn from_suffix(suffix: &str) -> Option<Self> {
3464        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
3465    }
3466
3467    /// Recognize a canonical rate-limit `Duration` as one of the three
3468    /// arms, or `None` when `window` carries sub-second residue or a
3469    /// second-magnitude outside the closed-set arm-window set
3470    /// [`Self::window`] emits. The single `Duration → Self` projection
3471    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
3472    /// both consume.
3473    ///
3474    /// `pub const fn` — the reverse `Duration → Self` projection now
3475    /// carries the same `const`-eval-surface posture the sibling
3476    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
3477    /// projection accessors on this closed-set typed enum already
3478    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
3479    /// typed-`RateLimit`-projection sibling composes through in `const`
3480    /// context. Routes byte-for-byte through the peer `pub const fn`
3481    /// [`Self::window`] canonical-`Duration` projection so any future
3482    /// arm-magnitude edit on the sibling accessor reaches this reverse
3483    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
3484    /// per-arm probes each dispatch through one `pub const fn` on the
3485    /// substrate primitive rather than a hand-authored per-arm second-
3486    /// magnitude literal that would silently drift on any future
3487    /// [`Self::window`] arm-magnitude edit.
3488    ///
3489    /// Prior to the `const` lift the body dispatched through
3490    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
3491    /// iterator-driven linear scan whose iterator methods
3492    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
3493    /// `PartialEq` dispatch each carry non-`const` bounds on stable
3494    /// Rust 1.94, so any downstream substrate-side `const`-context
3495    /// consumer of the reverse resolver (a module-scope
3496    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
3497    /// invariant pin on a typed fixture, a future M4
3498    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
3499    /// webhook `const fn` per-`:politicas` canonical-window floor over a
3500    /// typed [`RateLimit`] scalar, any future `const fn`
3501    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3502    /// the substrate primitive that wants to fan on the canonical unit
3503    /// at compile time) surfaced as a downstream E0015 far from the
3504    /// resolver's own declaration. The `pub const fn` posture closes
3505    /// the drift structurally at caixa-core build time.
3506    ///
3507    /// Pinned load-bearing at the substrate-primitive level by
3508    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
3509    /// eval-surface pin via `const fn` wrapper) and
3510    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
3511    /// (composition-witness pin against the peer `Self::window` scalar
3512    /// dispatch).
3513    #[must_use]
3514    pub const fn from_window(window: Duration) -> Option<Self> {
3515        if window.subsec_nanos() != 0 {
3516            return None;
3517        }
3518        // Route through the peer `pub const fn` [`Self::window`]
3519        // canonical-`Duration` projection so any future arm-magnitude
3520        // edit on the sibling accessor reaches this reverse resolver by
3521        // construction — the per-arm `secs` comparison keys off
3522        // `Duration::as_secs` (`pub const fn`), not a hand-authored
3523        // per-arm second-magnitude literal that would silently drift.
3524        let secs = window.as_secs();
3525        if secs == Self::Second.window().as_secs() {
3526            Some(Self::Second)
3527        } else if secs == Self::Minute.window().as_secs() {
3528            Some(Self::Minute)
3529        } else if secs == Self::Hour.window().as_secs() {
3530            Some(Self::Hour)
3531        } else {
3532            None
3533        }
3534    }
3535
3536    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
3537    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
3538    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
3539    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
3540    /// consumes.
3541    ///
3542    /// The peer `Duration → &'static str` axis folded onto the substrate
3543    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
3544    /// production consumers ([`rate_limit_codec::render`] and
3545    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
3546    /// migrated (61421a6): the free helper's `Duration → &str` projection
3547    /// is now the two-step composition
3548    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
3549    /// reads through the typed accessor. This lift closes the peer
3550    /// `&str → Duration` axis by folding the vestigial module-private
3551    /// `rate_limit_window_from_unit` delegate onto this associated method
3552    /// — the codec's parse arm and every future wire-side consumer of the
3553    /// `&str → Duration` projection (a future admission-webhook that
3554    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
3555    /// before it's promoted to a validated typed slot, a future
3556    /// `feira lint` shape-probe that reads the author-surface bytes
3557    /// verbatim) now reach for exactly one typed dispatch on the
3558    /// substrate primitive.
3559    ///
3560    /// Same "closed-set typed-enum discriminator with canonical
3561    /// projections per axis" discipline the sibling [`Self::as_suffix`]
3562    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
3563    /// methods carry — this associated method closes the fifth (and last
3564    /// unlifted) projection axis on the arm-table, so the closed-set enum
3565    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
3566    /// consumer of the `:politicas :rate-limit :window` axis reaches
3567    /// through. A future rate-limit-unit addition (a `"d"` day suffix
3568    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
3569    /// `"ms"` sub-second window once high-throughput per-edge policies
3570    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
3571    /// variant plus one arm per method — the compiler enforces
3572    /// exhaustiveness on every consumer's `match self` arms and picks
3573    /// the new unit up by construction across all five projections.
3574    #[must_use]
3575    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
3576        Self::from_suffix(suffix).map(Self::window)
3577    }
3578}
3579
3580/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
3581/// every consumer that formats a canonical rate-limit unit as user-
3582/// facing text (future M4 admission-webhook rejection bodies naming
3583/// the accepted-suffix set, future `feira app graph` per-`:politicas`
3584/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
3585/// codec's parse arm accepts and the render arm emits. Same
3586/// as_str-through-Display convergence discipline the sibling
3587/// [`PlacementStrategy`], [`crate::CaixaKind`],
3588/// [`crate::supervisor::RestartStrategy`], and
3589/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
3590impl std::fmt::Display for RateLimitUnit {
3591    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3592        f.write_str(self.as_suffix())
3593    }
3594}
3595
3596/// Upper-bound ceiling on the `:politicas :timeout` axis — every
3597/// validated [`MeshPolicy::timeout`] past
3598/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
3599/// (inclusive on both ends, integer-millisecond magnitudes by the
3600/// canonical-form gate immediately preceding).
3601///
3602/// The typed field is `Option<Duration>` (the zero-floor arm
3603/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
3604/// `Duration::ZERO`, and the canonical-form arm
3605/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
3606/// sub-millisecond residue), so a programmatic struct literal
3607/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
3608/// 24h) and the equivalent author-surface form
3609/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
3610/// integer-hour magnitude) both round-trip cleanly through serde — a
3611/// structurally unbounded `Duration` ceiling. A `:timeout` value far
3612/// above the documented production-playbook band (Envoy default `15s`,
3613/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
3614/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
3615/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
3616/// at `~3600s`) silently degenerates the mesh-policy contract: the
3617/// per-call deadline is structurally so long that no realistic
3618/// synchronous-`:contratos` traversal can reach it, so the typed slot
3619/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
3620/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
3621/// blocking" degenerates to a nominal-only contract on the
3622/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
3623/// the sibling `:politicas :retries` axis and the
3624/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
3625/// `:politicas :circuit-breaker :max-failures` axis — all three close
3626/// the "structurally unbounded ceiling on a typed `:politicas` axis"
3627/// footgun the prior zero-floor-and-canonical-form-only checks left
3628/// open.
3629///
3630/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3631/// shared duration codec emits (`"<n>h"` for any integer-hour
3632/// magnitude) — every value in the canonical authoring form's
3633/// `<integer><unit>` grammar at or below this cap renders to a clean
3634/// canonical string. The cap sits an order of magnitude above every
3635/// documented production-playbook recommendation band (Envoy default
3636/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
3637/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
3638/// configured maximum (`proxy_read_timeout` typical max `3600s`),
3639/// below the clearly-pathological "effectively no timeout" floor
3640/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
3641/// want for a long-running synchronous workflow, but a hard wall above
3642/// which the mesh-level deadline is structurally a non-deadline.
3643/// Lifted as a typed `pub const` so the bound has exactly one source
3644/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3645/// materializer's admission webhook and the caixa-mesh-side
3646/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3647/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3648/// other typed upper bound in this crate carries
3649/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3650/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3651/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3652/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3653pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
3654
3655/// Upper-bound ceiling on the `:politicas :retries` axis — every
3656/// validated [`MeshPolicy::retries`] past
3657/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
3658///
3659/// The typed slot is `Option<u32>` (`None` = no retries on transient
3660/// failure; `Some(0)` already rejected by the
3661/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
3662/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
3663/// .. }`) and the equivalent author-surface form
3664/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
3665/// serde / the codec — a structurally unbounded `u32` ceiling. The
3666/// runtime substrate that consumes the value (Envoy's
3667/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3668/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3669/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3670/// admission cap is 10) translates a four-billion-retry policy into a
3671/// thundering-herd amplification vector on transient failure — the
3672/// caller's one request fans out to `retries` server-side calls per
3673/// edge per traversal, multiplying load by `(retries+1)^depth` across
3674/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3675/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3676/// invariant on the retry axis; both belong at the typed-slot layer.
3677///
3678/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3679/// upstream mesh-policy schema that documents one) and sits above the
3680/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3681/// every documented production playbook): a value the author can
3682/// plausibly want, but a hard wall above which the policy is
3683/// structurally a footgun. Lifted as a typed `pub const` so the bound
3684/// has exactly one source of truth — a future axis reaching for the
3685/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3686/// materializer's admission webhook, the caixa-mesh-side
3687/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3688/// one place. Same shape every other typed upper bound in this crate
3689/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3690/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3691/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3692/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3693pub const POLICY_RETRIES_MAX: u32 = 10;
3694
3695/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3696/// axis — every validated [`CircuitBreaker::max_failures`] past
3697/// [`AplicacaoSpec::validate_politicas`] lies in
3698/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3699///
3700/// The typed field is `u32` (the zero-floor arm
3701/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3702/// `0` — a breaker that trips on the first call), so a programmatic
3703/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3704/// and the equivalent author-surface form
3705/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3706/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3707/// `max_failures` value far above the documented production-playbook
3708/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3709/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3710/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3711/// typical 5–50) silently disables the breaker's protection role:
3712/// the threshold is structurally so high that no realistic
3713/// failures-per-`:window` traffic shape can reach it, so the breaker
3714/// never trips and the typed slot becomes a no-op carried on every
3715/// emitted Envoy / Cilium L7 overlay. Pairs with the
3716/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3717/// axis — both close the "structurally unbounded `u32` ceiling on a
3718/// typed policy axis" footgun the prior zero-floor-only checks left
3719/// open.
3720///
3721/// The `1000` ceiling sits an order of magnitude above every
3722/// documented upstream production-playbook recommendation band (the
3723/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3724/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3725/// the clearly-pathological "effectively no protection"
3726/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3727/// plausibly want at hyperscale, but a hard wall above which the
3728/// policy is structurally a no-op. Lifted as a typed `pub const` so
3729/// the bound has exactly one source of truth — the future M4
3730/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3731/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3732/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3733/// one place. Same shape every other typed upper bound in this crate
3734/// carries ([`POLICY_RETRIES_MAX`],
3735/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3736/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3737/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3738pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3739
3740/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3741/// every validated [`CircuitBreaker::window`] past
3742/// [`AplicacaoSpec::validate_politicas`] lies in
3743/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3744/// integer-millisecond magnitudes by the canonical-form gate
3745/// immediately preceding).
3746///
3747/// The typed field is `Duration` (the zero-floor arm
3748/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3749/// `Duration::ZERO`, and the canonical-form arm
3750/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3751/// sub-millisecond residue), so a programmatic struct literal
3752/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3753/// and the equivalent author-surface form
3754/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3755/// integer-hour magnitude) both round-trip cleanly through serde — a
3756/// structurally unbounded `Duration` ceiling. A `:window` value far
3757/// above the documented production-playbook band (Hystrix
3758/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3759/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3760/// Istio `outlierDetection.interval` default `10s`, Envoy
3761/// `outlier_detection.interval` default `10s`, AWS App Mesh
3762/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3763/// breaker's role: a rolling-window failure counter whose window is
3764/// hours long is operationally a lifetime counter, the breaker's
3765/// "recent failures" memory is structurally so long that transient
3766/// failures are never forgotten, and the typed slot becomes a no-op
3767/// trigger that trips once and stays tripped for the lifetime of the
3768/// component carried on every emitted Envoy / Cilium L7 overlay.
3769///
3770/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3771/// shared duration codec emits (`"<n>h"` for any integer-hour
3772/// magnitude) — every value in the canonical authoring form's
3773/// `<integer><unit>` grammar at or below this cap renders to a clean
3774/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3775/// cap on the first typed-`Duration` `:politicas` axis: the two
3776/// duration-typed `:politicas` axes now share a single uniform top
3777/// edge so the next typed-slot wiring (the future caixa-mesh
3778/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3779/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3780/// admission webhook) reaches for either field knowing the value is
3781/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3782/// sits two orders of magnitude above every documented upstream
3783/// production-playbook recommendation band (Hystrix / resilience4j /
3784/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3785/// and below the clearly-pathological "rolling window degenerates to
3786/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3787/// author can plausibly want for a very-low-traffic long-tail
3788/// failure-detection window, but a hard wall above which the breaker's
3789/// rolling-window contract is structurally a lifetime-counter contract.
3790/// Lifted as a typed `pub const` so the bound has exactly one source
3791/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3792/// materializer's admission webhook and the caixa-mesh-side
3793/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3794/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3795/// other typed upper bound in this crate carries
3796/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3797/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3798/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3799/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3800/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3801pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3802
3803/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3804/// every validated [`RateLimit::rate`] past
3805/// [`AplicacaoSpec::validate_politicas`] lies in
3806/// `1..=POLICY_RATE_LIMIT_MAX`.
3807///
3808/// The typed field is `u32` (the zero-floor arm
3809/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3810/// zero-rate limit denies every request, the canonical "I forgot
3811/// that 0 means deny-everything" footgun), so a programmatic struct
3812/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3813/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3814/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3815/// round-trip cleanly through serde — a structurally unbounded `u32`
3816/// ceiling. The runtime substrate consuming the value (Envoy's
3817/// `local_rate_limit.token_bucket.max_tokens`, the future
3818/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3819/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3820/// rate-limit into a no-op rate-limiter: the bucket capacity is
3821/// structurally so high no realistic per-edge traffic shape can
3822/// drain it, the limiter never trips, and the typed slot becomes a
3823/// "rate-limit declared, no enforcement" footgun — the canonical
3824/// declared-but-inert shape every other `:politicas` cap arm
3825/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3826/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3827///
3828/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3829/// above every documented upstream production-playbook recommendation
3830/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3831/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3832/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3833/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3834/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3835/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3836/// `u32::MAX`): a value the author can plausibly want at hyperscale
3837/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3838/// /h-window arm), but a hard wall above which the policy is
3839/// structurally a no-op carried verbatim on every emitted Envoy /
3840/// Cilium L7 overlay. The cap brackets all three canonical windows
3841/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3842/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3843/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3844/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3845/// has exactly one source of truth — the future M4
3846/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3847/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3848/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3849/// one place. Same shape every other typed upper bound in this crate
3850/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3851/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3852/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3853/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3854/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3855/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3856pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3857
3858// `:entrada :host` total-length and per-label cap axes route through
3859// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3860// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3861// pair of aplicacao-private aliases the previous `validate_entrada_host`
3862// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3863// = 63`) were structurally the same K8s Gateway API v1 Hostname
3864// admission-schema bounds — the total-length cap on the OpenAPI
3865// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3866// same regex — that the peer axes at the caixa-core::render level pin,
3867// so hoisting both readers onto the shared lifted constants closes the
3868// third-occurrence duplication threshold structurally: the M4
3869// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3870// label validator, the future per-`Certificate` SAN emitter, and every
3871// other per-Gateway-API-Hostname landing site reach the same one place
3872// as the `:entrada :host` gate does — no per-axis alias drift surface
3873// between them, by construction.
3874
3875/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
3876/// extractor expression — the upper bound `validate_placement_shard_key`
3877/// enforces on every well-shaped shard-key past validate. The realistic
3878/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3879/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3880/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3881/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3882/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3883/// in `:shard-key`" footgun at validate time rather than at the future
3884/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3885const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3886
3887/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3888/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3889/// that maps the shared parser-shaped reason into the
3890/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3891/// is self-locating (the offending `caixa:` is named verbatim) and
3892/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3893/// fix it in one edit. Same diagnostic shape as
3894/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3895/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3896fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3897    // Empty is already gated by `MembroCaixaEmpty` at the call site;
3898    // re-checking here keeps the predicate usable from any future
3899    // call site (the M4 CR materializer) without an empty-check
3900    // footgun. The shared
3901    // [`crate::render::require_valid_dns_1123_label`] helper brackets
3902    // the empty-first + shape cascade every peer name axis
3903    // (`:placement :clusters`, `:placement :affinity`, `:contratos
3904    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3905    // `:upgrade-from :module`) routes through, so drift between the
3906    // eight axes' accepted DNS-1123-label sets is structurally
3907    // impossible.
3908    crate::render::require_valid_dns_1123_label(
3909        caixa,
3910        || AplicacaoError::MembroCaixaEmpty,
3911        |reason| AplicacaoError::MembroCaixaInvalid {
3912            caixa: caixa.to_string(),
3913            reason,
3914        },
3915    )
3916}
3917
3918/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3919/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3920/// that maps the shared parser-shaped reason into the
3921/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3922///
3923/// Cluster names land in DNS-1123-label territory across every consumer:
3924/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3925/// the `lareira-fleet-programs` aggregator applies to scope programs to
3926/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3927/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3928/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3929/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3930/// side schema enforces the DNS-1123 label rule on admission; a
3931/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3932/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3933/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3934/// only gate and the failure surfaces as a no-match at filter time —
3935/// the workload doesn't land in the named cluster, with no diagnostic
3936/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3937/// build time mirrors the `:membros :caixa` value-shape trajectory
3938/// (3f9d7a0) on the peer name axis.
3939///
3940/// The diagnostic carries the offending `cluster:` verbatim plus a
3941/// parser-shaped `reason:` naming the specific violation, so the
3942/// author can grep their caixa.lisp for `:clusters` and fix it in
3943/// one edit. Same diagnostic shape as
3944/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3945fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3946    // Empty is already gated by `PlacementClusterEmpty` at the call
3947    // site; re-checking here keeps the predicate usable from any
3948    // future call site (the M4 CR materializer's per-cluster validator)
3949    // without an empty-check footgun. Routes through the shared
3950    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3951    // name axes each land on.
3952    crate::render::require_valid_dns_1123_label(
3953        cluster,
3954        || AplicacaoError::PlacementClusterEmpty,
3955        |reason| AplicacaoError::PlacementClusterInvalid {
3956            cluster: cluster.to_string(),
3957            reason,
3958        },
3959    )
3960}
3961
3962/// Reject `:placement :affinity` hints whose shape can never legitimately
3963/// land in any downstream selector or label-keyed routing axis. Thin
3964/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3965/// shared parser-shaped reason into the
3966/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3967/// diagnostic is self-locating (the offending `:affinity` is named
3968/// verbatim) and the author can grep their caixa.lisp for
3969/// `:affinity "<hint>"` and fix it in one edit.
3970///
3971/// The `:affinity` slot carries a placement-engine hint — canonical
3972/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3973/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3974/// compression overlay and the future M4 placement-engine's per-hint
3975/// routing axis. Each downstream consumer (caixa-mesh's
3976/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3977/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3978/// `spec.placement.affinity` admission rule, the future M4 per-hint
3979/// node-affinity / pod-affinity rule generator keying off the same
3980/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3981/// selector) requires the value to be a DNS-1123 label — K8s label
3982/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3983/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3984/// admission rule the apiserver enforces.
3985///
3986/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3987/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3988/// Python-module-name leak), `:affinity "data.locality"` (the
3989/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3990/// `:affinity "data-locality-"` (boundary-hyphen violation),
3991/// `:affinity "data locality"` (paste-from-doc whitespace),
3992/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3993/// 64-byte over-cap slug silently passed the empty-only check and the
3994/// failure surfaced as a no-match at the M3 Adaptive compression
3995/// overlay's filter time (`placement.affinity` carried a malformed
3996/// value, no node matched, the workload landed on the default
3997/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3998/// the empty-:affinity / empty-shard-key / zero-:politicas /
3999/// empty-:contratos-target gates already close on every other
4000/// declare-but-no-opinion axis. Lifting the rejection to a build-time
4001/// gate closes the fifth typed slot on the Aplicacao surface to land
4002/// on the canonical DNS-1123 label floor (after the four Servico-name
4003/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
4004/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
4005/// b0e8748).
4006///
4007/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
4008/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
4009/// validated values are guaranteed-accepted by the apiserver without
4010/// re-validation at any downstream renderer or admission layer.
4011fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
4012    // Empty is gated separately at the call site for a self-locating
4013    // diagnostic; re-checking here keeps the predicate usable from any
4014    // future call site (the M4 CR materializer's per-affinity
4015    // validator) without an empty-check footgun. Routes through the
4016    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4017    // peer name axes each land on.
4018    crate::render::require_valid_dns_1123_label(
4019        affinity,
4020        || AplicacaoError::PlacementAffinityEmpty,
4021        |reason| AplicacaoError::PlacementAffinityInvalid {
4022            affinity: affinity.to_string(),
4023            reason,
4024        },
4025    )
4026}
4027
4028/// Reject `:placement :shard-key` extractor expressions whose shape can
4029/// never legitimately drive the future M4 Akka-style cluster-sharding
4030/// reconciler's hash-extractor pass. Maps the per-byte / length checks
4031/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
4032/// diagnostic is self-locating (the offending `:shard-key` value is
4033/// named verbatim alongside the parser-shaped reason) and the author can
4034/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
4035/// edit.
4036///
4037/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
4038/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
4039/// expression naming the message property to hash on. The realistic
4040/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
4041/// property name; `$tenantId` — Akka entity-id placeholder;
4042/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
4043/// `${tenant}` — interpolation-style template) all sit in the printable
4044/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
4045/// multi-line blob landing in `:shard-key`, an embedded space from a
4046/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
4047/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
4048/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
4049/// check and the failure surfaces at the future M4 reconciler's hash
4050/// pass as a runtime extractor-evaluation error far from the source
4051/// `caixa.lisp`, with no field naming which member's `:shard-key`
4052/// carried the offending value.
4053///
4054/// The contract — the printable ASCII single-token intersection-floor
4055/// every Akka-style entity-id extractor implementation admits:
4056///
4057///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
4058///     peer DNS-1123-label-shaped `:placement :affinity` /
4059///     `:placement :clusters` identifier axes; realistic shard-keys sit
4060///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
4061///     blob footguns at validate time;
4062///   - every byte in the printable ASCII range `0x21..=0x7E` —
4063///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
4064///     `"$tenantId\n"` from paste-from-aligned-doc /
4065///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
4066///     `\x7F` — the canonical "embedded null from a copy-paste-binary
4067///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
4068///     un-Punycode-encoded IDN that round-trips inconsistently across
4069///     NFC/NFD normalization).
4070///
4071/// The accepted set is broader than the DNS-1123 label floor the peer
4072/// `:placement :clusters` / `:placement :affinity` axes use because the
4073/// `:shard-key` value is not a K8s `metadata.name` / label-selector
4074/// landing site; it's an extractor expression the future Akka-style
4075/// reconciler reads as a property reference. The realistic forms
4076/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
4077/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
4078/// but every Akka-style entity-id extractor parses. The
4079/// printable-ASCII-token floor accepts every shape any such extractor
4080/// would accept while rejecting the cross-implementation footguns
4081/// (whitespace breaks token boundaries; non-ASCII round-trips
4082/// inconsistently across YAML emitters and NFC/NFD normalization;
4083/// control characters silently corrupt the next read).
4084///
4085/// Until this gate landed `validate_placement` only refused the
4086/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
4087/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
4088/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
4089/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
4090/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
4091/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
4092/// control character from paste-from-binary, the 64-byte over-cap
4093/// paste-from-doc multi-line slug) silently passed validate. The future
4094/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
4095/// would then surface the malformed value either as a runtime
4096/// extractor-evaluation error (whitespace breaks the extractor's token
4097/// boundary, no match) or as a silently-different shard assignment
4098/// across YAML emitters (non-ASCII normalizes differently between the
4099/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
4100/// parser, the same entity ID maps to two distinct shards on a
4101/// re-render). Lifting the shape gate to caixa-build time makes the
4102/// extractor-floor invariant a structural property of every validated
4103/// `Placement`: every `Sharded` placement past `validate_placement` has
4104/// a `:shard-key` the future M4 reconciler can hash without
4105/// re-validating at the runtime layer.
4106///
4107/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
4108/// [`AplicacaoError::ContratoSubjectInvalid`] /
4109/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
4110/// on the peer `:contratos` payload axes — each lifts the
4111/// runtime-side parser's intersection-floor to a caixa-build-time gate,
4112/// closing the canonical "this passed validate but the runtime parser
4113/// rejected it" surprise.
4114fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
4115    // Empty is gated separately at the call site via the more
4116    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
4117    // re-checking here keeps the predicate usable from any future call
4118    // site (the M4 CR materializer's per-shard-key validator) without
4119    // an empty-check footgun.
4120    if key.is_empty() {
4121        return Err(AplicacaoError::ShardedKeyEmpty);
4122    }
4123    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
4124        return Err(AplicacaoError::ShardKeyInvalid {
4125            shard_key: key.to_string(),
4126            reason: format!(
4127                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
4128                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
4129                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
4130                 well under 32 bytes, this length suggests a paste-from-doc \
4131                 multi-line blob landed in `:shard-key` instead of a single-token \
4132                 extractor expression)",
4133                key.len()
4134            ),
4135        });
4136    }
4137    for &b in key.as_bytes() {
4138        if (0x21..=0x7E).contains(&b) {
4139            continue;
4140        }
4141        let reason = if b == b' ' {
4142            "contains a space (Akka-style entity-id extractor expressions are \
4143             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
4144             whitespace breaks the extractor's token boundary at the runtime layer, \
4145             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
4146             a multi-token blob in one `:shard-key` slot)"
4147                .to_string()
4148        } else if b == b'\t' {
4149            "contains a tab character (paste-from-aligned-doc footgun; the \
4150             Akka-style entity-id extractor reads `:shard-key` as a single-token \
4151             reference, embedded whitespace breaks the token boundary at the \
4152             runtime hash-extractor pass)"
4153                .to_string()
4154        } else if b == b'\n' || b == b'\r' {
4155            format!(
4156                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
4157                 paste-from-multiline-doc footgun; the Akka-style entity-id \
4158                 extractor reads `:shard-key` as a single-token reference, embedded \
4159                 newlines either truncate the value at the YAML emitter layer or \
4160                 break the token boundary at the runtime hash-extractor pass)"
4161            )
4162        } else if b < 0x20 || b == 0x7F {
4163            format!(
4164                "contains control character 0x{b:02x} (the canonical \
4165                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
4166                 control characters silently corrupt round-trip serialization \
4167                 across YAML emitters and break the runtime hash-extractor's \
4168                 single-token parser)"
4169            )
4170        } else {
4171            format!(
4172                "contains non-ASCII byte 0x{b:02x} (the canonical \
4173                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
4174                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
4175                 across YAML emitter implementations — the same entity ID can \
4176                 silently map to two distinct shards on a re-render. Use a \
4177                 printable-ASCII extractor expression like `tenantId`, \
4178                 `$tenantId`, or `metadata.tenantId`)"
4179            )
4180        };
4181        return Err(AplicacaoError::ShardKeyInvalid {
4182            shard_key: key.to_string(),
4183            reason,
4184        });
4185    }
4186    Ok(())
4187}
4188
4189/// Reject `:contratos :de` / `:contratos :para` values whose shape
4190/// can never legitimately match a validated `:membros :caixa`. Thin
4191/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4192/// shared parser-shaped reason into the
4193/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
4194/// diagnostic is self-locating (which slot — `:de` or `:para` — and
4195/// the offending value verbatim) and the author can grep their
4196/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
4197/// one edit.
4198///
4199/// Until this gate landed an empty or DNS-1123-malformed `:de` /
4200/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
4201/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
4202/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
4203/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
4204/// un-Punycode-encoded IDN) silently passed the per-axis check and
4205/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
4206/// membership lookup — diagnostic-framed as "this caixa is not in
4207/// `:membros`" when the root cause is "this `:de` value is not a
4208/// well-shaped Servico-name identifier and could never legitimately
4209/// match any validated member". Because every `:membros :caixa` is
4210/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
4211/// `names` HashSet structurally never contains an empty / malformed
4212/// string, so the membership lookup arm misframes every empty /
4213/// malformed input. Lifting the shape arm ahead of the lookup
4214/// preserves the legitimate `ContratoMemberMissing` arm (a
4215/// well-shaped `:de` that simply isn't in `:membros` — a phantom
4216/// reference) while routing every structurally-impossible-to-match
4217/// input through the narrower self-locating shape diagnostic.
4218///
4219/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4220/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
4221/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
4222/// to land on the canonical [`crate::render::is_dns_1123_label`]
4223/// floor. The `slot: &'static str` field carries the kebab-case
4224/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
4225/// per-callback-slot diagnostic shape and the
4226/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
4227/// (85f102c) cross-list-tag pattern.
4228fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
4229    // Routes through the shared
4230    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4231    // name axes each land on. The `slot: &'static str` field flows
4232    // through both error variants so the diagnostic names which
4233    // per-edge axis (`:de` vs `:para`) the offending value came from.
4234    crate::render::require_valid_dns_1123_label(
4235        caixa,
4236        || AplicacaoError::ContratoCaixaEmpty { slot },
4237        |reason| AplicacaoError::ContratoCaixaInvalid {
4238            slot,
4239            caixa: caixa.to_string(),
4240            reason,
4241        },
4242    )
4243}
4244
4245/// Reject `:entrada :para` values whose shape can never legitimately
4246/// match a validated `:membros :caixa`. Thin wrapper around
4247/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
4248/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
4249/// variant, so the diagnostic is self-locating (the offending
4250/// `:entrada :para` value is named verbatim) and the author can grep
4251/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
4252///
4253/// Until this gate landed an empty or DNS-1123-malformed `:entrada
4254/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
4255/// ADR typo, `:para "my_cart"` the Python-module-name leak,
4256/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
4257/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
4258/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
4259/// silently passed the per-axis check and surfaced as
4260/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
4261/// — diagnostic-framed as "this caixa is not in `:membros`" when the
4262/// root cause is "this `:entrada :para` value is not a well-shaped
4263/// Servico-name identifier and could never legitimately match any
4264/// validated member". Because every `:membros :caixa` is shape-
4265/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
4266/// `HashSet` structurally never contains an empty / malformed string,
4267/// so the membership lookup arm misframes every empty / malformed
4268/// input. Lifting the shape arm ahead of the lookup preserves the
4269/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
4270/// simply isn't in `:membros` — a phantom reference) while routing
4271/// every structurally-impossible-to-match input through the narrower
4272/// self-locating shape diagnostic.
4273///
4274/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4275/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
4276/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
4277/// fourth and last Aplicacao-level Servico-name reference axis to
4278/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
4279/// No `slot: &'static str` field because there is only one axis
4280/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
4281/// the simpler shape mirrors [`validate_membro_caixa`] and
4282/// [`validate_placement_cluster`].
4283fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
4284    // Empty is gated separately at the call site for a self-locating
4285    // diagnostic; re-checking here keeps the predicate usable from any
4286    // future call site (the M4 CR materializer's per-`:entrada`
4287    // validator) without an empty-check footgun. Routes through the
4288    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4289    // peer name axes each land on.
4290    crate::render::require_valid_dns_1123_label(
4291        para,
4292        || AplicacaoError::EntradaParaEmpty,
4293        |reason| AplicacaoError::EntradaParaInvalid {
4294            para: para.to_string(),
4295            reason,
4296        },
4297    )
4298}
4299
4300/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
4301/// would refuse at admission time. The contract — exactly the regex
4302/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
4303/// and `HTTPRoute.spec.hostnames[]`,
4304/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
4305/// (max length 253; per-label max length 63):
4306///
4307///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
4308///     uppercase, no underscore, no Unicode/IDN — IDN must be
4309///     pre-encoded as Punycode `xn--…` by the author);
4310///   - exactly one optional leading wildcard label (`*.`); a wildcard
4311///     in any non-leading label position is rejected;
4312///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
4313///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
4314///   - total length 1..=253 bytes;
4315///   - no IPv4 literal (Gateway API forbids IP literals);
4316///   - no scheme (`https://`, `http://`), no port (`:8080`), no
4317///     whitespace, no path (`/`).
4318///
4319/// Lifted as a typed gate (rather than an inline cascade in
4320/// `validate()`) so the contract lives in one place — every future
4321/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4322/// materializer's host validator, the future per-`:entrada` SAN
4323/// emission for cert-manager Certificates, the multi-`:entrada`
4324/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
4325/// for the same predicate, not its own. Same compounding shape as
4326/// `is_canonical_rate_limit_window` (808017c) and
4327/// [`WitTarget::label`] (previously the free `contrato_target_label`
4328/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
4329/// per-variant label match is compiler-checked-exhaustive).
4330///
4331/// The diagnostic carries the offending `host:` verbatim plus a
4332/// parser-shaped `reason:` naming the specific violation, so the
4333/// author can grep their caixa.lisp for `:host "<host>"` and fix it
4334/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
4335/// (9888b13).
4336fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
4337    // Empty is already gated by `EmptyEntradaHost` at the call site;
4338    // re-checking here keeps the predicate usable from any future
4339    // call site (M4 CR materializer) without an empty-check footgun.
4340    if host.is_empty() {
4341        return Err(AplicacaoError::EmptyEntradaHost);
4342    }
4343    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
4344        return Err(AplicacaoError::EntradaHostInvalid {
4345            host: host.to_string(),
4346            reason: format!(
4347                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
4348                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
4349                host.len(),
4350                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
4351            ),
4352        });
4353    }
4354    if host.contains("://") {
4355        return Err(AplicacaoError::EntradaHostInvalid {
4356            host: host.to_string(),
4357            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
4358                     Gateway API takes the bare hostname)"
4359                .to_string(),
4360        });
4361    }
4362    if host.contains('/') {
4363        return Err(AplicacaoError::EntradaHostInvalid {
4364            host: host.to_string(),
4365            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
4366                     matching is in `:entrada :paths`)"
4367                .to_string(),
4368        });
4369    }
4370    // After the `://` scheme-prefix and `/` path arms have ruled out the
4371    // two `:`-bearing shapes the Gateway API actively rejects with
4372    // location-shaped diagnostics, any remaining `:` in the host body is
4373    // either the canonical "I put the port in the `:host` slot"
4374    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
4375    // slot lives one axis away on the same `:entrada` block) or an
4376    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
4377    // Hostname forbids identically to the IPv4-literal arm below. Both
4378    // shapes silently fell through the `://` and `/` arms before this
4379    // lift and surfaced as a deep `label "<rest>:<port>" contains
4380    // invalid character ':'` diagnostic from the per-byte loop near the
4381    // bottom of this predicate, which named the offending byte but not
4382    // the canonical authoring fix — for the port case the author has to
4383    // know the `:entrada` block carries a separate `:port u16` slot
4384    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
4385    // move the value over; for the IPv6 case the author has to know
4386    // Gateway API v1 forbids IP literals across the board. The contract
4387    // doc-comment above already promises "no port (`:8080`)" verbatim
4388    // in the rejected-shape enumeration but the predicate's
4389    // implementation refused the `:` only as a side-effect of the
4390    // per-label `[a-z0-9-]` character-class loop; this arm brings the
4391    // implementation in line with the documented contract by surfacing
4392    // the canonical fix at the top-level shape gate, peer with how the
4393    // `://` arm names the scheme prefix and the `/` arm names the
4394    // `:entrada :paths` axis. Same compounding trajectory the recent
4395    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
4396    // — the typed slot's rejected set matches the apiserver's rejected
4397    // set, structurally, with a self-locating diagnostic at the
4398    // offending axis instead of a deep parser-shape leak.
4399    if host.contains(':') {
4400        return Err(AplicacaoError::EntradaHostInvalid {
4401            host: host.to_string(),
4402            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
4403                     slot — a separate `u16` axis on the same `:entrada` block, \
4404                     defaulting to 8080 — not in the host body; drop the `:<port>` \
4405                     suffix and author the bare hostname. If you intended an IPv6 \
4406                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
4407                     Hostname forbids IP literals identically to the IPv4-literal \
4408                     arm — use a DNS name)"
4409                .to_string(),
4410        });
4411    }
4412    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
4413    // predicate — the same single source of truth every peer
4414    // ASCII-whitespace scan in caixa-core flows through: the four
4415    // typed-magnitude codec sites (`limits::parse_byte_size` backing
4416    // `:limits :memory`, `limits::parse_duration` backing `:limits
4417    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
4418    // `aplicacao::rate_limit_codec::parse` backing `:politicas
4419    // :rate-limit`) and the shared duration codec
4420    // (`supervisor::duration_codec::parse`) backing `:supervisor
4421    // :restart-window` / `:politicas :timeout` / `:politicas
4422    // :circuit-breaker :window`. This landing closes the last string-typed
4423    // slot in caixa-core still calling `.bytes().any(|b|
4424    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
4425    // across every typed slot now shares one predicate, so a future
4426    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
4427    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
4428    // deliberately excluded from the peer non-ASCII predicate) can
4429    // extend at this shared site in one edit rather than seven
4430    // independent scans diverging over time. Naming the offending byte
4431    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
4432    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
4433    // the offending byte verbatim" discipline every peer codec site
4434    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
4435    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
4436    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
4437        return Err(AplicacaoError::EntradaHostInvalid {
4438            host: host.to_string(),
4439            reason: format!(
4440                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
4441                 Hostname is a single-token DNS name — leading, trailing, \
4442                 or embedded whitespace breaks the K8s apiserver's Hostname \
4443                 regex at admission time; the paste-from-aligned-doc / \
4444                 paste-from-shell-history / paste-from-CSV footgun silently \
4445                 lands a multi-token blob in `:entrada :host`. Strip every \
4446                 whitespace byte and author the bare hostname — space \
4447                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
4448                 refuse identically)"
4449            ),
4450        });
4451    }
4452    // Peer of the ASCII-whitespace scan above: route the non-ASCII
4453    // subset of Unicode `White_Space` through the shared
4454    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
4455    // single source of truth every peer non-ASCII-whitespace scan in
4456    // caixa-core flows through: `limits::parse_byte_size` (`:limits
4457    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
4458    // `limits::parse_millicores` (`:limits :cpu`),
4459    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
4460    // and `supervisor::duration_codec::parse` (`:supervisor
4461    // :restart-window` / `:politicas :timeout` / `:politicas
4462    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
4463    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
4464    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
4465    // paste-from-web-doc), or an EM-SPACE-split host
4466    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
4467    // survived this predicate's ASCII byte-scan (none of the UTF-8
4468    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
4469    // `u8::is_ascii_whitespace`), then landed on the per-label
4470    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
4471    // predicate with the generic `label "…" must start and end with an
4472    // alphanumeric` diagnostic — a "far from source at build-time"
4473    // leak that names the label-shape violation but not the
4474    // paste-from-typography origin the author actually needs to fix.
4475    // Peer with the four codec sites the 1b75b38 landing pinned: the
4476    // typed slot's diagnostic axis names the offending codepoint
4477    // (`U+XXXX`) verbatim rather than laundering the value through a
4478    // downstream label-shape arm, so the author can grep their
4479    // caixa.lisp for the invisible codepoint at the surfaced position
4480    // rather than eyeball a multi-byte host for embedded NBSP / LINE
4481    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
4482    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
4483    // drift between any two typed-slot sites' non-ASCII-whitespace
4484    // rejection set becomes a single-edit fix at the shared predicate
4485    // rather than N independent inline scans diverging over time, and
4486    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
4487    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
4488    // `char::is_whitespace`" class the peer non-ASCII predicate's
4489    // doc-comment names as the follow-up trajectory) extends at the
4490    // shared predicate in one edit rather than seven.
4491    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
4492        return Err(AplicacaoError::EntradaHostInvalid {
4493            host: host.to_string(),
4494            reason: format!(
4495                "contains non-ASCII Unicode whitespace character {ch:?} \
4496                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
4497                 single-token DNS name limited to `[a-z0-9-]` labels; \
4498                 the paste-from-typography footgun silently lands an \
4499                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
4500                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
4501                 `U+3000`, and every other member of the Unicode \
4502                 `White_Space` property outside the ASCII byte range) \
4503                 in `:entrada :host`, which the K8s apiserver's \
4504                 Hostname regex refuses at admission time far from the \
4505                 caixa.lisp source line. Strip every non-ASCII \
4506                 whitespace character and author the bare hostname \
4507                 with only ASCII bytes (write \"checkout.quero.cloud\" \
4508                 verbatim)",
4509                codepoint = ch as u32,
4510            ),
4511        });
4512    }
4513
4514    // Strip the optional single leading wildcard label *before* the
4515    // trailing-dot check so the bare `"*."` form surfaces the more
4516    // self-locating "wildcard without domain" diagnostic instead of
4517    // the generic "trailing dot" one.
4518    let (had_wildcard, rest) = match host.strip_prefix("*.") {
4519        Some(r) => (true, r),
4520        None => (false, host),
4521    };
4522    if had_wildcard && rest.is_empty() {
4523        return Err(AplicacaoError::EntradaHostInvalid {
4524            host: host.to_string(),
4525            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
4526        });
4527    }
4528    if rest.contains('*') {
4529        return Err(AplicacaoError::EntradaHostInvalid {
4530            host: host.to_string(),
4531            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
4532                     no inner or trailing `*` labels"
4533                .to_string(),
4534        });
4535    }
4536    if rest.ends_with('.') {
4537        return Err(AplicacaoError::EntradaHostInvalid {
4538            host: host.to_string(),
4539            reason: "must not have a trailing `.` (Gateway API hostnames are not \
4540                     fully-qualified with a root dot; the apiserver regex rejects \
4541                     trailing dots)"
4542                .to_string(),
4543        });
4544    }
4545
4546    // Reject pure IPv4 literals: four dot-separated labels, every
4547    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
4548    // literals as Hostnames.
4549    let labels: Vec<&str> = rest.split('.').collect();
4550    if labels.len() == 4
4551        && labels
4552            .iter()
4553            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
4554    {
4555        return Err(AplicacaoError::EntradaHostInvalid {
4556            host: host.to_string(),
4557            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
4558                     literals; use a DNS name)"
4559                .to_string(),
4560        });
4561    }
4562
4563    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
4564    // hyphen, with non-hyphen at both boundaries.
4565    for label in &labels {
4566        if label.is_empty() {
4567            return Err(AplicacaoError::EntradaHostInvalid {
4568                host: host.to_string(),
4569                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
4570            });
4571        }
4572        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
4573            return Err(AplicacaoError::EntradaHostInvalid {
4574                host: host.to_string(),
4575                reason: format!(
4576                    "label {label:?} exceeds DNS-1123 label max length of \
4577                     {cap} bytes (got {} bytes)",
4578                    label.len(),
4579                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
4580                ),
4581            });
4582        }
4583        let bytes = label.as_bytes();
4584        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
4585            return Err(AplicacaoError::EntradaHostInvalid {
4586                host: host.to_string(),
4587                reason: format!(
4588                    "label {label:?} must start and end with an alphanumeric \
4589                     (no leading or trailing `-`)"
4590                ),
4591            });
4592        }
4593        for &b in bytes {
4594            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
4595            if !valid {
4596                let msg = if b.is_ascii_uppercase() {
4597                    format!(
4598                        "label {label:?} contains uppercase character {ch:?} \
4599                         (Gateway API hostnames are lowercase-only; use {lower:?})",
4600                        ch = b as char,
4601                        lower = label.to_ascii_lowercase()
4602                    )
4603                } else if b == b'_' {
4604                    format!(
4605                        "label {label:?} contains `_` (Gateway API hostnames \
4606                         allow only `[a-z0-9-]`; use `-` instead)"
4607                    )
4608                } else {
4609                    format!(
4610                        "label {label:?} contains invalid character {ch:?} \
4611                         (Gateway API hostnames allow only `[a-z0-9-]`)",
4612                        ch = b as char
4613                    )
4614                };
4615                return Err(AplicacaoError::EntradaHostInvalid {
4616                    host: host.to_string(),
4617                    reason: msg,
4618                });
4619            }
4620        }
4621    }
4622    Ok(())
4623}
4624
4625/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
4626/// would refuse at admission time. Thin wrapper around
4627/// [`crate::render::is_gateway_api_http_path`] that maps the shared
4628/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
4629/// variant, preserving the more self-locating
4630/// [`AplicacaoError::EntradaPathEmpty`] /
4631/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
4632/// path fails those narrower invariants first.
4633///
4634/// The contract is the canonical HTTP-path grammar — `1..=
4635/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
4636/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
4637/// whitespace/control/non-ASCII bytes — shared with the
4638/// `:contratos :endpoint` axis through the lifted predicate so drift
4639/// between either landing site and the K8s apiserver-side
4640/// HTTPPathMatch.value OpenAPI schema is a build error visible at
4641/// the predicate, not a per-renderer "this passed validate but failed
4642/// admission" surprise. The diagnostic carries the offending `path:`
4643/// verbatim plus a parser-shaped `reason:` naming the specific
4644/// violation, so the author can grep their caixa.lisp for `:paths`
4645/// and fix it in one edit. Same diagnostic shape as
4646/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
4647/// axis.
4648fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
4649    // Empty and missing-leading-`/` are already gated at the call
4650    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
4651    // checking here keeps the per-axis narrower diagnostics in force
4652    // when the predicate is reached directly (and `is_gateway_api_http_path`
4653    // itself defends against `bytes[0]`-style indexing on empty
4654    // input).
4655    if path.is_empty() {
4656        return Err(AplicacaoError::EntradaPathEmpty);
4657    }
4658    if !path.starts_with('/') {
4659        return Err(AplicacaoError::EntradaPathNotAbsolute {
4660            path: path.to_string(),
4661        });
4662    }
4663    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
4664        AplicacaoError::EntradaPathInvalid {
4665            path: path.to_string(),
4666            reason,
4667        }
4668    })
4669}
4670
4671mod rate_limit_codec {
4672    // `Duration` is no longer named here — the codec routes through
4673    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4674    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4675    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4676    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4677    // closed-set enum's arm-table rather than through vestigial free-helper
4678    // delegates.
4679    use super::{RateLimit, RateLimitUnit};
4680    use serde::{Deserialize, Deserializer, Serializer};
4681
4682    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4683        match v {
4684            Some(rl) => s.serialize_str(&render(*rl)),
4685            None => s.serialize_none(),
4686        }
4687    }
4688
4689    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4690        let opt: Option<String> = Option::deserialize(d)?;
4691        match opt {
4692            None => Ok(None),
4693            Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
4694        }
4695    }
4696
4697    fn parse(s: &str) -> Result<RateLimit, String> {
4698        // Whitespace-rejection arm — peer with the leading-`+`
4699        // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
4700        // same canonical-form render-determinism axis. Until this gate
4701        // landed the parser silently tolerated leading / trailing /
4702        // internal whitespace via the top-level `s.trim()` and the
4703        // per-part `rate_str.trim()` / `unit.trim()` calls, so every
4704        // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
4705        // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
4706        // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
4707        // serde silently round-tripped to `"100/s"` on the next emit
4708        // (a *different* canonical string) — breaking the THEORY.md
4709        // Part V render-determinism contract on the same
4710        // canonical-form-drift axis the leading-`+` arm below (the
4711        // 4eeae98 predecessor) and the leading-zero arm below (the
4712        // 4f46830 predecessor) already close.
4713        //
4714        // The canonical author shape is `<integer>/<s|m|h>` with no
4715        // whitespace bytes anywhere — every string [`render`] emits
4716        // carries none, so the parser's accepted set must match for
4717        // serialize / deserialize to round-trip losslessly. This gate
4718        // makes the pre-existing `s.trim()` / `rate_str.trim()` /
4719        // `unit.trim()` calls below strict no-ops on the accepted set
4720        // (every byte-position match they would perform is now already
4721        // trimmed away by the accepted set itself), while the arm
4722        // surfaces every rejected whitespace-carrying shape with a
4723        // self-locating diagnostic naming the offending byte and the
4724        // canonical form the author intended, peer with every prior
4725        // canonical-form-drift arm on this codec.
4726        //
4727        // Routed through the lifted
4728        // [`crate::render::find_ascii_whitespace_byte`] predicate — the
4729        // same source of truth the four peer typed-magnitude codec
4730        // sites (`limits::parse_byte_size`, `limits::parse_duration`,
4731        // `limits::parse_millicores`, `supervisor::duration_codec`)
4732        // share. `u8::is_ascii_whitespace()` at the predicate covers
4733        // the five WhatWG-conformant ASCII whitespace bytes (space,
4734        // tab, LF, FF, CR); the "single lifted predicate" discipline
4735        // the peer non-ASCII arm below carries on the strictly-
4736        // complementary Unicode `White_Space` class extends here to
4737        // the ASCII byte set as well.
4738        if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
4739            return Err(format!(
4740                "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4741                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4742                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4743                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4744                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4745                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4746                 on first serialize — breaking the THEORY.md Part V render-determinism \
4747                 contract every typed slot carries. Strip every whitespace byte (write \
4748                 `\"100/s\"` verbatim)"
4749            ));
4750        }
4751        // Non-ASCII Unicode `White_Space` arm — the strictly-
4752        // complementary class the ASCII arm above cannot see.
4753        // `str::trim` at the top of every peer codec uses
4754        // `char::is_whitespace` (Unicode `White_Space`, strictly
4755        // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
4756        // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4757        // survives the byte-scan (its UTF-8 bytes are not in
4758        // `is_ascii_whitespace`), gets silently stripped by the
4759        // top-level `s.trim()` below, and the value round-trips
4760        // through `render` to a *different* canonical form
4761        // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
4762        // render-determinism contract every typed slot carries.
4763        // Closed here (`:politicas :rate-limit`) and at the three
4764        // peer codec sites (`limits::parse_byte_size`,
4765        // `limits::parse_duration`, `supervisor::duration_codec`)
4766        // through the shared
4767        // [`crate::render::find_non_ascii_whitespace_char`] predicate
4768        // — the "single lifted predicate across all four codec sites
4769        // in one follow-up run" the 24a8ad4 commit body's `Forward
4770        // compounding` bullet named as the next compounding step.
4771        if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
4772            return Err(format!(
4773                "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4774                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4775                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4776                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4777                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4778                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4779                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4780                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4781                 silently strips it at parse entry, and the value round-trips through \
4782                 `render` to a *different* canonical form (`\"100/s\"`) on first \
4783                 serialize — breaking the THEORY.md Part V render-determinism contract \
4784                 every typed slot carries. Strip every non-ASCII whitespace character \
4785                 (write `\"100/s\"` verbatim with only ASCII bytes)",
4786                cp = ch as u32
4787            ));
4788        }
4789        let s = s.trim();
4790        let (rate_str, unit) = s
4791            .split_once('/')
4792            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4793        let rate_trim = rate_str.trim();
4794        // The canonical authoring form for `:politicas :rate-limit` is
4795        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4796        // non-negative integer with no decimal point and no leading
4797        // sign, so the parser's accepted set must match for
4798        // serialize/deserialize to round-trip without canonical-form
4799        // drift. Until this gate landed the parser accepted any
4800        // `u32::from_str`-shaped magnitude — and current Rust
4801        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4802        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4803        // serde silently round-tripped to `"100/s"` on the next emit
4804        // (a *different* canonical string) — breaking the THEORY.md
4805        // Part V render-determinism contract on the fifth typed-codec
4806        // surface in caixa-core (peer with the four duration codecs the
4807        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4808        // already covered: `supervisor::duration_codec` backing three
4809        // typed-duration slots, `limits::parse_duration` backing
4810        // `:limits :wall-clock`, `limits::parse_byte_size` backing
4811        // `:limits :memory`). The fractional / decimal-shaped sibling
4812        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4813        // existing rejection arm, but the diagnostic is value-laundered
4814        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4815        // doesn't name the canonical-form remediation or the round-trip
4816        // drift the next emit would produce); this gate lifts the
4817        // fractional arm onto the same canonical-form diagnostic the
4818        // peer codecs carry.
4819        //
4820        // Strict canonical form: every byte of the magnitude is an
4821        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4822        // inputs the gate distinguishes "non-canonical-but-numeric"
4823        // (parses as f64 or i64 — surfaced with a self-locating
4824        // diagnostic naming the canonical authoring form and the
4825        // round-trip drift the rejected shape would produce on first
4826        // serialize) from "garbage" (parses as neither — surfaced with
4827        // the existing narrower `"not a u32"` wording so its
4828        // diagnostic shape remains stable for the parser-shape footgun
4829        // case).
4830        //
4831        // Routed through the lifted
4832        // [`crate::render::is_digit_only_magnitude`] predicate — the
4833        // same source of truth the four peer typed-magnitude codec
4834        // sites share.
4835        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4836        if !digit_only {
4837            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4838            if numeric {
4839                return Err(format!(
4840                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4841                     canonical authoring form for `:politicas :rate-limit` is \
4842                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4843                     with no decimal point and no leading `+` / `-` sign. A fractional / \
4844                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4845                     through `render` to a *different* canonical form (`\"1/s\"`, \
4846                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
4847                     THEORY.md Part V render-determinism contract every typed slot \
4848                     carries. Pick an integer rate that fits the desired window \
4849                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4850                ));
4851            }
4852            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4853        }
4854        // Leading-zero arm — peer with the prior `"+100/s"` arm above
4855        // (4eeae98's predecessor) on the same canonical-form
4856        // render-determinism axis. The digit-only gate accepts
4857        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4858        // them losslessly (= 100, 0, 7), but `render` emits the
4859        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4860        // a *different* canonical string on the next emit, breaking
4861        // the THEORY.md Part V render-determinism contract the same
4862        // way `"+100/s"` did before the leading-`+` arm landed. The
4863        // single-byte magnitude `"0"` itself round-trips losslessly
4864        // through `render` (`render(0)` emits `"0/s"`) — the
4865        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4866        // what refuses rate-zero authoring, so `"0/s"` stays in the
4867        // accepted set at this codec layer and the diagnostic
4868        // partitioning between canonical-form drift (this arm) and
4869        // semantic-zero (the downstream gate) remains stable.
4870        // Peer with the future leading-zero arms on the three peer
4871        // typed-magnitude codecs the trajectory acknowledges:
4872        // `supervisor::duration_codec`, `limits::parse_duration`,
4873        // `limits::parse_byte_size` — each carries the same
4874        // canonical-form-drift class today; this gate lands the
4875        // discipline on the fourth typed-magnitude codec in
4876        // caixa-core first because the peer `"+100/s"` arm above is
4877        // the closest predecessor on the trajectory.
4878        //
4879        // Routed through the lifted
4880        // [`crate::render::is_leading_zero_padded_magnitude`]
4881        // predicate — the same source of truth the four peer
4882        // typed-magnitude codec sites share.
4883        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4884            return Err(format!(
4885                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4886                 canonical authoring form for `:politicas :rate-limit` is \
4887                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4888                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4889                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4890                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4891                 first serialize — breaking the THEORY.md Part V render-determinism \
4892                 contract every typed slot carries. Strip the leading zeros (write \
4893                 `\"100/s\"` instead of `\"0100/s\"`)"
4894            ));
4895        }
4896        // The digit-only gate guarantees every byte is `[0-9]`, and
4897        // the leading-zero arm above guarantees the magnitude is
4898        // either the single byte `"0"` or starts with `[1-9]`, so
4899        // the only way `u32::from_str` can fail here is overflow
4900        // (the magnitude exceeds `u32::MAX`). Surface that with an
4901        // overflow-shaped wording so the diagnostic names the
4902        // offending magnitude verbatim rather than collapsing onto
4903        // the non-canonical arm. Same shape
4904        // `supervisor::duration_codec` (1c55a2a) carries on the peer
4905        // duration-codec axis.
4906        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4907            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4908        })?;
4909        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
4910        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
4911        // arm reads the `&str → Duration` projection through the
4912        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4913        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
4914        // with [`super::RateLimitUnit::window`]) rather than the vestigial
4915        // module-private `rate_limit_window_from_unit` free helper the
4916        // predecessor 61421a6 left as the last unlifted delegate on this
4917        // axis. One typed dispatch on the substrate primitive instead of
4918        // one runtime call through the free-helper delegate; the sole
4919        // production consumer of the `&str → Duration` axis (this parse
4920        // arm) now reaches for exactly one typed method on the closed-set
4921        // enum, sibling to the codec's render arm's
4922        // [`super::RateLimit::canonical_unit`] dispatch on the paired
4923        // `Duration → RateLimitUnit` axis and to the validate gate's
4924        // [`super::RateLimit::canonical_unit`] shape-probe on the
4925        // canonical-window axis. A future rate-limit-unit addition (a
4926        // `"d"` day suffix once Envoy's `rate_limit_action` grows
4927        // daily-bucket support, a `"ms"` sub-second window once
4928        // high-throughput per-edge policies come into scope per
4929        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
4930        // on the closed-set enum, and the compiler enforces exhaustiveness
4931        // on every consumer's `match self` arms — this parse arm's
4932        // accepted-suffix set, the render arm's emitted-suffix set, the
4933        // validate gate's canonical-window set, and every future
4934        // per-`:contratos`-edge rate-limit-override overlay all pick it up
4935        // by construction.
4936        let unit = unit.trim();
4937        let window = RateLimitUnit::window_from_suffix(unit)
4938            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4939        Ok(RateLimit { rate, window })
4940    }
4941
4942    fn render(rl: RateLimit) -> String {
4943        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4944        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4945        // this render arm reads the `Duration → RateLimitUnit` projection
4946        // through the substrate primitive [`super::RateLimit::canonical_unit`]
4947        // (returns `None` on every non-canonical window — the sub-second /
4948        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4949        // formats the returned typed enum through its
4950        // [`std::fmt::Display`] impl (which routes through
4951        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4952        // the substrate primitive instead of one runtime `find_map`
4953        // walk through the free-helper delegate chain
4954        // [`super::rate_limit_window_unit`] (the vestigial free helper's
4955        // sole production consumer was this arm; every other consumer of
4956        // the `Duration → unit` axis — the validate gate below and the
4957        // future M4 per-Aplicacao Envoy config reconciler — now reads
4958        // the same typed method).
4959        //
4960        // A future rate-limit-unit addition (a `"d"` day suffix once
4961        // Envoy's `rate_limit_action` grows daily-bucket support) is
4962        // one variant + one arm per method on the closed-set enum, and
4963        // the compiler enforces exhaustiveness on every consumer's
4964        // `match self` arms — the codec's `parse` accepted-suffix set,
4965        // this render arm's emitted-suffix set, the validate gate's
4966        // canonical-window set, and every future per-`:contratos`-edge
4967        // rate-limit-override overlay all pick it up by construction.
4968        if let Some(unit) = rl.canonical_unit() {
4969            format!("{}/{unit}", rl.rate())
4970        } else {
4971            // Defensive fallback for non-canonical windows. Note:
4972            // [`AplicacaoSpec::validate_politicas`] rejects any
4973            // non-canonical `:rate-limit :window` via
4974            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4975            // a validated `RateLimit` never reaches this branch. The
4976            // emitted `<n>/<k>s` form is *not* round-trippable through
4977            // [`parse`] (which accepts only the closed-set
4978            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
4979            // explicit count) — the validate gate is what makes the
4980            // round-trip a structural property; this branch exists only
4981            // so a programmatic non-validated serialize doesn't panic.
4982            format!("{}/{}s", rl.rate(), rl.window().as_secs())
4983        }
4984    }
4985}
4986
4987// ── placement strategy ───────────────────────────────────────────────
4988
4989/// How the Aplicacao distributes across clusters. Three options:
4990///
4991/// - `SingleNode` — one cluster runs the app at a time; takeover on
4992///   death (Erlang/OTP distributed-app semantics).
4993/// - `Replicated` — every named cluster runs an instance (active-active).
4994/// - `Sharded` — entities distribute by hash key across clusters
4995///   (Akka cluster sharding).
4996#[derive(
4997    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4998)]
4999pub enum PlacementStrategy {
5000    SingleNode,
5001    Replicated,
5002    Sharded,
5003}
5004
5005/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
5006/// distribution-strategy default for the `:placement :estrategia` axis —
5007/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
5008/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
5009/// so every substrate-side consumer that resolves "what
5010/// [`PlacementStrategy`] variant does an author-omitted `:placement
5011/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
5012/// primitive [`PlacementStrategy`].
5013///
5014/// The `:placement :estrategia` default axis has three production
5015/// consumers on the substrate side today: the [`Default for
5016/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
5017/// impl's struct-literal `estrategia` field, and the serde-side
5018/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
5019/// author-omitted `:placement :estrategia` scalar through the [`Default
5020/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
5021/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
5022/// impl and implicit `PlacementStrategy::default()` routes at the sibling
5023/// consumers, with no compile-time link back to the paired
5024/// [`crate::manifest::Caixa::aplicacao_view`] fold's
5025/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
5026/// production consumer that resolves an author-omitted `:placement` slot
5027/// (entirely omitted, not just the `:estrategia` scalar within a declared
5028/// `:placement` block) through [`Placement::default`] which then routes
5029/// through this same discriminator. A future coherent rebrand of the
5030/// `:placement :estrategia` default (a widening to `Sharded` once the
5031/// substrate discovers hash-keyed distribution as the more common
5032/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
5033/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
5034/// names, a per-cluster overlay the operator pins through a future
5035/// `:placement-overrides` slot) would have had to migrate a lifted
5036/// discriminator on one path and open-coded discriminators on the peers
5037/// in lockstep or the four consumers would silently drift out of
5038/// pairing. Lifting the resolution rule to a typed `pub const` on the
5039/// substrate primitive means the M3-mesh-canonical `:placement
5040/// :estrategia` default migrates as one unit on any future axis change.
5041///
5042/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
5043/// §II.2's active-active-across-every-named-cluster arm — the closest
5044/// canonical M3 production reference the substrate carries, matching the
5045/// caixa-mesh default axis every M3 renderer already keys off (a
5046/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
5047/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
5048/// under the substrate's fleet-programs aggregator without an explicit
5049/// `:placement :estrategia` override). The two alternatives the closed
5050/// [`PlacementStrategy::ALL`] accept-set carries
5051/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
5052/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
5053/// Akka-style hash-keyed distribution across clusters,
5054/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
5055/// postures an author declares explicitly, never a posture an omitted
5056/// slot should silently assume.
5057///
5058/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
5059/// exactly one source of truth on the `:placement :estrategia` axis, on
5060/// the same substrate-primitive lift discipline the sibling M2
5061/// per-supervisor default set carries
5062/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
5063/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
5064/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
5065/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
5066/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
5067/// ([`crate::render::DEFAULT_NAMESPACE`],
5068/// [`crate::render::DEFAULT_LIBRARY_NAME`],
5069/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
5070/// the M3 mesh-primitive-defining slot family to converge onto the
5071/// substrate-primitive-lift discipline the M2 supervisor-slot family
5072/// already carries end-to-end.
5073pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
5074
5075impl Default for PlacementStrategy {
5076    fn default() -> Self {
5077        // Route the [`Default for PlacementStrategy`] impl through the
5078        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
5079        // `pub const` rather than a raw `Self::Replicated` arm — one
5080        // source of truth for the M3-mesh-canonical active-active-
5081        // across-every-named-cluster `:placement :estrategia` default
5082        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
5083        // lift discipline the sibling M2 per-supervisor default set
5084        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
5085        // paired halves) carries end-to-end. Pinned by
5086        // `placement_strategy_default_routes_through_lifted_default`.
5087        PLACEMENT_ESTRATEGIA_DEFAULT
5088    }
5089}
5090
5091impl PlacementStrategy {
5092    /// Exhaustive iteration surface for every consumer that reads the
5093    /// full closed-set (the future M4 admission-webhook's accepted-
5094    /// strategy listing in its rejection body, a future `feira app
5095    /// placement --list` CLI-side surfacing of the accepted arm-set,
5096    /// any future round-trip fuzz harness). A future variant addition
5097    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
5098    /// names as a trajectory item) extends this slice as a single edit
5099    /// and every consumer picks up the new entry by construction — the
5100    /// compiler-checked exhaustiveness on the sibling method `match`
5101    /// arms is the build-time guarantee that no arm forgets to grow.
5102    /// Same shape as the sibling closed-set typed enums'
5103    /// [`RateLimitUnit::ALL`] (6bce03d) and
5104    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5105    /// surfaces — the third closed-set typed enum on the caixa surface
5106    /// to converge onto the same discipline.
5107    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
5108
5109    /// Canonical camelCase-schema discriminator scalar this variant
5110    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
5111    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
5112    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5113    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
5114    /// every substrate consumer that dispatches on the strategy (the
5115    /// `lareira-fleet-programs` aggregator, the future `app-operator`
5116    /// reconciler, the M3 Adaptive compression pass) reads the same
5117    /// byte-string the `Serialize` derive emits — the pin test in
5118    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
5119    /// asserts the two paths agree.
5120    #[must_use]
5121    pub const fn as_str(self) -> &'static str {
5122        match self {
5123            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
5124            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
5125            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
5126        }
5127    }
5128
5129    /// Substrate-canonical reverse projection on the `:placement
5130    /// :estrategia` closed-set axis — parses the camelCase-schema
5131    /// discriminator scalar back to the typed variant, or `None` when
5132    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
5133    /// emits. Dispatches on the same lifted
5134    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5135    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5136    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
5137    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
5138    /// the round-trip migrate through one caixa-core edit on any future
5139    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
5140    /// §II.5 hint names as a trajectory item lands one variant + one
5141    /// arm per method and the compiler enforces exhaustiveness on every
5142    /// consumer's `match self` arms).
5143    ///
5144    /// Prior to this lift the substrate carried only the forward
5145    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
5146    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
5147    /// derive that emits the same byte-string under
5148    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
5149    /// consumer that wanted to parse a wire-form strategy scalar had to
5150    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
5151    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
5152    /// compile-time link back to the typed variant's canonical lifted
5153    /// constant. A future variant rename or a per-arm serde-attribute
5154    /// drift would silently split the wire byte-string one non-serde
5155    /// consumer parsed from the one the emitter wrote, with the
5156    /// failure surfacing at parse time far from the rebrand commit.
5157    ///
5158    /// Same closed-set-reverse-projection discipline the sibling
5159    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
5160    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
5161    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
5162    /// defining `:placement :estrategia` closed-set axis, the third
5163    /// substrate-side closed-set typed enum to converge on the two-way
5164    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
5165    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
5166    /// and side-step the [`std::str::FromStr`]-collision clippy
5167    /// (`clippy::should_implement_trait`) the plain `from_str` name
5168    /// carries; a future explicit [`std::str::FromStr`] impl can layer
5169    /// on top by delegating to this canonical arm-dispatch method.
5170    ///
5171    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
5172    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
5173    /// picks the diagnostic form appropriate for its use site — a
5174    /// future `feira app placement --set` CLI-side arg-parse that wants
5175    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
5176    /// Sharded)"` diagnostic builds one on top by iterating
5177    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
5178    /// path folds `None` onto its per-CR structured refusal body.
5179    #[must_use]
5180    pub fn from_wire(s: &str) -> Option<Self> {
5181        match s {
5182            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
5183            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
5184            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
5185            _ => None,
5186        }
5187    }
5188
5189    /// Substrate-canonical per-arm predicate naming the cross-slot
5190    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
5191    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
5192    /// consumes the paired [`Placement::shard_key`] axis (and therefore
5193    /// requires — and is the only strategy that permits — a non-empty
5194    /// `:shard-key` on the paired slot). Today the accept-set is the
5195    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
5196    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
5197    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
5198    /// distributed-app takeover — §II.1) and `Replicated` (active-active
5199    /// across every named cluster) have no hash-keyed routing axis to
5200    /// consume the slot and refuse a declared-but-inert `:shard-key`
5201    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
5202    ///
5203    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
5204    /// satisfies `placement.shard_key().is_some() ==
5205    /// placement.estrategia().requires_shard_key()` by construction — the
5206    /// cross-slot partition the pin
5207    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
5208    /// locks load-bearing, so every downstream consumer that reaches for
5209    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5210    /// CR materializer's per-CR shard-key resolver, the future
5211    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
5212    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
5213    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
5214    /// shard-key requirement probe, a future author-facing tatara-lisp
5215    /// linter that flags `(:placement (:estrategia Replicated :shard-key
5216    /// "tenantId"))` shapes before `feira lint` reaches
5217    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
5218    /// the substrate primitive — the predicate names *the cross-slot
5219    /// invariant*, not the arm identity.
5220    ///
5221    /// Prior to this lift the "does this strategy consume `:shard-key`"
5222    /// classification lived under the `gen_platform::IsVariant`-derived
5223    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
5224    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
5225    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
5226    /// } else { None }` cascade, the
5227    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
5228    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
5229    /// "tenantId".to_string())` cascade, and the
5230    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
5231    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
5232    /// cascade). Each site conflated two semantically distinct questions:
5233    /// "is the variant `Sharded`?" (arm-identity, what
5234    /// [`Self::is_sharded`] answers) and "does the variant consume
5235    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
5236    /// The two questions land on the same three-way answer under today's
5237    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
5238    /// future arm addition that consumed `:shard-key` under a different
5239    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
5240    /// §II.5 roadmap-hint names that hash-partitions across the cluster
5241    /// pool by client-IP hash rather than an author-declared extractor
5242    /// expression, a hypothetical `WeightedShard` variant that carries a
5243    /// shard-key + per-cluster weight table under a promoted M5
5244    /// adaptive-placement engine) or an addition that did *not* consume
5245    /// `:shard-key` on a semantically Sharded-shaped arm would silently
5246    /// split the two questions. Any consumer that read
5247    /// `.is_sharded().then(…)` for the shard-key requirement gate would
5248    /// silently misclassify the new arm as non-consuming — a fixture
5249    /// builder would omit `:shard-key` where the new arm required one and
5250    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
5251    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
5252    /// commit, a future M4 CR materializer would fall through the
5253    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
5254    /// silently emit an empty extractor at the Akka reconciler layer.
5255    ///
5256    /// Lifting the classification as a substrate-primitive method on the
5257    /// closed-set typed enum names the cross-slot invariant on the
5258    /// primitive that owns the partition: every future arm addition
5259    /// declares its `:shard-key` consumption in one place (this predicate's
5260    /// `match self` arm-set), and every downstream consumer that reaches
5261    /// for the paired shape reads through one typed dispatch. Same
5262    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
5263    /// per-arm predicate on the pre-projection WIT-shape axis and the
5264    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
5265    /// paired predicate on the post-projection typed-view axis — a
5266    /// per-arm semantic-classification predicate paired with the
5267    /// arm-identity predicate the derive already emits, closing the drift
5268    /// footgun on the cross-slot invariant axis.
5269    ///
5270    /// Method-named `requires_shard_key` (not `has_shard_key`, not
5271    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
5272    /// invariant reads as "this strategy *requires* the paired
5273    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
5274    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
5275    /// merely omit it. The `has_*` framing would read as an accessor
5276    /// (returning the presence of an already-carried value) rather than a
5277    /// requirement (naming the invariant the paired slot must satisfy).
5278    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
5279    /// shape as the sibling [`WitContract::is_capability`] /
5280    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
5281    /// arm-family, so every consumer reaches for `.requires_shard_key()`
5282    /// as a drop-in replacement for the `.is_sharded()` conflated read
5283    /// without a return-shape migration.
5284    #[must_use]
5285    pub const fn requires_shard_key(self) -> bool {
5286        match self {
5287            Self::Sharded => true,
5288            Self::SingleNode | Self::Replicated => false,
5289        }
5290    }
5291}
5292
5293// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5294// cross-slot-invariant per-arm predicate: the module-scope const-eval
5295// assertions below trip at caixa-core build time (not test time) if a
5296// future edit rewires the predicate's arm-set away from the singleton
5297// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5298// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5299// runtime pin covers the same truth-table with a more descriptive
5300// diagnostic on failure; these const-eval items add a build-time failure
5301// surface strictly stronger than the runtime pin (a downstream renderer's
5302// `const`-context reader that composed against a rebound predicate would
5303// still surface here before the test suite even ran) and side-step the
5304// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5305// would otherwise accumulate on the caixa-core module baseline.
5306const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5307const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5308const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5309
5310/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5311/// the pretty-printed byte-string every consumer that formats the strategy
5312/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5313/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5314/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5315/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5316/// admission-webhook rejection body) reaches for the same lifted
5317/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5318/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5319/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5320/// `Serialize` derive already emits under
5321/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5322/// [`PlacementStrategy::as_str`] helper already returns.
5323///
5324/// Until this lift landed the sibling OTP-shape typed enums —
5325/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5326/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5327/// so [`std::fmt::Display`] routes through the same discriminant string
5328/// the wire format emits) — carried a stable [`std::fmt::Display`]
5329/// surface but [`PlacementStrategy`] did not; every consumer reaching
5330/// for a strategy byte-string past the wire format had to pick between
5331/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5332/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5333/// derive), any two of which a future variant rename or
5334/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5335/// desynchronize — with the failure surfacing as a downstream renderer /
5336/// operator's per-strategy dispatch reading one spelling while the wire
5337/// format emitted another, far from the source rebrand commit and with
5338/// no field naming the drift. Routing `Display` through
5339/// [`PlacementStrategy::as_str`] makes the three paths
5340/// (`Debug` for structural inspection, `Display` for user-facing text,
5341/// `Serialize` for the wire format) converge on the same lifted
5342/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
5343/// the diagnostic byte-string, and the pretty-printed byte-string move
5344/// as a single unit through one canonical declaration each, by
5345/// construction. Same trajectory as [`PlacementStrategy::as_str`]
5346/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
5347/// closes the third path.
5348///
5349/// Pin tests
5350/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
5351/// and
5352/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
5353/// assert the three paths agree byte-for-byte on every variant, so a
5354/// future variant rename or per-arm serde attribute drift is a build
5355/// error visible at caixa-core test time, not a silent per-consumer
5356/// dispatch miss at apply / reconcile time.
5357impl std::fmt::Display for PlacementStrategy {
5358    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5359        f.write_str(self.as_str())
5360    }
5361}
5362
5363/// Where the Aplicacao runs.
5364#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5365#[serde(rename_all = "camelCase")]
5366pub struct Placement {
5367    /// Distribution strategy.
5368    #[serde(default)]
5369    pub estrategia: PlacementStrategy,
5370
5371    /// Named clusters that host this Aplicacao. Required for
5372    /// `Replicated` and `SingleNode`; for `Sharded` declares the
5373    /// shard pool.
5374    #[serde(default)]
5375    pub clusters: Vec<String>,
5376
5377    /// Optional hint to the placement engine: `"data-locality"`,
5378    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
5379    #[serde(default, skip_serializing_if = "Option::is_none")]
5380    pub affinity: Option<String>,
5381
5382    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
5383    #[serde(default, skip_serializing_if = "Option::is_none")]
5384    pub shard_key: Option<String>,
5385}
5386
5387impl Placement {
5388    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
5389    /// `:shard-key` extractor-expression scalar accessor every consumer
5390    /// of the Aplicacao's hash-keyed distribution routing keys off —
5391    /// returns the author-declared `:placement :shard-key` byte-string
5392    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
5393    /// own `Option<String>` storage; `None` when the slot is absent
5394    /// (the canonical shape under `:estrategia Replicated` /
5395    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
5396    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
5397    /// partition — `validate` refuses any `Placement` past this call
5398    /// that lands `Some` on a non-`Sharded` strategy or `None` on
5399    /// `Sharded`).
5400    ///
5401    /// The `:placement :shard-key` slot carries the Akka-style
5402    /// cluster-sharding entity-id extractor expression
5403    /// (MESH-COMPOSITION §II.4) — validated by
5404    /// [`validate_placement_shard_key`] to be a non-empty printable-
5405    /// ASCII single-token reference (`tenantId`, `$tenantId`,
5406    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
5407    /// future M4 Akka-style cluster-sharding reconciler hashes without
5408    /// re-validating at the runtime layer), and every downstream
5409    /// consumer that reads the key keys off this scalar (the
5410    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
5411    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5412    /// declared-but-inert refusal diagnostic, the caixa-mesh
5413    /// per-Aplicacao `placement.shardKey` emit path the substrate
5414    /// operator's per-entity hash-routing reader consumes, the future
5415    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5416    /// per-shard-key resolver).
5417    ///
5418    /// Prior to this lift the `.shard_key` field was accessed inline at
5419    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
5420    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
5421    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
5422    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
5423    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
5424    /// — two open-coded field-accesses that expressed no compile-time
5425    /// link back to the typed slot. A future extension of the
5426    /// `:placement :shard-key` axis to a richer author surface — a
5427    /// per-cluster override the operator pins through a future
5428    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
5429    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
5430    /// alias table the M4 CR materializer resolves per-CR, a
5431    /// per-Aplicacao dynamic `:shard-key` derivation the future
5432    /// adaptive placement engine computes from `:affinity` weights —
5433    /// would have had to be threaded through both open-coded copies in
5434    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
5435    /// arm refusal would silently disagree on which extractor
5436    /// expression a given Placement resolves to. Lifting the resolution
5437    /// rule to a typed method on the substrate primitive means every
5438    /// downstream consumer of the Aplicacao's per-`:placement`
5439    /// hash-key surface reaches for exactly one typed dispatch — the
5440    /// resolver's accept-set migrates as a unit on any future axis
5441    /// addition.
5442    ///
5443    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
5444    /// [`WitContract::destination`] / [`WitContract::world_ref`]
5445    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
5446    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
5447    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
5448    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
5449    /// typed dispatch on the substrate primitive, thin projections at
5450    /// each consumer" discipline extended onto the per-`:placement`
5451    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
5452    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
5453    /// — opens the "optional per-slot scalar" projection pattern the
5454    /// sibling per-`:placement` `:affinity`, per-`:politicas`
5455    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
5456    /// match the storage field's name; the accessor's identity name
5457    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
5458    /// slot's docstring already carries.
5459    #[must_use]
5460    pub const fn shard_key(&self) -> Option<&str> {
5461        match &self.shard_key {
5462            Some(s) => Some(s.as_str()),
5463            None => None,
5464        }
5465    }
5466
5467    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
5468    /// compression-hint scalar accessor every weighting-consumer of the
5469    /// Aplicacao's per-hint routing surface keys off — returns the
5470    /// author-declared `:placement :affinity` byte-string verbatim as
5471    /// an `Option<&str>`, borrowed from the typed slot's own
5472    /// `Option<String>` storage; `None` when the slot is absent (the
5473    /// canonical shape of an Aplicacao that leaves the compression
5474    /// weighting up to the placement engine's cluster-default arm — no
5475    /// author-authored `data-locality` / `low-latency` / etc. hint
5476    /// biases the routing).
5477    ///
5478    /// The `:placement :affinity` slot carries the M3 Adaptive-
5479    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
5480    /// by [`validate_placement_affinity`] to be a DNS-1123 label
5481    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
5482    /// K8s-conformant label-selector shape every apiserver-side pod-
5483    /// affinity / node-affinity materializer already gates on
5484    /// admission), and every downstream consumer that reads the hint
5485    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
5486    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
5487    /// `placement.affinity` overlay emit path the substrate operator's
5488    /// per-hint weighting-consumer reads, the future M4
5489    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
5490    /// pod-affinity / node-affinity selector resolver).
5491    ///
5492    /// Prior to this lift the `.affinity` field was accessed inline at
5493    /// the sole caixa-core site — the
5494    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
5495    /// `if let Some(a) = &self.placement.affinity { …
5496    /// validate_placement_affinity(a)? … }` cascade — one open-coded
5497    /// field-access that expressed no compile-time link back to the
5498    /// typed slot. A future extension of the `:placement :affinity`
5499    /// axis to a richer author surface — a per-cluster override the
5500    /// operator pins through a future `:placement :affinity-overrides`
5501    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
5502    /// tenant hint alias table the M4 CR materializer resolves per-CR,
5503    /// a per-Aplicacao dynamic `:affinity` derivation the future
5504    /// adaptive placement engine computes from `:clusters` topology —
5505    /// would have had to be threaded through the open-coded copy in
5506    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
5507    /// materializer reader that landed on the axis, or the per-hint
5508    /// value-shape gate and its downstream weighting consumers would
5509    /// silently disagree on which hint a given Placement resolves to.
5510    /// Lifting the resolution rule to a typed method on the substrate
5511    /// primitive means every downstream consumer of the Aplicacao's
5512    /// per-`:placement` compression-hint surface reaches for exactly
5513    /// one typed dispatch — the resolver's accept-set migrates as a
5514    /// unit on any future axis addition.
5515    ///
5516    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
5517    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
5518    /// optional-scalar axis — same "one typed dispatch on the substrate
5519    /// primitive, thin projections at each consumer" discipline extended
5520    /// onto the per-`:placement` M3-Adaptive-compression-hint
5521    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
5522    /// return accessor on the M3 mesh-slot family; closes the last
5523    /// un-lifted per-`:placement` `Option<String>` axis. Named
5524    /// `affinity()` to match the storage field's name; the accessor's
5525    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
5526    /// vocabulary the slot's docstring already carries.
5527    #[must_use]
5528    pub const fn affinity(&self) -> Option<&str> {
5529        match &self.affinity {
5530            Some(s) => Some(s.as_str()),
5531            None => None,
5532        }
5533    }
5534
5535    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
5536    /// strategy scalar accessor every consumer that dispatches on the
5537    /// Aplicacao's per-cluster distribution shape keys off — returns the
5538    /// author-declared `:placement :estrategia` variant verbatim as a
5539    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
5540    /// `PlacementStrategy` storage.
5541    ///
5542    /// The `:placement :estrategia` slot carries the closed-set
5543    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
5544    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
5545    /// `Replicated` — active-active across every named cluster; `Sharded`
5546    /// — Akka-style hash-keyed entity distribution across the cluster pool
5547    /// per §II.4) that every downstream consumer of the Aplicacao's
5548    /// per-cluster fan-out shape keys off. Validated by
5549    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
5550    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
5551    /// matches!(estrategia, Sharded)` — the cross-slot partition the
5552    /// [`Placement::shard_key`] accessor's docstring pins), and every
5553    /// downstream consumer that reads the strategy keys off this scalar
5554    /// (the [`AplicacaoSpec::validate_placement`]
5555    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
5556    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
5557    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
5558    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5559    /// declared-but-inert refusal's
5560    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
5561    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
5562    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
5563    /// emit path the substrate operator's per-strategy fan-out reader
5564    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5565    /// materializer's per-strategy admission-webhook resolver).
5566    ///
5567    /// Prior to this lift the `.estrategia` field was accessed inline at
5568    /// four sites — the [`AplicacaoSpec::validate_placement`]
5569    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
5570    /// `estrategia: self.placement.estrategia`, the same method's
5571    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
5572    /// partition dispatch, the non-`Sharded`-arm
5573    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
5574    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
5575    /// per-Aplicacao strategy print line at
5576    /// `println!("… {} …", spec.placement.estrategia, …)`
5577    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
5578    /// expressed no compile-time link back to the typed slot. A future
5579    /// extension of the `:placement :estrategia` axis to a richer author
5580    /// surface (a per-cluster override the operator pins through a future
5581    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
5582    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
5583    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
5584    /// derivation the future adaptive placement engine computes from
5585    /// `:affinity` + `:clusters` topology) would have had to be threaded
5586    /// through every open-coded copy in lockstep — one consumer reading
5587    /// the raw variant while a peer read the operator-resolved variant
5588    /// would silently split the `PlacementWithoutClusters` /
5589    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
5590    /// partition-dispatch input, a two-consumer split at the validator
5591    /// far from the source `caixa.lisp` with no field naming the
5592    /// strategy-drift root cause. Lifting the resolution rule to a typed
5593    /// method on the substrate primitive means every downstream consumer
5594    /// of the Aplicacao's per-`:placement` distribution-strategy surface
5595    /// reaches for exactly one typed dispatch — the resolver's accept-set
5596    /// migrates as a unit on any future axis addition.
5597    ///
5598    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
5599    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
5600    /// same "one typed dispatch on the substrate primitive, thin
5601    /// projections at each consumer" discipline extended onto the
5602    /// per-`:placement` distribution-strategy `Copy`-composite-enum
5603    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
5604    /// family; first `Copy`-return accessor on the M3 mesh-slot
5605    /// `Placement` type — companion to the sibling per-`:placement`
5606    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5607    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
5608    /// optional-scalar axes, closing the last unlifted per-`:placement`
5609    /// scalar-value axis (the closed-set `PlacementStrategy`
5610    /// distribution-strategy discriminator) so every downstream
5611    /// per-`:placement` reader now routes through a typed dispatch on
5612    /// the substrate primitive. Named `estrategia()` to match the storage
5613    /// field's name; the accessor's identity name maps onto the
5614    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
5615    /// already carries. Declared `pub const fn` (matching the peer M3
5616    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5617    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5618    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5619    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5620    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5621    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5622    /// [`RateLimit`] — every one a `pub const fn`) so every future
5623    /// substrate-side `const`-context consumer of the resolved
5624    /// distribution-strategy variant (a `const _: () = assert!(…)`
5625    /// module-scope invariant pin on a per-fixture typed [`Placement`],
5626    /// a future M4 admission-webhook `const fn` resolver over a typed
5627    /// [`Placement`], any `const fn` composer that fans on the strategy
5628    /// at compile time) reaches through the same typed dispatch on the
5629    /// substrate primitive at const-eval time as at runtime. Pinned by
5630    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
5631    /// const-eval posture at module scope via `const _:() = …` items so
5632    /// any future accidental downgrade to non-`const` trips at caixa-core
5633    /// build time.
5634    #[must_use]
5635    pub const fn estrategia(&self) -> PlacementStrategy {
5636        self.estrategia
5637    }
5638
5639    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
5640    /// per-cluster distribution-target slice accessor every consumer that
5641    /// walks the Aplicacao's declared cluster-pool keys off — returns the
5642    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
5643    /// `&[String]` slice-view, borrowed from the typed slot's own
5644    /// `Vec<String>` storage (a zero-copy slice-view over the same
5645    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5646    /// through). Non-optional: the empty slice is the load-bearing
5647    /// pre-validation sentinel every downstream consumer of the paired
5648    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
5649    /// off — every strategy in the closed
5650    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
5651    /// requires a non-empty list (`SingleNode` / `Replicated` use the
5652    /// list as hosting / takeover candidates per Erlang/OTP distributed-
5653    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
5654    /// shard pool per Akka cluster-sharding convention, §II.4), so the
5655    /// `.is_empty()` probe is the shared pre-condition every
5656    /// [`AplicacaoSpec::validate_placement`] arm heads on.
5657    ///
5658    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
5659    /// 1123-label per-cluster distribution-target list — the same
5660    /// set-not-multiset shape the sibling `:membros :caixa` /
5661    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
5662    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
5663    /// pins the shape). Every downstream consumer that fans on the list
5664    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
5665    /// pre-flight `.is_empty()` probe that trips
5666    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
5667    /// per-cluster value-shape + duplicate-detection fan-out loop, the
5668    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
5669    /// that materializes the list verbatim onto every
5670    /// programs.yaml entry the substrate operator's per-cluster
5671    /// `placement.clusters | contains .Values.cluster` filter reads,
5672    /// the `feira app graph` per-Aplicacao cluster print line, the
5673    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5674    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
5675    /// placement engine's cluster-topology reader).
5676    ///
5677    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
5678    /// inline at three production sites — the
5679    /// [`AplicacaoSpec::validate_placement`] pre-flight
5680    /// `self.placement.clusters.is_empty()` refusal probe, the same
5681    /// method's per-cluster validate loop's
5682    /// `for c in &self.placement.clusters` traversal head, and the
5683    /// `feira app graph` per-Aplicacao print line's
5684    /// `spec.placement.clusters` `{:?}` formatter argument
5685    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
5686    /// that expressed no compile-time link back to the typed slot. A
5687    /// future extension of the `:placement :clusters` axis to a richer
5688    /// author surface (a per-tenant cluster-pool overlay the operator
5689    /// pins through a future `:placement :clusters-overrides` slot the
5690    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
5691    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
5692    /// the future M5 adaptive-placement engine computes from
5693    /// `:affinity` weights + live cluster-topology probes, a promotion
5694    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
5695    /// partition once the substrate operator's cluster-membership
5696    /// reconciler comes into typed scope) would have had to be threaded
5697    /// through all three open-coded copies in lockstep or one consumer
5698    /// would silently disagree with the peers on which cluster-pool a
5699    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
5700    /// reading the raw slot while the peer per-cluster validate loop
5701    /// read an operator-resolved slot would silently split the paired
5702    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
5703    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
5704    /// input from the pre-flight input, a three-consumer split at the
5705    /// validator and formatter far from the source `caixa.lisp` with
5706    /// no field naming the cluster-pool-drift root cause. Lifting the
5707    /// resolution rule to a typed method on the substrate primitive
5708    /// means every downstream consumer of the Aplicacao's
5709    /// per-`:placement` cluster-pool surface reaches for exactly one
5710    /// typed dispatch — the resolver's accept-set migrates as a unit
5711    /// on any future axis addition.
5712    ///
5713    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
5714    /// slot — sibling to the seed M2
5715    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
5716    /// slice-return accessor on the peer per-`:supervisor` static-
5717    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
5718    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
5719    /// primitive, thin projections at each consumer" discipline. The
5720    /// three peer `Vec`-carry axes still unlifted at the time of this
5721    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
5722    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
5723    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
5724    /// [`crate::UpgradeFromEntry::instructions`]
5725    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5726    /// — inherit this accessor's discipline as future compounding runs
5727    /// migrate their consumers onto the shared slice-return shape.
5728    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
5729    /// type, sibling to the two `Option<&str>`-return
5730    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5731    /// (74ec2d3) accessors and the `Copy`-return
5732    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
5733    /// unlifted per-`:placement` field axis (the `Vec<String>`
5734    /// distribution-target-list carrier) so every downstream
5735    /// per-`:placement` reader now routes through a typed dispatch on
5736    /// the substrate primitive. Named `clusters()` to match the storage
5737    /// field's name verbatim and the tatara-lisp author-surface term
5738    /// (`:clusters`) the field's own docstring already carries; the
5739    /// accessor's identity maps onto the canonical MESH-COMPOSITION
5740    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
5741    /// for. Returns `&[String]` (not `&Vec<String>`) because every
5742    /// downstream consumer of the cluster list treats it as a read-only
5743    /// sequence — the slice-view is the narrowest borrow that supports
5744    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
5745    /// `.len()`) without leaking the backing `Vec`'s
5746    /// grow/push/reserve surface that no consumer of the typed view
5747    /// reaches for (the storage-side `Vec` remains reachable through
5748    /// the `pub clusters` field for the mutation-carrying serde
5749    /// round-trip and per-test fixture-mutation paths).
5750    #[must_use]
5751    pub const fn clusters(&self) -> &[String] {
5752        self.clusters.as_slice()
5753    }
5754}
5755
5756impl Default for Placement {
5757    fn default() -> Self {
5758        Self {
5759            // Route the struct-literal `estrategia` default arm through
5760            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
5761            // typed `pub const` rather than the transitively-derived
5762            // [`PlacementStrategy::default`] route — one source of truth
5763            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
5764            // active-active-across-every-named-cluster arm
5765            // (MESH-COMPOSITION §II.2) that both this struct-literal
5766            // altitude and the sibling [`Default for PlacementStrategy`]
5767            // impl already key off through the same substrate primitive.
5768            // Pinned by
5769            // `placement_default_estrategia_routes_through_lifted_default`.
5770            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
5771            clusters: Vec::new(),
5772            affinity: None,
5773            shard_key: None,
5774        }
5775    }
5776}
5777
5778// ── external entry point ─────────────────────────────────────────────
5779
5780/// External entry point — what an outside caller sees. Renders to a
5781/// Gateway / Ingress + a route to the named member Servico.
5782#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5783#[serde(rename_all = "camelCase")]
5784pub struct Entrada {
5785    /// Public hostname (e.g. `"checkout.quero.cloud"`).
5786    pub host: String,
5787
5788    /// Member Servico the gateway routes to. Must be in `:membros`.
5789    pub para: String,
5790
5791    /// Optional path filter — if set, only matching paths route to
5792    /// this Aplicacao (the rest fall through to other route rules).
5793    #[serde(default)]
5794    pub paths: Vec<String>,
5795
5796    /// Default port on the destination Servico (the trigger.service.port).
5797    #[serde(default = "default_port")]
5798    pub port: u16,
5799}
5800
5801impl Entrada {
5802    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
5803    /// every HTTPRoute-aware renderer keys off — returns the author-
5804    /// declared `:entrada :paths` list verbatim when non-empty, and the
5805    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
5806    /// all fallback otherwise (so an Aplicacao author who declares an
5807    /// external `:entrada` block but no per-path rule surface still
5808    /// gets a route whose sole `HTTPPathMatch` matches every incoming
5809    /// request under the paired
5810    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
5811    ///
5812    /// Prior to this lift the "if `:entrada :paths` is empty use the
5813    /// substrate catch-all; else return each declared path verbatim"
5814    /// cascade lived inline at
5815    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
5816    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
5817    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
5818    /// substrate ships today, with no typed method on the substrate
5819    /// primitive that named the rule. A future path-resolution axis
5820    /// addition — a per-cluster `:entrada :default-path` override the
5821    /// operator pins through a future `:placement`-scoped slot, an
5822    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5823    /// admission-webhook floor that materializes the catch-all before
5824    /// the CR lands, a future per-`:entrada :paths` overlay from a
5825    /// per-cluster policy the future `feira app deploy` pipeline
5826    /// consumes — would have to be threaded through every renderer's
5827    /// inline copy of the cascade in lockstep or one consumer would
5828    /// silently disagree with the peers on which path list a given
5829    /// `:entrada` block resolves to. Lifting the rule to a typed
5830    /// method on the substrate primitive means every downstream
5831    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
5832    /// per-cluster overlay resolver, every future per-Aplicacao
5833    /// snapshot renderer) reaches for exactly one typed dispatch —
5834    /// the resolver's accept-set moves as a unit on any future axis
5835    /// addition.
5836    ///
5837    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
5838    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
5839    /// per-`:entrada` scalar-value axes — extends the "one typed
5840    /// dispatch on the substrate primitive, thin projections at each
5841    /// consumer" discipline onto the per-`:entrada` path-list
5842    /// resolution axis every HTTPRoute-aware renderer consumes. Same
5843    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
5844    /// sibling `:politicas` primitive — one typed method on the
5845    /// substrate primitive that names the cascade every renderer
5846    /// otherwise re-inlines.
5847    #[must_use]
5848    pub fn resolved_paths(&self) -> Vec<&str> {
5849        // Route the internal cascade-head + per-entry projection reads
5850        // through the lifted [`Self::paths`] slice accessor rather than
5851        // the raw `self.paths` field access — the substrate-primitive
5852        // per-`:entrada` path-list resolver's two internal reads now
5853        // key off the canonical raw-slot surface every downstream
5854        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
5855        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
5856        // entrada summary line's `{:?}` Debug print) routes through, so
5857        // any future rebrand on the typed slot's raw-slot reader lands
5858        // at exactly one place. Same two-consumer coherence discipline
5859        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
5860        // the peer M3 mesh-slot `Vec<String>`-carry axis.
5861        if self.paths().is_empty() {
5862            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
5863        } else {
5864            self.paths().iter().map(String::as_str).collect()
5865        }
5866    }
5867
5868    /// Substrate-canonical per-`:entrada` DNS-hostname singular
5869    /// accessor every Gateway-API `Listener.hostname` reader keys off
5870    /// — returns the author-declared `:entrada :host` byte-string
5871    /// verbatim as a `&str`, borrowed from the typed slot's own
5872    /// [`String`] storage.
5873    ///
5874    /// Named the "singular" half of the DNS-hostname resolver pair on
5875    /// the substrate primitive: the parent-Gateway per-listener
5876    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
5877    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
5878    /// hostname per listener), and this accessor is the typed dispatch
5879    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
5880    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
5881    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
5882    /// per-Aplicacao ingress-hostname surface projects onto.
5883    ///
5884    /// Prior to this lift the `entrada.host.clone()` byte-string was
5885    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
5886    /// per-listener singular `hostname:` axis
5887    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
5888    /// per-HTTPRoute plural `spec.hostnames[]` axis
5889    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
5890    /// consumers read the same `entrada.host` field but the two-site
5891    /// duplication expressed no compile-time contract that the singular
5892    /// Gateway-listener filter and the plural `HTTPRoute` filter list
5893    /// stay in lockstep on future extensions of the `:entrada` slot to
5894    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
5895    /// overlay, a per-cluster SNI fan-out the operator pins through a
5896    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
5897    /// Aplicacao` CR materializer's per-listener virtual-host filter
5898    /// admission-webhook overlay). Any such extension would have to be
5899    /// threaded through every renderer's inline copy of the resolution
5900    /// in lockstep or the Gateway listener's `hostname:` filter would
5901    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
5902    /// — a Gateway-API-conformance divergence whose apply-time symptom
5903    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
5904    /// `NoMatchingParent` — the API server rejects the route because
5905    /// its `hostnames[]` filter doesn't intersect the parent listener's
5906    /// `hostname` filter) is far from the source `caixa.lisp` and never
5907    /// surfaces in the emitted YAML. Lifting the singular and plural
5908    /// resolvers to typed methods on the substrate primitive means
5909    /// every consumer of the Aplicacao's ingress-hostname surface
5910    /// reaches for exactly one typed dispatch, and the pair-invariant
5911    /// `hostnames() == vec![hostname()]` pinned by the sibling
5912    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
5913    /// keeps the two axes in lockstep by construction.
5914    ///
5915    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
5916    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
5917    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
5918    /// the substrate primitive, thin projections at each consumer"
5919    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5920    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5921    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5922    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
5923    /// `:entrada` scalar-value + list-value axes.
5924    #[must_use]
5925    pub const fn hostname(&self) -> &str {
5926        self.host.as_str()
5927    }
5928
5929    /// Substrate-canonical per-`:entrada` DNS-hostname plural
5930    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
5931    /// keys off — returns the singleton `[hostname()]` list under
5932    /// today's single-hostname-per-Aplicacao author surface, and the
5933    /// authoritative multi-hostname list under a future
5934    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
5935    ///
5936    /// Plural half of the DNS-hostname resolver pair — see the
5937    /// companion [`Entrada::hostname`] docstring for the two-consumer
5938    /// lift + pair-invariant discipline (`hostnames() ==
5939    /// vec![hostname()]`, pinned load-bearing by the sibling
5940    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
5941    /// test).
5942    ///
5943    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
5944    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
5945    /// per-rule path-list axis — same `Vec<&str>` shape, same
5946    /// substrate-primitive-owns-the-resolver discipline extended to
5947    /// the per-HTTPRoute virtual-host filter-list axis.
5948    #[must_use]
5949    pub fn hostnames(&self) -> Vec<&str> {
5950        vec![self.hostname()]
5951    }
5952
5953    /// Substrate-canonical per-`:entrada` destination-Servico scalar
5954    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
5955    /// the author-declared `:entrada :para` byte-string verbatim as a
5956    /// `&str`, borrowed from the typed slot's own [`String`] storage.
5957    ///
5958    /// The `:entrada :para` slot names the single member Servico the
5959    /// external Gateway routes to (validated by
5960    /// [`AplicacaoSpec::validate`] to be a
5961    /// [`Membro::caixa`] the Aplicacao declares — a stray
5962    /// `:para` that doesn't name a member is
5963    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
5964    /// backend-attachment miss at cluster-apply time). Under today's
5965    /// single-destination author surface `:entrada :para` is the ingress
5966    /// apex Servico's canonical identity; under a hypothetical
5967    /// future multi-backend author surface (a `:entrada
5968    /// :split :backends` weighted-fan-out overlay for canary /
5969    /// blue-green traffic-split rollouts, per-path override for
5970    /// path-based per-Servico routing beyond the single-apex model,
5971    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5972    /// per-CR admission-webhook that promotes the scalar to a
5973    /// weighted list) this accessor is the substrate primitive's typed
5974    /// dispatch every downstream `HTTPRoute`-aware consumer routes
5975    /// through, so the resolution shape migrates as a unit on one
5976    /// caixa-core edit rather than a coordinated rewrite across every
5977    /// renderer's inline field-access.
5978    ///
5979    /// Prior to this lift the `entrada.para` byte-string was accessed
5980    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
5981    /// `metadata.name` composer's per-destination discriminator arg
5982    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
5983    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
5984    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
5985    /// (`entrada.para.clone()`,
5986    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
5987    /// consumers read the same `entrada.para` field but the two-site
5988    /// duplication expressed no compile-time contract that the HTTPRoute
5989    /// name-discriminator and the per-rule backend name stay in
5990    /// lockstep on future extensions of the `:entrada` slot to a
5991    /// multi-destination author surface. Any such extension would have
5992    /// to be threaded through every renderer's inline copy of the
5993    /// destination projection in lockstep or the HTTPRoute
5994    /// `metadata.name` would silently reference a different destination
5995    /// than its own `backendRefs[]` — an operator-side
5996    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
5997    /// grep-by-name lookup would land on a route whose `backendRefs[]`
5998    /// silently point at a peer Servico, dropping every external
5999    /// `:entrada` flow at the gateway with the destination-drift root
6000    /// cause invisible in the emitted YAML.
6001    ///
6002    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
6003    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
6004    /// the per-listener singular / per-HTTPRoute plural filter axes and
6005    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
6006    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
6007    /// typed dispatch on the substrate primitive, thin projections at
6008    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6009    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6010    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6011    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
6012    /// sibling per-`:entrada` scalar-value + list-value axes — this
6013    /// accessor closes the last unlifted per-`:entrada` scalar axis
6014    /// (the destination-Servico byte-string) so every downstream
6015    /// per-`:entrada` reader now routes through a typed dispatch on
6016    /// the substrate primitive.
6017    #[must_use]
6018    pub const fn destination(&self) -> &str {
6019        self.para.as_str()
6020    }
6021
6022    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
6023    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
6024    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
6025    /// reader keys off — returns the author-declared `:entrada :port`
6026    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
6027    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
6028    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
6029    /// [`AplicacaoError::EntradaPortZero`], not a silent
6030    /// admission-webhook rejection at cluster-apply time).
6031    ///
6032    /// The `:entrada :port` slot carries the destination Servico's
6033    /// canonical in-cluster L4 listener port (`trigger.service.port` on
6034    /// the `pleme-computeunit` library chart), and every downstream
6035    /// consumer that reads the port keys off this scalar (the
6036    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
6037    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
6038    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
6039    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6040    /// CR materializer's per-Aplicacao gateway port resolver).
6041    ///
6042    /// Prior to this lift the `.port` field was accessed inline at two
6043    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
6044    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
6045    /// the [`AplicacaoSpec::port_for_destination`] resolver's
6046    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
6047    /// open-coded field-accesses that expressed no compile-time link
6048    /// back to the typed slot. A future extension of the `:entrada :port`
6049    /// axis to a richer author surface — a per-cluster override the
6050    /// operator pins through a future `:placement :default-port` slot the
6051    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
6052    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
6053    /// heterogeneous listener ports, an M4
6054    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6055    /// admission-webhook floor that promotes the scalar to a
6056    /// per-destination map — would have had to be threaded through both
6057    /// open-coded copies in lockstep or the structural-floor validator
6058    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
6059    /// silently disagree on which port a given [`Entrada`] resolves to.
6060    /// Lifting the resolution rule to a typed method on the substrate
6061    /// primitive means every downstream consumer of the Aplicacao's
6062    /// per-`:entrada` L4-port surface reaches for exactly one typed
6063    /// dispatch — the resolver's accept-set migrates as a unit on any
6064    /// future axis addition.
6065    ///
6066    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
6067    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
6068    /// accessors on the per-`:entrada` scalar-value axis — same "one
6069    /// typed dispatch on the substrate primitive, thin projections at
6070    /// each consumer" discipline extended onto the per-`:entrada`
6071    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
6072    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
6073    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
6074    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
6075    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
6076    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
6077    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
6078    /// storage field's name; the accessor's identity name maps onto the
6079    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
6080    /// already carries. Declared `pub const fn` (matching the peer M3
6081    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6082    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6083    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6084    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6085    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6086    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6087    /// [`RateLimit`], and the sibling per-`:placement`
6088    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
6089    /// enum scalar axis — every one a `pub const fn`) so every future
6090    /// substrate-side `const`-context consumer of the resolved
6091    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
6092    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
6093    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
6094    /// admission-webhook `const fn` per-CR gateway-port floor over a
6095    /// typed [`Entrada`], any `const fn` composer that fans on the port
6096    /// at compile time) reaches through the same typed dispatch on the
6097    /// substrate primitive at const-eval time as at runtime. Pinned by
6098    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
6099    /// const-eval posture at module scope via `const _:() = …` items so
6100    /// any future accidental downgrade to non-`const` trips at caixa-core
6101    /// build time.
6102    #[must_use]
6103    pub const fn port(&self) -> u16 {
6104        self.port
6105    }
6106
6107    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
6108    /// slice accessor every HTTPRoute-aware renderer keys off when it
6109    /// wants the raw author-declared path-list (not the fallback-
6110    /// applied projection [`Self::resolved_paths`] returns) — returns
6111    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
6112    /// borrowed from the typed slot's own [`Vec<String>`] storage.
6113    ///
6114    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
6115    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
6116    /// (1449891) closes the fallback-applying arm every per-Aplicacao
6117    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
6118    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
6119    /// catch-all; non-empty slot → per-entry verbatim projection); this
6120    /// accessor closes the raw-slot arm every consumer that must see the
6121    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
6122    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
6123    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
6124    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
6125    /// external-gateway summary line's `{:?}` Debug print — which must
6126    /// name the author's declaration, not the substrate's fallback, so
6127    /// an author reading their graph output can grep their caixa.lisp
6128    /// for the exact list they authored) routes through.
6129    ///
6130    /// Prior to this lift the `.paths` field was accessed inline at four
6131    /// production sites: the two internal reads in [`Self::resolved_paths`]
6132    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
6133    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
6134    /// value-shape gate's `for p in &e.paths` traversal head, and the
6135    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
6136    /// Debug print — four open-coded field-accesses that expressed no
6137    /// compile-time link back to the typed slot. A future extension of
6138    /// the `:entrada :paths` axis to a richer author surface — a
6139    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
6140    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
6141    /// spec supports through `matches[].method`), a per-path per-header
6142    /// filter overlay (`matches[].headers[]`), a per-cluster override
6143    /// the operator pins through a future `:placement :path-overlay`
6144    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6145    /// per-CR admission-webhook that normalized the list at admission
6146    /// time — would have had to be threaded through every open-coded
6147    /// copy in lockstep or the validator's per-entry gate would silently
6148    /// disagree with the renderer's per-entry emit on which list a given
6149    /// `:entrada` block resolves to. Lifting the resolution to a typed
6150    /// method on the substrate primitive means every downstream consumer
6151    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
6152    /// exactly one typed dispatch — the resolver's accept-set migrates
6153    /// as a unit on any future axis addition.
6154    ///
6155    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
6156    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
6157    /// carry axis — same "one typed dispatch on the substrate primitive,
6158    /// thin projections at each consumer" discipline extended onto the
6159    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
6160    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
6161    /// carrier) so every downstream per-`:entrada` reader now routes
6162    /// through a typed dispatch on the substrate primitive. Returns
6163    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
6164    /// treats the list as a read-only sequence — the slice-view is the
6165    /// narrowest borrow that supports every present + roadmapped consumer
6166    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
6167    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
6168    /// view reaches for (the storage-side `Vec` remains reachable through
6169    /// the `pub paths` field for the mutation-carrying serde round-trip
6170    /// and per-test fixture-mutation paths).
6171    #[must_use]
6172    pub const fn paths(&self) -> &[String] {
6173        self.paths.as_slice()
6174    }
6175}
6176
6177/// Canonical default L4 port every typed Servico exposes on its
6178/// in-cluster K8s Service (the `trigger.service.port` axis the
6179/// `pleme-computeunit` library chart emits, the `:entrada :port` author
6180/// surface defaults to when the author omits the slot, and the
6181/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
6182/// `:entrada` block matches the per-`:contratos` destination Servico).
6183/// The single source of truth all three typed-port consumers reach for:
6184///
6185///   - [`Entrada::port`]'s serde default (via the
6186///     [`default_port`] helper this constant feeds); the author surface
6187///     `(:entrada (:host … :para …))` without an explicit `:port` slot
6188///     reads back as a typed [`Entrada`] carrying this exact value;
6189///   - the
6190///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
6191///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
6192///     fallback, fired when the typed `:entrada` block doesn't name
6193///     the per-`:contratos` destination Servico — the typed
6194///     `:contratos` graph carries no per-destination port axis (the
6195///     destination port is the destination Servico's
6196///     `lareira-<nome>` chart's `trigger.service.port`, which the
6197///     Aplicacao-level renderer has no visibility into without a
6198///     resolver round-trip), so the renderer falls back to the
6199///     substrate's canonical Servico-port assumption — by
6200///     construction the same value the destination's own
6201///     `pleme-computeunit` chart emits, the same value the
6202///     destination's own typed `:entrada :port` slot defaults to;
6203///   - every future per-Servico renderer the absorption-roadmap
6204///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6205///     CR materializer's per-edge port resolver, the future
6206///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
6207///     emitter's per-route bucket key, the future caixa-otel
6208///     collector-pipeline emitter's per-Servico scrape port).
6209///
6210/// Until this lift landed the value `8080` lived at two production-code
6211/// call-sites: the [`default_port`] helper at
6212/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
6213/// and the `.unwrap_or(8080)` literal at
6214/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
6215/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
6216/// resolver). A future Servico-port rebrand — the substrate moving the
6217/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
6218/// gateway grows direct `:80` listeners, to `8443` once the substrate
6219/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
6220/// override the operator pins through a future
6221/// `:placement :default-port` slot — without a coordinated edit on
6222/// both sides would silently emit Servicos listening on one port and
6223/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
6224/// The CNP's apply-time symptom (the policy is admitted but every L4
6225/// flow on the destination Servico's actual port silently drops because
6226/// it doesn't match the whitelisted port) is far from the rebrand
6227/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
6228/// in hubble traces, not in `kubectl describe`. Lifting the literal to
6229/// a shared constant closes the drift footgun structurally — both
6230/// consumers read from the same `u16`, so any rebrand reaches both
6231/// sites by construction.
6232///
6233/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
6234/// per-renderer canonical-K8s-axis constant — the namespace string
6235/// and the canonical Servico port both lived as duplicated literals
6236/// across caixa-core / caixa-mesh / caixa-flux before their respective
6237/// lifts. Same "the typed constant lives in one place" discipline the
6238/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
6239/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
6240/// shared-string axes.
6241///
6242/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
6243pub const DEFAULT_SERVICO_PORT: u16 = 8080;
6244
6245/// Structural floor for the typed `:entrada :port` axis — every
6246/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
6247/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
6248///
6249/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
6250/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
6251/// interprets as "let the kernel pick a free port at bind time", not a
6252/// well-defined destination the substrate's per-`:entrada` Gateway API
6253/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
6254/// carrying `port: 0` degenerates to a nominal-only routing target: the
6255/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
6256/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
6257/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
6258/// at build time rather than at `kubectl apply` time), and the
6259/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
6260/// (caixa-mesh/src/lib.rs:2657 through
6261/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
6262/// [`Entrada::port`] typed value — silently emits a policy whose
6263/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
6264/// actual listener, dropping every L4 flow at the eBPF data plane far
6265/// from the source caixa.lisp with no field naming the port-zero-drift
6266/// root cause.
6267///
6268/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
6269/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
6270/// on the top edge (unlike the peer capped-`u32` `:politicas` /
6271/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
6272/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
6273/// well below `u32::MAX` and therefore need explicit typed caps).
6274///
6275/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
6276/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
6277/// scalar every `(:entrada (:host … :para …))` slot without an explicit
6278/// `:port` inherits through the serde default hook; this constant names
6279/// the accept-set floor every declared port must satisfy. The pair is
6280/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
6281/// substrate's default must satisfy its own accept-set floor by
6282/// construction) — a future rebrand that accidentally moved
6283/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
6284/// negative-cast typo, a per-cluster override the operator pins through
6285/// a future `:placement :default-port` slot that lands out-of-range)
6286/// would silently invalidate the serde-default emission at every
6287/// author-side `(:entrada (:host … :para …))` slot — the compile-time
6288/// invariant pin
6289/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
6290/// closes the drift footgun at caixa-core build time.
6291///
6292/// Lifted as a typed `pub const` (rather than an inline `0` literal at
6293/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
6294/// has exactly one source of truth — the future M4
6295/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6296/// gateway resolver, the future per-Servico
6297/// `computeunit.trigger.service.port` renderer's per-CR port-value
6298/// validator, and every downstream test-fixture navigator asserting
6299/// the accept-set floor all read from one place. Same shape every
6300/// other typed bracket-floor / bracket-ceiling in this crate carries
6301/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6302/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6303/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6304/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6305/// [`POLICY_RATE_LIMIT_MAX`]).
6306pub const SERVICO_PORT_MIN: u16 = 1;
6307
6308const fn default_port() -> u16 {
6309    DEFAULT_SERVICO_PORT
6310}
6311
6312// ── the typed view ───────────────────────────────────────────────────
6313
6314/// Typed composition view of the flat Aplicacao slots on
6315/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6316/// validation + downstream renderer consumption.
6317#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6318#[serde(rename_all = "camelCase")]
6319pub struct AplicacaoSpec {
6320    pub membros: Vec<Membro>,
6321    pub contratos: Vec<WitContract>,
6322    pub politicas: MeshPolicy,
6323    pub placement: Placement,
6324    pub entrada: Option<Entrada>,
6325}
6326
6327impl AplicacaoSpec {
6328    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6329    /// per-Aplicacao member-list slice-return accessor every
6330    /// per-Aplicacao member-list reader keys off — returns the author-
6331    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6332    /// over the same backing buffer the raw `self.membros.as_slice()`
6333    /// field access borrows from.
6334    ///
6335    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6336    /// member list — the load-bearing identity of the application graph
6337    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
6338    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
6339    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
6340    /// accessor) with a `:versao` semver-requirement string (through
6341    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
6342    /// and every downstream consumer that fans on the member-set keys
6343    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
6344    /// membership-lookup `HashSet<&str>` seed's collect input, the
6345    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
6346    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
6347    /// per-member DNS-1123 / semver-requirement / duplicate-detection
6348    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
6349    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
6350    /// programs.yaml per-`:membros` fan-out emitter's per-entry
6351    /// mapping-composition loop, the `feira app graph` per-Aplicacao
6352    /// member-count print line and per-member tree traversal,
6353    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
6354    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
6355    /// placement engine's per-member weight-topology reader).
6356    ///
6357    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
6358    /// inline at six production sites — the [`AplicacaoSpec::validate`]
6359    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
6360    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
6361    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
6362    /// probe, the same method's per-member `for m in &self.membros`
6363    /// validate-loop traversal head, the
6364    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6365    /// `for m in &self.membros` adjacency-list seed, the
6366    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
6367    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
6368    /// paired with the peer `for m in &spec.membros` per-entry fan-out
6369    /// loop, and the `feira app graph` per-Aplicacao print line's
6370    /// `spec.membros.len()` count formatter argument paired with the
6371    /// peer `for m in &spec.membros` per-member tree traversal — six
6372    /// open-coded field-accesses that expressed no compile-time link
6373    /// back to the typed slot. A future extension of the `:membros`
6374    /// axis to a richer author surface (a per-cluster member-set
6375    /// overlay the operator pins through a future
6376    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
6377    /// roadmap acknowledges, a per-tenant member-alias table the M4
6378    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
6379    /// CR at admission time, a per-Aplicacao dynamic member-set
6380    /// derivation the future adaptive-placement engine computes from
6381    /// weighted membership topology, a promotion of the plain
6382    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
6383    /// Orleans-style virtual-actor dynamic-membership comes into typed
6384    /// scope) would have had to be threaded through all six open-coded
6385    /// copies in lockstep or one consumer would silently disagree with
6386    /// the peers on which member-set a given Aplicacao resolves to —
6387    /// the `HashSet<&str>` name-set seed reading the raw slot while
6388    /// the peer `.is_empty()` refusal probe read an operator-resolved
6389    /// slot would silently split the `:contratos` membership-lookup
6390    /// input from the pre-flight-refusal input, a six-consumer split
6391    /// at the validator + programs.yaml emitter + graph printer far
6392    /// from the source `caixa.lisp` with no field naming the member-
6393    /// set-drift root cause. Lifting the resolution rule to a typed
6394    /// method on the substrate primitive means every downstream
6395    /// consumer of the Aplicacao's per-`:membros` member-list surface
6396    /// reaches for exactly one typed dispatch — the resolver's accept-
6397    /// set migrates as a unit on any future axis addition.
6398    ///
6399    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
6400    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6401    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6402    /// static-child-list `Vec`-carry axis, and to the M3
6403    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6404    /// on the peer per-`:placement` distribution-target-list `Vec`-
6405    /// carry axis. Same "one typed dispatch on the substrate primitive,
6406    /// thin projections at each consumer" discipline. The two peer
6407    /// `Vec`-carry axes still unlifted at the time of this lift —
6408    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
6409    /// WIT-typed edge list) and
6410    /// [`crate::UpgradeFromEntry::instructions`]
6411    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6412    /// — inherit this accessor's discipline as future compounding runs
6413    /// migrate their consumers onto the shared slice-return shape.
6414    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
6415    /// `AplicacaoSpec` type itself, extending the discipline beyond
6416    /// the inner per-slot types ([`crate::Placement`],
6417    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
6418    /// view every renderer consumes. Named `membros()` to match the
6419    /// storage field's name verbatim and the tatara-lisp author-
6420    /// surface term (`:membros`) the field's own docstring already
6421    /// carries; the accessor's identity maps onto the canonical
6422    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
6423    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
6424    /// every downstream consumer of the member list treats it as a
6425    /// read-only sequence — the slice-view is the narrowest borrow
6426    /// that supports every present + roadmapped consumer
6427    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6428    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6429    /// the typed view reaches for (the storage-side `Vec` remains
6430    /// reachable through the `pub membros` field for the mutation-
6431    /// carrying serde round-trip and per-test fixture-mutation paths).
6432    #[must_use]
6433    pub const fn membros(&self) -> &[Membro] {
6434        self.membros.as_slice()
6435    }
6436
6437    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
6438    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
6439    /// accessor every per-Aplicacao contract-list reader keys off —
6440    /// returns the author-declared `:contratos` list verbatim as a
6441    /// `&[WitContract]` slice-view over the same backing buffer the raw
6442    /// `self.contratos.as_slice()` field access borrows from.
6443    ///
6444    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
6445    /// WIT-typed edge list — the load-bearing set of directed edges
6446    /// on the application graph whose nodes are the `:membros` entries
6447    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
6448    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
6449    /// six-tuple is the edge identity every downstream duplicate gate
6450    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
6451    /// Servico caller name + a `:para` destination-Servico callee name
6452    /// (through the lifted [`WitContract::source`] +
6453    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
6454    /// caller/callee-Servico axis) with a `:wit` world-reference
6455    /// (through the lifted [`WitContract::world_ref`] (0804823)
6456    /// accessor) and the target-shape-appropriate payload-carrier
6457    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
6458    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
6459    /// (ed22b66) accessor on the per-target-shape payload-carrier
6460    /// axis). Every downstream consumer that fans on the edge-set
6461    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
6462    /// name-set / self-edge / target-shape / dedup fan-out loop, the
6463    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
6464    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
6465    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
6466    /// grouping loop, the `feira app graph` per-Aplicacao contract-
6467    /// count print line and per-contract tree traversal, every future
6468    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
6469    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
6470    /// mesh-policy overlay resolver's per-contract typed-edge weight
6471    /// reader).
6472    ///
6473    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
6474    /// accessed inline at four production sites — the
6475    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
6476    /// per-edge validate-loop traversal head (which drives every
6477    /// per-edge name-set membership lookup, self-edge check,
6478    /// target-shape dispatch, and dedup `HashSet` insert), the
6479    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6480    /// `for c in &self.contratos` adjacency-list seed head (which
6481    /// drives every per-edge sync-vs-pub-sub partition and per-edge
6482    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
6483    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
6484    /// `BTreeMap` grouping loop head (which drives every per-CNP
6485    /// fan-out emit), and the `feira app graph` per-Aplicacao print
6486    /// line's `spec.contratos.len()` count formatter argument paired
6487    /// with the peer `for c in &spec.contratos` per-contract tree
6488    /// traversal — four open-coded field-accesses that expressed no
6489    /// compile-time link back to the typed slot. A future extension
6490    /// of the `:contratos` axis to a richer author surface (a
6491    /// per-cluster contract overlay the operator pins through a
6492    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
6493    /// federation roadmap acknowledges, a per-tenant edge-policy
6494    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6495    /// materializer resolves per-CR at admission time, a per-edge
6496    /// weight scalar the future adaptive-placement engine reads to
6497    /// bias sync-subgraph routing, a promotion of the plain
6498    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
6499    /// once virtual-actor-style dynamic-edge composition comes into
6500    /// typed scope) would have had to be threaded through all four
6501    /// open-coded copies in lockstep or one consumer would silently
6502    /// disagree with the peers on which edge-set a given Aplicacao
6503    /// resolves to — the validator's per-edge dedup `HashSet` seed
6504    /// reading the raw slot while the peer sync-cycle adjacency-list
6505    /// seed read an operator-resolved slot would silently split the
6506    /// build-time edge-set gate from the runtime deadlock-detection
6507    /// gate, a four-consumer split at the validator, the cycle
6508    /// detector, the CNP emitter, and the graph printer far from
6509    /// the source `caixa.lisp` with no field naming the edge-set-
6510    /// drift root cause. Lifting the resolution rule to a typed method on the
6511    /// substrate primitive means every downstream consumer of the
6512    /// Aplicacao's per-`:contratos` edge-list surface reaches for
6513    /// exactly one typed dispatch — the resolver's accept-set
6514    /// migrates as a unit on any future axis addition.
6515    ///
6516    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
6517    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6518    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6519    /// static-child-list `Vec`-carry axis, to the M3
6520    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6521    /// on the peer per-`:placement` distribution-target-list `Vec`-
6522    /// carry axis, and to the immediately-adjacent sibling M3
6523    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
6524    /// the peer per-`:membros` node-list `Vec`-carry axis — the
6525    /// per-`:contratos` edge-list accessor is the natural pair of
6526    /// the per-`:membros` node-list accessor (graph edges over graph
6527    /// nodes; every graph-shaped consumer reads both). Same "one
6528    /// typed dispatch on the substrate primitive, thin projections
6529    /// at each consumer" discipline. The last remaining `Vec`-carry
6530    /// axis still unlifted at the time of this lift —
6531    /// [`crate::UpgradeFromEntry::instructions`]
6532    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
6533    /// list) — inherits this accessor's discipline as future
6534    /// compounding runs migrate its consumers onto the shared slice-
6535    /// return shape. Second `&[T]`-return accessor on the top-level
6536    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
6537    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
6538    /// `:contratos` are the two `Vec` fields on the outer typed
6539    /// composition view — `:politicas`, `:placement`, `:entrada` are
6540    /// scalar/option-shaped and already route through their per-slot
6541    /// accessor families). Named `contratos()` to match the storage
6542    /// field's name verbatim and the tatara-lisp author-surface term
6543    /// (`:contratos`) the field's own docstring already carries; the
6544    /// accessor's identity maps onto the canonical MESH-COMPOSITION
6545    /// §III.1 vocabulary the slot's docstring already reaches for.
6546    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
6547    /// every downstream consumer of the contract list treats it as a
6548    /// read-only sequence — the slice-view is the narrowest borrow
6549    /// that supports every present + roadmapped consumer
6550    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6551    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6552    /// the typed view reaches for (the storage-side `Vec` remains
6553    /// reachable through the `pub contratos` field for the mutation-
6554    /// carrying serde round-trip and per-test fixture-mutation paths).
6555    #[must_use]
6556    pub const fn contratos(&self) -> &[WitContract] {
6557        self.contratos.as_slice()
6558    }
6559
6560    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
6561    /// per-Aplicacao mesh-policy composite-reference accessor every
6562    /// per-Aplicacao policy-block reader keys off — returns the author-
6563    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
6564    /// reference over the same backing storage the raw `&self.politicas`
6565    /// field access borrows from.
6566    ///
6567    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
6568    /// mesh-policy composite — the load-bearing container of every
6569    /// mesh-level operational-policy axis every downstream mesh-artifact
6570    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
6571    /// mesh-policy overlay is the single typed surface a
6572    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
6573    /// from). Every per-`:politicas` axis threads through a lifted
6574    /// per-slot accessor on the [`MeshPolicy`] type: the
6575    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
6576    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
6577    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
6578    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
6579    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
6580    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
6581    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
6582    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
6583    /// accessor. Every downstream consumer that reaches for a policy
6584    /// axis first passes through this outer accessor onto the composite
6585    /// and then dispatches onto the per-axis accessor — the two-level
6586    /// dispatch means every per-`:politicas` reader now routes through
6587    /// a typed dispatch on the substrate primitive at both altitudes.
6588    ///
6589    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
6590    /// accessed inline at four production sites — the
6591    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
6592    /// &self.politicas;` traversal seed (which drives every per-axis
6593    /// zero-floor + upper-cap + canonical-form bracket dispatch through
6594    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
6595    /// `p.rate_limit()` on the axis-level lifted accessors), the
6596    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
6597    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
6598    /// chain (which drives every per-`(:de, :para)` CNP
6599    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
6600    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
6601    /// timeout + retry overlay emitter's paired
6602    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
6603    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
6604    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
6605    /// open-coded outer-field accesses that expressed no compile-time
6606    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
6607    /// future extension of the `:politicas` outer axis to a richer
6608    /// author surface (a per-cluster policy overlay the operator pins
6609    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
6610    /// §V federation roadmap acknowledges, a per-tenant policy-alias
6611    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6612    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6613    /// policy-composite derivation the future adaptive-placement engine
6614    /// computes from a per-cluster load-topology reader, a promotion of
6615    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
6616    /// partition once virtual-actor-style dynamic-mesh-policy
6617    /// composition comes into typed scope) would have had to be threaded
6618    /// through all four open-coded copies in lockstep or one consumer
6619    /// would silently disagree with the peers on which mesh-policy
6620    /// composite a given Aplicacao resolves to — the validator's
6621    /// per-axis bracket-dispatch seed reading the raw slot while the
6622    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
6623    /// would silently split the build-time policy-shape gate from the
6624    /// runtime CNP-emission gate, a four-consumer split at the
6625    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
6626    /// the source `caixa.lisp` with no field naming the policy-drift
6627    /// root cause. Lifting the resolution rule to a typed method on the
6628    /// substrate primitive means every downstream consumer of the
6629    /// Aplicacao's per-`:politicas` mesh-policy composite surface
6630    /// reaches for exactly one typed dispatch — the resolver's accept-
6631    /// set migrates as a unit on any future axis addition.
6632    ///
6633    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
6634    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
6635    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6636    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
6637    /// close the two `Vec`-carry axes on the outer typed composition
6638    /// view; the outer `:politicas` composite-reference axis is the
6639    /// natural pair to the paired outer `Vec`-carry accessors on the
6640    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
6641    /// emitter reads all four axes as one unit (graph nodes + graph
6642    /// edges + mesh policy + placement pool). Peer to the same
6643    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
6644    /// slot: every M2 `SupervisorSpec`-scoped composite reader
6645    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
6646    /// `restart_window`, `children`) already routes through the M2
6647    /// `SupervisorSpec` accessor family — this lift extends the same
6648    /// "one typed dispatch on the substrate primitive at the outer
6649    /// composition altitude" discipline to the M3 mesh-slot
6650    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
6651    /// remaining peer outer-composite axes still unlifted at the time
6652    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
6653    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
6654    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
6655    /// inherit this accessor's discipline as future compounding runs
6656    /// migrate their consumers onto the shared reference-return shape.
6657    /// Named `politicas()` to match the storage field's name verbatim
6658    /// and the tatara-lisp author-surface term (`:politicas`) the
6659    /// field's own docstring already carries; the accessor's identity
6660    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
6661    /// slot's docstring already reaches for. Returns `&MeshPolicy`
6662    /// (not the owning composite by copy or clone) because every
6663    /// downstream consumer of the mesh-policy composite treats it as a
6664    /// read-only per-axis dispatch source — the reference-view is the
6665    /// narrowest borrow that supports every present + roadmapped
6666    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
6667    /// emptiness probe) without cloning the composite through every
6668    /// consumer's fast path.
6669    #[must_use]
6670    pub const fn politicas(&self) -> &MeshPolicy {
6671        &self.politicas
6672    }
6673
6674    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
6675    /// per-Aplicacao distribution-composite composite-reference accessor
6676    /// every per-Aplicacao placement-block reader keys off — returns the
6677    /// author-declared `:placement` composite verbatim as a `&Placement`
6678    /// reference over the same backing storage the raw `&self.placement`
6679    /// field access borrows from.
6680    ///
6681    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
6682    /// distribution composite — the load-bearing container of every
6683    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
6684    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
6685    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
6686    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
6687    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
6688    /// `:affinity` hint). Every per-`:placement` axis threads through a
6689    /// lifted per-slot accessor on the [`Placement`] type: the
6690    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
6691    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
6692    /// per-cluster distribution-target slice-return accessor, the
6693    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
6694    /// optional-scalar accessor, and the [`Placement::shard_key`]
6695    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
6696    /// downstream consumer that reaches for a placement axis first passes
6697    /// through this outer accessor onto the composite and then dispatches
6698    /// onto the per-axis accessor — the two-level dispatch means every
6699    /// per-`:placement` reader now routes through a typed dispatch on the
6700    /// substrate primitive at both altitudes.
6701    ///
6702    /// Prior to this lift the `.placement` `Placement` composite was
6703    /// accessed inline at three production sites — the
6704    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
6705    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
6706    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
6707    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
6708    /// cluster `.clusters()` validate-loop traversal head, the per-
6709    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
6710    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
6711    /// paired with the shape-gate cascade's `.shard_key()` /
6712    /// `.estrategia()` diagnostic-carry pair), the
6713    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
6714    /// per-entry placement-block emitter's outer
6715    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
6716    /// seed (which fans onto every per-cluster `programs[]` entry as a
6717    /// self-describing distribution overlay the aggregator filters by),
6718    /// and the `feira app graph` per-Aplicacao print line's paired
6719    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
6720    /// then-inner-accessor chains (which drive the human-readable
6721    /// distribution summary of the typed Aplicacao view) — three open-
6722    /// coded outer-field accesses that expressed no compile-time link
6723    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
6724    /// extension of the `:placement` outer axis to a richer author surface
6725    /// (a per-cluster placement overlay the operator pins through a
6726    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
6727    /// federation roadmap acknowledges, a per-tenant placement-alias
6728    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6729    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6730    /// placement-composite derivation the future M5 adaptive-placement
6731    /// engine computes from a per-cluster load-topology reader, a
6732    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
6733    /// partition once Orleans-style virtual-actor dynamic-placement comes
6734    /// into typed scope) would have had to be threaded through all three
6735    /// open-coded copies in lockstep or one consumer would silently
6736    /// disagree with the peers on which placement composite a given
6737    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
6738    /// seed reading the raw slot while the peer
6739    /// `programs_for_aplicacao` emitter read an operator-resolved slot
6740    /// would silently split the build-time distribution-shape gate from
6741    /// the runtime programs.yaml distribution-annotation gate, a three-
6742    /// consumer split at the validator, the programs.yaml emitter, and
6743    /// the `feira app graph` printer far from the source `caixa.lisp`
6744    /// with no field naming the placement-drift root cause. Lifting the
6745    /// resolution rule to a typed method on the substrate primitive
6746    /// means every downstream consumer of the Aplicacao's per-
6747    /// `:placement` distribution composite surface reaches for exactly
6748    /// one typed dispatch — the resolver's accept-set migrates as a unit
6749    /// on any future axis addition.
6750    ///
6751    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
6752    /// `AplicacaoSpec` type itself — sibling to the seed
6753    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
6754    /// composite-reference accessor on the peer per-`:politicas` outer-
6755    /// composite axis, and to the paired slice-return accessors
6756    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6757    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
6758    /// the two `Vec`-carry axes on the outer typed composition view; the
6759    /// outer `:placement` composite-reference axis is the natural pair
6760    /// to the peer `:politicas` composite-reference axis on the two
6761    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
6762    /// how-to-run policy overlay, `:placement` carries the where-to-run
6763    /// distribution composite — every whole-Aplicacao mesh-artifact
6764    /// emitter reads both as one unit). Same "one typed dispatch on the
6765    /// substrate primitive, thin projections at each consumer"
6766    /// discipline the peer per-`:politicas` composite-reference axis
6767    /// already routes through. The one remaining outer-composite axis
6768    /// still unlifted at the time of this lift —
6769    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
6770    /// external-gateway composite) — inherits this accessor's discipline
6771    /// as the next compounding run migrates its consumers onto the shared
6772    /// reference-return shape, closing the outer-composite altitude on
6773    /// every M3 mesh-slot axis. Named `placement()` to match the storage
6774    /// field's name verbatim and the tatara-lisp author-surface term
6775    /// (`:placement`) the field's own docstring already carries; the
6776    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
6777    /// vocabulary the slot's docstring already reaches for. Returns
6778    /// `&Placement` (not the owning composite by copy or clone) because
6779    /// every downstream consumer of the placement composite treats it as
6780    /// a read-only per-axis dispatch source — the reference-view is the
6781    /// narrowest borrow that supports every present + roadmapped consumer
6782    /// (per-axis accessor dispatch, serde composite-serialization) without
6783    /// cloning the composite through every consumer's fast path.
6784    #[must_use]
6785    pub const fn placement(&self) -> &Placement {
6786        &self.placement
6787    }
6788
6789    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
6790    /// per-Aplicacao external-gateway composite optional-composite-
6791    /// reference accessor every per-Aplicacao gateway-block reader
6792    /// keys off — returns the author-declared `:entrada` composite
6793    /// verbatim as an `Option<&Entrada>` reference over the same
6794    /// backing storage the raw `self.entrada.as_ref()` field access
6795    /// borrows from, with `None` naming the internal-only mesh shape
6796    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
6797    /// gateway_routes emitter treats as "emit nothing" and the peer
6798    /// `feira app graph` printer treats as "internal-only mesh").
6799    ///
6800    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
6801    /// external-gateway composite — the load-bearing container of
6802    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
6803    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
6804    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
6805    /// hostname axis, §III.4 for the `:para` destination-Servico
6806    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
6807    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
6808    /// axis threads through a lifted per-slot accessor on the
6809    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
6810    /// Gateway-API `Listener.hostname` scalar accessor, the paired
6811    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
6812    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
6813    /// backendRefs destination-Servico scalar accessor, the
6814    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
6815    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
6816    /// scalar accessor. Every downstream consumer that reaches for
6817    /// an entrada axis first passes through this outer accessor onto
6818    /// the composite and then dispatches onto the per-axis accessor
6819    /// — the two-level dispatch means every per-`:entrada` reader
6820    /// now routes through a typed dispatch on the substrate primitive
6821    /// at both altitudes.
6822    ///
6823    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
6824    /// was accessed inline at four production sites — the
6825    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
6826    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
6827    /// (which drives every per-axis refusal on the composite: the
6828    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
6829    /// `EntradaMemberMissing` membership lookup against the
6830    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
6831    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
6832    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
6833    /// per-path shape gate on each entry of `e.paths`), the
6834    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
6835    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
6836    /// composite-projection seed (which drives the destination-
6837    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
6838    /// backendRefs port emitter fans on), the
6839    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
6840    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
6841    /// early-return seed (which drives the "no `:entrada` ⇒ no
6842    /// external artifacts" partition on the whole-Aplicacao Gateway-
6843    /// API emitter's fan-out), and the `feira app graph` per-
6844    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
6845    /// external-gateway summary emitter (which drives the human-
6846    /// readable `entrada: host → para (paths=…, port=…)` /
6847    /// `entrada: (internal-only mesh)` partition on the typed
6848    /// Aplicacao view) — four open-coded outer-field accesses that
6849    /// expressed no compile-time link back to the typed slot at the
6850    /// [`AplicacaoSpec`] altitude. A future extension of the
6851    /// `:entrada` outer axis to a richer author surface (a
6852    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
6853    /// at admission time so an Aplicacao can expose a public-web +
6854    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
6855    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
6856    /// operator can pin a per-cluster hostname override without
6857    /// re-authoring the `caixa.lisp`, a promotion of the plain
6858    /// `Option<Entrada>` to a richer `{single, multi}` partition once
6859    /// the multi-`:entrada` roadmap lands) would have had to be
6860    /// threaded through all four open-coded copies in lockstep or one
6861    /// consumer would silently disagree with the peers on which
6862    /// entrada composite a given Aplicacao resolves to — the
6863    /// validator's per-axis bracket-dispatch seed reading the raw
6864    /// slot while the peer `gateway_routes` emitter read an
6865    /// operator-resolved slot would silently split the build-time
6866    /// gateway-shape gate from the runtime Gateway + HTTPRoute
6867    /// emission gate, a four-consumer split at the validator, the
6868    /// `port_for_destination` L4-port resolver, the `gateway_routes`
6869    /// emitter, and the `feira app graph` printer far from the
6870    /// source `caixa.lisp` with no field naming the entrada-drift
6871    /// root cause. Lifting the resolution rule to a typed method on
6872    /// the substrate primitive means every downstream consumer of
6873    /// the Aplicacao's per-`:entrada` external-gateway composite
6874    /// surface reaches for exactly one typed dispatch — the
6875    /// resolver's accept-set migrates as a unit on any future axis
6876    /// addition.
6877    ///
6878    /// Third and final `&Composite`-return accessor on the top-level
6879    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
6880    /// unlifted outer-composite axis on the outer typed composition
6881    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
6882    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
6883    /// accessor on the per-`:politicas` outer-composite axis and to
6884    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
6885    /// distribution-composite composite-reference accessor on the
6886    /// per-`:placement` outer-composite axis; extends the outer-
6887    /// composite reference-return discipline the two peers already
6888    /// route through onto the last unlifted per-`AplicacaoSpec`
6889    /// outer-composite axis. The `:entrada` outer-composite axis is
6890    /// the natural pair to the two peer outer-composite axes on the
6891    /// three operationally-symmetric M3 mesh-slot outer composites
6892    /// (`:politicas` carries the how-to-run policy overlay,
6893    /// `:placement` carries the where-to-run distribution composite,
6894    /// `:entrada` carries the who-can-reach-it external-gateway
6895    /// composite — every whole-Aplicacao mesh-artifact emitter reads
6896    /// all three as one unit). Same "one typed dispatch on the
6897    /// substrate primitive, thin projections at each consumer"
6898    /// discipline the peer outer-composite axes already route through.
6899    /// Named `entrada()` to match the storage field's name verbatim
6900    /// and the tatara-lisp author-surface term (`:entrada`) the
6901    /// field's own docstring already carries; the accessor's
6902    /// identity maps onto the canonical MESH-COMPOSITION §III.4
6903    /// vocabulary the slot's docstring already reaches for. Returns
6904    /// `Option<&Entrada>` (not the owning composite by copy or
6905    /// clone) because every downstream consumer of the entrada
6906    /// composite treats it as a read-only per-axis dispatch source
6907    /// — the reference-view is the narrowest borrow that supports
6908    /// every present + roadmapped consumer (per-axis accessor
6909    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
6910    /// port-fallback projection, early-return partition on the
6911    /// `None` arm) without cloning the composite through every
6912    /// consumer's fast path. The `Option` half of the return-type
6913    /// preserves the load-bearing "author-omitted `:entrada` ⇒
6914    /// internal-only mesh" partition (not a default composite the
6915    /// downstream must reject on emptiness) — the accessor projects
6916    /// the raw `Option<Entrada>` slot's presence bit through the
6917    /// reference-return unchanged.
6918    #[must_use]
6919    pub const fn entrada(&self) -> Option<&Entrada> {
6920        self.entrada.as_ref()
6921    }
6922
6923    /// Validate the typed shape:
6924    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
6925    ///     and a non-empty `:versao`; no two entries share the same
6926    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
6927    ///     not a multiset)
6928    ///   - every `:contratos` :de + :para must be in `:membros`
6929    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
6930    ///     contract is an inter-Servico edge, so a Servico contracting
6931    ///     with itself is a build error under every WIT shape
6932    ///     (MESH-COMPOSITION §III.1)
6933    ///   - no two `:contratos` entries agree on
6934    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
6935    ///     edges are a set, not a multiset (peer of the `:membros` /
6936    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
6937    ///   - `:entrada :para` must be in `:membros`
6938    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
6939    ///     `:placement Replicated`/`SingleNode` must NOT declare
6940    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
6941    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
6942    ///     between strategy and shard-key is symmetric: every validated
6943    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
6944    ///     Sharded`
6945    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
6946    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
6947    ///     the shard pool (MESH-COMPOSITION §III.1)
6948    ///   - every `:clusters` entry is non-empty and unique
6949    ///   - `:placement :affinity`, when set, is non-empty
6950    ///   - the synchronous-`:contratos` subgraph is acyclic
6951    ///     (MESH-COMPOSITION §III.3)
6952    ///   - every declared `:politicas` value is operationally meaningful
6953    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
6954    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
6955    ///     omit the field instead to express "no policy on this axis")
6956    pub fn validate(&self) -> Result<(), AplicacaoError> {
6957        self.validate_membros()?;
6958        let names: std::collections::HashSet<&str> =
6959            self.membros().iter().map(Membro::nome).collect();
6960
6961        // Identity key for the typed-edge duplicate gate below: every
6962        // field that distinguishes one contract from another. Two
6963        // entries that agree on all six are *the same edge declared
6964        // twice*, the typed-graph analogue of duplicate `:membros` /
6965        // `:placement :clusters` / `:entrada :paths` entries (which
6966        // are already build errors at this layer). Rejecting it at the
6967        // validate gate closes a renderer-side footgun: caixa-mesh's
6968        // `cilium_network_policies` keys each emitted policy by
6969        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
6970        // (de, para) and identical payload would land as two K8s
6971        // objects with colliding `metadata.name`, rejected at apply
6972        // time far from the source caixa.lisp.
6973        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
6974            std::collections::HashSet::new();
6975        for c in self.contratos() {
6976            // Per-axis value-shape gate on every `:contratos` name
6977            // reference, before any graph-membership lookup. Empty +
6978            // DNS-1123-malformed `:de`/`:para` values silently fell
6979            // through to `ContratoMemberMissing` at the lookup arm
6980            // because every `:membros :caixa` is shape-validated
6981            // (3f9d7a0), so the `names` set structurally cannot contain
6982            // an empty / malformed string and the membership-lookup
6983            // diagnostic always misframed the root cause as
6984            // "this caixa is not in `:membros`". The shape gate runs
6985            // ahead of the lookup so structurally-impossible-to-match
6986            // inputs route through the narrower self-locating
6987            // diagnostic, preserving the legitimate "well-shaped
6988            // phantom reference" arm. `:de` runs before `:para` per
6989            // the canonical edge-direction order the existing
6990            // membership lookup, self-edge check, target dispatch,
6991            // and diagnostic strings already use.
6992            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
6993            // + the paired [`AplicacaoError::ContratoMemberMissing`]
6994            // diagnostic's `caixa:` carrier through the lifted
6995            // [`WitContract::source`] / [`WitContract::destination`]
6996            // scalar accessors rather than the raw `&c.de` / `&c.para`
6997            // `&String`-borrow arg site + the raw `c.de.clone()` /
6998            // `c.para.clone()` field-access `String`-carry sites — the
6999            // last unlifted per-`:contratos` raw-field-access sites in
7000            // the M3 mesh-slot validator's per-edge per-arm shape-gate
7001            // arg + phantom-name diagnostic wrap-envelope emit surface.
7002            // `c.source()` is byte-identical to `&c.de` (pinned by the
7003            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
7004            // + `wit_contract_source_borrows_from_de_storage` accessor
7005            // tests) and `c.destination()` is byte-identical to `&c.para`
7006            // (pinned by the sibling
7007            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
7008            // + `wit_contract_destination_borrows_from_para_storage`
7009            // accessor tests) — so a future rebrand of either underlying
7010            // storage flows through the accessor's one body without a
7011            // coordinated per-consumer rewrite across the M3 mesh
7012            // validator's per-edge shape-gate + phantom-name refusal
7013            // arms. Peer of the sibling per-`:contratos` self-loop
7014            // arm's `.source().to_string()` / `.world_ref().to_string()`
7015            // `String`-carry sites the earlier convergence lifted onto
7016            // the same accessor pair.
7017            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
7018            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
7019            if !names.contains(c.source()) {
7020                return Err(AplicacaoError::ContratoMemberMissing {
7021                    caixa: c.source().to_string(),
7022                });
7023            }
7024            if !names.contains(c.destination()) {
7025                return Err(AplicacaoError::ContratoMemberMissing {
7026                    caixa: c.destination().to_string(),
7027                });
7028            }
7029            // A `:contratos` entry is an *inter*-Servico contract
7030            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
7031            // typed edge between two distinct graph nodes. An edge whose
7032            // `:de` equals its `:para` is a Servico contracting with
7033            // itself — a degenerate edge under every WIT shape. The
7034            // synchronous shapes were caught only incidentally, and with
7035            // a misleading diagnostic: `detect_sync_cycles` reported
7036            // `cart → cart` as a `ContratoCycle` whose path is
7037            // `["cart", "cart"]` — framing a self-edge as a multi-node
7038            // deadlock. The pub-sub shape slipped through entirely
7039            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
7040            // `nats:pub-sub` edge from a member to itself silently
7041            // validated, then rendered a `CiliumNetworkPolicy` whose
7042            // endpointSelector and fromEndpoints both name the same
7043            // program — a self-allow rule that is a no-op, since
7044            // intra-pod traffic never traverses the mesh). A self-edge's
7045            // runtime meaning is an in-process call, which doesn't go
7046            // through the mesh at all, so no `:contratos` edge can carry
7047            // it. Firing the gate before the `:wit`/`target()` shape
7048            // checks means the structural "this edge can't exist" error
7049            // precedes the narrower payload-shape diagnostics, and shape-
7050            // agnostically covers all four `WitTarget` arms (HTTP / Store
7051            // / Capability / PubSub) at one point — closing the pub-sub
7052            // hole and replacing the misleading cycle diagnostic in one
7053            // gate. Peer of the duplicate-`:contratos` / duplicate-
7054            // `:membros` set gates: both reject a structurally
7055            // ill-formed graph at the typed surface, before the renderer
7056            // emits a K8s object that fails or no-ops far from the source
7057            // caixa.lisp.
7058            // Route the per-`:contratos` structural self-edge probe
7059            // through the lifted [`WitContract::is_self_loop`] typed
7060            // predicate rather than the raw `c.de == c.para` field-
7061            // equality check — the one production consumer of the per-
7062            // `:contratos` caller-equals-callee endpoint-equality axis
7063            // now keys off exactly one typed dispatch on the substrate
7064            // primitive, so any future rebrand of the axis (an M4-typed-
7065            // caller enum whose identity comparison rule the predicate
7066            // could route through, a per-cluster caller/callee-alias
7067            // table the M4 CR materializer resolves per-CR before the
7068            // equality probe) migrates as a single caixa-core edit
7069            // rather than a coordinated rewrite of the gate + every
7070            // downstream self-edge consumer. Peer of the sibling
7071            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
7072            // [`WitContract::is_store`] shape-predicate routing on the
7073            // `:wit` world-ref axis, extended onto the per-edge
7074            // endpoint-equality axis.
7075            //
7076            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
7077            // diagnostic's `caixa:` / `wit:` carriers through the
7078            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
7079            // scalar accessors rather than the raw `c.de.clone()` /
7080            // `c.wit.clone()` field-access `String`-carry sites — the
7081            // last unlifted per-`:contratos` raw-field-access
7082            // `.clone()` sites in the M3 mesh-slot validator's self-
7083            // edge refusal arm. `.source().to_string()` is byte-
7084            // identical to `.de.clone()` (pinned by the sibling
7085            // `source_returns_de_byte_equal_across_permutations` accessor
7086            // test), and `.world_ref().to_string()` is byte-identical
7087            // to `.wit.clone()` (pinned by the sibling
7088            // `world_ref_returns_wit_byte_equal_across_permutations`
7089            // accessor test) — so a future rebrand of either underlying
7090            // storage flows through the accessor's one body without a
7091            // coordinated per-consumer rewrite across the M3 mesh
7092            // validator.
7093            if c.is_self_loop() {
7094                return Err(AplicacaoError::ContratoSelfLoop {
7095                    caixa: c.source().to_string(),
7096                    wit: c.world_ref().to_string(),
7097                });
7098            }
7099            if c.world_ref().is_empty() {
7100                let (de, para) = c.edge_pair();
7101                return Err(AplicacaoError::EmptyWit { de, para });
7102            }
7103            // Shape ↔ target consistency — surfaces "HTTP wit without
7104            // :endpoint", "NATS wit with :endpoint set", etc. as named
7105            // build errors instead of silent renderer drops. Threaded
7106            // through the duplicate-edge diagnostic below (via
7107            // [`WitTarget::label`]) so the "which typed target arm did
7108            // the duplicate carry" question is answered by the typed
7109            // enum's variant discriminator, not by re-probing the raw
7110            // `Option<String>` payload fields.
7111            let target_view = c.target()?;
7112            // Contract identity: (de, para, wit, endpoint, subject, slot).
7113            // Two contracts that match on all six are the same typed edge
7114            // declared twice — author error, not a legitimate variant of
7115            // "same caller-callee pair, different payload" (e.g.
7116            // cart→catalog at /products vs /search), which keeps distinct
7117            // identity keys via the differing endpoint payloads.
7118            //
7119            // Route the six-axis dedup key through the lifted
7120            // [`WitContract::identity`] composite-projection accessor
7121            // rather than the inline six-tuple builder — the two
7122            // substrate primitives on the per-`:contratos` identity axis
7123            // (the [`ContratoIdentity`] type alias's six axes, this
7124            // dedup-key's six tuple arms) now migrate as a unit on any
7125            // future axis addition. Peer of the sibling per-`:contratos`
7126            // composite-projection [`WitContract::edge_pair`] /
7127            // [`WitContract::edge_triple`] accessors on the
7128            // caller-callee / caller-callee-wit prefix axes; extends
7129            // the discipline onto the full-identity axis that carries
7130            // the three payload-shape arms too.
7131            let key = c.identity();
7132            crate::render::insert_first_seen(&mut seen_contracts, key, || {
7133                // Route the per-`:contratos` duplicate-gate diagnostic's
7134                // `(de, para, wit)` triple through the lifted
7135                // [`WitContract::edge_triple`] typed accessor rather
7136                // than pairing `edge_pair()` for the `(de, para)` prefix
7137                // with a raw `c.wit.clone()` for the `wit:` tail — the
7138                // paired-with-raw-field-access shape was the last
7139                // per-`:contratos` diagnostic constructor bypassing the
7140                // substrate-primitive composite projection, sibling to
7141                // the eight [`AplicacaoError::Contrato*`] triple-
7142                // carrying constructors [`WitContract::target`]'s edge
7143                // closure feeds through the same accessor.
7144                let (de, para, wit) = c.edge_triple();
7145                AplicacaoError::ContratoDuplicate {
7146                    de,
7147                    para,
7148                    wit,
7149                    target: target_view.label(),
7150                }
7151            })?;
7152        }
7153
7154        // Cycles in the synchronous-edge subgraph are build errors
7155        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
7156        // are "acyclic by construction" because the publisher fires
7157        // and forgets, so no caller blocks on a downstream that loops
7158        // back to it.
7159        self.detect_sync_cycles()?;
7160
7161        if let Some(e) = self.entrada() {
7162            // Route the per-`:entrada` composite-reference read
7163            // through the lifted [`AplicacaoSpec::entrada`] accessor
7164            // rather than the raw `&self.entrada` field access — the
7165            // shape-and-membership gate's traversal head is now the
7166            // canonical read-side surface every per-Aplicacao entrada
7167            // consumer routes through, closing the fourth of four
7168            // open-coded outer-field accesses on the per-`:entrada`
7169            // outer-composite axis.
7170            //
7171            // Shape gate on `:entrada :para` runs ahead of the
7172            // membership lookup. Every `:membros :caixa` past
7173            // `validate_membro_caixa` is a valid DNS-1123 label
7174            // (3f9d7a0), so the `names` set structurally cannot
7175            // contain an empty / malformed string and the membership-
7176            // lookup diagnostic always misframed the root cause as
7177            // "this caixa is not in `:membros`". The shape gate
7178            // routes structurally-impossible-to-match inputs through
7179            // the narrower self-locating diagnostic, preserving the
7180            // legitimate "well-shaped phantom reference" arm — the
7181            // same trajectory the peer `:membros :caixa` (3f9d7a0),
7182            // `:placement :clusters` (6c8c00b), and `:contratos :de`
7183            // / `:para` (8d5af6b) axes already follow. This closes
7184            // the fourth and last Aplicacao-level Servico-name
7185            // reference axis on the canonical DNS-1123 floor.
7186            // Route the per-`:entrada :para` byte-string reads through
7187            // the lifted [`Entrada::destination`] accessor rather than
7188            // the raw `e.para` field access — the three
7189            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
7190            // (shape-gate `validate_entrada_para` arg, membership
7191            // lookup, `EntradaMemberMissing` diagnostic carry) now key
7192            // off exactly one typed dispatch on the substrate
7193            // primitive, closing the last unlifted per-`:entrada :para`
7194            // raw-field-access axis on the M3 mesh-slot validator.
7195            // The `.destination().to_string()` at the diagnostic site
7196            // is byte-identical to `.para.clone()` — pinned by the
7197            // sibling `destination_returns_entrada_para_byte_equal` +
7198            // `destination_borrows_from_entrada_para_storage` accessor
7199            // tests — so a future rebrand of the underlying `:para`
7200            // storage (a lift from `String` to a typed
7201            // `ServicoName(String)` newtype, a per-Aplicacao interning
7202            // arena the M4 CR materializer authors, a
7203            // `smol_str::SmolStr` inline-buffer swap) flows through
7204            // the accessor's one body without a coordinated
7205            // per-consumer rewrite across the M3 mesh validator.
7206            validate_entrada_para(e.destination())?;
7207            if !names.contains(e.destination()) {
7208                return Err(AplicacaoError::EntradaMemberMissing {
7209                    para: e.destination().to_string(),
7210                });
7211            }
7212            // Route the per-`:entrada :host` byte-string reads through
7213            // the lifted [`Entrada::hostname`] accessor rather than
7214            // the raw `e.host` field access — the emptiness gate and
7215            // the shape-gate `validate_entrada_host` arg now key off
7216            // exactly one typed dispatch on the substrate primitive,
7217            // closing the last unlifted per-`:entrada :host` raw-
7218            // field-access axis on the M3 mesh-slot validator. Peer
7219            // of the sibling per-`:entrada :para` convergence above
7220            // and pinned by the existing
7221            // `hostname_returns_entrada_host_byte_equal` +
7222            // `hostnames_returns_singleton_of_hostname_accessor`
7223            // accessor tests, so any future
7224            // Gateway-API-shaped host renormalization (a wildcard-
7225            // label lift, a trailing-`.` FQDN substitution, an IDNA
7226            // Punycode round-trip the SNI fan-out overlay authors)
7227            // flows through the accessor's one body without a
7228            // coordinated per-consumer rewrite across the M3 mesh
7229            // validator.
7230            if e.hostname().is_empty() {
7231                return Err(AplicacaoError::EmptyEntradaHost);
7232            }
7233            // The `:host` lands verbatim as a K8s Gateway API v1
7234            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
7235            // both apiserver-validated against the same restrictive
7236            // pattern: lowercase RFC 1123 DNS subdomain, optional
7237            // single leading wildcard label (`*.`), max length 253,
7238            // per-label max length 63, no IP literals, no scheme,
7239            // no port. Until this gate landed `validate()` only
7240            // refused the empty string (`EmptyEntradaHost`); a
7241            // structurally invalid hostname (`"https://example.com"`,
7242            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
7243            // `"_underscored.example.com"`, `"FOO.example.com"`,
7244            // `"checkout.quero.cloud."`) silently passed validate
7245            // and the apiserver `field is invalid` error surfaced at
7246            // `kubectl apply` time, far from the source caixa.lisp.
7247            // Lifting the gate to caixa-build time mirrors the
7248            // `:entrada :paths` value-shape trajectory (eb3456d) and
7249            // closes the last unstructured `:entrada` axis.
7250            validate_entrada_host(e.hostname())?;
7251            // Structural-floor gate on `:entrada :port`: every
7252            // validated `Entrada::port` past this gate lies in
7253            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
7254            // type-inferred ceiling closes the top edge, so no companion
7255            // upper-cap arm is needed here — unlike the peer capped-
7256            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
7257            // `require_positive_bounded_u32` bracket covers both edges).
7258            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
7259            // accept-set-floor const rather than the prior inline
7260            // `if e.port == 0` byte-check so a future rebrand of the
7261            // accept-set floor (a hypothetical unprivileged-only
7262            // migration lifting the floor to `1024`, a per-cluster
7263            // scoping the operator pins through a future
7264            // `:placement :port-floor` slot as the M4 typed-slot
7265            // trajectory adds it, the future
7266            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7267            // per-Aplicacao gateway resolver reaching for the same
7268            // floor) is a one-line edit on the canonical
7269            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
7270            // rewrite across the emit site + the pin test + every
7271            // future per-target renderer the substrate adds.
7272            if e.port() < SERVICO_PORT_MIN {
7273                return Err(AplicacaoError::EntradaPortZero);
7274            }
7275            // Each `:entrada :paths` entry becomes a K8s Gateway API
7276            // HTTPRoute `matches[].path.value`. The Gateway API rejects
7277            // values that don't start with `/` for `type: PathPrefix`,
7278            // and an empty value is meaningless. Surface those as build
7279            // errors (MESH-COMPOSITION §III.3) rather than apply-time
7280            // failures. Empty `:paths` itself is fine — caixa-mesh
7281            // falls back to a single `/` catch-all.
7282            let mut seen = std::collections::HashSet::new();
7283            // Route the per-entry value-shape gate's traversal head
7284            // through the lifted [`Entrada::paths`] slice accessor
7285            // rather than the raw `&e.paths` field access — the
7286            // per-Aplicacao `:entrada :paths` validate loop now keys
7287            // off the canonical raw-slot surface every downstream
7288            // per-`:entrada` path-list consumer (the sibling
7289            // [`Entrada::resolved_paths`] fallback-applying resolver
7290            // internal reads, `feira app graph`'s per-Aplicacao entrada
7291            // summary line's `{:?}` Debug print) routes through, so any
7292            // future rebrand on the typed slot's raw-slot reader lands
7293            // at exactly one place. Same convergence discipline as the
7294            // sibling [`Placement::clusters`] (a6e18d7) reader-site
7295            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
7296            // axis.
7297            for p in e.paths() {
7298                if p.is_empty() {
7299                    return Err(AplicacaoError::EntradaPathEmpty);
7300                }
7301                if !p.starts_with('/') {
7302                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
7303                }
7304                // Per-entry value-shape gate: the path lands verbatim
7305                // as a K8s Gateway API HTTPRoute `matches[].path.value`
7306                // (caixa-mesh/src/lib.rs:498), apiserver-validated
7307                // against `maxLength: 1024` + the Gateway API webhook's
7308                // path-grammar rules (no `//`, no `/./`, no `/../`, no
7309                // query/fragment separators, no whitespace, no control
7310                // characters, no non-ASCII bytes). Until this gate
7311                // landed `validate` only refused the empty string and
7312                // missing-leading-slash (eb3456d); a structurally
7313                // invalid path (`"/api?q=1"`, `"/api#frag"`,
7314                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
7315                // 1025-byte URL-shaped slug) silently passed validate
7316                // and the failure surfaced at `kubectl apply` time as
7317                // a Gateway API webhook rejection, far from the source
7318                // caixa.lisp, with no field naming the offending
7319                // `:paths` entry. Lifting the gate to caixa-build time
7320                // mirrors the `:entrada :host` value-shape trajectory
7321                // (c7d05ec) on the sibling axis — every author surface
7322                // that emits a Gateway API field now matches the
7323                // apiserver's accepted set at validate time.
7324                validate_entrada_path(p)?;
7325                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
7326                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
7327                })?;
7328            }
7329        }
7330
7331        self.validate_placement()?;
7332
7333        self.validate_politicas()?;
7334
7335        Ok(())
7336    }
7337
7338    /// Reject `:membros` values that are operationally meaningless. The
7339    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
7340    /// every entry names a Servico that participates in the Aplicacao,
7341    /// and the rendered programs.yaml fan-out emits one entry per
7342    /// `:membros`. Three authoring footguns are closed here:
7343    ///
7344    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
7345    ///     a `programs:` entry whose `name:` is the empty string, which
7346    ///     downstream `lareira-fleet-programs` rejects at template time
7347    ///     with a non-localized error;
7348    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
7349    ///     an empty semver constraint, so the failure surfaces far from
7350    ///     the source caixa.lisp;
7351    ///   - duplicate `:caixa` names — two entries with the same name
7352    ///     produce duplicate programs.yaml entries (one silently
7353    ///     overwrites the other in the cluster's HelmRelease values), and
7354    ///     contract membership lookups against `:contratos` collapse the
7355    ///     two onto one node, masking authoring mistakes.
7356    ///
7357    /// Same value-shape discipline as `:placement :clusters` (where empty
7358    /// + duplicate cluster names are rejected) and `:entrada :paths`
7359    /// (where empty + duplicate path entries are rejected). Lifting these
7360    /// invariants to the typed surface mirrors the MESH-COMPOSITION
7361    /// §III.3 promise that the `:membros` set — the load-bearing identity
7362    /// of the application graph — is well-formed by construction.
7363    fn validate_membros(&self) -> Result<(), AplicacaoError> {
7364        if self.membros().is_empty() {
7365            return Err(AplicacaoError::NoMembros);
7366        }
7367        let mut seen = std::collections::HashSet::new();
7368        for m in self.membros() {
7369            // Route the `MembroCaixaEmpty` refusal-arm's per-member
7370            // empty-`:caixa` shape-gate through the typed
7371            // [`Membro::nome`] accessor rather than the raw `.caixa`
7372            // field access — the last un-lifted `.caixa` production-
7373            // code read site on the per-`:membros` member-caixa `:nome`
7374            // axis, sibling to the six caixa-core validator read sites
7375            // (member-set collector, per-member value-shape gate,
7376            // duplicate dedup key, cycle-detector adjacency-map seed,
7377            // self-loop gate) the 4a32abf lift already routed through
7378            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
7379            // per-`programs[]` entry-`name:` `String`-carry converge.
7380            // Prior to this converge the `MembroCaixaEmpty` refusal
7381            // arm was the solitary consumer bypassing the typed
7382            // dispatch — the same-loop iteration's very next call
7383            // `validate_membro_caixa(m.nome())` already routed through
7384            // the accessor, so an author landing an empty-`:caixa`
7385            // entry hit the accessor on the shape-gate line but
7386            // bypassed it on the emptiness line one line above. A
7387            // future extension of the `:membros :caixa` axis to a
7388            // richer author surface (a per-cluster alias table pinned
7389            // through a future `:placement`-scoped slot, a namespace-
7390            // qualified rewrite the M4 CR materializer applies per-CR,
7391            // a per-member overlay from the future `:membros
7392            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
7393            // that lands on the accessor would silently disagree
7394            // between the emptiness gate and every peer consumer —
7395            // an author-declared `:caixa "checkout"` value the
7396            // accessor rewrote to `""` under a future alias arm would
7397            // pass the raw `.is_empty()` gate here while the peer
7398            // `validate_membro_caixa(m.nome())` call one line below
7399            // (and every downstream emit-side consumer routing through
7400            // the accessor) tripped on the empty-value shape far from
7401            // this diagnostic. Pinned by the drift-detection test
7402            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
7403            // below.
7404            if m.nome().is_empty() {
7405                return Err(AplicacaoError::MembroCaixaEmpty);
7406            }
7407            // Every emitted cluster artifact's `metadata.name` derives
7408            // from a `:membros :caixa` value verbatim — the rendered
7409            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
7410            // the [`crate::LABEL_PROGRAM`] label value on every CNP
7411            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
7412            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
7413            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
7414            // `metadata.name` when the member is the `:entrada :para`
7415            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
7416            // schema enforces the DNS-1123 label rule on admission;
7417            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
7418            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
7419            // mistaken-identity slug) silently passes the prior empty-/
7420            // duplicate-only gate and the failure surfaces at `kubectl
7421            // apply` time as a `metadata.name: Invalid value` rejection,
7422            // far from the source caixa.lisp, with no field naming the
7423            // offending `:membros` entry. Lifting the gate to caixa-build
7424            // time mirrors the `:entrada :host` value-shape trajectory
7425            // (c7d05ec) on the peer axis — every author surface that
7426            // emits a K8s name now matches the apiserver's accepted set
7427            // at validate time.
7428            validate_membro_caixa(m.nome())?;
7429            // The author surface for `:versao` is the same Cargo-shaped
7430            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
7431            // `"*"`) every `:deps` entry carries — and the lacre pipeline
7432            // resolves both axes through the same
7433            // [`crate::version::parse_requirement`] entry-point. The
7434            // shared [`crate::render::require_valid_versao_requirement`]
7435            // helper brackets the empty-first + parse cascade both peer
7436            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
7437            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
7438            // route through, so drift between the three axes' accepted
7439            // requirement sets is structurally impossible and the parse-
7440            // side no-op the empty-first arm closes (semver's empty
7441            // parse yields an implicit `*`) lives in exactly one
7442            // predicate.
7443            crate::render::require_valid_versao_requirement(
7444                m.versao_requirement(),
7445                || AplicacaoError::MembroVersaoEmpty {
7446                    caixa: m.nome().to_string(),
7447                },
7448                |reason| AplicacaoError::MembroVersaoInvalid {
7449                    caixa: m.nome().to_string(),
7450                    versao: m.versao_requirement().to_string(),
7451                    reason,
7452                },
7453            )?;
7454            crate::render::insert_first_seen(&mut seen, m.nome(), || {
7455                AplicacaoError::MembroDuplicate {
7456                    caixa: m.nome().to_string(),
7457                }
7458            })?;
7459        }
7460        Ok(())
7461    }
7462
7463    /// Reject `:placement` values that are operationally meaningless or
7464    /// internally contradictory. Each strategy variant has the same
7465    /// invariants on `:clusters` (non-empty list, non-empty unique
7466    /// entries) — the §III.1 author surface is uniform on this axis,
7467    /// even though the *meaning* of the list differs by strategy
7468    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
7469    /// shard pool).
7470    ///
7471    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
7472    /// are the same authoring footgun closed for `:politicas` zero
7473    /// values and `:entrada` empty paths: the field is *declared* but
7474    /// carries no meaning, so downstream renderers either skip it
7475    /// silently (cluster-fanout drops the empty entry, no diagnostic)
7476    /// or apply it literally and fail at admission time. Lifting both
7477    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
7478    /// violation is a build error" promise.
7479    ///
7480    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
7481    /// is required exactly when `:estrategia Sharded` (hash-keyed
7482    /// distribution, Akka cluster-sharding convention, §II.4) and
7483    /// refused on `:estrategia Replicated`/`SingleNode` (where no
7484    /// hash-keyed routing axis consumes it). The partition closes the
7485    /// "I think I configured sharding" footgun where an author writes
7486    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
7487    /// the typed slot's value silently vanishes at the renderer layer
7488    /// — every validated `Placement` past this call satisfies
7489    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
7490    fn validate_placement(&self) -> Result<(), AplicacaoError> {
7491        // Every strategy needs at least one named cluster: `Replicated`
7492        // and `SingleNode` use the list as hosting/takeover candidates
7493        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
7494        // §II.1), while `Sharded` uses it as the shard pool
7495        // (Akka cluster-sharding convention — §II.4). An empty list is
7496        // meaningless under any of the three.
7497        //
7498        // Route the paired pre-flight `.is_empty()` refusal probe and
7499        // the per-cluster validate loop's traversal head through the
7500        // lifted [`Placement::clusters`] slice-return accessor rather
7501        // than the raw `self.placement.clusters` field access — the
7502        // two production consumers of the per-`:placement` cluster-
7503        // pool `Vec`-carry now key off exactly one typed dispatch on
7504        // the substrate primitive, so any future rebrand on the axis
7505        // (a per-tenant cluster-pool overlay the operator pins through
7506        // a future `:placement :clusters-overrides` slot, a per-
7507        // Aplicacao dynamic cluster-pool derivation the future M5
7508        // adaptive-placement engine computes from `:affinity` weights)
7509        // migrates as a single caixa-core edit rather than a
7510        // coordinated rewrite of the paired arms — sibling of the
7511        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
7512        // arm migration on the per-`:supervisor` static-child-list
7513        // `Vec`-carry axis.
7514        //
7515        // Route the per-`:placement` outer-composite reference read
7516        // through the lifted [`AplicacaoSpec::placement`] outer accessor
7517        // rather than the raw `&self.placement` field access — the
7518        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
7519        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
7520        // axis-level lifted accessor family) now routes through the
7521        // substrate-primitive typed dispatch at the outer composition
7522        // altitude, the same shape the peer caixa-mesh
7523        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
7524        // and the sibling `feira app graph` per-Aplicacao print line
7525        // now key off after this accessor lift.
7526        let p = self.placement();
7527        if p.clusters().is_empty() {
7528            return Err(AplicacaoError::PlacementWithoutClusters {
7529                estrategia: p.estrategia(),
7530            });
7531        }
7532        let mut seen = std::collections::HashSet::new();
7533        for c in p.clusters() {
7534            // Per-entry value-shape gate: the cluster name lands in
7535            // every K8s context / `lareira-fleet-programs` aggregator
7536            // filter / future M4 CR materializer's per-cluster axis
7537            // a validated `:clusters` entry passes through, each
7538            // enforcing the DNS-1123 label rule on admission. Same
7539            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
7540            // on the peer name axis — both axes' validated values
7541            // are guaranteed-accepted by the apiserver without
7542            // re-validation at any downstream renderer or admission
7543            // layer.
7544            validate_placement_cluster(c)?;
7545            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
7546                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
7547            })?;
7548        }
7549        // Route the per-`:placement :affinity` per-hint value-shape
7550        // gate through the typed [`Placement::affinity`] accessor rather
7551        // than the raw `&self.placement.affinity` field access — the
7552        // sole open-coded field-access site on the per-`:placement`
7553        // M3-Adaptive-compression-hint axis the accessor lift now owns.
7554        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
7555        // the accessor's `Option<&str>` return type;
7556        // [`validate_placement_affinity`]'s `&str` parameter accepts
7557        // the narrower borrow without a re-allocation, so the routing
7558        // change is byte-for-byte in the pass arm and remains
7559        // byte-for-byte in every failure diagnostic
7560        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
7561        // String` field is populated inside
7562        // [`validate_placement_affinity`] via the peer `.to_string()`
7563        // path on the same borrowed slice). Peer of the sibling
7564        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
7565        // routing through [`Placement::shard_key`] at the caixa-core
7566        // site above — extends the "read `:placement` optional-scalars
7567        // through the typed accessor" discipline to the second
7568        // `Option<String>`-shape slot on the M3 mesh-slot family.
7569        //
7570        // Per-hint value-shape gate: the `:affinity` value lands
7571        // verbatim in the M3 Adaptive compression overlay
7572        // (caixa-mesh's `placement.affinity` emission) and every
7573        // future M4 placement-engine routing axis keying off the
7574        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
7575        // selector — each enforces the DNS-1123 label rule on
7576        // admission. Same typed-shape trajectory as `:placement
7577        // :clusters` (6c8c00b) on the sibling slot and the four
7578        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
7579        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
7580        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
7581        // on the Aplicacao surface to land on the canonical
7582        // [`crate::render::is_dns_1123_label`] floor.
7583        if let Some(a) = p.affinity() {
7584            validate_placement_affinity(a)?;
7585        }
7586        match p.estrategia() {
7587            // Route the `Sharded`-arm shape-gate cascade through the
7588            // typed [`Placement::shard_key`] accessor rather than the
7589            // raw `&self.placement.shard_key` field access — one of the
7590            // two open-coded field-access sites on the per-`:placement`
7591            // Akka-cluster-sharding-key axis the accessor lift now
7592            // owns. The `Some(k)`-bound `k` narrows from `&String` to
7593            // `&str` under the accessor's `Option<&str>` return type;
7594            // `str::is_empty` and [`validate_placement_shard_key`]'s
7595            // `&str` parameter both accept the narrower borrow without
7596            // a re-allocation.
7597            PlacementStrategy::Sharded => match p.shard_key() {
7598                None => return Err(AplicacaoError::ShardedWithoutKey),
7599                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
7600                // Per-axis value-shape gate on the Akka-cluster-sharding
7601                // `:shard-key` extractor expression. The shape gate runs
7602                // after the more self-locating `ShardedKeyEmpty` arm so
7603                // a `:shard-key ""` surfaces the narrower empty
7604                // diagnostic first; every non-empty `:shard-key` past
7605                // this call is guaranteed to be a printable-ASCII
7606                // single-token reference the future M4 Akka-style
7607                // cluster-sharding reconciler can hash without
7608                // re-validating at the runtime layer. Mirrors the
7609                // payload-axis shape gates on the peer `:contratos`
7610                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
7611                // 63e18a0 / c4213a4) — each lifts the runtime parser's
7612                // intersection-floor to a caixa-build-time gate.
7613                Some(k) => validate_placement_shard_key(k)?,
7614            },
7615            // `:shard-key` is the Akka-cluster-sharding axis
7616            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
7617            // across the cluster pool. `Replicated` (active-active across
7618            // every named cluster) and `SingleNode` (Erlang/OTP
7619            // distributed-app takeover/failover, §II.1) have no hash-keyed
7620            // routing axis to consume the slot; downstream renderers
7621            // (caixa-mesh's `placement.shardKey` overlay at
7622            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
7623            // sharding reconciler) ignore `:shard-key` outside the
7624            // `Sharded` arm by construction. Until this gate landed an
7625            // author who wrote `:placement (:estrategia Replicated
7626            // :shard-key "tenantId")` (an off-by-one strategy typo, a
7627            // copy-paste from a Sharded sibling caixa, the "I think I
7628            // configured sharding" footgun) silently passed validate and
7629            // the typed slot's value vanished at the renderer layer with
7630            // no diagnostic — the canonical "declared-but-inert" footgun
7631            // the empty-:affinity / empty-shard-key / zero-:politicas /
7632            // empty-:contratos-target gates already close on every other
7633            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
7634            // Lifting the rejection to a build-time gate closes the
7635            // Sharded ↔ non-Sharded partition over the typed
7636            // `:placement` slot: every validated `Placement` past this
7637            // call has `shard_key.is_some()` iff `estrategia ==
7638            // Sharded`, structurally — the future Akka reconciler can
7639            // reach for `placement.shard_key` knowing it's `Some` exactly
7640            // when the strategy consumes it, without re-deriving the
7641            // partition from inline strategy probes.
7642            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
7643                // Route the non-`Sharded`-arm declared-but-inert refusal
7644                // through the typed [`Placement::shard_key`] accessor —
7645                // the second of the two open-coded field-access sites the
7646                // accessor lift now owns. The `Some(k)`-bound `k` narrows
7647                // from `&String` to `&str`; the `AplicacaoError::
7648                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
7649                // materializes the owned `String` via `k.to_string()`
7650                // (peer to the sibling per-Membro `String`-carry sites
7651                // 4127bb6 routed through `m.nome().to_string()` /
7652                // `m.versao_requirement().to_string()`), so the whole
7653                // `Sharded` ↔ non-`Sharded` partition on the
7654                // `:shard-key` axis now flows through the same typed
7655                // dispatch as the sibling `Sharded`-arm shape gate.
7656                if let Some(k) = p.shard_key() {
7657                    return Err(AplicacaoError::ShardKeyOnNonSharded {
7658                        estrategia: p.estrategia(),
7659                        shard_key: k.to_string(),
7660                    });
7661                }
7662            }
7663        }
7664        Ok(())
7665    }
7666
7667    /// Reject `:politicas` values that are operationally meaningless.
7668    /// Each axis is optional — omitting it expresses "no policy on this
7669    /// axis". Carrying a *zero* value for a declared axis is the bug
7670    /// this function rejects: zero is either
7671    ///
7672    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
7673    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
7674    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
7675    ///     "every Aplicacao declares :politicas :timeout (no infinite
7676    ///     blocking)", or
7677    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
7678    ///     first call; a 0-rate rate-limit denies every request).
7679    ///
7680    /// Lifting these "0 means the opposite of what you think" idioms to
7681    /// the typed Aplicacao surface as build errors mirrors the §III.3
7682    /// promise that contract drift, capability leaks, and cycles are all
7683    /// build errors — not runtime surprises.
7684    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
7685        // Route the per-`:politicas` composite-reference read through
7686        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
7687        // than the raw `&self.politicas` field access — the per-axis
7688        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
7689        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
7690        // the substrate-primitive typed dispatch at the outer
7691        // composition altitude AND at every per-axis altitude, matching
7692        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
7693        // timeout/retry-overlay emitters that already key off the same
7694        // per-axis accessor family. The four-axis fan-out is now
7695        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
7696        // `p.retries` field-access sites (co-resident with the peer
7697        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
7698        // b0e741a / 21a6c3b already lifted) now route through
7699        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
7700        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
7701        // access axis on the M3 mesh-slot family.
7702        let p = self.politicas();
7703        if let Some(t) = p.timeout() {
7704            // Zero-floor + integer-millisecond canonical-form +
7705            // upper-cap bracket on the typed `:timeout` axis. See
7706            // [`crate::render::require_positive_canonical_bounded_duration`]
7707            // for the full three-arm ordering discipline (zero-floor
7708            // strictly precedes the canonical-form arm so
7709            // `Duration::ZERO` surfaces the self-locating
7710            // `PolicyTimeoutZero` diagnostic naming the omit-axis
7711            // remediation; canonical-form strictly precedes the cap
7712            // arm so a sub-millisecond above-cap `Duration` surfaces
7713            // the more fundamental round-trip-shape diagnostic first)
7714            // and the four peer typed-`Duration` sites that now share
7715            // this canonical bracket. Every validated value lies in
7716            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
7717            // granularity — the same top-and-bottom-edge discipline
7718            // [`POLICY_RETRIES_MAX`] and
7719            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
7720            // capped-`u32` `:politicas` axes.
7721            crate::render::require_positive_canonical_bounded_duration(
7722                t,
7723                POLICY_TIMEOUT_MAX,
7724                || AplicacaoError::PolicyTimeoutZero,
7725                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
7726                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
7727            )?;
7728        }
7729        if let Some(r) = p.retries() {
7730            // Zero-floor + upper-cap bracket on the typed `:retries`
7731            // axis. See [`crate::render::require_positive_bounded_u32`]
7732            // for the ordering discipline (zero-floor arm strictly
7733            // precedes cap arm so `Some(0)` surfaces the self-locating
7734            // `PolicyRetriesZero` diagnostic with its omit-axis
7735            // remediation directly named, not the misleading
7736            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
7737            // this bracket landed the top edge ran all the way to
7738            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
7739            // Some(100_000), .. }` (or the equivalent author-surface
7740            // `(:retries 100000)` / `(:retries 4294967295)` typo
7741            // landing in the slot) silently passed validate. The
7742            // runtime substrate consuming the value (Envoy's
7743            // `retry_policy.num_retries`, the future
7744            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7745            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7746            // policy into a thundering-herd amplification vector —
7747            // the caller's one request fans out to `retries`
7748            // server-side calls per edge per traversal, multiplying
7749            // load by `(retries+1)^depth` across the
7750            // synchronous-`:contratos` subgraph at the precise moment
7751            // the substrate is already failing (transient failure is
7752            // the trigger), exactly the failure mode AWS App Mesh's
7753            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
7754            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
7755            // the sibling capped-`u32` `:politicas` axes
7756            // (`max_failures`, `rate_limit.rate`) and the peer capped-
7757            // `u32` axes in `:supervisor :max-restarts` +
7758            // `:limits :cpu`; all five now route through the same
7759            // canonical bracket helper.
7760            crate::render::require_positive_bounded_u32(
7761                r,
7762                POLICY_RETRIES_MAX,
7763                || AplicacaoError::PolicyRetriesZero,
7764                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
7765            )?;
7766        }
7767        if let Some(cb) = p.circuit_breaker() {
7768            // Zero-floor + upper-cap bracket on the typed
7769            // `:max-failures` axis. See
7770            // [`crate::render::require_positive_bounded_u32`] for the
7771            // ordering discipline (zero-floor arm strictly precedes
7772            // cap arm so `max_failures == 0` surfaces the
7773            // self-locating `PolicyBreakerZeroFailures` diagnostic
7774            // with its omit-axis remediation directly named, not the
7775            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
7776            // false` cap-arm miss). Until this bracket landed the top
7777            // edge ran all the way to `u32::MAX` and a struct-literal
7778            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
7779            // equivalent author-surface `(:max-failures 100000)` /
7780            // `(:max-failures 4294967295)` typo landing in the slot)
7781            // silently passed validate. The runtime substrate
7782            // consuming the value (Envoy's
7783            // `outlier_detection.consecutive_5xx`, the future
7784            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7785            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7786            // breaker policy into a no-op — the trip threshold is
7787            // structurally so high that no realistic
7788            // failures-per-`:window` traffic shape can reach it, the
7789            // breaker never trips, and every typed-slot consumer
7790            // emits an Envoy / Cilium L7 overlay carrying a
7791            // protection that is structurally never enforced. The
7792            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
7793            // peer with `retries` and `rate_limit.rate` on the same
7794            // helper.
7795            crate::render::require_positive_bounded_u32(
7796                cb.max_failures(),
7797                POLICY_BREAKER_MAX_FAILURES_MAX,
7798                || AplicacaoError::PolicyBreakerZeroFailures,
7799                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
7800            )?;
7801            // Zero-floor + integer-millisecond canonical-form +
7802            // upper-cap bracket on the typed `:window` axis. See
7803            // [`crate::render::require_positive_canonical_bounded_duration`]
7804            // for the full three-arm ordering discipline (peer to the
7805            // `:timeout` site immediately above); every validated
7806            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
7807            // (1ms..=1h), integer-millisecond granularity — the same
7808            // top-and-bottom-edge discipline
7809            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
7810            // duration-typed `:politicas :timeout` axis.
7811            crate::render::require_positive_canonical_bounded_duration(
7812                cb.window(),
7813                POLICY_BREAKER_WINDOW_MAX,
7814                || AplicacaoError::PolicyBreakerZeroWindow,
7815                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
7816                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
7817            )?;
7818        }
7819        if let Some(rl) = p.rate_limit() {
7820            // Zero-floor + upper-cap bracket on the typed
7821            // `:rate-limit` rate axis. See
7822            // [`crate::render::require_positive_bounded_u32`] for the
7823            // ordering discipline (zero-floor arm strictly precedes
7824            // cap arm so `rl.rate == 0` surfaces the self-locating
7825            // `PolicyRateLimitZero` diagnostic with its omit-axis
7826            // remediation directly named, not the misleading
7827            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
7828            // Until this bracket landed the top edge ran all the way
7829            // to `u32::MAX` and a struct-literal
7830            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
7831            // author-surface `(:rate-limit "4294967295/s")` /
7832            // `(:rate-limit "100000000/m")` typo landing in the slot)
7833            // silently passed validate. The runtime substrate
7834            // consuming the value (Envoy's
7835            // `local_rate_limit.token_bucket.max_tokens`, the future
7836            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7837            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7838            // rate-limit policy into a no-op limiter: the bucket
7839            // capacity is structurally so high that no realistic
7840            // per-edge traffic shape can drain it, the limiter never
7841            // trips, and every typed-slot consumer emits a "rate
7842            // declared" L7 overlay carrying enforcement that is
7843            // structurally never reached — the canonical
7844            // declared-but-inert footgun the sibling
7845            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
7846            // the peer no-op-breaker shape. The bracket set is
7847            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
7848            // `max_failures` on the same helper. The rate bracket
7849            // strictly precedes the window-canonical gate so a
7850            // structurally absurd rate magnitude surfaces the more
7851            // fundamental amplification-shape diagnostic before the
7852            // narrower codec-round-trip-shape diagnostic on `:window`.
7853            crate::render::require_positive_bounded_u32(
7854                rl.rate(),
7855                POLICY_RATE_LIMIT_MAX,
7856                || AplicacaoError::PolicyRateLimitZero,
7857                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
7858            )?;
7859            // The `:rate-limit` author surface is the canonical
7860            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
7861            // accepts exactly the three-unit set (1s/60s/3600s) the
7862            // [`rate_limit_codec::render`] formatter emits the canonical
7863            // unit suffix for. A `RateLimit` whose `:window` is anything
7864            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
7865            // programmatically (struct literals in Rust + the typed
7866            // `Duration` field) but renders to a `<n>/<k>s` fragment
7867            // (the codec's fall-through) the parser then rejects on
7868            // round-trip — silently breaking the THEORY.md §V.2.7
7869            // render-determinism contract for any consumer that
7870            // serializes-then-deserializes the typed slot. Lifting the
7871            // canonical-window invariant to a build-time gate at
7872            // `validate_politicas` makes the codec's round-trip property
7873            // a structural property of the validated typed value:
7874            // every `RateLimit` past `AplicacaoSpec::validate` has a
7875            // window the codec round-trips losslessly, so the next
7876            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
7877            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
7878            // §III.2 #3) reaches for `rate_limit.window` knowing the
7879            // value is in the codec's accepted set without re-validating
7880            // at the renderer layer. Same trajectory as c4213a4 (typed
7881            // WitContract endpoint/subject/slot value-shape gates) and
7882            // the b0c8389 :behavior + :upgrade-from script-path lifts:
7883            // the typed slot's valid set matches its codec's accepted
7884            // set, structurally.
7885            // Route the canonical-window shape-gate through the substrate
7886            // primitive [`RateLimit::canonical_unit`] rather than the free
7887            // module-private [`is_canonical_rate_limit_window`] predicate:
7888            // both projections resolve `Duration → Option<RateLimitUnit>`
7889            // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
7890            // arm on the closed-set typed enum), but the accessor is the
7891            // typed method every downstream consumer of the validated slot
7892            // ([`rate_limit_codec::render`]'s canonical arm above, the
7893            // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7894            // per-`:politicas :rate-limit` admission webhook, the future
7895            // per-`:contratos`-edge rate-limit-override overlay
7896            // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
7897            // production consumers of the canonical-unit axis (the codec
7898            // render and this validate gate) now key off exactly one typed
7899            // dispatch on the substrate primitive, so any future extension
7900            // to `canonical_unit` (a per-cluster canonical-window overlay
7901            // the operator pins through a future `:contratos :rate-limit
7902            // -unit-overrides` slot, a per-tenant unit-alias table the M4
7903            // CR materializer resolves per-CR) reaches both consumers by
7904            // construction rather than a coordinated rewrite of every
7905            // free-helper call site.
7906            if rl.canonical_unit().is_none() {
7907                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
7908                    window: rl.window(),
7909                });
7910            }
7911        }
7912        Ok(())
7913    }
7914
7915    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
7916    /// A synchronous edge is any contract whose typed [`WitTarget`] is
7917    /// `Http`, `Store`, or `Capability` — the caller blocks on the
7918    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
7919    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
7920    /// block on its subscribers, so they can never close a sync loop.
7921    ///
7922    /// Iterative DFS with three-coloring; the reported cycle is the
7923    /// path of caixa names traversed from the back-edge target around
7924    /// to itself, in declaration order. Adjacency lists and DFS roots
7925    /// are visited in `BTreeMap` key order so the diagnostic is
7926    /// deterministic across runs.
7927    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
7928        use std::collections::{BTreeMap, BTreeSet};
7929
7930        #[derive(Clone, Copy, PartialEq, Eq)]
7931        enum Mark {
7932            White,
7933            Gray,
7934            Black,
7935        }
7936
7937        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
7938        for m in self.membros() {
7939            adj.entry(m.nome()).or_default();
7940        }
7941        for c in self.contratos() {
7942            // target() was already called by validate(); re-running here
7943            // keeps detect_sync_cycles self-contained for callers that
7944            // reuse it (M4 per-edge policy resolver) without revalidating.
7945            //
7946            // The pub-sub-arm check routes through the lifted
7947            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
7948            // arm-discriminator predicate rather than a raw `matches!(…,
7949            // WitTarget::PubSub { .. })` on the variant so a future
7950            // rebrand on the axis (an M4 per-edge WIT registry split of
7951            // [`WitTarget::PubSub`] into shape-specific peers, a
7952            // per-consumer rename that the accept-set already carries)
7953            // reaches this call site through the derive rather than a
7954            // scattered per-arm `matches!` rewrite — same
7955            // `IsVariant`-derived-arm-discriminator discipline the
7956            // peer closed-set typed enums ([`crate::CaixaKind`] via
7957            // f5bba80, [`PlacementStrategy`] via 766ec63,
7958            // [`crate::supervisor::RestartStrategy`] +
7959            // [`crate::supervisor::RestartPolicy`],
7960            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
7961            // already route through on the substrate's other typed-enum
7962            // arm-discriminator axes.
7963            if c.target()?.is_pubsub() {
7964                continue;
7965            }
7966            adj.entry(c.source()).or_default().insert(c.destination());
7967        }
7968
7969        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
7970        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
7971
7972        // Stable DFS root order — BTreeMap iteration is sorted by key.
7973        let roots: Vec<&str> = adj.keys().copied().collect();
7974
7975        // Frame: (node, sorted-neighbours snapshot, next-edge index).
7976        for root in roots {
7977            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
7978                continue;
7979            }
7980            let root_neighbors: Vec<&str> = adj
7981                .get(root)
7982                .map(|s| s.iter().copied().collect())
7983                .unwrap_or_default();
7984            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
7985            color.insert(root, Mark::Gray);
7986
7987            loop {
7988                // Read+advance the top frame in one borrow scope so we
7989                // can later mutate the stack (push/pop) without holding
7990                // a borrow across.
7991                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
7992                    let node = top.0;
7993                    if top.2 >= top.1.len() {
7994                        (node, None)
7995                    } else {
7996                        let nxt = top.1[top.2];
7997                        top.2 += 1;
7998                        (node, Some(nxt))
7999                    }
8000                });
8001                let Some((node, nxt_opt)) = step else { break };
8002                let Some(nxt) = nxt_opt else {
8003                    color.insert(node, Mark::Black);
8004                    stack.pop();
8005                    continue;
8006                };
8007                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
8008                match nxt_color {
8009                    Mark::Gray => {
8010                        // Reconstruct the cycle from `node` back through
8011                        // the parent chain to `nxt`, then close.
8012                        let mut cycle = Vec::new();
8013                        let mut cur = node;
8014                        cycle.push(cur.to_string());
8015                        while cur != nxt {
8016                            match parent.get(cur).copied() {
8017                                Some(p) => {
8018                                    cur = p;
8019                                    cycle.push(cur.to_string());
8020                                }
8021                                None => break,
8022                            }
8023                        }
8024                        cycle.reverse();
8025                        cycle.push(nxt.to_string());
8026                        return Err(AplicacaoError::ContratoCycle { cycle });
8027                    }
8028                    Mark::White => {
8029                        parent.insert(nxt, node);
8030                        color.insert(nxt, Mark::Gray);
8031                        let nxt_neighbors: Vec<&str> = adj
8032                            .get(nxt)
8033                            .map(|s| s.iter().copied().collect())
8034                            .unwrap_or_default();
8035                        stack.push((nxt, nxt_neighbors, 0));
8036                    }
8037                    Mark::Black => {}
8038                }
8039            }
8040        }
8041        Ok(())
8042    }
8043
8044    /// Substrate-canonical destination-facing TCP port every emitted
8045    /// per-Aplicacao artifact must key `destination`-shaped port axes
8046    /// off. Returns the typed `:entrada :port` scalar when this
8047    /// Aplicacao's `:entrada` block names `destination` under its
8048    /// `:para` axis (the destination Servico *is* the ingress apex, so
8049    /// the substrate honors the author-declared listener port
8050    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8051    /// fallback otherwise (every non-apex destination — the internal
8052    /// mesh Servicos `:contratos` reach across, the future per-edge
8053    /// policy resolver's per-destination probe targets, the
8054    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8055    /// L4 port resolver — reads the same substrate-canonical port floor
8056    /// by construction).
8057    ///
8058    /// Prior to this lift the "if :entrada matches this destination use
8059    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8060    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8061    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8062    /// prior to this lift), with no typed method on the substrate primitive
8063    /// that named the rule. A future per-destination port axis addition
8064    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8065    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8066    /// per-Servico listener ports land, a per-cluster override the operator
8067    /// pins through a future `:placement :default-port` slot — would have
8068    /// to be threaded through every renderer's inline cascade in lockstep
8069    /// or one consumer would silently disagree on which port a given
8070    /// destination Servico's ingress lands at. Lifting the rule to a
8071    /// typed method on the substrate primitive means the M4 CR
8072    /// materializer, the future per-edge policy resolver, and every
8073    /// downstream test-fixture navigator reach for exactly one typed
8074    /// dispatch — the resolver's accept-set moves as a unit on any
8075    /// future axis addition.
8076    ///
8077    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8078    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8079    /// the typed primitive, thin projections at each consumer"
8080    /// discipline lifts on the sibling `:contratos` payload / `:politicas
8081    /// :rate-limit` unit-suffix axes; extends the discipline onto the
8082    /// destination-facing port-resolution axis every per-Aplicacao
8083    /// L4-fallback renderer consumes.
8084    #[must_use]
8085    pub fn port_for_destination(&self, destination: &str) -> u16 {
8086        // Route the per-`:entrada` composite-reference read through
8087        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8088        // the raw `self.entrada.as_ref()` field access — the
8089        // per-destination L4-port fallback resolver's composite-
8090        // projection seed is now the canonical read-side surface
8091        // every per-Aplicacao entrada consumer routes through, peer
8092        // of the sibling `validate` per-`:entrada` shape-and-
8093        // membership gate migration on the same outer-composite
8094        // axis.
8095        // Route the per-`:entrada` apex-destination membership probe
8096        // through the lifted [`Entrada::destination`] accessor rather
8097        // than the raw `e.para == destination` field access — the last
8098        // un-lifted `.para` production-code read site on the per-
8099        // `:entrada` `:para` axis, sibling to the four caixa-core
8100        // consumer sites the peer 15ddd8c converge already routed
8101        // through the accessor (the three
8102        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8103        // membership gate sites: the `validate_entrada_para` DNS-1123
8104        // shape gate, the per-`:membros` membership lookup, and the
8105        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8106        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8107        // `entrada.para`-projection converge at
8108        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8109        // route-name projection site). Prior to this converge the
8110        // `port_for_destination` resolver was the solitary consumer
8111        // bypassing the typed dispatch on the `.para` axis — the two
8112        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8113        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8114        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8115        // reach through the same accessor family compose with this
8116        // resolver at the emit boundary via the apex-identity
8117        // invariant `spec.port_for_destination(entrada.destination())
8118        // == entrada.port` the sibling
8119        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8120        // pin pins across four permutations. A future extension of the
8121        // `:entrada :para` axis to a richer author surface (a per-
8122        // cluster alias overlay the operator pins through a future
8123        // `:placement`-scoped slot, a namespace-qualified rewrite the
8124        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8125        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8126        // §III.2 acknowledges) that lands on the accessor would silently
8127        // disagree between this resolver and the two `caixa-mesh` emit
8128        // sites — an author-declared `:para "cart"` value the accessor
8129        // rewrote to `"cart-v2"` under a future canary arm would leave
8130        // the resolver's membership arm falling through to
8131        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8132        // `.para`) while the peer emit-site consumers landed on the
8133        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8134        // silently disagreed on which destination port a given typed
8135        // `:entrada` resolves to at cluster-apply time. Pinned by the
8136        // drift-detection test
8137        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8138        // below.
8139        self.entrada()
8140            .filter(|e| e.destination() == destination)
8141            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8142    }
8143}
8144
8145/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8146/// entry may name the Aplicacao's own `:nome`.
8147///
8148/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8149/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8150/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8151/// Servicos that compose the app; an Aplicacao is never its own constituent),
8152/// and the lacre pipeline's closure-resolution would otherwise be handed a
8153/// node that is its own parent: a one-node cycle it either rejects far from
8154/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8155/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8156/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8157/// label + lacre closure root), a member whose `:caixa` equals the
8158/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8159/// peer.
8160///
8161/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8162/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8163/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8164/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8165/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8166/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8167/// (the Aplicacao :membros set; the supervision-tree :children list was the
8168/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8169/// every validated Supervisor's children are distinct from its `:nome`,
8170/// every validated Aplicacao's membros are distinct from its `:nome`. The
8171/// transitive consequence is that `:entrada :para` and `:contratos`
8172/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8173/// name the Aplicacao itself, without re-deriving the partition.
8174pub fn validate_no_self_membership(
8175    membros: &[Membro],
8176    parent_nome: &str,
8177) -> Result<(), AplicacaoError> {
8178    for m in membros {
8179        if m.nome() == parent_nome {
8180            return Err(AplicacaoError::MembroIsSelfAplicacao {
8181                caixa: parent_nome.to_string(),
8182            });
8183        }
8184    }
8185    Ok(())
8186}
8187
8188#[derive(Debug, Error, PartialEq, Eq)]
8189pub enum AplicacaoError {
8190    #[error("Aplicacao must declare at least one :membros entry")]
8191    NoMembros,
8192    #[error(
8193        ":membros entry has empty :caixa (every member must name a Servico; \
8194         omit the entry instead of carrying an empty name)"
8195    )]
8196    MembroCaixaEmpty,
8197    #[error(
8198        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8199         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8200         name / label value the member name lands in; use a lowercase \
8201         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8202    )]
8203    MembroCaixaInvalid { caixa: String, reason: String },
8204    #[error(
8205        ":membros entry {caixa:?} has empty :versao (every member must pin a \
8206         semver constraint that resolves through the lacre pipeline)"
8207    )]
8208    MembroVersaoEmpty { caixa: String },
8209    #[error(
8210        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8211         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8212         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8213         carries; the lacre pipeline resolves both through the same parser)"
8214    )]
8215    MembroVersaoInvalid {
8216        caixa: String,
8217        versao: String,
8218        reason: String,
8219    },
8220    #[error(
8221        ":membros entry {caixa:?} appears more than once (the graph node set \
8222         is a set, not a multiset; duplicate members produce duplicate \
8223         programs.yaml entries and ambiguous :contratos membership lookups)"
8224    )]
8225    MembroDuplicate { caixa: String },
8226    #[error(
8227        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8228         never its own constituent Servico (the application graph is a DAG rooted \
8229         at the Aplicacao; :membros names the *other* caixas that compose the \
8230         app, not the app itself). Since every :nome is a globally-unique \
8231         substrate identity, a member naming the Aplicacao's own :nome is a \
8232         one-node lacre-closure recursion, not a coincidentally-named peer; \
8233         drop the self-referential :membros entry or rename it to the actual \
8234         constituent caixa."
8235    )]
8236    MembroIsSelfAplicacao { caixa: String },
8237    #[error(
8238        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8239         caixa declared in :membros; omit the contract or fill the {slot} field with a \
8240         member name)"
8241    )]
8242    ContratoCaixaEmpty { slot: &'static str },
8243    #[error(
8244        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8245         :contratos {slot} value names a member of :membros, which is itself a \
8246         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8247         object the member name lands in — Service, Pod, identity-based Cilium \
8248         selector; use a lowercase alphanumeric + hyphen identifier like \
8249         `\"checkout\"` or `\"cart-v2\"`)"
8250    )]
8251    ContratoCaixaInvalid {
8252        slot: &'static str,
8253        caixa: String,
8254        reason: String,
8255    },
8256    #[error("contrato references caixa {caixa:?} not declared in :membros")]
8257    ContratoMemberMissing { caixa: String },
8258    #[error(
8259        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8260         entry is an inter-Servico contract whose :de and :para must name distinct \
8261         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8262         the contract, or point :para at the member it actually calls)"
8263    )]
8264    ContratoSelfLoop { caixa: String, wit: String },
8265    #[error("contrato {de:?} → {para:?} has empty :wit")]
8266    EmptyWit { de: String, para: String },
8267    #[error(
8268        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8269         {reason} (the substrate dispatches `:wit` values on the canonical \
8270         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8271         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8272         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8273         kebab-case identifier per segment)"
8274    )]
8275    ContratoWitInvalid {
8276        de: String,
8277        para: String,
8278        wit: String,
8279        reason: String,
8280    },
8281    #[error(
8282        ":entrada :para is empty (every :entrada must route to a caixa declared in \
8283         :membros; fill the :para field with a member name)"
8284    )]
8285    EntradaParaEmpty,
8286    #[error(
8287        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8288         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8289         label per the K8s apiserver's `metadata.name` rule on every object the \
8290         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8291         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8292         `\"checkout\"` or `\"cart-v2\"`)"
8293    )]
8294    EntradaParaInvalid { para: String, reason: String },
8295    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8296    EntradaMemberMissing { para: String },
8297    #[error(":entrada must declare a non-empty :host")]
8298    EmptyEntradaHost,
8299    #[error(
8300        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8301         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8302         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8303         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8304    )]
8305    EntradaHostInvalid { host: String, reason: String },
8306    #[error(":entrada :port must be in 1..=65535, got 0")]
8307    EntradaPortZero,
8308    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8309    EntradaPathEmpty,
8310    #[error(
8311        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8312    )]
8313    EntradaPathNotAbsolute { path: String },
8314    #[error(
8315        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8316         value: {reason} (the K8s apiserver enforces the same shape on \
8317         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8318         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8319         requires percent-encoding `%XX` for non-ASCII and whitespace)"
8320    )]
8321    EntradaPathInvalid { path: String, reason: String },
8322    #[error(":entrada :paths entry {path:?} appears more than once")]
8323    EntradaPathDuplicate { path: String },
8324    #[error(
8325        ":placement {estrategia} requires at least one :clusters entry \
8326         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8327    )]
8328    PlacementWithoutClusters { estrategia: PlacementStrategy },
8329    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8330    PlacementClusterEmpty,
8331    #[error(
8332        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8333         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8334         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8335         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8336         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8337         identifier like `\"rio\"` or `\"mar-east\"`)"
8338    )]
8339    PlacementClusterInvalid { cluster: String, reason: String },
8340    #[error(":placement :clusters entry {cluster:?} appears more than once")]
8341    PlacementClusterDuplicate { cluster: String },
8342    #[error(
8343        ":placement :affinity must be non-empty when set (omit :affinity to express \
8344         `no placement hint`)"
8345    )]
8346    PlacementAffinityEmpty,
8347    #[error(
8348        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8349         (placement hints land verbatim in the M3 Adaptive compression overlay's \
8350         `placement.affinity` field and in every future M4 placement-engine routing \
8351         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8352         selector — both enforce the DNS-1123 label rule on admission; use a \
8353         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8354         `\"low-latency\"`, or `\"anti-affinity\"`)"
8355    )]
8356    PlacementAffinityInvalid { affinity: String, reason: String },
8357    #[error(":placement Sharded requires :shard-key")]
8358    ShardedWithoutKey,
8359    #[error(
8360        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8361         hashes every entity onto the same shard, defeating sharding entirely)"
8362    )]
8363    ShardedKeyEmpty,
8364    #[error(
8365        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8366         entity-id extractor expression: {reason} (the future M4 Akka-style \
8367         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8368         as a single-token property reference and hashes the extracted entity ID \
8369         to compute shard placement; use a printable-ASCII extractor expression \
8370         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8371         `\"${{tenant}}\"`)"
8372    )]
8373    ShardKeyInvalid { shard_key: String, reason: String },
8374    #[error(
8375        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8376         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8377         convention); :estrategia Replicated runs every cluster active-active and \
8378         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8379         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8380         to :estrategia Sharded if hash-keyed routing is the intent"
8381    )]
8382    ShardKeyOnNonSharded {
8383        estrategia: PlacementStrategy,
8384        shard_key: String,
8385    },
8386    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8387    ContratoMissingTarget {
8388        de: String,
8389        para: String,
8390        wit: String,
8391        expected: &'static str,
8392    },
8393    #[error(
8394        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8395         expected `:{expected}` only"
8396    )]
8397    ContratoWrongTarget {
8398        de: String,
8399        para: String,
8400        wit: String,
8401        expected: &'static str,
8402    },
8403    #[error(
8404        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8405         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8406         that matches no traffic and silently drops every request)"
8407    )]
8408    ContratoEndpointEmpty { de: String, para: String },
8409    #[error(
8410        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8411         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8412         :entrada :paths)"
8413    )]
8414    ContratoEndpointNotAbsolute {
8415        de: String,
8416        para: String,
8417        endpoint: String,
8418    },
8419    #[error(
8420        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8421         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8422         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8423         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8424         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8425         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8426         and whitespace)"
8427    )]
8428    ContratoEndpointInvalid {
8429        de: String,
8430        para: String,
8431        endpoint: String,
8432        reason: String,
8433    },
8434    #[error(
8435        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8436         subject is a no-op subscribe; omit :subject only if the WIT world is not \
8437         pub-sub-shaped)"
8438    )]
8439    ContratoSubjectEmpty { de: String, para: String },
8440    #[error(
8441        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8442         NATS subject: {reason} (the NATS server's subject parser enforces the \
8443         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8444         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8445         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8446         `\"orders.*.completed\"` — a malformed subject silently drops every \
8447         message at runtime far from the source caixa.lisp)"
8448    )]
8449    ContratoSubjectInvalid {
8450        de: String,
8451        para: String,
8452        subject: String,
8453        reason: String,
8454    },
8455    #[error(
8456        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8457         addresses the bucket root, defeating the per-key isolation the slot exists \
8458         for; omit :slot only if the WIT world is not store-shaped)"
8459    )]
8460    ContratoSlotEmpty { de: String, para: String },
8461    #[error(
8462        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8463         WASI keyvalue store slot template: {reason} (the substrate enforces \
8464         the printable-ASCII intersection-floor every kv backend admits — \
8465         use a single-token path / template expression like `\"checkout/$orderId\"`, \
8466         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8467         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8468         slot either gets rejected on write by strict backends or silently \
8469         corrupts the next read on permissive ones, far from the source caixa.lisp)"
8470    )]
8471    ContratoSlotInvalid {
8472        de: String,
8473        para: String,
8474        slot: String,
8475        reason: String,
8476    },
8477    #[error(
8478        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
8479         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
8480        cycle.join(" → ")
8481    )]
8482    ContratoCycle { cycle: Vec<String> },
8483    #[error(
8484        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
8485         than once (the typed graph edges are a set, not a multiset; duplicate \
8486         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
8487         values that K8s admission rejects far from the source caixa.lisp)"
8488    )]
8489    ContratoDuplicate {
8490        de: String,
8491        para: String,
8492        wit: String,
8493        target: String,
8494    },
8495    #[error(
8496        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
8497         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
8498         express `no per-call deadline on this axis`"
8499    )]
8500    PolicyTimeoutZero,
8501    #[error(
8502        ":politicas :retries must be > 0 when set; omit :retries to express \
8503         `no retries on transient failure`"
8504    )]
8505    PolicyRetriesZero,
8506    #[error(
8507        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
8508         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
8509         retry policy into a thundering-herd amplification vector on transient \
8510         failure (one caller request fans out to `(retries+1)^depth` server-side \
8511         calls across the synchronous-:contratos subgraph), exactly the failure \
8512         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
8513         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
8514         or omit :retries to disable retries entirely"
8515    )]
8516    PolicyRetriesExceedsCap { retries: u32 },
8517    #[error(
8518        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
8519         breaker trips on the first call); omit :circuit-breaker to disable it"
8520    )]
8521    PolicyBreakerZeroFailures,
8522    #[error(
8523        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
8524         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
8525         above this cap turns the typed breaker policy into a no-op: the trip \
8526         threshold is structurally so high that no realistic failures-per-:window \
8527         traffic shape can reach it, so the breaker never trips and every typed-slot \
8528         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
8529         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
8530         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
8531         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
8532         omit :circuit-breaker to disable the breaker entirely"
8533    )]
8534    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
8535    #[error(
8536        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
8537         tracks no failures); omit :circuit-breaker to disable it"
8538    )]
8539    PolicyBreakerZeroWindow,
8540    #[error(
8541        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
8542         request); omit :rate-limit to disable rate limiting"
8543    )]
8544    PolicyRateLimitZero,
8545    #[error(
8546        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
8547         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
8548         rate-limit policy into a no-op limiter: the token-bucket capacity is \
8549         structurally so high that no realistic per-edge traffic shape can drain it, \
8550         so the limiter never trips and every typed-slot consumer (the future \
8551         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8552         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
8553         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
8554         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
8555         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
8556         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
8557         to disable rate limiting entirely"
8558    )]
8559    PolicyRateLimitExceedsCap { rate: u32 },
8560    #[error(
8561        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
8562         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
8563         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
8564         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
8565         three canonical windows)"
8566    )]
8567    PolicyRateLimitWindowNotCanonical { window: Duration },
8568    #[error(
8569        ":politicas :timeout must be an integer number of milliseconds — the canonical \
8570         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
8571         duration codec round-trips losslessly; got {timeout:?} which carries a \
8572         sub-millisecond residue that either truncates to a different `Duration` on \
8573         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
8574         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
8575         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
8576         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
8577    )]
8578    PolicyTimeoutNotCanonical { timeout: Duration },
8579    #[error(
8580        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
8581         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
8582         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
8583         overlays carry a deadline so long no realistic synchronous-:contratos \
8584         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
8585         CSE invariant degenerates to enforcement only at the per-Servico \
8586         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
8587         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
8588         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
8589         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
8590         maxes out at the same `3600s` ceiling) or omit :timeout to express \
8591         `no per-call deadline on this axis` (the synchronous-call deadline then \
8592         relies entirely on the per-Servico `:limits :wall-clock` axis)"
8593    )]
8594    PolicyTimeoutExceedsCap { timeout: Duration },
8595    #[error(
8596        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
8597         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
8598         the shared duration codec round-trips losslessly; got {window:?} which carries a \
8599         sub-millisecond residue that either truncates to a different `Duration` on \
8600         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
8601         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
8602    )]
8603    PolicyBreakerWindowNotCanonical { window: Duration },
8604    #[error(
8605        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
8606         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
8607         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
8608         is structurally so long that transient failures are never forgotten, the breaker \
8609         trips once and stays tripped for the lifetime of the component, and every typed-slot \
8610         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8611         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
8612         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
8613         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
8614         the breaker entirely"
8615    )]
8616    PolicyBreakerWindowExceedsCap { window: Duration },
8617}
8618
8619#[cfg(test)]
8620mod tests {
8621    use super::*;
8622
8623    fn membro(name: &str, ver: &str) -> Membro {
8624        Membro {
8625            caixa: name.into(),
8626            versao: ver.into(),
8627        }
8628    }
8629
8630    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
8631        WitContract {
8632            de: de.into(),
8633            para: para.into(),
8634            wit: "wasi:http/proxy".into(),
8635            endpoint: Some(ep.into()),
8636            subject: None,
8637            slot: None,
8638        }
8639    }
8640
8641    fn three_member_spec() -> AplicacaoSpec {
8642        AplicacaoSpec {
8643            membros: vec![
8644                membro("catalog", "^0.1"),
8645                membro("cart", "^0.1"),
8646                membro("payment", "^0.2"),
8647            ],
8648            contratos: vec![
8649                contract_http("cart", "catalog", "/products/:id"),
8650                contract_http("cart", "payment", "/charge"),
8651            ],
8652            politicas: MeshPolicy {
8653                timeout: Some(Duration::from_secs(30)),
8654                retries: Some(3),
8655                mtls_required: Some(true),
8656                ..Default::default()
8657            },
8658            placement: Placement {
8659                estrategia: PlacementStrategy::Replicated,
8660                clusters: vec!["rio".into(), "mar".into()],
8661                affinity: Some("data-locality".into()),
8662                shard_key: None,
8663            },
8664            entrada: Some(Entrada {
8665                host: "checkout.quero.cloud".into(),
8666                para: "cart".into(),
8667                paths: vec!["/api/cart".into(), "/api/products".into()],
8668                port: 8080,
8669            }),
8670        }
8671    }
8672
8673    #[test]
8674    fn happy_path_validates() {
8675        three_member_spec().validate().unwrap();
8676    }
8677
8678    #[test]
8679    fn rejects_empty_membros() {
8680        let mut s = three_member_spec();
8681        s.membros = vec![];
8682        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
8683    }
8684
8685    #[test]
8686    fn rejects_empty_membro_caixa() {
8687        // A `:caixa ""` entry has no name to render into programs.yaml
8688        // and no caixa.lisp to resolve at lacre time.
8689        let mut s = three_member_spec();
8690        s.membros[1].caixa = String::new();
8691        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
8692    }
8693
8694    #[test]
8695    fn rejects_empty_membro_versao() {
8696        // A `:versao ""` entry can't pin a semver constraint, so the
8697        // lacre pipeline fails far from the source.
8698        let mut s = three_member_spec();
8699        s.membros[2].versao = String::new();
8700        let err = s.validate().unwrap_err();
8701        assert!(
8702            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
8703            "got {err:?}"
8704        );
8705    }
8706
8707    #[test]
8708    fn rejects_duplicate_membro_caixa() {
8709        // Two `:membros` entries with the same `:caixa` collapse to one
8710        // node in the membership HashSet, which masks `:contratos`
8711        // membership errors and produces duplicate programs.yaml entries.
8712        let mut s = three_member_spec();
8713        s.membros.push(membro("cart", "^0.2"));
8714        let err = s.validate().unwrap_err();
8715        assert!(
8716            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8717            "got {err:?}"
8718        );
8719    }
8720
8721    #[test]
8722    fn rejects_invalid_membro_versao_requirement() {
8723        // The fail-before-pass-after pin: a non-empty but malformed
8724        // semver requirement (`"^bad-version"`) silently passed
8725        // `validate()` on every pre-gate codebase because the prior
8726        // shape only refused the empty string. The parse failure
8727        // surfaced far downstream at lacre-resolve time with a
8728        // `semver::Error` that didn't name which `:membros` entry
8729        // carried the typo. The new gate moves the check to caixa-build
8730        // time at the source caixa.lisp.
8731        let mut s = three_member_spec();
8732        s.membros[2].versao = "^bad-version".into();
8733        let err = s.validate().unwrap_err();
8734        assert!(
8735            matches!(
8736                err,
8737                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8738                    if caixa == "payment" && versao == "^bad-version"
8739            ),
8740            "got {err:?}"
8741        );
8742    }
8743
8744    #[test]
8745    fn rejects_membro_versao_with_double_caret_typo() {
8746        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
8747        // Cargo-shaped requirement on first glance but fails the parser
8748        // because semver doesn't accept stacked operators. Pin this
8749        // adjacent-shape footgun explicitly so a future relaxation that
8750        // accepts "looks-canonical-but-isn't" forms surfaces here.
8751        let mut s = three_member_spec();
8752        s.membros[0].versao = "^^0.1".into();
8753        let err = s.validate().unwrap_err();
8754        assert!(
8755            matches!(
8756                err,
8757                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8758                    if caixa == "catalog" && versao == "^^0.1"
8759            ),
8760            "got {err:?}"
8761        );
8762    }
8763
8764    #[test]
8765    fn rejects_membro_versao_with_v_prefixed_tag() {
8766        // `"v0.1"` is the canonical "git-tag-shape leaking into the
8767        // semver requirement slot" typo — an author copies the
8768        // publish-side git-tag string verbatim into `:versao`, but
8769        // Cargo's semver parser rejects the leading `v` (only digits +
8770        // canonical operators are valid in the major-version
8771        // position). The gate's diagnostic names which member entry
8772        // carried the v-prefix so the fix is one edit, not a grep
8773        // through every member's `:versao`. (Note: bare `x`-glob
8774        // shorthands like `^0.1.x` are *accepted* by the semver crate
8775        // as an `*` wildcard on the patch axis — they're a Cargo-side
8776        // valid shape, not a typo, so the gate intentionally lets them
8777        // through.)
8778        let mut s = three_member_spec();
8779        s.membros[1].versao = "v0.1".into();
8780        let err = s.validate().unwrap_err();
8781        assert!(
8782            matches!(
8783                err,
8784                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8785                    if caixa == "cart" && versao == "v0.1"
8786            ),
8787            "got {err:?}"
8788        );
8789    }
8790
8791    #[test]
8792    fn accepts_canonical_membro_versao_forms() {
8793        // The four Cargo-shaped requirement forms `:deps :versao`
8794        // already accepts via `crate::parse_requirement` must pass the
8795        // membros gate without re-validating at the resolver layer.
8796        // Pin every leg so a future tightening of the canonical set
8797        // surfaces here as a test failure.
8798        for form in [
8799            "^0.1",      // caret — minor-range pin (the most common shape)
8800            "~0.1.2",    // tilde — patch-range pin
8801            "0.1.0",     // exact — single-version pin
8802            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
8803            ">=0.1, <2", // multi-range — comma-separated comparators
8804        ] {
8805            let mut s = three_member_spec();
8806            for m in &mut s.membros {
8807                m.versao = form.into();
8808            }
8809            s.validate()
8810                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8811        }
8812    }
8813
8814    #[test]
8815    fn membro_versao_empty_takes_precedence_over_invalid() {
8816        // Order pin: the existing `MembroVersaoEmpty` diagnostic
8817        // (which doesn't try to parse) fires before the new
8818        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
8819        // `:versao` keeps its narrower error message — `parse_requirement`
8820        // would also reject `""`, but the empty-string arm is the more
8821        // self-locating diagnostic for the author.
8822        let mut s = three_member_spec();
8823        s.membros[1].versao = String::new();
8824        let err = s.validate().unwrap_err();
8825        assert!(
8826            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
8827            "got {err:?}"
8828        );
8829    }
8830
8831    #[test]
8832    fn membro_versao_invalid_fires_before_duplicate_check() {
8833        // Order pin: a malformed requirement on a non-duplicate entry
8834        // surfaces *its own* diagnostic (which names the offending
8835        // `:versao` string), even when a later entry would otherwise
8836        // collapse onto an earlier name. The per-entry shape gate runs
8837        // inline before the duplicate-key insert, parallel to
8838        // `membros_validation_runs_before_contratos_membership_check`
8839        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
8840        let mut s = three_member_spec();
8841        s.membros[0].versao = "^bad".into();
8842        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8843        let err = s.validate().unwrap_err();
8844        assert!(
8845            matches!(
8846                err,
8847                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
8848            ),
8849            "got {err:?}"
8850        );
8851    }
8852
8853    #[test]
8854    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
8855        // The diagnostic-shape pin: the error names the offending
8856        // `:versao` value verbatim so the author can grep their
8857        // caixa.lisp without re-running the build, and carries a
8858        // non-empty `reason` from `semver::VersionReq::parse` so the
8859        // parser's own wording flows through to the diagnostic.
8860        let mut s = three_member_spec();
8861        s.membros[2].versao = "not-a-req".into();
8862        let err = s.validate().unwrap_err();
8863        let AplicacaoError::MembroVersaoInvalid {
8864            caixa,
8865            versao,
8866            reason,
8867        } = err
8868        else {
8869            panic!("expected MembroVersaoInvalid, got other variant");
8870        };
8871        assert_eq!(caixa, "payment");
8872        assert_eq!(versao, "not-a-req");
8873        assert!(
8874            !reason.is_empty(),
8875            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
8876        );
8877    }
8878
8879    #[test]
8880    fn membro_versao_invalid_runs_before_contratos_check() {
8881        // A malformed `:versao` on any member must surface its own
8882        // diagnostic (which names *which* member to fix) before any
8883        // `:contratos` membership lookup raises `ContratoMemberMissing`.
8884        // The `:contratos` gate runs after `validate_membros`, so this
8885        // is structurally guaranteed — pin it explicitly so a future
8886        // refactor that reorders the gates surfaces here.
8887        let mut s = three_member_spec();
8888        s.membros[1].versao = "^^0.1".into();
8889        // Add a contrato whose `:para` doesn't exist — would normally
8890        // raise ContratoMemberMissing at the membership lookup, but
8891        // the membros gate must fire first.
8892        s.contratos
8893            .push(contract_http("cart", "phantom", "/never-reached"));
8894        let err = s.validate().unwrap_err();
8895        assert!(
8896            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
8897            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
8898        );
8899    }
8900
8901    #[test]
8902    fn membros_validation_runs_before_contratos_membership_check() {
8903        // If `:membros` carries a duplicate, the membership-collapse
8904        // would silently accept a `:contratos :para "phantom"` so long
8905        // as some entry hashes to "phantom". Pinning order: the
8906        // duplicate-membros error fires first, regardless of whether
8907        // contratos reference real members.
8908        let mut s = three_member_spec();
8909        s.membros = vec![
8910            membro("cart", "^0.1"),
8911            membro("cart", "^0.2"),
8912            membro("catalog", "^0.1"),
8913            membro("payment", "^0.1"),
8914        ];
8915        let err = s.validate().unwrap_err();
8916        assert!(
8917            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8918            "got {err:?}"
8919        );
8920    }
8921
8922    #[test]
8923    fn distinct_membros_validate() {
8924        // Pin the happy-path: every `:membros` entry has a non-empty
8925        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
8926        // The fixture already satisfies this; this test makes the
8927        // invariant explicit so a future refactor of the fixture can't
8928        // silently break the guarantee.
8929        three_member_spec().validate().unwrap();
8930    }
8931
8932    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
8933
8934    #[test]
8935    fn rejects_membro_caixa_with_uppercase() {
8936        // The canonical "I copied the Servico's display name verbatim"
8937        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
8938        // but author tools often round-trip a TitleCase or CamelCase
8939        // identifier from an ADR or a sketch. Pin the diagnostic names
8940        // the offending name and suggests the lower-cased fix in one
8941        // edit, mirroring the `rejects_entrada_host_with_uppercase`
8942        // gate's shape (c7d05ec).
8943        let mut s = three_member_spec();
8944        s.membros[1].caixa = "Cart".into();
8945        let err = s.validate().unwrap_err();
8946        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8947            panic!("expected MembroCaixaInvalid, got other variant");
8948        };
8949        assert_eq!(caixa, "Cart");
8950        assert!(
8951            reason.contains("uppercase"),
8952            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8953        );
8954        assert!(
8955            reason.contains("\"cart\""),
8956            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
8957        );
8958    }
8959
8960    #[test]
8961    fn rejects_membro_caixa_with_underscore() {
8962        // The canonical "I'm thinking of a Python module / Postgres
8963        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
8964        // label schema. K8s rejects `metadata.name: my_cart` at admission
8965        // time with an opaque `field is invalid` (no source-citing
8966        // diagnostic). The gate moves it to caixa-build time.
8967        let mut s = three_member_spec();
8968        s.membros[0].caixa = "my_cart".into();
8969        let err = s.validate().unwrap_err();
8970        assert!(
8971            matches!(
8972                err,
8973                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8974                    if caixa == "my_cart" && reason.contains('_')
8975            ),
8976            "got {err:?}"
8977        );
8978    }
8979
8980    #[test]
8981    fn rejects_membro_caixa_with_dot() {
8982        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
8983        // subdomain — even though K8s `metadata.name` itself accepts
8984        // dots (DNS-1123 subdomain rule), this string also lands as a
8985        // K8s Service name (DNS-1035 label — no dots) and as a label
8986        // value on identity-based Cilium selectors. The strictest floor
8987        // among the use sites wins. The "I want to namespace my member
8988        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
8989        let mut s = three_member_spec();
8990        s.membros[2].caixa = "team.cart".into();
8991        let err = s.validate().unwrap_err();
8992        assert!(
8993            matches!(
8994                err,
8995                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8996                    if caixa == "team.cart" && reason.contains('.')
8997            ),
8998            "got {err:?}"
8999        );
9000    }
9001
9002    #[test]
9003    fn rejects_membro_caixa_with_leading_hyphen() {
9004        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
9005        // with an alphanumeric. The K8s apiserver rejects `-cart`
9006        // outright; the renderer would emit a `metadata.name: "-cart"`
9007        // that fails admission far from the source caixa.lisp.
9008        let mut s = three_member_spec();
9009        s.membros[0].caixa = "-cart".into();
9010        let err = s.validate().unwrap_err();
9011        assert!(
9012            matches!(
9013                err,
9014                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9015                    if caixa == "-cart" && reason.contains("start and end")
9016            ),
9017            "got {err:?}"
9018        );
9019    }
9020
9021    #[test]
9022    fn rejects_membro_caixa_with_trailing_hyphen() {
9023        // The symmetric arm of the boundary rule. Pin separately so
9024        // both ends of the label are covered against a future relaxation
9025        // that only checks one boundary.
9026        let mut s = three_member_spec();
9027        s.membros[1].caixa = "cart-".into();
9028        let err = s.validate().unwrap_err();
9029        assert!(
9030            matches!(
9031                err,
9032                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9033                    if caixa == "cart-"
9034            ),
9035            "got {err:?}"
9036        );
9037    }
9038
9039    #[test]
9040    fn rejects_membro_caixa_with_unicode() {
9041        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9042        // (`xn--…`) by the author before it reaches K8s. The byte-by-
9043        // byte ASCII validity check rejects multi-byte UTF-8 sequences
9044        // by the first byte that fails the `[a-z0-9-]` predicate.
9045        let mut s = three_member_spec();
9046        s.membros[2].caixa = "café".into();
9047        let err = s.validate().unwrap_err();
9048        assert!(
9049            matches!(
9050                err,
9051                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9052                    if caixa == "café"
9053            ),
9054            "got {err:?}"
9055        );
9056    }
9057
9058    #[test]
9059    fn rejects_membro_caixa_with_whitespace() {
9060        // Whitespace is the canonical "I pasted from a sketch / doc"
9061        // footgun. The apiserver rejects every `metadata.name` value
9062        // carrying whitespace; pin the gate fires at the right boundary.
9063        let mut s = three_member_spec();
9064        s.membros[0].caixa = "my cart".into();
9065        let err = s.validate().unwrap_err();
9066        assert!(
9067            matches!(
9068                err,
9069                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9070                    if caixa == "my cart"
9071            ),
9072            "got {err:?}"
9073        );
9074    }
9075
9076    #[test]
9077    fn rejects_membro_caixa_too_long() {
9078        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
9079        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
9080        // exactly. The gate's reason names both the cap and the actual
9081        // length so the author can shorten in one edit.
9082        let mut s = three_member_spec();
9083        let too_long = "a".repeat(64);
9084        s.membros[1].caixa = too_long.clone();
9085        let err = s.validate().unwrap_err();
9086        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9087            panic!("expected MembroCaixaInvalid");
9088        };
9089        assert_eq!(caixa, too_long);
9090        assert!(
9091            reason.contains("63") && reason.contains("64"),
9092            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
9093        );
9094    }
9095
9096    #[test]
9097    fn membro_caixa_max_length_validates() {
9098        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
9099        // so a future tightening (e.g. dropping to 62) surfaces here as
9100        // a regression, mirroring `entrada_host_max_length_validates`
9101        // (c7d05ec).
9102        let mut s = three_member_spec();
9103        s.membros[2].caixa = "a".repeat(63);
9104        s.entrada.as_mut().unwrap().para = "a".repeat(63);
9105        // remove contratos referencing the renamed member; they'd
9106        // raise ContratoMemberMissing otherwise
9107        s.contratos
9108            .retain(|c| c.de != "payment" && c.para != "payment");
9109        s.validate().unwrap();
9110    }
9111
9112    #[test]
9113    fn accepts_canonical_membro_caixa_forms() {
9114        // The DNS-1123 label shapes a caixa author is realistically
9115        // going to write: single-word lowercase, hyphen-joined, ending
9116        // in a digit-suffixed version (`cart-v2`), starting with a
9117        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
9118        // DNS-1035 which requires a letter at position 0), single-
9119        // character (`a` — boundary). Pin every leg so a future
9120        // tightening that bans (e.g.) digit-start identifiers surfaces
9121        // here.
9122        for form in [
9123            "checkout",
9124            "cart",
9125            "cart-v2",
9126            "a",
9127            "c0",
9128            "3rd-party-shim",
9129            "x-1-2-3-4",
9130        ] {
9131            let mut s = three_member_spec();
9132            // Renaming a member also requires updating downstream refs;
9133            // drop everything else and rebuild a minimal spec around
9134            // just the one renamed member.
9135            s.membros = vec![membro(form, "^0.1")];
9136            s.contratos = vec![];
9137            s.entrada = None;
9138            s.validate()
9139                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
9140        }
9141    }
9142
9143    #[test]
9144    fn membro_caixa_empty_takes_precedence_over_invalid() {
9145        // Order pin: the existing `MembroCaixaEmpty` diagnostic
9146        // (which doesn't try to parse) fires before the new
9147        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
9148        // `:caixa` keeps its narrower error message — the new gate
9149        // would also reject `""`, but the empty-string arm is the more
9150        // self-locating diagnostic for the author. Mirrors the
9151        // `entrada_host_empty_takes_precedence_over_invalid` pin
9152        // (c7d05ec).
9153        let mut s = three_member_spec();
9154        s.membros[1].caixa = String::new();
9155        let err = s.validate().unwrap_err();
9156        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
9157    }
9158
9159    #[test]
9160    fn membro_caixa_invalid_fires_before_versao_check() {
9161        // Order pin: an invalid-shape `:caixa` surfaces *its own*
9162        // diagnostic (which names the offending caixa name), even when
9163        // the same entry's `:versao` is also empty/invalid. The shape
9164        // gate runs first because the diagnostic is more self-locating —
9165        // an empty/invalid `:versao` on an invalid-shape caixa name is
9166        // a downstream-fix-after-the-caixa-rename concern.
9167        let mut s = three_member_spec();
9168        s.membros[1].caixa = "Cart".into();
9169        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
9170        let err = s.validate().unwrap_err();
9171        assert!(
9172            matches!(
9173                err,
9174                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
9175            ),
9176            "got {err:?}"
9177        );
9178    }
9179
9180    #[test]
9181    fn membro_caixa_invalid_fires_before_duplicate_check() {
9182        // Order pin: a malformed-shape `:caixa` on an earlier entry
9183        // surfaces *its own* diagnostic, even when a later entry would
9184        // otherwise collapse onto a duplicate name. The per-entry shape
9185        // gate runs inline before the duplicate-key insert, parallel
9186        // to `membro_versao_invalid_fires_before_duplicate_check`.
9187        let mut s = three_member_spec();
9188        s.membros[0].caixa = "Catalog".into();
9189        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
9190        let err = s.validate().unwrap_err();
9191        assert!(
9192            matches!(
9193                err,
9194                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
9195            ),
9196            "got {err:?}"
9197        );
9198    }
9199
9200    #[test]
9201    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
9202        // The diagnostic-shape pin: the error names the offending
9203        // `:caixa` value verbatim so the author can grep their
9204        // caixa.lisp without re-running the build, and carries a
9205        // non-empty `reason` naming the specific violation. Same
9206        // shape every typed-shape gate enshrines (c7d05ec's
9207        // `entrada_host_diagnostic_carries_offending_host`,
9208        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
9209        let mut s = three_member_spec();
9210        s.membros[2].caixa = "BAD_NAME".into();
9211        let err = s.validate().unwrap_err();
9212        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9213            panic!("expected MembroCaixaInvalid");
9214        };
9215        assert_eq!(caixa, "BAD_NAME");
9216        assert!(
9217            !reason.is_empty(),
9218            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
9219        );
9220    }
9221
9222    #[test]
9223    fn rejects_contrato_with_unknown_de() {
9224        let mut s = three_member_spec();
9225        s.contratos.push(contract_http("phantom", "catalog", "/x"));
9226        let err = s.validate().unwrap_err();
9227        assert!(
9228            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9229        );
9230    }
9231
9232    #[test]
9233    fn rejects_contrato_with_unknown_para() {
9234        let mut s = three_member_spec();
9235        s.contratos.push(contract_http("cart", "phantom", "/x"));
9236        let err = s.validate().unwrap_err();
9237        assert!(
9238            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9239        );
9240    }
9241
9242    #[test]
9243    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
9244        // The read-path pin: the phantom-`:de` refusal arm's
9245        // `ContratoMemberMissing.caixa` carrier must be observed through
9246        // the lifted [`WitContract::source`] accessor, not the raw
9247        // `.de.clone()` field-access `String`-carry. Peer of the sibling
9248        // per-`:contratos` self-loop arm's `.source().to_string()` /
9249        // `.world_ref().to_string()` `String`-carry sites the earlier
9250        // convergence lifted onto the same accessor pair. A future
9251        // silent detour that reintroduced the raw `.de.clone()` at the
9252        // wrap envelope while the shape-gate and membership lookup
9253        // routed through the accessor would surface here as a byte-equal
9254        // miss between the fired diagnostic's `caixa:` field and the
9255        // offending edge's `.source()` — pinning the accessor as the
9256        // sole read path across the phantom-name refusal arm's arg +
9257        // wrap-envelope emit surface.
9258        let mut s = three_member_spec();
9259        let phantom = contract_http("phantom", "catalog", "/x");
9260        s.contratos.push(phantom.clone());
9261        let err = s.validate().unwrap_err();
9262        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9263            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
9264        };
9265        assert_eq!(
9266            caixa,
9267            phantom.source(),
9268            "ContratoMemberMissing.caixa on the phantom-:de arm must \
9269             byte-equal WitContract::source — the wrap envelope must \
9270             route through the lifted accessor rather than the raw \
9271             .de.clone() field-access String-carry"
9272        );
9273    }
9274
9275    #[test]
9276    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9277        // The symmetric read-path pin on the `:para` phantom-name
9278        // refusal arm — same shape as the sibling `:de` pin above but
9279        // on the callee-Servico axis. Pins the wrap envelope's
9280        // `caixa:` field is observed through the lifted
9281        // [`WitContract::destination`] accessor, not the raw
9282        // `.para.clone()` field-access `String`-carry.
9283        let mut s = three_member_spec();
9284        let phantom = contract_http("cart", "phantom", "/x");
9285        s.contratos.push(phantom.clone());
9286        let err = s.validate().unwrap_err();
9287        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9288            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
9289        };
9290        assert_eq!(
9291            caixa,
9292            phantom.destination(),
9293            "ContratoMemberMissing.caixa on the phantom-:para arm must \
9294             byte-equal WitContract::destination — the wrap envelope \
9295             must route through the lifted accessor rather than the raw \
9296             .para.clone() field-access String-carry"
9297        );
9298    }
9299
9300    #[test]
9301    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
9302        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
9303        // refusal arm — the `validate_contrato_caixa` arg must be
9304        // observed through the lifted [`WitContract::source`] accessor,
9305        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
9306        // value routes through the shared
9307        // [`crate::render::require_valid_dns_1123_label`] floor with the
9308        // accessor-projected value; the fired
9309        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
9310        // the offending edge's `.source()`, pinning that the arg + the
9311        // downstream `caixa: caixa.to_string()` wrap route through the
9312        // same accessor's read path.
9313        let mut s = three_member_spec();
9314        let malformed = contract_http("BAD_NAME", "catalog", "/x");
9315        s.contratos.push(malformed.clone());
9316        let err = s.validate().unwrap_err();
9317        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9318            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
9319        };
9320        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9321        assert_eq!(
9322            caixa,
9323            malformed.source(),
9324            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
9325             byte-equal WitContract::source — the shape-gate arg + wrap \
9326             envelope must route through the lifted accessor rather \
9327             than the raw &c.de &String-borrow"
9328        );
9329    }
9330
9331    #[test]
9332    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9333        // Symmetric arm to the sibling `:de` malformed-shape pin above,
9334        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
9335        // route through the lifted [`WitContract::destination`]
9336        // accessor. `:para` runs after the `:de` shape gate in the
9337        // canonical edge-direction order, so the `:de` value must be
9338        // well-shaped for the `:para` gate to fire — the `cart` :de is
9339        // canonical.
9340        let mut s = three_member_spec();
9341        let malformed = contract_http("cart", "BAD_NAME", "/x");
9342        s.contratos.push(malformed.clone());
9343        let err = s.validate().unwrap_err();
9344        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9345            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
9346        };
9347        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9348        assert_eq!(
9349            caixa,
9350            malformed.destination(),
9351            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
9352             byte-equal WitContract::destination — the shape-gate arg + \
9353             wrap envelope must route through the lifted accessor \
9354             rather than the raw &c.para &String-borrow"
9355        );
9356    }
9357
9358    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
9359
9360    #[test]
9361    fn rejects_contrato_de_empty() {
9362        // `:de ""` previously fell through to `ContratoMemberMissing`
9363        // (with `caixa: ""`) because the validated `:membros :caixa`
9364        // set never contains the empty string. The narrower
9365        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
9366        // the offending slot.
9367        let mut s = three_member_spec();
9368        s.contratos.push(contract_http("", "catalog", "/x"));
9369        let err = s.validate().unwrap_err();
9370        assert_eq!(
9371            err,
9372            AplicacaoError::ContratoCaixaEmpty {
9373                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9374            },
9375            "got {err:?}"
9376        );
9377    }
9378
9379    #[test]
9380    fn rejects_contrato_para_empty() {
9381        // Symmetric arm to `:de ""` — `:para ""` previously fell
9382        // through to `ContratoMemberMissing { caixa: "" }`.
9383        let mut s = three_member_spec();
9384        s.contratos.push(contract_http("cart", "", "/x"));
9385        let err = s.validate().unwrap_err();
9386        assert_eq!(
9387            err,
9388            AplicacaoError::ContratoCaixaEmpty {
9389                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9390            },
9391            "got {err:?}"
9392        );
9393    }
9394
9395    #[test]
9396    fn rejects_contrato_de_with_uppercase() {
9397        // The canonical "I copied the Servico's TitleCase display
9398        // name from an ADR" typo. Until this gate landed `:de "Cart"`
9399        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
9400        // as "this caixa isn't in `:membros`" when the root cause is
9401        // "this `:de` value's shape can never legitimately match a
9402        // validated member (DNS-1123 labels are lowercase)". The
9403        // narrower diagnostic names the offending slot, the value
9404        // verbatim, and the parser-shaped reason.
9405        let mut s = three_member_spec();
9406        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9407        let err = s.validate().unwrap_err();
9408        let AplicacaoError::ContratoCaixaInvalid {
9409            slot,
9410            caixa,
9411            reason,
9412        } = err
9413        else {
9414            panic!("expected ContratoCaixaInvalid, got other variant");
9415        };
9416        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9417        assert_eq!(caixa, "Cart");
9418        assert!(
9419            reason.contains("uppercase"),
9420            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9421        );
9422    }
9423
9424    #[test]
9425    fn rejects_contrato_para_with_underscore() {
9426        // The canonical "I'm thinking of a Python module" leak —
9427        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9428        // Pin the `:para` axis surfaces the same diagnostic shape as
9429        // the `:de` axis on the underscore violation.
9430        let mut s = three_member_spec();
9431        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
9432        let err = s.validate().unwrap_err();
9433        assert!(
9434            matches!(
9435                err,
9436                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9437                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
9438            ),
9439            "got {err:?}"
9440        );
9441    }
9442
9443    #[test]
9444    fn rejects_contrato_de_with_dot() {
9445        // A `:contratos :de` value is a single DNS-1123 *label*, not
9446        // a subdomain — mirroring the `:membros :caixa` floor. The
9447        // strictest floor among the use sites wins.
9448        let mut s = three_member_spec();
9449        s.contratos
9450            .push(contract_http("team.cart", "catalog", "/x"));
9451        let err = s.validate().unwrap_err();
9452        assert!(
9453            matches!(
9454                err,
9455                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9456                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
9457            ),
9458            "got {err:?}"
9459        );
9460    }
9461
9462    #[test]
9463    fn rejects_contrato_para_with_unicode() {
9464        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9465        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
9466        // validity check rejects multi-byte UTF-8 by the first
9467        // non-`[a-z0-9-]` byte.
9468        let mut s = three_member_spec();
9469        s.contratos.push(contract_http("cart", "café", "/x"));
9470        let err = s.validate().unwrap_err();
9471        assert!(
9472            matches!(
9473                err,
9474                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9475                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
9476            ),
9477            "got {err:?}"
9478        );
9479    }
9480
9481    #[test]
9482    fn rejects_contrato_de_with_leading_hyphen() {
9483        // DNS-1123 boundary rule: labels must start and end with an
9484        // alphanumeric. K8s rejects `-cart` outright; the narrower
9485        // shape diagnostic now names the violation at caixa-build
9486        // time rather than the misframed membership-lookup arm.
9487        let mut s = three_member_spec();
9488        s.contratos.push(contract_http("-cart", "catalog", "/x"));
9489        let err = s.validate().unwrap_err();
9490        assert!(
9491            matches!(
9492                err,
9493                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9494                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
9495            ),
9496            "got {err:?}"
9497        );
9498    }
9499
9500    #[test]
9501    fn contrato_de_empty_takes_precedence_over_invalid() {
9502        // Order pin: the `ContratoCaixaEmpty` arm fires before the
9503        // `ContratoCaixaInvalid` parse-side arm — same empty-first
9504        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9505        // / `validate_entrada_host` already establish on their peer
9506        // name axes. The empty string is a structurally distinct
9507        // authoring footgun (the author left the field blank, vs.
9508        // typed a malformed value), so it gets its own diagnostic.
9509        let mut s = three_member_spec();
9510        s.contratos.push(contract_http("", "catalog", "/x"));
9511        let err = s.validate().unwrap_err();
9512        assert_eq!(
9513            err,
9514            AplicacaoError::ContratoCaixaEmpty {
9515                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9516            }
9517        );
9518    }
9519
9520    #[test]
9521    fn contrato_de_shape_fires_before_para_shape() {
9522        // Per-axis order pin: within one `:contratos` entry, the `:de`
9523        // shape gate fires before the `:para` shape gate — same
9524        // edge-direction order the existing `ContratoMemberMissing` /
9525        // `ContratoSelfLoop` / target-dispatch checks use, so the
9526        // diagnostic for a contract with both `:de` and `:para`
9527        // malformed is stable. Authors fixing the surfaced `:de`
9528        // first will see `:para`'s diagnostic on re-run.
9529        let mut s = three_member_spec();
9530        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
9531        let err = s.validate().unwrap_err();
9532        assert!(
9533            matches!(
9534                err,
9535                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9536                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9537            ),
9538            "got {err:?}"
9539        );
9540    }
9541
9542    #[test]
9543    fn contrato_shape_fires_before_membership_lookup() {
9544        // The load-bearing pin: an invalid-shape `:de` surfaces its
9545        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
9546        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9547        // an invalid-shape `:de` could never legitimately match any
9548        // member — the prior `ContratoMemberMissing` diagnostic was
9549        // a structural impossibility framed as a graph-membership
9550        // failure. The shape gate now routes every such input through
9551        // the narrower self-locating diagnostic.
9552        let mut s = three_member_spec();
9553        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9554        let err = s.validate().unwrap_err();
9555        assert!(
9556            matches!(
9557                err,
9558                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
9559            ),
9560            "got {err:?}"
9561        );
9562        // And the symmetric case: an invalid-shape `:para` surfaces
9563        // its own diagnostic too, even when `:de` is well-shaped.
9564        let mut s = three_member_spec();
9565        s.contratos.push(contract_http("cart", "Catalog", "/x"));
9566        let err = s.validate().unwrap_err();
9567        assert!(
9568            matches!(
9569                err,
9570                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
9571            ),
9572            "got {err:?}"
9573        );
9574    }
9575
9576    #[test]
9577    fn contrato_shape_fires_before_self_edge_check() {
9578        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
9579        // bugs: the shape violation (uppercase) and the self-edge
9580        // violation. The narrower per-axis shape diagnostic surfaces
9581        // first because fixing the shape may reveal that the author
9582        // also meant to point `:para` at a different member — the
9583        // self-edge framing is only useful once both endpoints have
9584        // valid shape.
9585        let mut s = three_member_spec();
9586        s.contratos.push(contract_http("Cart", "Cart", "/x"));
9587        let err = s.validate().unwrap_err();
9588        assert!(
9589            matches!(
9590                err,
9591                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9592                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9593            ),
9594            "got {err:?}"
9595        );
9596    }
9597
9598    #[test]
9599    fn contrato_well_shaped_phantom_still_raises_member_missing() {
9600        // Strict-improvement pin: a well-shaped `:de` that simply
9601        // isn't in `:membros` (a phantom reference — author meant
9602        // to add the member but didn't, or renamed and missed an
9603        // update) still surfaces `ContratoMemberMissing`, unchanged.
9604        // The shape gate only intercepts inputs that could never
9605        // legitimately match a validated member; legitimately-shaped
9606        // phantom references remain on the graph-membership axis.
9607        let mut s = three_member_spec();
9608        s.contratos
9609            .push(contract_http("phantom-shim", "catalog", "/x"));
9610        let err = s.validate().unwrap_err();
9611        assert!(
9612            matches!(
9613                err,
9614                AplicacaoError::ContratoMemberMissing { ref caixa }
9615                    if caixa == "phantom-shim"
9616            ),
9617            "got {err:?}"
9618        );
9619    }
9620
9621    #[test]
9622    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
9623        // The diagnostic-shape pin: the error names the offending
9624        // slot (`:de` or `:para`) verbatim and the offending value
9625        // verbatim plus a non-empty parser-shaped reason, so the
9626        // author can grep their caixa.lisp for `:de "<name>"` /
9627        // `:para "<name>"` and fix it in one edit. Same diagnostic
9628        // shape as `MembroCaixaInvalid` (3f9d7a0) and
9629        // `PlacementClusterInvalid` (6c8c00b).
9630        let mut s = three_member_spec();
9631        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
9632        let err = s.validate().unwrap_err();
9633        let AplicacaoError::ContratoCaixaInvalid {
9634            slot,
9635            caixa,
9636            reason,
9637        } = err
9638        else {
9639            panic!("expected ContratoCaixaInvalid, got {err:?}");
9640        };
9641        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9642        assert_eq!(caixa, "BAD_NAME");
9643        assert!(
9644            !reason.is_empty(),
9645            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
9646        );
9647    }
9648
9649    #[test]
9650    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
9651        // Scalar-value pin: the two author-facing kebab-case labels the
9652        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
9653        // admits on the `:contratos` per-entry endpoint-shape axis,
9654        // one arm per typed sub-slot. Mirrors the peer scalar-value
9655        // pin the sibling top-level M2 / M3 / Supervisor
9656        // author-facing-label consts carry
9657        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
9658        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
9659        // slot itself), so every altitude of the typed-slot algebra
9660        // shares the same "one canonical byte-string per arm"
9661        // discipline. A future rebrand (`:de` → `:from` matching the
9662        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
9663        // sibling, `:para` → `:to` matching the same, or
9664        // `:de`/`:para` → `:source`/`:target` matching the WIT
9665        // world's `import`/`export` half-vocabulary) lands as an
9666        // edit to exactly one const, and every consumer that reaches
9667        // for the label picks it up at build time rather than at
9668        // runtime as a downstream `ContratoCaixaEmpty` /
9669        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
9670        // diagnostic mismatch far from the rename's commit.
9671        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
9672        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
9673    }
9674
9675    #[test]
9676    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
9677        // Production-through-const pin: the two per-axis labels the
9678        // per-`:contratos` entry endpoint-shape gate at
9679        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
9680        // argument to [`validate_contrato_caixa`] route through the
9681        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
9682        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
9683        // future rebrand that reaches the const but not the gate (or
9684        // vice versa) surfaces here at build time rather than at
9685        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
9686        // `slot: <stale-kebab-case>` diagnostic far from the rename's
9687        // commit. Mirror of the peer
9688        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
9689        // pin (882f498) on the sibling M3 top-level slot axis.
9690        let mut s = three_member_spec();
9691        s.contratos.push(contract_http("", "catalog", "/x"));
9692        assert_eq!(
9693            s.validate().unwrap_err(),
9694            AplicacaoError::ContratoCaixaEmpty {
9695                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9696            }
9697        );
9698        let mut s = three_member_spec();
9699        s.contratos.push(contract_http("cart", "", "/x"));
9700        assert_eq!(
9701            s.validate().unwrap_err(),
9702            AplicacaoError::ContratoCaixaEmpty {
9703                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9704            }
9705        );
9706    }
9707
9708    #[test]
9709    fn accepts_canonical_contrato_caixa_forms() {
9710        // The DNS-1123 label shapes a caixa author is realistically
9711        // going to write on a `:contratos :de` / `:para`. Pin every
9712        // leg so a future tightening that bans (e.g.) digit-start
9713        // identifiers surfaces here, mirroring
9714        // `accepts_canonical_membro_caixa_forms` on the peer name
9715        // axis.
9716        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9717            let mut s = three_member_spec();
9718            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
9719            s.contratos = vec![contract_http("checkout", form, "/x")];
9720            s.entrada = None;
9721            s.validate().unwrap_or_else(|e| {
9722                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
9723            });
9724
9725            let mut s = three_member_spec();
9726            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9727            s.contratos = vec![contract_http(form, "catalog", "/x")];
9728            s.entrada = None;
9729            s.validate().unwrap_or_else(|e| {
9730                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
9731            });
9732        }
9733    }
9734
9735    #[test]
9736    fn rejects_empty_wit() {
9737        let mut s = three_member_spec();
9738        s.contratos.push(WitContract {
9739            de: "cart".into(),
9740            para: "catalog".into(),
9741            wit: "".into(),
9742            endpoint: None,
9743            subject: None,
9744            slot: None,
9745        });
9746        let err = s.validate().unwrap_err();
9747        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
9748    }
9749
9750    #[test]
9751    fn rejects_entrada_to_unknown_member() {
9752        let mut s = three_member_spec();
9753        s.entrada.as_mut().unwrap().para = "phantom".into();
9754        assert!(matches!(
9755            s.validate().unwrap_err(),
9756            AplicacaoError::EntradaMemberMissing { .. }
9757        ));
9758    }
9759
9760    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
9761
9762    #[test]
9763    fn rejects_entrada_para_empty() {
9764        // `:para ""` previously fell through to
9765        // `EntradaMemberMissing { para: "" }` because the validated
9766        // `:membros :caixa` set never contains the empty string. The
9767        // narrower `EntradaParaEmpty` diagnostic now names the
9768        // offending slot directly — same empty-first cascade
9769        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
9770        // `ContratoCaixaEmpty` establish on the peer name axes.
9771        let mut s = three_member_spec();
9772        s.entrada.as_mut().unwrap().para = String::new();
9773        let err = s.validate().unwrap_err();
9774        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
9775    }
9776
9777    #[test]
9778    fn rejects_entrada_para_with_uppercase() {
9779        // The canonical "I copied the Servico's TitleCase display
9780        // name from an ADR" typo. Until this gate landed `:para "Cart"`
9781        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
9782        // as "this caixa isn't in `:membros`" when the root cause is
9783        // "this `:para` value's shape can never legitimately match a
9784        // validated member (DNS-1123 labels are lowercase)". The
9785        // narrower diagnostic names the value verbatim plus the
9786        // parser-shaped reason.
9787        let mut s = three_member_spec();
9788        s.entrada.as_mut().unwrap().para = "Cart".into();
9789        let err = s.validate().unwrap_err();
9790        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9791            panic!("expected EntradaParaInvalid, got other variant");
9792        };
9793        assert_eq!(para, "Cart");
9794        assert!(
9795            reason.contains("uppercase"),
9796            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9797        );
9798    }
9799
9800    #[test]
9801    fn rejects_entrada_para_with_underscore() {
9802        // The canonical "I'm thinking of a Python module" leak —
9803        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9804        let mut s = three_member_spec();
9805        s.entrada.as_mut().unwrap().para = "my_cart".into();
9806        let err = s.validate().unwrap_err();
9807        assert!(
9808            matches!(
9809                err,
9810                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9811                    if para == "my_cart" && reason.contains('_')
9812            ),
9813            "got {err:?}"
9814        );
9815    }
9816
9817    #[test]
9818    fn rejects_entrada_para_with_dot() {
9819        // An `:entrada :para` value is a single DNS-1123 *label*, not
9820        // a subdomain — mirroring the `:membros :caixa` floor. The
9821        // strictest floor among the use sites wins.
9822        let mut s = three_member_spec();
9823        s.entrada.as_mut().unwrap().para = "team.cart".into();
9824        let err = s.validate().unwrap_err();
9825        assert!(
9826            matches!(
9827                err,
9828                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9829                    if para == "team.cart" && reason.contains('.')
9830            ),
9831            "got {err:?}"
9832        );
9833    }
9834
9835    #[test]
9836    fn rejects_entrada_para_with_unicode() {
9837        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9838        // (`xn--…`) before it reaches K8s.
9839        let mut s = three_member_spec();
9840        s.entrada.as_mut().unwrap().para = "café".into();
9841        let err = s.validate().unwrap_err();
9842        assert!(
9843            matches!(
9844                err,
9845                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
9846            ),
9847            "got {err:?}"
9848        );
9849    }
9850
9851    #[test]
9852    fn rejects_entrada_para_with_leading_hyphen() {
9853        // DNS-1123 boundary rule: labels must start and end with an
9854        // alphanumeric. K8s rejects `-cart` outright.
9855        let mut s = three_member_spec();
9856        s.entrada.as_mut().unwrap().para = "-cart".into();
9857        let err = s.validate().unwrap_err();
9858        assert!(
9859            matches!(
9860                err,
9861                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9862                    if para == "-cart" && reason.contains("start and end")
9863            ),
9864            "got {err:?}"
9865        );
9866    }
9867
9868    #[test]
9869    fn rejects_entrada_para_with_trailing_hyphen() {
9870        // Symmetric boundary arm.
9871        let mut s = three_member_spec();
9872        s.entrada.as_mut().unwrap().para = "cart-".into();
9873        let err = s.validate().unwrap_err();
9874        assert!(
9875            matches!(
9876                err,
9877                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9878                    if para == "cart-" && reason.contains("start and end")
9879            ),
9880            "got {err:?}"
9881        );
9882    }
9883
9884    #[test]
9885    fn rejects_entrada_para_too_long() {
9886        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
9887        // bytes per label. K8s rejects longer names at admission on
9888        // every `metadata.name` axis.
9889        let mut s = three_member_spec();
9890        s.entrada.as_mut().unwrap().para = "a".repeat(64);
9891        let err = s.validate().unwrap_err();
9892        assert!(
9893            matches!(
9894                err,
9895                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9896                    if para.len() == 64 && reason.contains("max length")
9897            ),
9898            "got {err:?}"
9899        );
9900    }
9901
9902    #[test]
9903    fn entrada_para_empty_takes_precedence_over_invalid() {
9904        // Order pin: the `EntradaParaEmpty` arm fires before the
9905        // `EntradaParaInvalid` parse-side arm — same empty-first
9906        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9907        // / `validate_contrato_caixa` already establish.
9908        let mut s = three_member_spec();
9909        s.entrada.as_mut().unwrap().para = String::new();
9910        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
9911    }
9912
9913    #[test]
9914    fn entrada_para_shape_fires_before_membership_lookup() {
9915        // The load-bearing pin: an invalid-shape `:para` surfaces its
9916        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
9917        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9918        // an invalid-shape `:para` could never legitimately match any
9919        // member — the prior `EntradaMemberMissing` diagnostic framed
9920        // a structural impossibility as a graph-membership failure.
9921        let mut s = three_member_spec();
9922        s.entrada.as_mut().unwrap().para = "Cart".into();
9923        let err = s.validate().unwrap_err();
9924        assert!(
9925            matches!(
9926                err,
9927                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9928            ),
9929            "got {err:?}"
9930        );
9931    }
9932
9933    #[test]
9934    fn entrada_para_shape_fires_before_host_gate() {
9935        // Per-`:entrada` order pin: the `:para` shape gate fires
9936        // before the `:host` gate, mirroring the existing
9937        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
9938        // ordering where the member-lookup arm preceded the host gate.
9939        // The shape gate slots ahead of that, so a malformed `:para`
9940        // surfaces its own diagnostic even when `:host` is also wrong.
9941        let mut s = three_member_spec();
9942        let e = s.entrada.as_mut().unwrap();
9943        e.para = "Cart".into();
9944        e.host = "BAD HOST".into();
9945        let err = s.validate().unwrap_err();
9946        assert!(
9947            matches!(
9948                err,
9949                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9950            ),
9951            "got {err:?}"
9952        );
9953    }
9954
9955    #[test]
9956    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
9957        // Strict-improvement pin: a well-shaped `:para` that simply
9958        // isn't in `:membros` (a phantom reference — author meant to
9959        // add the member but didn't, or renamed and missed an
9960        // update) still surfaces `EntradaMemberMissing`, unchanged.
9961        // The shape gate only intercepts inputs that could never
9962        // legitimately match a validated member.
9963        let mut s = three_member_spec();
9964        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
9965        let err = s.validate().unwrap_err();
9966        assert!(
9967            matches!(
9968                err,
9969                AplicacaoError::EntradaMemberMissing { ref para }
9970                    if para == "phantom-shim"
9971            ),
9972            "got {err:?}"
9973        );
9974    }
9975
9976    #[test]
9977    fn entrada_para_invalid_diagnostic_carries_offending_para() {
9978        // The diagnostic-shape pin: the error names the offending
9979        // `:para` value verbatim plus a non-empty parser-shaped
9980        // reason, so the author can grep their caixa.lisp for
9981        // `:para "<name>"` and fix it in one edit. Same diagnostic
9982        // shape as `MembroCaixaInvalid` (3f9d7a0),
9983        // `PlacementClusterInvalid` (6c8c00b), and
9984        // `ContratoCaixaInvalid` (8d5af6b).
9985        let mut s = three_member_spec();
9986        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
9987        let err = s.validate().unwrap_err();
9988        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9989            panic!("expected EntradaParaInvalid, got {err:?}");
9990        };
9991        assert_eq!(para, "BAD_NAME");
9992        assert!(
9993            !reason.is_empty(),
9994            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
9995        );
9996    }
9997
9998    #[test]
9999    fn accepts_canonical_entrada_para_forms() {
10000        // Positive-control sweep covering the DNS-1123 label shapes a
10001        // caixa author is realistically going to write on `:entrada
10002        // :para`. Pin every leg so a future tightening that bans
10003        // (e.g.) digit-start identifiers surfaces here, mirroring
10004        // `accepts_canonical_membro_caixa_forms` and
10005        // `accepts_canonical_contrato_caixa_forms` on the peer name
10006        // axes.
10007        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
10008            let mut s = three_member_spec();
10009            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
10010            s.contratos = vec![contract_http(form, "catalog", "/x")];
10011            s.entrada = Some(Entrada {
10012                host: "checkout.quero.cloud".into(),
10013                para: form.into(),
10014                paths: vec!["/api".into()],
10015                port: 8080,
10016            });
10017            s.validate().unwrap_or_else(|e| {
10018                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
10019            });
10020        }
10021    }
10022
10023    #[test]
10024    fn rejects_replicated_without_clusters() {
10025        let mut s = three_member_spec();
10026        s.placement.clusters = vec![];
10027        assert!(matches!(
10028            s.validate().unwrap_err(),
10029            AplicacaoError::PlacementWithoutClusters { .. }
10030        ));
10031    }
10032
10033    #[test]
10034    fn rejects_sharded_without_key() {
10035        let mut s = three_member_spec();
10036        s.placement.estrategia = PlacementStrategy::Sharded;
10037        s.placement.shard_key = None;
10038        s.placement.clusters = vec!["rio".into()];
10039        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
10040    }
10041
10042    #[test]
10043    fn sharded_with_key_validates() {
10044        let mut s = three_member_spec();
10045        s.placement.estrategia = PlacementStrategy::Sharded;
10046        s.placement.shard_key = Some("$tenantId".into());
10047        s.validate().unwrap();
10048    }
10049
10050    #[test]
10051    fn round_trip_via_json_preserves_shape() {
10052        let s = three_member_spec();
10053        let json = serde_json::to_string(&s.membros).unwrap();
10054        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
10055        assert_eq!(back, s.membros);
10056
10057        let json = serde_json::to_string(&s.contratos).unwrap();
10058        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
10059        assert_eq!(back, s.contratos);
10060
10061        let json = serde_json::to_string(&s.placement).unwrap();
10062        let back: Placement = serde_json::from_str(&json).unwrap();
10063        assert_eq!(back, s.placement);
10064
10065        let json = serde_json::to_string(&s.entrada).unwrap();
10066        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
10067        assert_eq!(back, s.entrada);
10068    }
10069
10070    #[test]
10071    fn rate_limit_round_trip_seconds() {
10072        let policy = MeshPolicy {
10073            rate_limit: Some(RateLimit {
10074                rate: 100,
10075                window: Duration::from_secs(1),
10076            }),
10077            ..Default::default()
10078        };
10079        let json = serde_json::to_string(&policy).unwrap();
10080        assert!(json.contains("\"100/s\""));
10081        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10082        assert_eq!(back.rate_limit.unwrap().rate, 100);
10083        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
10084    }
10085
10086    #[test]
10087    fn rate_limit_round_trip_minutes() {
10088        let policy = MeshPolicy {
10089            rate_limit: Some(RateLimit {
10090                rate: 5000,
10091                window: Duration::from_secs(60),
10092            }),
10093            ..Default::default()
10094        };
10095        let json = serde_json::to_string(&policy).unwrap();
10096        assert!(json.contains("\"5000/m\""));
10097    }
10098
10099    #[test]
10100    fn circuit_breaker_round_trip() {
10101        let policy = MeshPolicy {
10102            circuit_breaker: Some(CircuitBreaker {
10103                max_failures: 5,
10104                window: Duration::from_secs(60),
10105            }),
10106            ..Default::default()
10107        };
10108        let json = serde_json::to_string(&policy).unwrap();
10109        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10110        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
10111        assert_eq!(
10112            back.circuit_breaker.unwrap().window,
10113            Duration::from_secs(60)
10114        );
10115    }
10116
10117    #[test]
10118    fn rejects_http_contrato_without_endpoint() {
10119        let mut s = three_member_spec();
10120        s.contratos.push(WitContract {
10121            de: "cart".into(),
10122            para: "catalog".into(),
10123            wit: "wasi:http/proxy".into(),
10124            endpoint: None,
10125            subject: None,
10126            slot: None,
10127        });
10128        let err = s.validate().unwrap_err();
10129        assert!(matches!(
10130            err,
10131            AplicacaoError::ContratoMissingTarget {
10132                expected: WitTarget::HTTP_FIELD_NAME,
10133                ..
10134            }
10135        ));
10136    }
10137
10138    #[test]
10139    fn rejects_http_contrato_with_subject() {
10140        let mut s = three_member_spec();
10141        s.contratos.push(WitContract {
10142            de: "cart".into(),
10143            para: "catalog".into(),
10144            wit: "wasi:http/proxy".into(),
10145            endpoint: Some("/x".into()),
10146            subject: Some("not.allowed.here".into()),
10147            slot: None,
10148        });
10149        let err = s.validate().unwrap_err();
10150        assert!(matches!(
10151            err,
10152            AplicacaoError::ContratoWrongTarget {
10153                expected: WitTarget::HTTP_FIELD_NAME,
10154                ..
10155            }
10156        ));
10157    }
10158
10159    #[test]
10160    fn rejects_pubsub_contrato_without_subject() {
10161        let mut s = three_member_spec();
10162        s.contratos.push(WitContract {
10163            de: "cart".into(),
10164            para: "catalog".into(),
10165            wit: "nats:pub-sub".into(),
10166            endpoint: None,
10167            subject: None,
10168            slot: None,
10169        });
10170        let err = s.validate().unwrap_err();
10171        assert!(matches!(
10172            err,
10173            AplicacaoError::ContratoMissingTarget {
10174                expected: WitTarget::PUBSUB_FIELD_NAME,
10175                ..
10176            }
10177        ));
10178    }
10179
10180    #[test]
10181    fn rejects_pubsub_contrato_with_endpoint() {
10182        let mut s = three_member_spec();
10183        s.contratos.push(WitContract {
10184            de: "cart".into(),
10185            para: "catalog".into(),
10186            wit: "kafka:topic".into(),
10187            endpoint: Some("/wrong".into()),
10188            subject: Some("topic.x".into()),
10189            slot: None,
10190        });
10191        let err = s.validate().unwrap_err();
10192        assert!(matches!(
10193            err,
10194            AplicacaoError::ContratoWrongTarget {
10195                expected: WitTarget::PUBSUB_FIELD_NAME,
10196                ..
10197            }
10198        ));
10199    }
10200
10201    #[test]
10202    fn rejects_store_contrato_without_slot() {
10203        let mut s = three_member_spec();
10204        s.contratos.push(WitContract {
10205            de: "cart".into(),
10206            para: "catalog".into(),
10207            wit: "wasi:keyvalue/store".into(),
10208            endpoint: None,
10209            subject: None,
10210            slot: None,
10211        });
10212        let err = s.validate().unwrap_err();
10213        assert!(matches!(
10214            err,
10215            AplicacaoError::ContratoMissingTarget {
10216                expected: WitTarget::STORE_FIELD_NAME,
10217                ..
10218            }
10219        ));
10220    }
10221
10222    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
10223
10224    #[test]
10225    fn rejects_http_contrato_with_empty_endpoint() {
10226        // `Some("")` for an HTTP endpoint passes the presence check
10227        // (target() previously returned WitTarget::Http { endpoint: "" })
10228        // but renders as a `path: ""` Cilium L7 rule that matches no
10229        // traffic. Same value-shape footgun closed for :entrada :paths
10230        // entries (eb3456d).
10231        let mut s = three_member_spec();
10232        s.contratos.push(WitContract {
10233            de: "cart".into(),
10234            para: "catalog".into(),
10235            wit: "wasi:http/proxy".into(),
10236            endpoint: Some(String::new()),
10237            subject: None,
10238            slot: None,
10239        });
10240        let err = s.validate().unwrap_err();
10241        assert!(
10242            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
10243                if de == "cart" && para == "catalog"),
10244            "got {err:?}"
10245        );
10246    }
10247
10248    #[test]
10249    fn rejects_http_contrato_with_relative_endpoint() {
10250        // Cilium L7 :path + Gateway API PathPrefix both require a
10251        // leading `/`. Same shape required of :entrada :paths
10252        // (eb3456d). Lifted into target() so every consumer of the
10253        // typed WitTarget view inherits the guarantee.
10254        let mut s = three_member_spec();
10255        s.contratos.push(WitContract {
10256            de: "cart".into(),
10257            para: "catalog".into(),
10258            wit: "wasi:http/proxy".into(),
10259            endpoint: Some("products/:id".into()),
10260            subject: None,
10261            slot: None,
10262        });
10263        let err = s.validate().unwrap_err();
10264        assert!(
10265            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10266                if endpoint == "products/:id"),
10267            "got {err:?}"
10268        );
10269    }
10270
10271    #[test]
10272    fn rejects_pubsub_contrato_with_empty_subject() {
10273        // NATS / Kafka publish without a subject is a no-op subscribe;
10274        // never the author's intent. Same empty-string rejection as
10275        // :membros :caixa, :placement :clusters entries, :entrada
10276        // :paths entries — every value carried by every typed slot is
10277        // value-shape-checked at validate().
10278        let mut s = three_member_spec();
10279        s.contratos.push(WitContract {
10280            de: "cart".into(),
10281            para: "catalog".into(),
10282            wit: "nats:pub-sub".into(),
10283            endpoint: None,
10284            subject: Some(String::new()),
10285            slot: None,
10286        });
10287        let err = s.validate().unwrap_err();
10288        assert!(
10289            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
10290                if de == "cart" && para == "catalog"),
10291            "got {err:?}"
10292        );
10293    }
10294
10295    #[test]
10296    fn rejects_store_contrato_with_empty_slot() {
10297        // An empty slot template addresses the bucket root, defeating
10298        // the per-key isolation the slot exists for — a footgun on
10299        // `wasi:keyvalue/store` whose closest analog is the empty
10300        // shard-key rejected on :placement Sharded (c7c7799).
10301        let mut s = three_member_spec();
10302        s.contratos.push(WitContract {
10303            de: "cart".into(),
10304            para: "catalog".into(),
10305            wit: "wasi:keyvalue/store".into(),
10306            endpoint: None,
10307            subject: None,
10308            slot: Some(String::new()),
10309        });
10310        let err = s.validate().unwrap_err();
10311        assert!(
10312            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
10313                if de == "cart" && para == "catalog"),
10314            "got {err:?}"
10315        );
10316    }
10317
10318    #[test]
10319    fn http_contrato_root_endpoint_validates() {
10320        // Pin the boundary case: a single-`/` endpoint is the catch-all
10321        // form the Gateway HTTPRoute renderer falls back to when
10322        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
10323        // must remain a valid contrato endpoint too.
10324        let mut s = three_member_spec();
10325        s.contratos.push(contract_http("cart", "catalog", "/"));
10326        s.validate().unwrap();
10327    }
10328
10329    // ── :contratos :endpoint value-shape gate ────────────────────────────
10330    //
10331    // Mirrors the `:entrada :paths` value-shape suite on the peer
10332    // HTTP-path axis. Until this gate landed `WitContract::target()`
10333    // only refused the empty string + the missing-leading-`/` form
10334    // (c4213a4); a structurally invalid endpoint passed validate and
10335    // landed verbatim as a Cilium L7 `path:` rule
10336    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
10337    // traffic or was rejected at apply time by Cilium policy admission.
10338    // Every authoring footgun the K8s Gateway API webhook / Cilium
10339    // policy validator would catch on admission now becomes a caixa-
10340    // build-time `ContratoEndpointInvalid` with the offending
10341    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
10342    // shape as `EntradaPathInvalid` on the sibling axis; same shared
10343    // predicate (`crate::render::is_gateway_api_http_path`) ensures
10344    // drift between the two axes' rule enforcement is a build error
10345    // at the predicate.
10346
10347    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
10348        // Fresh spec per call so the would-be-duplicate edge
10349        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
10350        // `three_member_spec`'s pre-existing
10351        // `(cart, catalog, …, /products/:id)` entry — only the
10352        // endpoint payload differs.
10353        let mut s = three_member_spec();
10354        s.contratos.push(contract_http("cart", "catalog", ep));
10355        s.validate().unwrap_err()
10356    }
10357
10358    #[test]
10359    fn rejects_http_contrato_endpoint_with_query() {
10360        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
10361        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
10362        // rule the L7 matcher would never satisfy.
10363        let err = contrato_endpoint_err("/charge?token=X");
10364        assert!(
10365            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10366                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
10367            "got {err:?}"
10368        );
10369    }
10370
10371    #[test]
10372    fn rejects_http_contrato_endpoint_with_fragment() {
10373        let err = contrato_endpoint_err("/charge#frag");
10374        assert!(
10375            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10376                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
10377            "got {err:?}"
10378        );
10379    }
10380
10381    #[test]
10382    fn rejects_http_contrato_endpoint_with_whitespace() {
10383        let err = contrato_endpoint_err("/foo bar");
10384        assert!(
10385            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10386                if endpoint == "/foo bar" && reason.contains("whitespace")),
10387            "got {err:?}"
10388        );
10389    }
10390
10391    #[test]
10392    fn rejects_http_contrato_endpoint_with_control_char() {
10393        let err = contrato_endpoint_err("/api/\x01bar");
10394        assert!(
10395            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10396                if endpoint == "/api/\x01bar" && reason.contains("control character")),
10397            "got {err:?}"
10398        );
10399    }
10400
10401    #[test]
10402    fn rejects_http_contrato_endpoint_with_non_ascii() {
10403        let err = contrato_endpoint_err("/api/café");
10404        assert!(
10405            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10406                if endpoint == "/api/café" && reason.contains("non-ASCII")),
10407            "got {err:?}"
10408        );
10409    }
10410
10411    #[test]
10412    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
10413        let err = contrato_endpoint_err("/api//cart");
10414        assert!(
10415            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10416                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
10417            "got {err:?}"
10418        );
10419    }
10420
10421    #[test]
10422    fn rejects_http_contrato_endpoint_with_dot_segment() {
10423        let err = contrato_endpoint_err("/api/./cart");
10424        assert!(
10425            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10426                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
10427            "got {err:?}"
10428        );
10429    }
10430
10431    #[test]
10432    fn rejects_http_contrato_endpoint_with_parent_segment() {
10433        // Path-traversal in a contrato endpoint is the canonical
10434        // "L7 rule that the workload's HTTP server's path-resolution
10435        // logic interprets differently than the policy enforcer"
10436        // footgun. Rejected outright at validate time.
10437        let err = contrato_endpoint_err("/api/../etc");
10438        assert!(
10439            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10440                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
10441            "got {err:?}"
10442        );
10443    }
10444
10445    #[test]
10446    fn rejects_http_contrato_endpoint_too_long() {
10447        // 1025-byte endpoint — one over the Gateway API
10448        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
10449        // path matcher has no inherent length limit but the policy
10450        // CR itself rides through the K8s apiserver, which enforces
10451        // ConfigMap-shaped limits; sharing the Gateway API cap is the
10452        // conservative floor.
10453        let big = format!("/api/{}", "a".repeat(1020));
10454        assert_eq!(big.len(), 1025);
10455        let err = contrato_endpoint_err(&big);
10456        assert!(
10457            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10458                if endpoint == &big && reason.contains("max length of 1024")),
10459            "got {err:?}"
10460        );
10461    }
10462
10463    #[test]
10464    fn http_contrato_endpoint_max_length_validates() {
10465        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
10466        // in the cap surfaces here and at
10467        // `rejects_http_contrato_endpoint_too_long` simultaneously,
10468        // mirroring `entrada_path_max_length_validates` on the peer
10469        // axis.
10470        let big = format!("/api/{}", "a".repeat(1019));
10471        assert_eq!(big.len(), 1024);
10472        let mut s = three_member_spec();
10473        s.contratos.push(contract_http("cart", "catalog", &big));
10474        s.validate().unwrap();
10475    }
10476
10477    #[test]
10478    fn http_contrato_endpoint_accepts_canonical_forms() {
10479        // Positive-set sweep: every canonical HTTP-path shape the
10480        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
10481        // plain paths, hidden-file-style `.config` segments distinct
10482        // from the `.` segment, digit-bearing segments, the canonical
10483        // route-template `:param` form, trailing-slash form,
10484        // percent-encoded segments, the `/foo..bar` interior-`..`-
10485        // substring forms that are NOT `..` segments) must remain a
10486        // valid contrato endpoint too. Drift between this list and
10487        // the entrada path positive sweep surfaces at the shared
10488        // `is_gateway_api_http_path` substrate-side suite — one
10489        // source of truth. Uses a fresh `(payment, catalog)` edge so
10490        // none of the swept endpoints collide with the pre-existing
10491        // `(cart, catalog, /products/:id)` / `(cart, payment,
10492        // /charge)` entries in `three_member_spec`.
10493        for ep in [
10494            "/",
10495            "/charge",
10496            "/v1/charge",
10497            "/api/.config",
10498            "/products/:id",
10499            "/api/cart/",
10500            "/api/caf%C3%A9",
10501            "/foo..bar",
10502            "/...",
10503        ] {
10504            let mut s = three_member_spec();
10505            s.contratos.push(contract_http("payment", "catalog", ep));
10506            s.validate()
10507                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
10508        }
10509    }
10510
10511    #[test]
10512    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
10513        // Ordering pin: `ContratoEndpointEmpty` is the more self-
10514        // locating diagnostic on `""` and must lead — the value-
10515        // shape gate is only reached after the empty-check fires.
10516        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
10517        // on the peer axis.
10518        let mut s = three_member_spec();
10519        s.contratos.push(WitContract {
10520            de: "cart".into(),
10521            para: "catalog".into(),
10522            wit: "wasi:http/proxy".into(),
10523            endpoint: Some(String::new()),
10524            subject: None,
10525            slot: None,
10526        });
10527        let err = s.validate().unwrap_err();
10528        assert!(
10529            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
10530            "got {err:?}"
10531        );
10532    }
10533
10534    #[test]
10535    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
10536        // Ordering pin: an endpoint without a leading `/` surfaces the
10537        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
10538        // value-shape gate is only consulted on endpoints that already
10539        // satisfy the absolute-prefix invariant. Mirrors
10540        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
10541        let err = contrato_endpoint_err("bad path");
10542        assert!(
10543            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10544                if endpoint == "bad path"),
10545            "got {err:?}"
10546        );
10547    }
10548
10549    #[test]
10550    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
10551        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
10552        // `:para` + a non-empty reason flow through verbatim so the
10553        // author can grep their caixa.lisp for the offending contrato
10554        // block and fix it in one edit. Same shape as
10555        // `entrada_path_diagnostic_carries_offending_path`.
10556        let err = contrato_endpoint_err("/api?q=1");
10557        match err {
10558            AplicacaoError::ContratoEndpointInvalid {
10559                de,
10560                para,
10561                endpoint,
10562                reason,
10563            } => {
10564                assert_eq!(de, "cart");
10565                assert_eq!(para, "catalog");
10566                assert_eq!(endpoint, "/api?q=1");
10567                assert!(!reason.is_empty(), "reason field must be non-empty");
10568            }
10569            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
10570        }
10571    }
10572
10573    #[test]
10574    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
10575        // The compounding theorem: every &str inside a WitTarget
10576        // returned by target() is non-empty (and absolute, for Http).
10577        // Renderers downstream of typed_view() can rely on this
10578        // without re-checking — the type system carries the proof.
10579        let http = contract_http("cart", "catalog", "/x");
10580        match http.target().unwrap() {
10581            WitTarget::Http { endpoint } => {
10582                assert!(!endpoint.is_empty());
10583                assert!(endpoint.starts_with('/'));
10584            }
10585            other => panic!("expected Http, got {other:?}"),
10586        }
10587        let nats = WitContract {
10588            de: "a".into(),
10589            para: "b".into(),
10590            wit: "nats:pub-sub".into(),
10591            endpoint: None,
10592            subject: Some("topic.x".into()),
10593            slot: None,
10594        };
10595        match nats.target().unwrap() {
10596            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
10597            other => panic!("expected PubSub, got {other:?}"),
10598        }
10599        let kv = WitContract {
10600            de: "a".into(),
10601            para: "b".into(),
10602            wit: "wasi:keyvalue/store".into(),
10603            endpoint: None,
10604            subject: None,
10605            slot: Some("checkout/$orderId".into()),
10606        };
10607        match kv.target().unwrap() {
10608            WitTarget::Store { slot } => assert!(!slot.is_empty()),
10609            other => panic!("expected Store, got {other:?}"),
10610        }
10611    }
10612
10613    #[test]
10614    fn target_diagnostic_names_offending_endpoint_value() {
10615        // When the malformed endpoint string is non-trivial, the
10616        // diagnostic carries the actual value back to the author —
10617        // not a generic "endpoint malformed" error.
10618        let bad = WitContract {
10619            de: "src".into(),
10620            para: "dst".into(),
10621            wit: "wasi:http/proxy".into(),
10622            endpoint: Some("api/v1/charge".into()),
10623            subject: None,
10624            slot: None,
10625        };
10626        match bad.target().unwrap_err() {
10627            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
10628                assert_eq!(de, "src");
10629                assert_eq!(para, "dst");
10630                assert_eq!(endpoint, "api/v1/charge");
10631            }
10632            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
10633        }
10634    }
10635
10636    #[test]
10637    fn rejects_unknown_wit_with_target_set() {
10638        let mut s = three_member_spec();
10639        s.contratos.push(WitContract {
10640            de: "cart".into(),
10641            para: "catalog".into(),
10642            wit: "custom:exchange".into(),
10643            endpoint: Some("/leaked".into()),
10644            subject: None,
10645            slot: None,
10646        });
10647        let err = s.validate().unwrap_err();
10648        assert!(matches!(
10649            err,
10650            AplicacaoError::ContratoWrongTarget {
10651                expected: WitTarget::CAPABILITY_EXPECTED,
10652                ..
10653            }
10654        ));
10655    }
10656
10657    #[test]
10658    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
10659        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
10660        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
10661        // fourth arm of the same "which payload field name goes in the
10662        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
10663        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10664        // consts cover on the peer HTTP / PubSub / Store arms
10665        // (`wit_target_field_name_pins_per_variant`). Until this lift
10666        // landed the byte-string sat twice — once inline in the
10667        // [`WitContract::target`] Capability-arm rejection at the
10668        // production dispatch, once in `rejects_unknown_wit_with_target_set`
10669        // pinning against the same literal — with no compile-time link
10670        // between them. Same "one canonical declaration, next to the
10671        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
10672        // lift established for the payload-less arm's human-readable
10673        // label axis; this test is the shape peer of
10674        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
10675        // pair (routes-through-const + scalar-value pin) on the
10676        // wrong-target diagnostic-scalar axis.
10677        //
10678        // Fail-before-pass-after was verified locally by mutating the
10679        // const declaration to `"capability"` — the scalar-value pin
10680        // below fires (`"capability" != "none"`) and the routes-through
10681        // assertion below still holds (production and const walk in
10682        // lockstep), which is the correct behavior: a rename on the
10683        // const drifts here first, not at a downstream consumer.
10684        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
10685
10686        let mut s = three_member_spec();
10687        s.contratos.push(WitContract {
10688            de: "cart".into(),
10689            para: "catalog".into(),
10690            wit: "custom:exchange".into(),
10691            endpoint: Some("/leaked".into()),
10692            subject: None,
10693            slot: None,
10694        });
10695        match s.validate().unwrap_err() {
10696            AplicacaoError::ContratoWrongTarget { expected, .. } => {
10697                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
10698            }
10699            other => panic!("expected ContratoWrongTarget, got {other:?}"),
10700        }
10701    }
10702
10703    #[test]
10704    fn unknown_wit_capability_only_validates() {
10705        let mut s = three_member_spec();
10706        s.contratos.push(WitContract {
10707            de: "cart".into(),
10708            para: "catalog".into(),
10709            // A WIT world we haven't yet shaped — accept it as a typed
10710            // capability edge so authors aren't blocked while the WIT
10711            // registry catches up. No payload field may be carried.
10712            wit: "custom:exchange".into(),
10713            endpoint: None,
10714            subject: None,
10715            slot: None,
10716        });
10717        s.validate().unwrap();
10718        let added = s.contratos.last().unwrap();
10719        assert_eq!(added.target().unwrap(), WitTarget::Capability);
10720    }
10721
10722    #[test]
10723    fn target_typed_view_round_trips_each_shape() {
10724        let http = contract_http("cart", "catalog", "/products/:id");
10725        assert_eq!(
10726            http.target().unwrap(),
10727            WitTarget::Http {
10728                endpoint: "/products/:id"
10729            }
10730        );
10731        let nats = WitContract {
10732            de: "a".into(),
10733            para: "b".into(),
10734            wit: "nats:pub-sub".into(),
10735            endpoint: None,
10736            subject: Some("topic.x".into()),
10737            slot: None,
10738        };
10739        assert_eq!(
10740            nats.target().unwrap(),
10741            WitTarget::PubSub { subject: "topic.x" }
10742        );
10743        let kv = WitContract {
10744            de: "a".into(),
10745            para: "b".into(),
10746            wit: "wasi:keyvalue/store".into(),
10747            endpoint: None,
10748            subject: None,
10749            slot: Some("checkout/$orderId".into()),
10750        };
10751        assert_eq!(
10752            kv.target().unwrap(),
10753            WitTarget::Store {
10754                slot: "checkout/$orderId"
10755            }
10756        );
10757    }
10758
10759    #[test]
10760    fn wit_contract_kind_predicates() {
10761        let http = contract_http("a", "b", "/x");
10762        assert!(http.is_http());
10763        assert!(!http.is_pubsub());
10764        assert!(!http.is_store());
10765        assert!(!http.is_capability());
10766
10767        let nats = WitContract {
10768            de: "a".into(),
10769            para: "b".into(),
10770            wit: "nats:pub-sub".into(),
10771            endpoint: None,
10772            subject: Some("topic.x".into()),
10773            slot: None,
10774        };
10775        assert!(nats.is_pubsub());
10776        assert!(!nats.is_http());
10777        assert!(!nats.is_capability());
10778
10779        let kv = WitContract {
10780            de: "a".into(),
10781            para: "b".into(),
10782            wit: "wasi:keyvalue/store".into(),
10783            endpoint: None,
10784            subject: None,
10785            slot: Some("checkout/$orderId".into()),
10786        };
10787        assert!(kv.is_store());
10788        assert!(!kv.is_http());
10789        assert!(!kv.is_capability());
10790
10791        // Fourth arm on the paired closed-set predicate family: the
10792        // payload-less capability edge that projects to the payload-
10793        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
10794        // Extends the 3-arm predicate sweep this test opened to cover
10795        // the closed 4-way partition [`WitContract::is_capability`]
10796        // closes on the pre-projection WIT-shape axis, matched with the
10797        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
10798        // 4-arm predicate set.
10799        let cap = WitContract {
10800            de: "a".into(),
10801            para: "b".into(),
10802            wit: "custom:capability-only".into(),
10803            endpoint: None,
10804            subject: None,
10805            slot: None,
10806        };
10807        assert!(cap.is_capability());
10808        assert!(!cap.is_http());
10809        assert!(!cap.is_pubsub());
10810        assert!(!cap.is_store());
10811    }
10812
10813    // ── :contratos :wit value-shape gate ─────────────────────────────────
10814    //
10815    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
10816    // dispatch-discriminator axis. Until this gate landed
10817    // `WitContract::target()` accepted any non-empty string and
10818    // silently demoted unrecognized shapes to a capability-only L4
10819    // edge — the canonical "I thought I had L7 HTTP routing, got
10820    // L4-only" footgun. Every authoring footgun the WIT registry's
10821    // own grammar rejects (uppercase, hyphen-for-colon typo,
10822    // whitespace, empty package, doubled `@`, …) now becomes a
10823    // caixa-build-time `ContratoWitInvalid` with the offending
10824    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
10825    // as `ContratoEndpointInvalid` on the sibling axis; same shared
10826    // predicate (`crate::render::is_wit_world_ref`) ensures drift
10827    // between any two axes' rule enforcement is a build error at the
10828    // predicate, not piecemeal across renderers.
10829
10830    fn contrato_wit_err(wit: &str) -> AplicacaoError {
10831        // Fresh spec per call so the new contract doesn't collide on
10832        // identity with `three_member_spec`'s pre-existing entries.
10833        // The new edge uses `(payment, catalog)` — a pair the fixture
10834        // doesn't already declare — with no payload field set, so the
10835        // wit-shape gate fires before any payload-shape arm.
10836        let mut s = three_member_spec();
10837        s.contratos.push(WitContract {
10838            de: "payment".into(),
10839            para: "catalog".into(),
10840            wit: wit.into(),
10841            endpoint: None,
10842            subject: None,
10843            slot: None,
10844        });
10845        s.validate().unwrap_err()
10846    }
10847
10848    #[test]
10849    fn rejects_wit_with_uppercase_namespace() {
10850        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
10851        // didn't match the lowercase `wasi:http/` prefix is_http() keys
10852        // off, so the dispatch fell through to the capability arm and
10853        // the contract silently rendered as an L4-only Cilium edge.
10854        // The new gate surfaces the uppercase typo at validate time
10855        // with the offending `:wit` named.
10856        let err = contrato_wit_err("WASI:http/proxy");
10857        assert!(
10858            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10859                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
10860            "got {err:?}"
10861        );
10862    }
10863
10864    #[test]
10865    fn rejects_wit_with_hyphen_for_colon_typo() {
10866        // The canonical "I forgot the `:` separator" typo — pre-gate
10867        // this passed as Capability silently, so the renderer emitted
10868        // an L4-only policy where the author expected L7 HTTP rules.
10869        let err = contrato_wit_err("wasi-http/proxy");
10870        assert!(
10871            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10872                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
10873            "got {err:?}"
10874        );
10875    }
10876
10877    #[test]
10878    fn rejects_wit_with_multiple_colons() {
10879        // Doubled `:` — the namespace/package split has nowhere to
10880        // anchor, so the dispatch silently demotes to Capability.
10881        let err = contrato_wit_err("wasi:http:proxy");
10882        assert!(
10883            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10884                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
10885            "got {err:?}"
10886        );
10887    }
10888
10889    #[test]
10890    fn rejects_wit_with_empty_package() {
10891        // `wasi:` — namespace alone with no package. Pre-gate this
10892        // failed neither the is_http nor is_pubsub nor is_store
10893        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
10894        // a bare `wasi:`), so it silently demoted to Capability.
10895        let err = contrato_wit_err("wasi:");
10896        assert!(
10897            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10898                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
10899            "got {err:?}"
10900        );
10901    }
10902
10903    #[test]
10904    fn rejects_wit_with_underscore() {
10905        // Underscore — WIT identifiers are kebab-case, same rule
10906        // DNS-1123 enforces on its peer axes. The diagnostic carries
10907        // the explicit "use `-` instead" remediation.
10908        let err = contrato_wit_err("wasi:http_proxy");
10909        assert!(
10910            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10911                if wit == "wasi:http_proxy" && reason.contains('_')),
10912            "got {err:?}"
10913        );
10914    }
10915
10916    #[test]
10917    fn rejects_wit_with_whitespace() {
10918        // Whitespace mid-token — the prefix check matches but the
10919        // package-and-onward parse silently demoted to Capability.
10920        let err = contrato_wit_err("wasi:http proxy");
10921        assert!(
10922            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10923                if wit == "wasi:http proxy" && reason.contains("whitespace")),
10924            "got {err:?}"
10925        );
10926    }
10927
10928    #[test]
10929    fn rejects_wit_with_non_ascii() {
10930        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10931        // the package name from a doc with smart quotes / accented
10932        // characters" footgun.
10933        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
10934        assert!(
10935            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10936                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
10937            "got {err:?}"
10938        );
10939    }
10940
10941    #[test]
10942    fn rejects_wit_with_consecutive_hyphens() {
10943        // `pub--sub` — WIT identifiers join words with single hyphens.
10944        let err = contrato_wit_err("nats:pub--sub");
10945        assert!(
10946            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10947                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
10948            "got {err:?}"
10949        );
10950    }
10951
10952    #[test]
10953    fn rejects_wit_with_trailing_at_no_version() {
10954        // `wasi:http/proxy@` — the version-suffix author started to
10955        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
10956        // parser would reject this; surface it at validate time.
10957        let err = contrato_wit_err("wasi:http/proxy@");
10958        assert!(
10959            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10960                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
10961            "got {err:?}"
10962        );
10963    }
10964
10965    #[test]
10966    fn rejects_wit_too_long() {
10967        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
10968        // The legitimate-shape arms all pass (lowercase, single `:`,
10969        // kebab-case identifiers); only the cap arm fires. Surfaces
10970        // the paste-from-binary / accidental-multi-line-blob landing
10971        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10972        // on the peer axis.
10973        let big = format!("wasi:{}", "a".repeat(124));
10974        assert_eq!(big.len(), 129);
10975        let err = contrato_wit_err(&big);
10976        assert!(
10977            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10978                if wit == &big && reason.contains("max length of 128")),
10979            "got {err:?}"
10980        );
10981    }
10982
10983    #[test]
10984    fn wit_max_length_validates() {
10985        // 128-byte WIT reference — exactly the cap. Boundary pin:
10986        // drift in the cap surfaces here and at `rejects_wit_too_long`
10987        // simultaneously, mirroring
10988        // `http_contrato_endpoint_max_length_validates` on the peer
10989        // axis.
10990        let big = format!("wasi:{}", "a".repeat(123));
10991        assert_eq!(big.len(), 128);
10992        let mut s = three_member_spec();
10993        s.contratos.push(WitContract {
10994            de: "payment".into(),
10995            para: "catalog".into(),
10996            wit: big,
10997            endpoint: None,
10998            subject: None,
10999            slot: None,
11000        });
11001        s.validate().unwrap();
11002    }
11003
11004    #[test]
11005    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
11006        // Positive-set sweep through the AplicacaoSpec::validate
11007        // surface (rather than the substrate-side predicate directly)
11008        // — pins every shape the existing test fixtures + the
11009        // checkout-aplicacao example carry, so the gate's accept-set
11010        // matches the substrate's emit-set. Drift between this list
11011        // and `render::tests::wit_world_ref_accepts_canonical_forms`
11012        // surfaces at the substrate layer's positive sweep — one
11013        // source of truth for the rule.
11014        for wit in [
11015            "wasi:http/proxy",
11016            "wasi:keyvalue/store",
11017            "nats:pub-sub",
11018            "kafka:topic",
11019            "custom:exchange",
11020            "pleme:cap/audit",
11021            "wasi:http/proxy@0.2.0",
11022        ] {
11023            // Payload field paired to the dispatched WIT shape so the
11024            // shape-↔-target arm doesn't fire instead of the wit-shape
11025            // arm we're exercising. Routes off the same
11026            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
11027            // `wit_shape_is_store` free functions the production
11028            // `WitContract::is_http` / `is_pubsub` / `is_store`
11029            // methods delegate to (both consult the lifted
11030            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
11031            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
11032            // future prefix addition to the routing accept-set
11033            // reaches this test's payload-dispatch arm by
11034            // construction — no per-test-site drift can hide a
11035            // shape-→-target-slot mismatch that would silently
11036            // demote a canonical `:wit` value to the
11037            // `(None, None, None)` capability-only arm and let the
11038            // `AplicacaoSpec::validate` positive sweep pass on a
11039            // shape it should exercise as HTTP / pub-sub / store.
11040            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
11041                (Some("/x".into()), None, None)
11042            } else if wit_shape_is_pubsub(wit) {
11043                (None, Some("topic.x".into()), None)
11044            } else if wit_shape_is_store(wit) {
11045                (None, None, Some("bucket/$key".into()))
11046            } else {
11047                (None, None, None)
11048            };
11049            let mut s = three_member_spec();
11050            s.contratos.push(WitContract {
11051                de: "payment".into(),
11052                para: "catalog".into(),
11053                wit: wit.into(),
11054                endpoint,
11055                subject,
11056                slot,
11057            });
11058            s.validate()
11059                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
11060        }
11061    }
11062
11063    #[test]
11064    fn wit_shape_predicates_accept_canonical_prefix_set() {
11065        // Positive-set sweep pinning every prefix in
11066        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
11067        // WIT_STORE_SHAPE_PREFIXES against the three free-function
11068        // dispatch predicates. The six prefixes are the load-bearing
11069        // routing keys the substrate's WIT-shape dispatch consults
11070        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
11071        // key/value-store-slot admission); any drift between the
11072        // free-function accept-set and this list surfaces here
11073        // rather than at apply time as a silent
11074        // shape-→-capability-only demotion.
11075        assert!(wit_shape_is_http("wasi:http/proxy"));
11076        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
11077        assert!(wit_shape_is_http("http:incoming"));
11078
11079        assert!(wit_shape_is_pubsub("nats:pub-sub"));
11080        assert!(wit_shape_is_pubsub("kafka:topic"));
11081
11082        assert!(wit_shape_is_store("wasi:keyvalue/store"));
11083        assert!(wit_shape_is_store("kv:cache/session"));
11084    }
11085
11086    #[test]
11087    fn wit_shape_predicates_reject_uncanonical_forms() {
11088        // Negative-set pin: the six canonical prefixes are
11089        // lowercase-only (mirrors the `is_wit_world_ref` substrate
11090        // predicate's lowercase invariant — see its docstring on the
11091        // "I thought I had L7 HTTP routing, got L4-only" footgun).
11092        // The empty string, an uppercase-prefixed form, a hyphen-
11093        // instead-of-colon typo, and a bare kebab identifier all miss
11094        // every shape arm — reachable-by-construction only via the
11095        // `is_wit_world_ref` gate that admission-checks the `:wit`
11096        // value first, but pinned here so any future
11097        // free-function change (e.g. a case-insensitive
11098        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
11099        // this unit level.
11100        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
11101            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
11102            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
11103            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
11104        }
11105    }
11106
11107    #[test]
11108    fn wit_shape_predicates_partition_canonical_set() {
11109        // Every canonical prefix routes to exactly one shape arm —
11110        // the three prefix sets are pairwise disjoint. Pins the
11111        // routing property [`WitContract::target`] relies on: an
11112        // `is_http()` return of `true` guarantees `is_pubsub()` and
11113        // `is_store()` return `false`, so the shape-→-target-slot
11114        // dispatch (endpoint vs subject vs slot) is unambiguous.
11115        // Drift (e.g. a future `"kv:"` moved into the HTTP set
11116        // without removal from the store set) would silently route
11117        // one prefix to two arms and the first-matching-arm order
11118        // becomes load-bearing — this pin surfaces it as a build
11119        // error instead.
11120        for prefix in WIT_HTTP_SHAPE_PREFIXES {
11121            let sample = format!("{prefix}x");
11122            assert!(wit_shape_is_http(&sample));
11123            assert!(!wit_shape_is_pubsub(&sample));
11124            assert!(!wit_shape_is_store(&sample));
11125        }
11126        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
11127            let sample = format!("{prefix}x");
11128            assert!(!wit_shape_is_http(&sample));
11129            assert!(wit_shape_is_pubsub(&sample));
11130            assert!(!wit_shape_is_store(&sample));
11131        }
11132        for prefix in WIT_STORE_SHAPE_PREFIXES {
11133            let sample = format!("{prefix}x");
11134            assert!(!wit_shape_is_http(&sample));
11135            assert!(!wit_shape_is_pubsub(&sample));
11136            assert!(wit_shape_is_store(&sample));
11137        }
11138    }
11139
11140    #[test]
11141    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
11142        // Positive pin: [`wit_shape_matches`] is exactly the
11143        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
11144        // parameterized on the accept-set. Two-prefix accept-set,
11145        // one-prefix accept-set, and empty accept-set (which must
11146        // reject everything, including the empty string — an empty
11147        // `any()` fold returns `false`) all pinned so a future
11148        // reimplementation that swaps `starts_with` for `contains`,
11149        // `==`, or a case-folded comparator surfaces at unit-test
11150        // time.
11151        let two = &["wasi:http/", "http:"];
11152        assert!(wit_shape_matches("wasi:http/proxy", two));
11153        assert!(wit_shape_matches("http:incoming", two));
11154        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
11155
11156        let one = &["nats:"];
11157        assert!(wit_shape_matches("nats:pub-sub", one));
11158        assert!(!wit_shape_matches("kafka:topic", one));
11159
11160        // Empty accept-set matches nothing — the identity element
11161        // for the disjunctive `any()` fold across the prefix set.
11162        // Reachable via a future `wit_shape_is_<name>` const paired
11163        // to a still-empty prefix table on a nascent shape-arm draft.
11164        let empty: &[&str] = &[];
11165        assert!(!wit_shape_matches("wasi:http/proxy", empty));
11166        assert!(!wit_shape_matches("", empty));
11167
11168        // starts_with, not contains: a prefix embedded mid-string
11169        // never matches. Pins the routing invariant [`WitContract::target`]
11170        // relies on (an authored `:wit "custom:wasi:http/"` string
11171        // does not silently route through the HTTP arm just because
11172        // it happens to contain the canonical HTTP prefix).
11173        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
11174    }
11175
11176    #[test]
11177    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
11178        // Equivalence pin: each per-shape predicate is exactly
11179        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
11180        // every canonical prefix + the empty string + one negative
11181        // sample against every peer so a future predicate that grew
11182        // its own inline `iter().any(starts_with)` (rather than
11183        // delegating through the lifted combinator) drifts loudly here
11184        // — the peer-const table's contents must agree with the
11185        // predicate's accept-set by construction.
11186        let samples = [
11187            String::new(),
11188            "wasi:http/proxy".to_string(),
11189            "http:incoming".to_string(),
11190            "nats:pub-sub".to_string(),
11191            "kafka:topic".to_string(),
11192            "wasi:keyvalue/store".to_string(),
11193            "kv:cache/session".to_string(),
11194            "custom-shape".to_string(),
11195            "WASI:HTTP/proxy".to_string(),
11196        ];
11197        for wit in &samples {
11198            assert_eq!(
11199                wit_shape_is_http(wit),
11200                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11201                "wit_shape_is_http drifted from combinator on {wit:?}",
11202            );
11203            assert_eq!(
11204                wit_shape_is_pubsub(wit),
11205                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
11206                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
11207            );
11208            assert_eq!(
11209                wit_shape_is_store(wit),
11210                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
11211                "wit_shape_is_store drifted from combinator on {wit:?}",
11212            );
11213        }
11214    }
11215
11216    #[test]
11217    fn wit_contract_shape_methods_delegate_to_free_functions() {
11218        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
11219        // `is_store` are `&self` conveniences on top of the free
11220        // functions — for every canonical prefix the method's return
11221        // matches its free-function peer. Sweeps the union of the
11222        // three prefix sets so a future method that grew its own
11223        // inline prefix logic (rather than delegating) drifts loudly
11224        // here on the first prefix the free function accepts and the
11225        // method doesn't.
11226        for shape_set in [
11227            WIT_HTTP_SHAPE_PREFIXES,
11228            WIT_PUBSUB_SHAPE_PREFIXES,
11229            WIT_STORE_SHAPE_PREFIXES,
11230        ] {
11231            for prefix in shape_set {
11232                let c = WitContract {
11233                    de: "cart".into(),
11234                    para: "catalog".into(),
11235                    wit: format!("{prefix}x"),
11236                    endpoint: None,
11237                    subject: None,
11238                    slot: None,
11239                };
11240                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
11241                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
11242                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
11243                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11244            }
11245        }
11246        // Capability-arm delegation sweep: two representative
11247        // Capability-shaped `:wit` values (a bare non-prefix-matching
11248        // WIT world, the deliberately-shaped empty string
11249        // [`WitContract::is_capability`]'s docstring calls out as
11250        // syntactically Capability). Extends the free-function
11251        // delegation pin onto the fourth arm so a future
11252        // [`WitContract::is_capability`] rewrite that grew an inline
11253        // prefix-set scan (rather than delegating through
11254        // [`wit_shape_is_capability`]) drifts loudly here on the first
11255        // Capability-shaped sample.
11256        for wit in ["custom:capability-only", ""] {
11257            let c = WitContract {
11258                de: "cart".into(),
11259                para: "catalog".into(),
11260                wit: wit.into(),
11261                endpoint: None,
11262                subject: None,
11263                slot: None,
11264            };
11265            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11266        }
11267    }
11268
11269    #[test]
11270    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
11271        // 4-way partition-witness pin on the raw `&str` axis: for every
11272        // canonical prefix in the three payload-arm accept-sets,
11273        // exactly one of the four [`wit_shape_is_http`] /
11274        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11275        // [`wit_shape_is_capability`] free functions returns `true` and
11276        // the other three return `false` — the four-arm partition
11277        // witness that locks the free-function WIT-shape-classifier
11278        // family into a partition of the `:contratos :wit` axis
11279        // load-bearing. Peer of the sibling [`WitContract`]-surface
11280        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
11281        // partition pin — extends the discipline onto the raw `&str`
11282        // axis so any future arm addition (a hypothetical
11283        // `wasi:sockets/*` transport-layer shape, an `oci:*`
11284        // capability-import carrier per the sibling
11285        // [`wit_shape_matches`] docstring's trajectory bullet) that
11286        // landed on one of the payload-arm free functions without
11287        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
11288        // here as two arms returning `true` simultaneously at
11289        // caixa-core build time rather than a silent per-consumer
11290        // misclassification at renderer emit time.
11291        for shape_set in [
11292            WIT_HTTP_SHAPE_PREFIXES,
11293            WIT_PUBSUB_SHAPE_PREFIXES,
11294            WIT_STORE_SHAPE_PREFIXES,
11295        ] {
11296            for prefix in shape_set {
11297                let wit = format!("{prefix}x");
11298                let hits = [
11299                    wit_shape_is_http(&wit),
11300                    wit_shape_is_pubsub(&wit),
11301                    wit_shape_is_store(&wit),
11302                    wit_shape_is_capability(&wit),
11303                ]
11304                .iter()
11305                .filter(|&&b| b)
11306                .count();
11307                assert_eq!(
11308                    hits,
11309                    1,
11310                    "raw-&str WIT-shape 4-way predicate partition must \
11311                     admit exactly one arm per canonical prefix; got {hits} \
11312                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
11313                     is_capability={})",
11314                    wit_shape_is_http(&wit),
11315                    wit_shape_is_pubsub(&wit),
11316                    wit_shape_is_store(&wit),
11317                    wit_shape_is_capability(&wit),
11318                );
11319            }
11320        }
11321        // Capability-arm sweep on the raw `&str` axis: two
11322        // representative Capability-shaped `:wit` values (a bare non-
11323        // prefix-matching WIT world, the deliberately-shaped empty
11324        // string the pure classifier still admits per
11325        // [`wit_shape_is_capability`]'s docstring). Both must land on
11326        // the fourth arm exclusively so the partition witness holds
11327        // across the full 4-arm closure on the raw `&str` axis.
11328        for wit in ["custom:capability-only", ""] {
11329            let hits = [
11330                wit_shape_is_http(wit),
11331                wit_shape_is_pubsub(wit),
11332                wit_shape_is_store(wit),
11333                wit_shape_is_capability(wit),
11334            ]
11335            .iter()
11336            .filter(|&&b| b)
11337            .count();
11338            assert_eq!(
11339                hits, 1,
11340                "raw-&str WIT-shape 4-way predicate partition must \
11341                 admit exactly one arm on Capability-shaped wit={wit:?}"
11342            );
11343            assert!(
11344                wit_shape_is_capability(wit),
11345                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
11346            );
11347        }
11348    }
11349
11350    #[test]
11351    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
11352        // Composition-witness pin: [`wit_shape_is_capability`] is the
11353        // exact-inverse disjunction of the sibling payload-arm free-
11354        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
11355        // / [`wit_shape_is_store`]. A future reimplementation that
11356        // grew its own prefix-set scan (e.g. inlining a fourth
11357        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
11358        // not own today) rather than delegating to the sibling trio
11359        // would drift loudly here — the composition contract binds the
11360        // fourth-arm free-function predicate to the exact-inverse of
11361        // the three payload-arm free-function predicates, so any
11362        // rebrand of any prefix-set const flows through
11363        // [`wit_shape_is_capability`] by construction without a
11364        // coordinated per-consumer rewrite. Peer of the sibling
11365        // [`WitContract`]-surface
11366        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
11367        // composition pin — extends the discipline onto the raw
11368        // `&str` axis.
11369        let mut cases: Vec<String> = Vec::new();
11370        for shape_set in [
11371            WIT_HTTP_SHAPE_PREFIXES,
11372            WIT_PUBSUB_SHAPE_PREFIXES,
11373            WIT_STORE_SHAPE_PREFIXES,
11374        ] {
11375            for prefix in shape_set {
11376                cases.push(format!("{prefix}x"));
11377            }
11378        }
11379        cases.push("custom:capability-only".to_string());
11380        cases.push(String::new());
11381        for wit in cases {
11382            assert_eq!(
11383                wit_shape_is_capability(&wit),
11384                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
11385                "wit_shape_is_capability must equal \
11386                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
11387                 at wit={wit:?}"
11388            );
11389        }
11390    }
11391
11392    #[test]
11393    fn wit_shape_classifier_family_is_const_fn() {
11394        // Fail-before-pass-after pin on the 4-arm free-function WIT-
11395        // shape classifier family's `const`-eval posture. Each of the
11396        // four peer classifiers ([`wit_shape_is_http`] /
11397        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11398        // [`wit_shape_is_capability`]) and the underlying combinator
11399        // [`wit_shape_matches`] must be `pub const fn` — any future
11400        // accidental downgrade to non-`const` fails the `const fn`
11401        // wrappers below at caixa-core build time with E0015
11402        // (`cannot call non-const function`), strictly stronger than
11403        // a runtime `assert!` and strictly stronger than the module-
11404        // scope `const _: () = assert!(…)` pins immediately after the
11405        // classifier declarations (those anchor specific accept-set
11406        // truth-table entries; this pin anchors the `const` posture
11407        // itself via `const fn` wrappers that are only well-formed
11408        // when the callee is itself `const fn`).
11409        //
11410        // Verified fail-before-pass-after by locally reverting
11411        // `pub const fn` → `pub fn` on each classifier and observing
11412        // E0015 at every corresponding wrapper call site (build
11413        // error, no test-time surface), then restoring `pub const fn`
11414        // and observing the pin pass at test time. Peer of the
11415        // sibling M3
11416        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11417        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11418        // M2
11419        // [`child_spec_restart_accessor_is_const_fn`] /
11420        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11421        // and M3
11422        // [`placement_estrategia_accessor_is_const_fn`] /
11423        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11424        // sibling `const`-eval-surface-pass axes.
11425        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
11426            wit_shape_matches(wit, prefixes)
11427        }
11428        const fn http_via_const_fn(wit: &str) -> bool {
11429            wit_shape_is_http(wit)
11430        }
11431        const fn pubsub_via_const_fn(wit: &str) -> bool {
11432            wit_shape_is_pubsub(wit)
11433        }
11434        const fn store_via_const_fn(wit: &str) -> bool {
11435            wit_shape_is_store(wit)
11436        }
11437        const fn capability_via_const_fn(wit: &str) -> bool {
11438            wit_shape_is_capability(wit)
11439        }
11440        // Sweep one canonical accept-set sample per arm plus the
11441        // payload-less/empty capability samples, asserting the
11442        // wrapper and direct dispatches agree byte-for-byte across
11443        // the closed 4-arm partition.
11444        let cases: [(&str, bool, bool, bool, bool); 6] = [
11445            ("wasi:http/proxy", true, false, false, false),
11446            ("http:incoming", true, false, false, false),
11447            ("nats:events", false, true, false, false),
11448            ("kafka:topic", false, true, false, false),
11449            ("wasi:keyvalue/store", false, false, true, false),
11450            ("kv:cache", false, false, true, false),
11451        ];
11452        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
11453            assert_eq!(
11454                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
11455                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11456                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
11457            );
11458            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
11459            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
11460            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
11461            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11462            assert_eq!(wit_shape_is_http(wit), is_http);
11463            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
11464            assert_eq!(wit_shape_is_store(wit), is_store);
11465        }
11466        // Payload-less capability arm (the 4th partition arm).
11467        let capability_samples: [&str; 3] =
11468            ["wasi:filesystem/preopens", "custom:capability-only", ""];
11469        for wit in capability_samples {
11470            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11471            assert!(wit_shape_is_capability(wit));
11472            assert!(!wit_shape_is_http(wit));
11473            assert!(!wit_shape_is_pubsub(wit));
11474            assert!(!wit_shape_is_store(wit));
11475        }
11476    }
11477
11478    #[test]
11479    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
11480        // Composition-witness pin: [`wit_shape_matches`] agrees with
11481        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
11482        // dispatch (the prior non-`const` implementation) across
11483        // boundary lengths — empty `wit`, empty prefix, one-byte
11484        // slack, prefix longer than `wit`, one-byte trailing slack.
11485        // The rewrite to a byte-level manual starts_with loop (the
11486        // enabler for the `pub const fn` posture) must not change any
11487        // truth-table entry on the canonical accept-set — this pin
11488        // sweeps a targeted boundary corpus and asserts byte-for-byte
11489        // agreement, locking the const-fn rewrite's semantics against
11490        // the prior iterator body by construction.
11491        let prefixes = &["wasi:http/", "http:"][..];
11492        let cases: [(&str, bool); 12] = [
11493            ("wasi:http/proxy", true),
11494            ("wasi:http/", true), // exact-length match on prefix
11495            ("wasi:http", false), // one byte short
11496            ("http:", true),
11497            ("http:incoming", true),
11498            ("http", false), // one byte short
11499            ("", false),
11500            ("wasi:https/proxy", false),
11501            ("nats:events", false),
11502            ("HTTPS:", false), // uppercase — no case-fold in classifier
11503            ("wasi:HTTP/proxy", false),
11504            ("wasi:http", false),
11505        ];
11506        for (wit, expected) in cases {
11507            assert_eq!(
11508                wit_shape_matches(wit, prefixes),
11509                expected,
11510                "wit_shape_matches disagrees with reference at wit={wit:?}",
11511            );
11512            // Byte-equal to the iterator body it replaced.
11513            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
11514            assert_eq!(
11515                wit_shape_matches(wit, prefixes),
11516                via_iter,
11517                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
11518            );
11519        }
11520        // Empty prefix set → always false regardless of `wit`.
11521        let empty: &[&str] = &[];
11522        assert!(!wit_shape_matches("", empty));
11523        assert!(!wit_shape_matches("wasi:http/proxy", empty));
11524        // Empty prefix inside a non-empty set → always true (every
11525        // string starts with the empty string, matching the
11526        // iterator body's semantics on `str::starts_with("")`).
11527        let contains_empty: &[&str] = &["nats:", ""];
11528        assert!(wit_shape_matches("", contains_empty));
11529        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
11530    }
11531
11532    #[test]
11533    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
11534        // 4-way partition-witness pin: for every canonical prefix in
11535        // the payload-arm accept-sets, exactly one of the four
11536        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11537        // [`WitContract::is_store`] / [`WitContract::is_capability`]
11538        // predicates returns `true` and the other three return `false`
11539        // — the four-arm partition witness that locks the substrate's
11540        // WIT-shape-space closure on the pre-projection axis load-
11541        // bearing. A future arm addition (a hypothetical fourth
11542        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
11543        // shape) that landed on one of the payload-arm predicates
11544        // without shrinking [`WitContract::is_capability`]'s accept-set
11545        // would surface here as two arms returning `true` simultaneously
11546        // — a partition-witness break the pin catches at caixa-core
11547        // build time rather than a silent per-consumer misclassification
11548        // at renderer emit time. Peer of the sibling `WitTarget`-side
11549        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
11550        // partition-witness pin on the post-projection payload-scalar
11551        // arm-set — extends the discipline onto the pre-projection
11552        // 4-arm shape-space.
11553        for shape_set in [
11554            WIT_HTTP_SHAPE_PREFIXES,
11555            WIT_PUBSUB_SHAPE_PREFIXES,
11556            WIT_STORE_SHAPE_PREFIXES,
11557        ] {
11558            for prefix in shape_set {
11559                let c = WitContract {
11560                    de: "cart".into(),
11561                    para: "catalog".into(),
11562                    wit: format!("{prefix}x"),
11563                    endpoint: None,
11564                    subject: None,
11565                    slot: None,
11566                };
11567                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11568                    .iter()
11569                    .filter(|&&b| b)
11570                    .count();
11571                assert_eq!(
11572                    hits,
11573                    1,
11574                    "WitContract WIT-shape 4-way predicate partition must \
11575                     admit exactly one arm per canonical prefix; got {hits} \
11576                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
11577                     is_capability={})",
11578                    c.wit,
11579                    c.is_http(),
11580                    c.is_pubsub(),
11581                    c.is_store(),
11582                    c.is_capability(),
11583                );
11584            }
11585        }
11586        // Capability-arm sweep: two representative capability shapes
11587        // (a bare WIT world outside the three payload-arm prefix sets,
11588        // and the deliberately-shaped empty string that
11589        // [`crate::render::is_wit_world_ref`] rejects at
11590        // [`WitContract::target`] time but which the pure classifier
11591        // still admits — see the method docstring's "purely syntactic
11592        // classification" note). Both must land on the fourth arm
11593        // exclusively, so the partition witness holds across the full
11594        // 4-arm closure.
11595        for wit in ["custom:capability-only", ""] {
11596            let c = WitContract {
11597                de: "cart".into(),
11598                para: "catalog".into(),
11599                wit: wit.into(),
11600                endpoint: None,
11601                subject: None,
11602                slot: None,
11603            };
11604            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11605                .iter()
11606                .filter(|&&b| b)
11607                .count();
11608            assert_eq!(
11609                hits, 1,
11610                "WitContract WIT-shape 4-way predicate partition must \
11611                 admit exactly one arm on Capability-shaped wit={wit:?}"
11612            );
11613            assert!(
11614                c.is_capability(),
11615                "wit={wit:?} must project onto the Capability arm"
11616            );
11617        }
11618    }
11619
11620    #[test]
11621    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
11622        // Composition-witness pin: [`WitContract::is_capability`] is the
11623        // exact-inverse disjunction of the sibling payload-arm predicate
11624        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11625        // [`WitContract::is_store`]. A future reimplementation that
11626        // grew its own prefix-set scan (e.g. inlining a fourth
11627        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
11628        // own today) rather than delegating to the sibling trio would
11629        // drift loudly here — the composition contract binds the
11630        // fourth-arm predicate to the exact-inverse of the three
11631        // payload-arm predicates, so any rebrand of any prefix-set const
11632        // flows through this method by construction without a
11633        // coordinated per-consumer rewrite. Sweeps the union of the
11634        // three payload-arm prefix sets plus two Capability-shaped
11635        // shapes (a bare non-prefix-matching WIT world, the deliberately-
11636        // empty string the pure classifier still admits per the method
11637        // docstring's "purely syntactic classification" note).
11638        let mut cases: Vec<String> = Vec::new();
11639        for shape_set in [
11640            WIT_HTTP_SHAPE_PREFIXES,
11641            WIT_PUBSUB_SHAPE_PREFIXES,
11642            WIT_STORE_SHAPE_PREFIXES,
11643        ] {
11644            for prefix in shape_set {
11645                cases.push(format!("{prefix}x"));
11646            }
11647        }
11648        cases.push("custom:capability-only".to_string());
11649        cases.push(String::new());
11650        for wit in cases {
11651            let c = WitContract {
11652                de: "cart".into(),
11653                para: "catalog".into(),
11654                wit: wit.clone(),
11655                endpoint: None,
11656                subject: None,
11657                slot: None,
11658            };
11659            assert_eq!(
11660                c.is_capability(),
11661                !c.is_http() && !c.is_pubsub() && !c.is_store(),
11662                "WitContract::is_capability must equal \
11663                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
11664            );
11665        }
11666    }
11667
11668    #[test]
11669    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
11670        // Cross-projection-witness pin: whenever [`WitContract::target`]
11671        // succeeds, the pre-projection [`WitContract::is_capability`]
11672        // classification agrees with the post-projection
11673        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
11674        // predicate — the 4-arm typed partition on the substrate's
11675        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
11676        // partition on the pre-projection axis line up by construction.
11677        // A future divergence between the two axes (a peer
11678        // [`WitTarget`] variant addition that landed on the typed-view
11679        // surface without a peer prefix-set + [`WitContract`] predicate
11680        // extension, or vice versa) would surface here at caixa-core
11681        // build time rather than a silent per-consumer split at renderer
11682        // emit time. Peer of the sibling pre-/post-projection
11683        // agreement pins the payload-carrier trio
11684        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
11685        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
11686        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
11687        // post-projection — b11bb49 trio lift) already carry across the
11688        // three payload arms — this pin closes the pair on the fourth
11689        // payload-less arm.
11690        let http = WitContract {
11691            de: "cart".into(),
11692            para: "catalog".into(),
11693            wit: "wasi:http/proxy".into(),
11694            endpoint: Some("/x".into()),
11695            subject: None,
11696            slot: None,
11697        };
11698        assert!(!http.is_capability());
11699        assert!(!http.target().unwrap().is_capability());
11700
11701        let nats = WitContract {
11702            de: "cart".into(),
11703            para: "catalog".into(),
11704            wit: "nats:pub-sub".into(),
11705            endpoint: None,
11706            subject: Some("events.x".into()),
11707            slot: None,
11708        };
11709        assert!(!nats.is_capability());
11710        assert!(!nats.target().unwrap().is_capability());
11711
11712        let kv = WitContract {
11713            de: "cart".into(),
11714            para: "catalog".into(),
11715            wit: "wasi:keyvalue/store".into(),
11716            endpoint: None,
11717            subject: None,
11718            slot: Some("checkout/$orderId".into()),
11719        };
11720        assert!(!kv.is_capability());
11721        assert!(!kv.target().unwrap().is_capability());
11722
11723        let cap = WitContract {
11724            de: "cart".into(),
11725            para: "catalog".into(),
11726            wit: "custom:capability-only".into(),
11727            endpoint: None,
11728            subject: None,
11729            slot: None,
11730        };
11731        assert!(cap.is_capability());
11732        assert!(cap.target().unwrap().is_capability());
11733    }
11734
11735    #[test]
11736    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
11737        // Fail-before-pass-after pin on the [`WitContract`] pre-
11738        // projection accessor family's `const`-eval-surface posture.
11739        // Each of the three per-`:contratos` byte-string scalar
11740        // accessors ([`WitContract::source`] / [`WitContract::destination`]
11741        // / [`WitContract::world_ref`], each projecting through
11742        // `String::as_str` — const-stable since Rust 1.87, well within
11743        // the workspace MSRV) and each of the four peer WIT-shape
11744        // predicates ([`WitContract::is_http`] /
11745        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
11746        // [`WitContract::is_capability`], each composing
11747        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
11748        // free-function classifier family the sibling
11749        // [`wit_shape_classifier_family_is_const_fn`] pin already
11750        // anchors on the raw `&str → bool` axis) must be `pub const fn`
11751        // — any future accidental downgrade to non-`const` fails the
11752        // `const fn` wrappers below at caixa-core build time with E0015
11753        // (`cannot call non-const function`), strictly stronger than a
11754        // runtime `assert!` and strictly stronger than a
11755        // module-scope `const _: () = assert!(…)` pin (which cannot be
11756        // formed on a `&WitContract` fixture because the type's
11757        // `String` / `Option<String>` carriers rule out `const`-context
11758        // construction; the `const fn` wrapper is the load-bearing
11759        // shape that side-steps the destructor-in-const restriction on
11760        // the value axis while still pinning the `const`-fn posture on
11761        // the callee).
11762        //
11763        // Peer of the sibling free-function classifier pin
11764        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
11765        // raw `&str → bool` axis — this pin extends the same
11766        // `const`-eval-surface discipline onto the peer method surface
11767        // that composes through those free-function classifiers, and
11768        // simultaneously onto the underlying per-`:contratos`
11769        // byte-string scalar-accessor trio each predicate reads
11770        // through. Sibling of the peer M3
11771        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11772        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11773        // M2
11774        // [`child_spec_restart_accessor_is_const_fn`] /
11775        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11776        // and M3
11777        // [`placement_estrategia_accessor_is_const_fn`] /
11778        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11779        // sibling `const`-eval-surface-pass axes.
11780        const fn source_via_const_fn(c: &WitContract) -> &str {
11781            c.source()
11782        }
11783        const fn destination_via_const_fn(c: &WitContract) -> &str {
11784            c.destination()
11785        }
11786        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
11787            c.world_ref()
11788        }
11789        const fn is_http_via_const_fn(c: &WitContract) -> bool {
11790            c.is_http()
11791        }
11792        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
11793            c.is_pubsub()
11794        }
11795        const fn is_store_via_const_fn(c: &WitContract) -> bool {
11796            c.is_store()
11797        }
11798        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
11799            c.is_capability()
11800        }
11801        // Sweep one canonical accept-set sample per WIT-shape arm plus
11802        // a payload-less capability sample, asserting the wrapper and
11803        // direct dispatches agree byte-for-byte across the closed
11804        // 4-arm partition on both the scalar-accessor trio and the
11805        // WIT-shape-predicate family.
11806        for (wit, is_http, is_pubsub, is_store, is_capability) in [
11807            ("wasi:http/proxy", true, false, false, false),
11808            ("http:incoming", true, false, false, false),
11809            ("nats:events", false, true, false, false),
11810            ("kafka:topic", false, true, false, false),
11811            ("wasi:keyvalue/store", false, false, true, false),
11812            ("kv:cache", false, false, true, false),
11813            ("custom:capability-only", false, false, false, true),
11814            ("", false, false, false, true),
11815        ] {
11816            let c = WitContract {
11817                de: "cart".into(),
11818                para: "catalog".into(),
11819                wit: wit.into(),
11820                endpoint: None,
11821                subject: None,
11822                slot: None,
11823            };
11824            assert_eq!(source_via_const_fn(&c), c.source());
11825            assert_eq!(destination_via_const_fn(&c), c.destination());
11826            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
11827            assert_eq!(is_http_via_const_fn(&c), c.is_http());
11828            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
11829            assert_eq!(is_store_via_const_fn(&c), c.is_store());
11830            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
11831            assert_eq!(c.source(), "cart");
11832            assert_eq!(c.destination(), "catalog");
11833            assert_eq!(c.world_ref(), wit);
11834            assert_eq!(c.is_http(), is_http);
11835            assert_eq!(c.is_pubsub(), is_pubsub);
11836            assert_eq!(c.is_store(), is_store);
11837            assert_eq!(c.is_capability(), is_capability);
11838        }
11839    }
11840
11841    #[test]
11842    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
11843        // Fail-before-pass-after pin on the four M3 mesh-slot
11844        // `String → &str` scalar accessors ([`Membro::nome`] /
11845        // [`Membro::versao_requirement`] on the per-`:membros` axis,
11846        // [`Entrada::hostname`] / [`Entrada::destination`] on the
11847        // per-`:entrada` axis) — each projects the typed slot's
11848        // [`String`] storage through the `pub const fn`
11849        // [`String::as_str`] (const-stable since Rust 1.87, well
11850        // within the workspace MSRV) and any future accidental
11851        // downgrade to non-`const` fails the corresponding
11852        // `<name>_via_const_fn` wrapper at caixa-core build time with
11853        // E0015 (`cannot call non-const method`), strictly stronger
11854        // than a runtime `assert!` and strictly stronger than a
11855        // module-scope `const _: () = assert!(…)` pin (which cannot
11856        // be formed on `&Membro` / `&Entrada` fixtures because the
11857        // types' `String` carriers rule out `const`-context value
11858        // construction; the `const fn` wrapper is the load-bearing
11859        // shape that side-steps the destructor-in-const restriction
11860        // on the value axis while still pinning the `const`-fn
11861        // posture on the callee — mirror of the sibling
11862        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
11863        // (279823b) pin on the per-`:contratos` axis). Peer of the
11864        // sibling per-M2/M3/universal-axis `String → &str` accessor
11865        // family pins on the sibling `const`-eval-surface passes
11866        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
11867        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
11868        // typed-newtype wrapper,
11869        // [`crate::supervisor::ChildSpec::nome`] /
11870        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
11871        // M2 supervisor-tree axis,
11872        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
11873        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
11874        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
11875        // axis, and the sibling per-`:contratos`
11876        // [`WitContract::source`] / [`WitContract::destination`] /
11877        // [`WitContract::world_ref`] trio at 279823b).
11878        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
11879            m.nome()
11880        }
11881        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
11882            m.versao_requirement()
11883        }
11884        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
11885            e.hostname()
11886        }
11887        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
11888            e.destination()
11889        }
11890        for (caixa, versao) in [
11891            ("cart", "^0.1"),
11892            ("catalog-v2", "~0.2.3"),
11893            ("checkout", "*"),
11894        ] {
11895            let m = Membro {
11896                caixa: caixa.into(),
11897                versao: versao.into(),
11898            };
11899            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
11900            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
11901            assert_eq!(m.nome(), caixa);
11902            assert_eq!(m.versao_requirement(), versao);
11903        }
11904        for (host, para) in [
11905            ("cart.example.com", "cart"),
11906            ("api.checkout.io", "checkout"),
11907        ] {
11908            let e = Entrada {
11909                host: host.into(),
11910                para: para.into(),
11911                paths: vec![],
11912                port: DEFAULT_SERVICO_PORT,
11913            };
11914            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
11915            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
11916            assert_eq!(e.hostname(), host);
11917            assert_eq!(e.destination(), para);
11918        }
11919    }
11920
11921    #[test]
11922    fn m3_option_string_scalar_accessor_family_is_const_fn() {
11923        // Fail-before-pass-after pin on the five M3 mesh-slot
11924        // `Option<String> → Option<&str>` scalar accessors
11925        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
11926        // [`WitContract::slot`] on the per-`:contratos` HTTP /
11927        // pub-sub / key-value payload-carrier trio,
11928        // [`Placement::shard_key`] / [`Placement::affinity`] on the
11929        // per-`:placement` Akka-sharding-key + Adaptive-compression-
11930        // hint pair). Each accessor destructures the typed slot's
11931        // `Option<String>` storage through the `match &self.<field> {
11932        // Some(s) => Some(s.as_str()), None => None }` shape —
11933        // routing through [`String::as_str`] (const-stable since Rust
11934        // 1.87, well within the workspace MSRV) rather than the
11935        // non-const [`Option::as_deref`] the pre-lift bodies carried
11936        // — and any future accidental downgrade to non-`const` fails
11937        // the corresponding `<name>_via_const_fn` wrapper at
11938        // caixa-core build time with E0015 (`cannot call non-const
11939        // method`), strictly stronger than a runtime `assert!` and
11940        // strictly stronger than a module-scope `const _: () =
11941        // assert!(…)` pin (which cannot be formed on `&WitContract`
11942        // / `&Placement` fixtures because the types' `String` /
11943        // `Option<String>` carriers rule out `const`-context value
11944        // construction; the `const fn` wrapper is the load-bearing
11945        // shape that side-steps the destructor-in-const restriction
11946        // on the value axis while still pinning the `const`-fn
11947        // posture on the callee — mirror of the sibling
11948        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
11949        // (279823b) and
11950        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
11951        // (29c5d7e) pins on the peer `String → &str` axes at the same
11952        // structs).
11953        //
11954        // Peer of the sibling per-`Caixa` `Option<String> →
11955        // Option<&str>` accessor family pin
11956        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
11957        // on the top-level manifest's optional universal-axis surface
11958        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
11959        // `:restart-window`).
11960        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
11961            w.endpoint()
11962        }
11963        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
11964            w.subject()
11965        }
11966        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
11967            w.slot()
11968        }
11969        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
11970            p.shard_key()
11971        }
11972        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
11973            p.affinity()
11974        }
11975        // Sweep every closed shape-arm partition on the
11976        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
11977        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
11978        // pair None), key-value (`:slot` Some, sibling pair None),
11979        // and Capability (all three None) so each accessor's
11980        // Some/None arm carries a pin through the const dispatch.
11981        for (wit, endpoint, subject, slot) in [
11982            ("wasi:http/proxy", Some("/api"), None, None),
11983            ("nats:pub-sub", None, Some("orders.paid"), None),
11984            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
11985            ("custom:capability-only", None, None, None),
11986        ] {
11987            let c = WitContract {
11988                de: "cart".into(),
11989                para: "catalog".into(),
11990                wit: wit.into(),
11991                endpoint: endpoint.map(str::to_string),
11992                subject: subject.map(str::to_string),
11993                slot: slot.map(str::to_string),
11994            };
11995            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
11996            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
11997            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
11998            assert_eq!(c.endpoint(), endpoint);
11999            assert_eq!(c.subject(), subject);
12000            assert_eq!(c.slot(), slot);
12001        }
12002        // Sweep both `Some`/`None` arms on each per-`:placement`
12003        // optional-scalar so the shard-key + affinity pair carries a
12004        // const-dispatch pin on both arms.
12005        for (shard_key, affinity) in [
12006            (Some("tenantId"), Some("data-locality")),
12007            (Some("$tenantId"), None),
12008            (None, Some("low-latency")),
12009            (None, None),
12010        ] {
12011            let p = Placement {
12012                estrategia: PlacementStrategy::default(),
12013                clusters: vec![],
12014                affinity: affinity.map(str::to_string),
12015                shard_key: shard_key.map(str::to_string),
12016            };
12017            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
12018            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
12019            assert_eq!(p.shard_key(), shard_key);
12020            assert_eq!(p.affinity(), affinity);
12021        }
12022    }
12023
12024    #[test]
12025    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
12026        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
12027        // composite `Vec → &[String]` slice-return accessors on
12028        // [`Placement::clusters`] and [`Entrada::paths`]. Each
12029        // destructures the typed slot's `Vec<String>` storage through
12030        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
12031        // 1.66, well within the workspace MSRV) — any future accidental
12032        // downgrade to non-`const` fails the corresponding
12033        // `<name>_via_const_fn` wrapper at caixa-core build time with
12034        // E0015 (`cannot call non-const method`), strictly stronger
12035        // than a runtime `assert!`. Sibling of the peer
12036        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
12037        // pin on the outer-`AplicacaoSpec` reference-return family
12038        // (`:membros` / `:contratos` slice-return + `:politicas` /
12039        // `:placement` / `:entrada` composite-reference), and of the
12040        // peer M2 slice-return axis pins
12041        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
12042        // (on `SupervisorSpec::children`) and
12043        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
12044        // (on `UpgradeFromEntry::instructions`). Together the four
12045        // pins close the last unlifted reference-return accessor
12046        // family across the substrate primitive.
12047        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
12048            p.clusters()
12049        }
12050        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
12051            e.paths()
12052        }
12053        // Sweep both the empty-Vec (no author-declared entries) and
12054        // the populated-Vec arms on every slice-return accessor so
12055        // each carries a const-dispatch pin on both arms.
12056        let p_empty = Placement {
12057            estrategia: PlacementStrategy::default(),
12058            clusters: vec![],
12059            affinity: None,
12060            shard_key: None,
12061        };
12062        let p_full = Placement {
12063            estrategia: PlacementStrategy::default(),
12064            clusters: vec!["prod-a".into(), "prod-b".into()],
12065            affinity: None,
12066            shard_key: None,
12067        };
12068        assert_eq!(
12069            placement_clusters_via_const_fn(&p_empty),
12070            p_empty.clusters()
12071        );
12072        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
12073        assert!(p_empty.clusters().is_empty());
12074        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
12075        let e_empty = Entrada {
12076            host: "web.example.com".into(),
12077            para: "web".into(),
12078            paths: vec![],
12079            port: DEFAULT_SERVICO_PORT,
12080        };
12081        let e_full = Entrada {
12082            host: "web.example.com".into(),
12083            para: "web".into(),
12084            paths: vec!["/api".into(), "/health".into()],
12085            port: DEFAULT_SERVICO_PORT,
12086        };
12087        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
12088        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
12089        assert!(e_empty.paths().is_empty());
12090        assert_eq!(e_full.paths(), &["/api", "/health"]);
12091    }
12092
12093    #[test]
12094    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
12095        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
12096        // reference-return accessors — the two `Vec → &[T]` slice-
12097        // return accessors on [`AplicacaoSpec::membros`] and
12098        // [`AplicacaoSpec::contratos`] (each routes through the
12099        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
12100        // 1.66), the two `&Composite` composite-reference accessors
12101        // on [`AplicacaoSpec::politicas`] and
12102        // [`AplicacaoSpec::placement`] (each routes through a raw
12103        // `&self.<field>` borrow, trivially const), and the one
12104        // `Option<&Composite>` optional-composite-reference accessor
12105        // on [`AplicacaoSpec::entrada`] (routes through the
12106        // `pub const fn` [`Option::as_ref`], const-stable since Rust
12107        // 1.83). Any future accidental downgrade to non-`const` fails
12108        // the corresponding `<name>_via_const_fn` wrapper at caixa-
12109        // core build time with E0015 (`cannot call non-const
12110        // method`), strictly stronger than a runtime `assert!`.
12111        // Sibling of the peer inner-composite pin
12112        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
12113        // on the `Placement::clusters` + `Entrada::paths` slice-
12114        // return pair, and of the peer M2 axis pins on
12115        // [`crate::supervisor::SupervisorSpec::children`] and
12116        // [`crate::upgrade::UpgradeFromEntry::instructions`].
12117        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
12118            s.membros()
12119        }
12120        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
12121            s.contratos()
12122        }
12123        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
12124            s.politicas()
12125        }
12126        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
12127            s.placement()
12128        }
12129        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
12130            s.entrada()
12131        }
12132        // Construct both a minimal "no :entrada" (internal-only
12133        // mesh) and a full "with :entrada" (external-gateway)
12134        // fixture so the family pins both the `None`-arm (author-
12135        // omitted `:entrada`) and the `Some`-arm (author-declared
12136        // `:entrada`) on the optional-composite axis.
12137        let membro = Membro {
12138            caixa: "web".into(),
12139            versao: "^0.1".into(),
12140        };
12141        let entrada_full = Entrada {
12142            host: "web.example.com".into(),
12143            para: "web".into(),
12144            paths: vec!["/api".into()],
12145            port: DEFAULT_SERVICO_PORT,
12146        };
12147        let internal_only = AplicacaoSpec {
12148            membros: vec![membro.clone()],
12149            contratos: vec![],
12150            politicas: MeshPolicy::default(),
12151            placement: Placement::default(),
12152            entrada: None,
12153        };
12154        let with_entrada = AplicacaoSpec {
12155            membros: vec![membro],
12156            contratos: vec![],
12157            politicas: MeshPolicy::default(),
12158            placement: Placement::default(),
12159            entrada: Some(entrada_full),
12160        };
12161        assert_eq!(
12162            aplicacao_membros_via_const_fn(&internal_only),
12163            internal_only.membros()
12164        );
12165        assert_eq!(
12166            aplicacao_membros_via_const_fn(&with_entrada),
12167            with_entrada.membros()
12168        );
12169        assert_eq!(
12170            aplicacao_contratos_via_const_fn(&internal_only),
12171            internal_only.contratos()
12172        );
12173        assert!(std::ptr::eq(
12174            aplicacao_politicas_via_const_fn(&internal_only),
12175            internal_only.politicas(),
12176        ));
12177        assert!(std::ptr::eq(
12178            aplicacao_placement_via_const_fn(&internal_only),
12179            internal_only.placement(),
12180        ));
12181        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
12182        match (
12183            aplicacao_entrada_via_const_fn(&with_entrada),
12184            with_entrada.entrada(),
12185        ) {
12186            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
12187            _ => panic!(
12188                "aplicacao_entrada_via_const_fn must agree with \
12189                 AplicacaoSpec::entrada on the Some-arm reference"
12190            ),
12191        }
12192    }
12193
12194    #[test]
12195    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
12196        // Load-bearing contract pin: on every canonical
12197        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
12198        // [`WitContract::target_projected`] returns byte-equal to
12199        // [`WitContract::target`]`().unwrap()` — the post-validation
12200        // projection accessor is a thin panicking wrapper over the
12201        // pre-validation validator, no extra work in the projection
12202        // path. Any future divergence (a validator-side normalization
12203        // the projection doesn't route through, an accessor-side
12204        // caching layer the validator doesn't populate) would surface
12205        // here at caixa-core build time rather than a silent per-consumer
12206        // split at renderer emit time. Sweeps the closed 4-arm
12207        // [`WitTarget`] partition ([`WitTarget::Http`] /
12208        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
12209        // [`WitTarget::Capability`]) so every arm carries a byte-equality
12210        // pin on the two-accessor pair.
12211        for (wit, endpoint, subject, slot) in [
12212            ("wasi:http/proxy", Some("/x"), None, None),
12213            ("nats:pub-sub", None, Some("events.x"), None),
12214            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
12215            ("custom:capability-only", None, None, None),
12216        ] {
12217            let c = WitContract {
12218                de: "cart".into(),
12219                para: "catalog".into(),
12220                wit: wit.into(),
12221                endpoint: endpoint.map(str::to_string),
12222                subject: subject.map(str::to_string),
12223                slot: slot.map(str::to_string),
12224            };
12225            assert_eq!(
12226                c.target_projected(),
12227                c.target().unwrap(),
12228                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
12229            );
12230        }
12231    }
12232
12233    #[test]
12234    #[should_panic(expected = "validated by typed_view")]
12235    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
12236        // Panic-path pin: [`WitContract::target_projected`] threads the
12237        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
12238        // through its expect-panic when called on a contract whose
12239        // (`:wit`, payload) shape has not been crossed by
12240        // [`AplicacaoSpec::validate`] — a contract with a structurally-
12241        // invalid `:wit` (hyphen-for-colon typo) that would surface
12242        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
12243        // A future rebrand on the panic-message axis would land at one
12244        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
12245        // and this pin's [`should_panic(expected = …)`] literal would
12246        // migrate alongside — the pin catches drift between the const
12247        // and the accessor's `expect(…)` call by construction.
12248        let c = WitContract {
12249            de: "cart".into(),
12250            para: "catalog".into(),
12251            // Hyphen-for-colon typo: `WitContract::target` returns
12252            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
12253            // driving the [`WitContract::target_projected`] expect-panic.
12254            wit: "wasi-http/proxy".into(),
12255            endpoint: Some("/x".into()),
12256            subject: None,
12257            slot: None,
12258        };
12259        let _ = c.target_projected();
12260    }
12261
12262    #[test]
12263    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
12264        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
12265        // carries the exact byte-string the two prior open-coded
12266        // `.target().expect("validated by typed_view")` production
12267        // consumers threaded through inline before this lift converged
12268        // them onto [`WitContract::target_projected`] — the caixa-mesh
12269        // per-`(:de, :para)` CNP L7 introspection branch at
12270        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
12271        // graph` per-`:contratos` payload-column printer at
12272        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
12273        // byte-string load-bearing so a well-meaning const-side rebrand
12274        // that didn't carry a matched pin migration would surface here
12275        // at caixa-core build time rather than a silent per-consumer
12276        // panic-message drift at cluster-apply time. Peer of the
12277        // sibling [`WitTarget::CAPABILITY_LABEL`] /
12278        // [`WitTarget::CAPABILITY_EXPECTED`] /
12279        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
12280        // the paired payload-less-arm scalar-const family.
12281        assert_eq!(
12282            WitContract::PROJECTED_INVARIANT_MSG,
12283            "validated by typed_view"
12284        );
12285    }
12286
12287    #[test]
12288    fn empty_wit_takes_precedence_over_invalid() {
12289        // Ordering pin: `EmptyWit` is the more self-locating
12290        // diagnostic on `""` and must lead — the value-shape gate is
12291        // only reached after the empty-check fires. Mirrors
12292        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12293        // the peer payload axis.
12294        let mut s = three_member_spec();
12295        s.contratos.push(WitContract {
12296            de: "payment".into(),
12297            para: "catalog".into(),
12298            wit: String::new(),
12299            endpoint: None,
12300            subject: None,
12301            slot: None,
12302        });
12303        let err = s.validate().unwrap_err();
12304        assert!(
12305            matches!(err, AplicacaoError::EmptyWit { .. }),
12306            "got {err:?}"
12307        );
12308    }
12309
12310    #[test]
12311    fn wit_invalid_fires_before_payload_shape_arm() {
12312        // Ordering pin: a malformed `:wit` surfaces *its own*
12313        // diagnostic (which names the offending wit verbatim) before
12314        // any payload-field check — a contrato whose wit is
12315        // structurally invalid AND carries a wrong target field
12316        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
12317        // because the dispatch on the wit is what decides which
12318        // payload field is "right" in the first place. Without this
12319        // ordering, the author would see "wrong target field" for a
12320        // wit that hasn't even been parsed, which doesn't name the
12321        // root cause.
12322        let mut s = three_member_spec();
12323        s.contratos.push(WitContract {
12324            de: "payment".into(),
12325            para: "catalog".into(),
12326            // Hyphen-for-colon typo + endpoint set: pre-gate this
12327            // raised `ContratoWrongTarget { expected: "none" }` (the
12328            // Capability arm rejecting the endpoint), masking the
12329            // real authoring mistake (the wit isn't `wasi:http/proxy`).
12330            wit: "wasi-http/proxy".into(),
12331            endpoint: Some("/x".into()),
12332            subject: None,
12333            slot: None,
12334        });
12335        let err = s.validate().unwrap_err();
12336        assert!(
12337            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
12338                if wit == "wasi-http/proxy"),
12339            "got {err:?}"
12340        );
12341    }
12342
12343    #[test]
12344    fn wit_invalid_diagnostic_carries_offending_wit() {
12345        // Diagnostic-shape pin — the offending `:wit` + `:de` +
12346        // `:para` + a non-empty reason flow through verbatim so the
12347        // author can grep their caixa.lisp for the offending contrato
12348        // block and fix it in one edit. Same shape as
12349        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
12350        let err = contrato_wit_err("WASI:HTTP/proxy");
12351        match err {
12352            AplicacaoError::ContratoWitInvalid {
12353                de,
12354                para,
12355                wit,
12356                reason,
12357            } => {
12358                assert_eq!(de, "payment");
12359                assert_eq!(para, "catalog");
12360                assert_eq!(wit, "WASI:HTTP/proxy");
12361                assert!(!reason.is_empty(), "reason field must be non-empty");
12362            }
12363            other => panic!("expected ContratoWitInvalid, got {other:?}"),
12364        }
12365    }
12366
12367    // ── :contratos :subject value-shape gate ─────────────────────────────
12368    //
12369    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
12370    // suites on the peer payload axes. Until this gate landed
12371    // `WitContract::target()` only refused the empty string; a
12372    // structurally invalid subject silently passed validate and the
12373    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
12374    // Subject'` on publish / subscribe, or as a silent message drop,
12375    // far from the source caixa.lisp. Every authoring footgun the
12376    // NATS server's subject parser would catch on admission now
12377    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
12378    // offending `:subject` + `:de` + `:para` named verbatim. Same
12379    // diagnostic shape as `ContratoEndpointInvalid` /
12380    // `ContratoWitInvalid` on the peer payload axes; same shared
12381    // predicate (`crate::render::is_nats_subject`) ensures drift
12382    // between any two axes' rule enforcement is a build error at the
12383    // predicate, not piecemeal across renderers.
12384
12385    fn contrato_subject_err(subject: &str) -> AplicacaoError {
12386        // Fresh spec per call so the new contract doesn't collide on
12387        // identity with `three_member_spec`'s pre-existing entries.
12388        // The new edge uses `(payment, catalog)` — a pair the fixture
12389        // doesn't already declare — with `:wit "nats:pub-sub"` and the
12390        // varying `:subject`, so the subject-shape gate fires cleanly
12391        // after the wit-shape gate (which `"nats:pub-sub"` passes).
12392        let mut s = three_member_spec();
12393        s.contratos.push(WitContract {
12394            de: "payment".into(),
12395            para: "catalog".into(),
12396            wit: "nats:pub-sub".into(),
12397            endpoint: None,
12398            subject: Some(subject.into()),
12399            slot: None,
12400        });
12401        s.validate().unwrap_err()
12402    }
12403
12404    #[test]
12405    fn rejects_pubsub_contrato_subject_with_whitespace() {
12406        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
12407        // landed at the NATS server as a malformed subject the parser
12408        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
12409        // source caixa.lisp.
12410        let err = contrato_subject_err("foo bar");
12411        assert!(
12412            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12413                if subject == "foo bar" && reason.contains("whitespace")),
12414            "got {err:?}"
12415        );
12416    }
12417
12418    #[test]
12419    fn rejects_pubsub_contrato_subject_with_control_char() {
12420        let err = contrato_subject_err("foo\x01bar");
12421        assert!(
12422            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12423                if subject == "foo\x01bar" && reason.contains("control character")),
12424            "got {err:?}"
12425        );
12426    }
12427
12428    #[test]
12429    fn rejects_pubsub_contrato_subject_with_non_ascii() {
12430        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12431        // the subject from a doc with smart quotes / accented
12432        // characters" footgun.
12433        let err = contrato_subject_err("foo.caf\u{e9}");
12434        assert!(
12435            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12436                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
12437            "got {err:?}"
12438        );
12439    }
12440
12441    #[test]
12442    fn rejects_pubsub_contrato_subject_with_leading_dot() {
12443        // Empty leading token — NATS rejects.
12444        let err = contrato_subject_err(".foo");
12445        assert!(
12446            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12447                if subject == ".foo" && reason.contains("must not start with `.`")),
12448            "got {err:?}"
12449        );
12450    }
12451
12452    #[test]
12453    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
12454        // Empty trailing token — NATS rejects. The remediation
12455        // (use `>` instead) is in the reason string.
12456        let err = contrato_subject_err("foo.");
12457        assert!(
12458            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12459                if subject == "foo." && reason.contains("must not end with `.`")),
12460            "got {err:?}"
12461        );
12462    }
12463
12464    #[test]
12465    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
12466        // The canonical "I forgot to fill in the middle segment"
12467        // typo — `"foo..bar"`. NATS rejects empty tokens.
12468        let err = contrato_subject_err("foo..bar");
12469        assert!(
12470            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12471                if subject == "foo..bar" && reason.contains("consecutive `.`")),
12472            "got {err:?}"
12473        );
12474    }
12475
12476    #[test]
12477    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
12478        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
12479        // as the final segment. Pre-gate this passed as a typed edge
12480        // and surfaced at runtime as a NATS subscribe rejection.
12481        let err = contrato_subject_err("foo.>.bar");
12482        assert!(
12483            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12484                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
12485            "got {err:?}"
12486        );
12487    }
12488
12489    #[test]
12490    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
12491        // `foo*.bar` — NATS wildcards are standalone tokens. The
12492        // remediation is in the reason string.
12493        let err = contrato_subject_err("foo*.bar");
12494        assert!(
12495            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12496                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
12497            "got {err:?}"
12498        );
12499    }
12500
12501    #[test]
12502    fn rejects_pubsub_contrato_subject_with_invalid_char() {
12503        // `foo,bar` — comma is not a valid NATS subject character.
12504        // Pinned separately from the wildcard arms so the invalid-
12505        // character diagnostic is in force.
12506        let err = contrato_subject_err("foo,bar");
12507        assert!(
12508            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12509                if subject == "foo,bar" && reason.contains("invalid character")),
12510            "got {err:?}"
12511        );
12512    }
12513
12514    #[test]
12515    fn rejects_pubsub_contrato_subject_too_long() {
12516        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
12517        // The legitimate-shape arms all pass (one all-`a` token, no
12518        // `.`, no wildcards); only the cap arm fires. Surfaces the
12519        // paste-from-binary / accidental-multi-line-blob landing
12520        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
12521        // on the peer axis.
12522        let big = "a".repeat(257);
12523        assert_eq!(big.len(), 257);
12524        let err = contrato_subject_err(&big);
12525        assert!(
12526            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12527                if subject == &big && reason.contains("max length of 256")),
12528            "got {err:?}"
12529        );
12530    }
12531
12532    #[test]
12533    fn pubsub_contrato_subject_max_length_validates() {
12534        // 256-byte subject — exactly the cap. Boundary pin: drift in
12535        // the cap surfaces here and at
12536        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
12537        // mirroring `http_contrato_endpoint_max_length_validates` and
12538        // `wit_max_length_validates` on the peer axes.
12539        let big = "a".repeat(256);
12540        assert_eq!(big.len(), 256);
12541        let mut s = three_member_spec();
12542        s.contratos.push(WitContract {
12543            de: "payment".into(),
12544            para: "catalog".into(),
12545            wit: "nats:pub-sub".into(),
12546            endpoint: None,
12547            subject: Some(big),
12548            slot: None,
12549        });
12550        s.validate().unwrap();
12551    }
12552
12553    #[test]
12554    fn pubsub_contrato_subject_accepts_canonical_forms() {
12555        // Positive-set sweep: every canonical NATS subject shape the
12556        // substrate-side `is_nats_subject` predicate accepts (the
12557        // multi-dot `events.order.charged`, the snake_case / kebab-
12558        // case / mixed-case tokens, the digit-bearing tokens, the
12559        // single-token wildcard `*` at every segment position, and
12560        // the trailing `>` multi-token wildcard) must remain a valid
12561        // contrato subject too. Drift between this list and the
12562        // substrate-side `nats_subject_accepts_canonical_forms` sweep
12563        // surfaces at the shared predicate — one source of truth.
12564        // Uses a fresh `(payment, catalog)` edge so none of the swept
12565        // subjects collide with the pre-existing entries in
12566        // `three_member_spec`.
12567        for subject in [
12568            "checkout.events.charge.failed",
12569            "rio.events.order.charged",
12570            "orders",
12571            "orders.123",
12572            "snake_case.token",
12573            "kebab-case.token",
12574            "MixedCase.Token",
12575            "orders.*.charged",
12576            "*.events.*",
12577            "orders.>",
12578        ] {
12579            let mut s = three_member_spec();
12580            s.contratos.push(WitContract {
12581                de: "payment".into(),
12582                para: "catalog".into(),
12583                wit: "nats:pub-sub".into(),
12584                endpoint: None,
12585                subject: Some(subject.into()),
12586                slot: None,
12587            });
12588            s.validate()
12589                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
12590        }
12591    }
12592
12593    #[test]
12594    fn contrato_subject_empty_takes_precedence_over_invalid() {
12595        // Ordering pin: `ContratoSubjectEmpty` is the more self-
12596        // locating diagnostic on `""` and must lead — the value-shape
12597        // gate is only reached after the empty-check fires. Mirrors
12598        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12599        // the peer payload axis.
12600        let mut s = three_member_spec();
12601        s.contratos.push(WitContract {
12602            de: "payment".into(),
12603            para: "catalog".into(),
12604            wit: "nats:pub-sub".into(),
12605            endpoint: None,
12606            subject: Some(String::new()),
12607            slot: None,
12608        });
12609        let err = s.validate().unwrap_err();
12610        assert!(
12611            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
12612            "got {err:?}"
12613        );
12614    }
12615
12616    #[test]
12617    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
12618        // Diagnostic-shape pin — the offending `:subject` + `:de` +
12619        // `:para` + a non-empty reason flow through verbatim so the
12620        // author can grep their caixa.lisp for the offending contrato
12621        // block and fix it in one edit. Same shape as
12622        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12623        // and `wit_invalid_diagnostic_carries_offending_wit`.
12624        let err = contrato_subject_err("foo..bar");
12625        match err {
12626            AplicacaoError::ContratoSubjectInvalid {
12627                de,
12628                para,
12629                subject,
12630                reason,
12631            } => {
12632                assert_eq!(de, "payment");
12633                assert_eq!(para, "catalog");
12634                assert_eq!(subject, "foo..bar");
12635                assert!(!reason.is_empty(), "reason field must be non-empty");
12636            }
12637            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
12638        }
12639    }
12640
12641    #[test]
12642    fn target_view_pubsub_subject_passes_through_to_typed_view() {
12643        // The compounding theorem on the pub-sub axis: every
12644        // `WitTarget::PubSub { subject }` returned by `target()` carries
12645        // a NATS-server-accepted subject. Renderers downstream of
12646        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
12647        // NATS Stream/Consumer CR emitter, the future `feira app graph`
12648        // view's subject labeller) can rely on this without re-checking
12649        // — the type system carries the proof. Mirrors
12650        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
12651        // on the peer axes.
12652        let nats = WitContract {
12653            de: "a".into(),
12654            para: "b".into(),
12655            wit: "nats:pub-sub".into(),
12656            endpoint: None,
12657            subject: Some("orders.events.*.charged".into()),
12658            slot: None,
12659        };
12660        match nats.target().unwrap() {
12661            WitTarget::PubSub { subject } => {
12662                assert_eq!(subject, "orders.events.*.charged");
12663            }
12664            other => panic!("expected PubSub, got {other:?}"),
12665        }
12666    }
12667
12668    // ── :contratos :slot value-shape gate ────────────────────────────────
12669    //
12670    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
12671    // (63e18a0) value-shape suites on the peer payload axes. Until this
12672    // gate landed `WitContract::target()` only refused the empty string
12673    // for the Store arm; a structurally invalid slot (raw whitespace,
12674    // control character, non-ASCII byte, paste-from-binary multi-line
12675    // blob) silently passed validate and surfaced at runtime as a
12676    // per-backend kv write rejection or a silent next-read corruption,
12677    // far from the source caixa.lisp with no field naming which
12678    // `:contratos` edge carried the typo. Every authoring footgun the
12679    // kv backend intersection-floor would catch on write now becomes a
12680    // caixa-build-time `ContratoSlotInvalid` with the offending
12681    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
12682    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
12683    // peer payload axes; same shared predicate
12684    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
12685    // any two axes' rule enforcement is a build error at the
12686    // predicate, not piecemeal across renderers. Closes the typed
12687    // payload-axis value-shape trajectory across all three legs of the
12688    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
12689
12690    fn contrato_slot_err(slot: &str) -> AplicacaoError {
12691        // Fresh spec per call so the new contract doesn't collide on
12692        // identity with `three_member_spec`'s pre-existing entries
12693        // and doesn't close a synchronous cycle the cycle detector
12694        // would reject before the slot-shape gate fires. The new edge
12695        // uses `(payment, catalog)` — a pair the fixture doesn't
12696        // already declare in either direction (the fixture carries
12697        // `cart -> catalog` and `cart -> payment`, so `payment ->
12698        // catalog` doesn't form a cycle on the sync subgraph) — with
12699        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
12700        // slot-shape gate fires cleanly after the wit-shape gate
12701        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
12702        // peer `contrato_subject_err` helper uses (63e18a0).
12703        let mut s = three_member_spec();
12704        s.contratos.push(WitContract {
12705            de: "payment".into(),
12706            para: "catalog".into(),
12707            wit: "wasi:keyvalue/store".into(),
12708            endpoint: None,
12709            subject: None,
12710            slot: Some(slot.into()),
12711        });
12712        s.validate().unwrap_err()
12713    }
12714
12715    #[test]
12716    fn rejects_store_contrato_slot_with_whitespace() {
12717        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
12718        // silently landed at the kv backend with whitespace whose
12719        // runtime behavior varies unpredictably across backends (etcd
12720        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
12721        // rejects on write). Now caught at the source caixa.lisp.
12722        let err = contrato_slot_err("check out/$order");
12723        assert!(
12724            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12725                if slot == "check out/$order" && reason.contains("whitespace")),
12726            "got {err:?}"
12727        );
12728    }
12729
12730    #[test]
12731    fn rejects_store_contrato_slot_with_tab() {
12732        // Tab byte arm-pinned separately from the space arm so a
12733        // future relaxation that admits one but not the other surfaces
12734        // here.
12735        let err = contrato_slot_err("check\tout");
12736        assert!(
12737            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12738                if slot == "check\tout" && reason.contains("whitespace")),
12739            "got {err:?}"
12740        );
12741    }
12742
12743    #[test]
12744    fn rejects_store_contrato_slot_with_control_char() {
12745        // SOH (0x01) — distinct from the whitespace arm. Redis admits
12746        // and corrupts on RESP protocol framing; DynamoDB rejects on
12747        // write.
12748        let err = contrato_slot_err("checkout/\x01order");
12749        assert!(
12750            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12751                if slot == "checkout/\x01order" && reason.contains("control character")),
12752            "got {err:?}"
12753        );
12754    }
12755
12756    #[test]
12757    fn rejects_store_contrato_slot_with_newline() {
12758        // Embedded newline — the canonical "the paste-from-binary slug
12759        // spans multiple lines" footgun. Distinct from the whitespace
12760        // arm because `\n` is a control character (0x0A).
12761        let err = contrato_slot_err("checkout\norder");
12762        assert!(
12763            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12764                if slot == "checkout\norder" && reason.contains("control character")),
12765            "got {err:?}"
12766        );
12767    }
12768
12769    #[test]
12770    fn rejects_store_contrato_slot_with_non_ascii() {
12771        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12772        // the slot from a doc with accented characters" footgun. Each
12773        // kv backend re-encodes non-ASCII differently (etcd preserves
12774        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
12775        // rejects), so the typed slot's value set is the intersection-
12776        // floor every backend admits identically (printable ASCII).
12777        let err = contrato_slot_err("ch\u{e9}ckout/$order");
12778        assert!(
12779            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12780                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
12781            "got {err:?}"
12782        );
12783    }
12784
12785    #[test]
12786    fn rejects_store_contrato_slot_too_long() {
12787        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
12788        // legitimate-shape arms all pass (a single all-`a` token, no
12789        // separators); only the cap arm fires. Surfaces the paste-
12790        // from-binary / accidental-multi-line-blob landing footgun.
12791        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
12792        // `rejects_http_contrato_endpoint_too_long` on the peer
12793        // payload axes.
12794        let big = "a".repeat(513);
12795        assert_eq!(big.len(), 513);
12796        let err = contrato_slot_err(&big);
12797        assert!(
12798            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12799                if slot == &big && reason.contains("max length of 512")),
12800            "got {err:?}"
12801        );
12802    }
12803
12804    #[test]
12805    fn store_contrato_slot_max_length_validates() {
12806        // 512-byte slot — exactly the cap. Boundary pin: drift in the
12807        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
12808        // simultaneously, mirroring
12809        // `pubsub_contrato_subject_max_length_validates` and
12810        // `http_contrato_endpoint_max_length_validates` on the peer
12811        // payload axes.
12812        let big = "a".repeat(512);
12813        assert_eq!(big.len(), 512);
12814        let mut s = three_member_spec();
12815        s.contratos.push(WitContract {
12816            de: "payment".into(),
12817            para: "catalog".into(),
12818            wit: "wasi:keyvalue/store".into(),
12819            endpoint: None,
12820            subject: None,
12821            slot: Some(big),
12822        });
12823        s.validate().unwrap();
12824    }
12825
12826    #[test]
12827    fn store_contrato_slot_accepts_canonical_forms() {
12828        // Positive-set sweep: every canonical kv slot template the
12829        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
12830        // (single-token identifiers, path-namespaced `$`-templates,
12831        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
12832        // snake_case / kebab-case / MixedCase tokens, digit-bearing
12833        // tokens, percent-encoded fragments) must remain valid
12834        // contrato slots too. Drift between this list and the
12835        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
12836        // surfaces at the shared predicate — one source of truth.
12837        // Uses a fresh `(payment, catalog)` edge so none of the swept
12838        // slots collide with the pre-existing entries in
12839        // `three_member_spec`.
12840        for slot in [
12841            "checkout",
12842            "checkout/$orderId",
12843            "users:{tenant}/{id}",
12844            "session.<sid>",
12845            "session.tokens.<sid>",
12846            "snake_case_key",
12847            "kebab-case-key",
12848            "MixedCase",
12849            "shard0",
12850            "v2/key",
12851            "users/caf%C3%A9",
12852        ] {
12853            let mut s = three_member_spec();
12854            s.contratos.push(WitContract {
12855                de: "payment".into(),
12856                para: "catalog".into(),
12857                wit: "wasi:keyvalue/store".into(),
12858                endpoint: None,
12859                subject: None,
12860                slot: Some(slot.into()),
12861            });
12862            s.validate()
12863                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
12864        }
12865    }
12866
12867    #[test]
12868    fn contrato_slot_empty_takes_precedence_over_invalid() {
12869        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
12870        // diagnostic on `""` and must lead — the value-shape gate is
12871        // only reached after the empty-check fires. Mirrors
12872        // `contrato_subject_empty_takes_precedence_over_invalid` and
12873        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12874        // the peer payload axes.
12875        let mut s = three_member_spec();
12876        s.contratos.push(WitContract {
12877            de: "payment".into(),
12878            para: "catalog".into(),
12879            wit: "wasi:keyvalue/store".into(),
12880            endpoint: None,
12881            subject: None,
12882            slot: Some(String::new()),
12883        });
12884        let err = s.validate().unwrap_err();
12885        assert!(
12886            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
12887            "got {err:?}"
12888        );
12889    }
12890
12891    #[test]
12892    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
12893        // Diagnostic-shape pin — the offending `:slot` + `:de` +
12894        // `:para` + a non-empty reason flow through verbatim so the
12895        // author can grep their caixa.lisp for the offending contrato
12896        // block and fix it in one edit. Same shape as
12897        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
12898        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12899        // on the peer payload axes.
12900        let err = contrato_slot_err("check out/$order");
12901        match err {
12902            AplicacaoError::ContratoSlotInvalid {
12903                de,
12904                para,
12905                slot,
12906                reason,
12907            } => {
12908                assert_eq!(de, "payment");
12909                assert_eq!(para, "catalog");
12910                assert_eq!(slot, "check out/$order");
12911                assert!(!reason.is_empty(), "reason field must be non-empty");
12912            }
12913            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
12914        }
12915    }
12916
12917    #[test]
12918    fn target_view_store_slot_passes_through_to_typed_view() {
12919        // The compounding theorem on the store axis: every
12920        // `WitTarget::Store { slot }` returned by `target()` carries a
12921        // kv-backend-accepted slot template. Renderers downstream of
12922        // `typed_view()` (the future per-Servico `:capabilities
12923        // wasi:keyvalue/store` axis emitter, the future `feira app
12924        // graph` view's slot labeller, the future kv-provider CR
12925        // materializer) can rely on this without re-checking — the
12926        // type system carries the proof. Mirrors
12927        // `target_view_pubsub_subject_passes_through_to_typed_view` on
12928        // the peer payload axis.
12929        let store = WitContract {
12930            de: "a".into(),
12931            para: "b".into(),
12932            wit: "wasi:keyvalue/store".into(),
12933            endpoint: None,
12934            subject: None,
12935            slot: Some("checkout/$orderId".into()),
12936        };
12937        match store.target().unwrap() {
12938            WitTarget::Store { slot } => {
12939                assert_eq!(slot, "checkout/$orderId");
12940            }
12941            other => panic!("expected Store, got {other:?}"),
12942        }
12943    }
12944
12945    #[test]
12946    fn rejects_self_loop_in_synchronous_contratos() {
12947        // A synchronous self-edge (`cart → cart` over HTTP) is now
12948        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
12949        // "this edge is degenerate" diagnostic — rather than incidentally
12950        // by the cycle detector framing it as a `["cart", "cart"]`
12951        // multi-node deadlock.
12952        let mut s = three_member_spec();
12953        s.contratos.push(contract_http("cart", "cart", "/loop"));
12954        let err = s.validate().unwrap_err();
12955        match err {
12956            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
12957                assert_eq!(caixa, "cart");
12958                assert_eq!(wit, "wasi:http/proxy");
12959            }
12960            other => panic!("expected ContratoSelfLoop, got {other:?}"),
12961        }
12962    }
12963
12964    #[test]
12965    fn rejects_self_loop_in_pubsub_contratos() {
12966        // The cycle detector excludes pub-sub edges (acyclic by
12967        // construction), so before the explicit gate a `nats:pub-sub`
12968        // self-edge silently validated and rendered a self-allow CNP.
12969        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
12970        let mut s = three_member_spec();
12971        s.contratos.push(WitContract {
12972            de: "payment".into(),
12973            para: "payment".into(),
12974            wit: "nats:pub-sub".into(),
12975            endpoint: None,
12976            subject: Some("rio.events.payment".into()),
12977            slot: None,
12978        });
12979        let err = s.validate().unwrap_err();
12980        match err {
12981            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
12982                assert_eq!(caixa, "payment");
12983                assert_eq!(wit, "nats:pub-sub");
12984            }
12985            other => panic!("expected ContratoSelfLoop, got {other:?}"),
12986        }
12987    }
12988
12989    #[test]
12990    fn self_loop_fires_before_payload_shape_check() {
12991        // The structural "this edge can't exist" error precedes the
12992        // narrower payload-shape diagnostics: a self-edge carrying an
12993        // otherwise-malformed endpoint still reports ContratoSelfLoop,
12994        // not ContratoEndpointInvalid.
12995        let mut s = three_member_spec();
12996        s.contratos.push(WitContract {
12997            de: "cart".into(),
12998            para: "cart".into(),
12999            wit: "wasi:http/proxy".into(),
13000            endpoint: Some("not-absolute".into()),
13001            subject: None,
13002            slot: None,
13003        });
13004        match s.validate().unwrap_err() {
13005            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
13006            other => panic!("expected ContratoSelfLoop, got {other:?}"),
13007        }
13008    }
13009
13010    #[test]
13011    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
13012        // A self-edge naming a non-member reports the more fundamental
13013        // ContratoMemberMissing first (the member doesn't exist), so the
13014        // self-loop gate is reached only once both endpoints resolve.
13015        let mut s = three_member_spec();
13016        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
13017        match s.validate().unwrap_err() {
13018            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
13019            other => panic!("expected ContratoMemberMissing, got {other:?}"),
13020        }
13021    }
13022
13023    #[test]
13024    fn rejects_two_node_synchronous_cycle() {
13025        let mut s = three_member_spec();
13026        // existing edges: cart → catalog, cart → payment
13027        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
13028        s.contratos
13029            .push(contract_http("catalog", "cart", "/refresh"));
13030        let err = s.validate().unwrap_err();
13031        match err {
13032            AplicacaoError::ContratoCycle { cycle } => {
13033                // Cycle traversal should mention both endpoints, with
13034                // the back-edge target appearing as both first and last
13035                // element to close the loop.
13036                assert!(cycle.len() >= 3);
13037                assert_eq!(cycle.first(), cycle.last());
13038                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
13039                assert!(body.contains("cart"));
13040                assert!(body.contains("catalog"));
13041            }
13042            other => panic!("expected ContratoCycle, got {other:?}"),
13043        }
13044    }
13045
13046    #[test]
13047    fn rejects_three_node_synchronous_cycle() {
13048        let mut s = three_member_spec();
13049        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
13050        s.contratos = vec![
13051            contract_http("catalog", "cart", "/x"),
13052            contract_http("cart", "payment", "/y"),
13053            contract_http("payment", "catalog", "/z"),
13054        ];
13055        let err = s.validate().unwrap_err();
13056        match err {
13057            AplicacaoError::ContratoCycle { cycle } => {
13058                assert_eq!(cycle.first(), cycle.last());
13059                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
13060                assert_eq!(body.len(), 3);
13061                assert!(body.contains("cart"));
13062                assert!(body.contains("catalog"));
13063                assert!(body.contains("payment"));
13064            }
13065            other => panic!("expected ContratoCycle, got {other:?}"),
13066        }
13067    }
13068
13069    #[test]
13070    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
13071        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
13072        // "acyclic by construction" — so a cycle whose closing edge
13073        // is pub-sub should NOT raise ContratoCycle.
13074        let mut s = three_member_spec();
13075        s.contratos = vec![
13076            contract_http("catalog", "cart", "/x"),
13077            contract_http("cart", "payment", "/y"),
13078            // Closing edge is pub-sub — async; not a sync deadlock.
13079            WitContract {
13080                de: "payment".into(),
13081                para: "catalog".into(),
13082                wit: "nats:pub-sub".into(),
13083                endpoint: None,
13084                subject: Some("checkout.events.charge.completed".into()),
13085                slot: None,
13086            },
13087        ];
13088        s.validate().expect("pub-sub edge breaks the sync cycle");
13089    }
13090
13091    #[test]
13092    fn store_edge_counts_as_synchronous_for_cycle_detection() {
13093        // wasi:keyvalue/store is request/response; a cycle through one
13094        // *is* a sync deadlock, just like HTTP.
13095        let mut s = three_member_spec();
13096        s.contratos = vec![
13097            contract_http("catalog", "cart", "/x"),
13098            WitContract {
13099                de: "cart".into(),
13100                para: "catalog".into(),
13101                wit: "wasi:keyvalue/store".into(),
13102                endpoint: None,
13103                subject: None,
13104                slot: Some("session/$id".into()),
13105            },
13106        ];
13107        let err = s.validate().unwrap_err();
13108        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
13109    }
13110
13111    #[test]
13112    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
13113        // Capability-only edges (unknown WIT shape, no payload) default
13114        // to synchronous — safer; authors with truly async capability
13115        // semantics can model them as pub-sub explicitly.
13116        let mut s = three_member_spec();
13117        s.contratos = vec![
13118            contract_http("catalog", "cart", "/x"),
13119            WitContract {
13120                de: "cart".into(),
13121                para: "catalog".into(),
13122                wit: "custom:exchange".into(),
13123                endpoint: None,
13124                subject: None,
13125                slot: None,
13126            },
13127        ];
13128        let err = s.validate().unwrap_err();
13129        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
13130    }
13131
13132    #[test]
13133    fn long_acyclic_chain_validates() {
13134        // A long sync chain (no back-edges) must validate even when
13135        // every node is reachable from the first.
13136        let mut s = three_member_spec();
13137        s.membros = vec![
13138            membro("a", "^0.1"),
13139            membro("b", "^0.1"),
13140            membro("c", "^0.1"),
13141            membro("d", "^0.1"),
13142            membro("e", "^0.1"),
13143        ];
13144        s.contratos = vec![
13145            contract_http("a", "b", "/1"),
13146            contract_http("b", "c", "/2"),
13147            contract_http("c", "d", "/3"),
13148            contract_http("d", "e", "/4"),
13149        ];
13150        s.entrada.as_mut().unwrap().para = "a".into();
13151        s.validate().unwrap();
13152    }
13153
13154    #[test]
13155    fn diamond_acyclic_validates() {
13156        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
13157        let mut s = three_member_spec();
13158        s.membros = vec![
13159            membro("a", "^0.1"),
13160            membro("b", "^0.1"),
13161            membro("c", "^0.1"),
13162            membro("d", "^0.1"),
13163        ];
13164        s.contratos = vec![
13165            contract_http("a", "b", "/1"),
13166            contract_http("a", "c", "/2"),
13167            contract_http("b", "d", "/3"),
13168            contract_http("c", "d", "/4"),
13169        ];
13170        s.entrada.as_mut().unwrap().para = "a".into();
13171        s.validate().unwrap();
13172    }
13173
13174    // ── duplicate-`:contratos` build-error gate ──────────────────────────
13175
13176    #[test]
13177    fn rejects_duplicate_http_contrato() {
13178        // Fail-before-pass-after pin: the fixture's `cart → catalog`
13179        // HTTP edge appears once. Push an identical entry — same
13180        // (de, para, wit, endpoint) — and validate() must reject it.
13181        // Until this gate landed the typed surface accepted the
13182        // duplicate silently and caixa-mesh's `cilium_network_policies`
13183        // emitted two ``CiliumNetworkPolicy`` objects with identical
13184        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
13185        // admission rejects on `kubectl apply` far from the source.
13186        let mut s = three_member_spec();
13187        s.contratos
13188            .push(contract_http("cart", "catalog", "/products/:id"));
13189        let err = s.validate().unwrap_err();
13190        assert!(
13191            matches!(
13192                err,
13193                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13194                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
13195            ),
13196            "got {err:?}"
13197        );
13198    }
13199
13200    #[test]
13201    fn rejects_duplicate_pubsub_contrato() {
13202        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
13203        // edges with identical (de, para, subject) are degenerate;
13204        // pin that the typed surface refuses both at validate time.
13205        let mut s = three_member_spec();
13206        let pubsub = WitContract {
13207            de: "payment".into(),
13208            para: "cart".into(),
13209            wit: "nats:pub-sub".into(),
13210            endpoint: None,
13211            subject: Some("checkout.events.charge.failed".into()),
13212            slot: None,
13213        };
13214        s.contratos.push(pubsub.clone());
13215        s.contratos.push(pubsub);
13216        let err = s.validate().unwrap_err();
13217        assert!(
13218            matches!(
13219                err,
13220                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13221                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
13222            ),
13223            "got {err:?}"
13224        );
13225    }
13226
13227    #[test]
13228    fn rejects_duplicate_store_contrato() {
13229        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
13230        // edges with identical (de, para, slot) collapse to one mesh-
13231        // policy edge; pin the build error.
13232        let mut s = three_member_spec();
13233        let store = WitContract {
13234            de: "cart".into(),
13235            para: "payment".into(),
13236            wit: "wasi:keyvalue/store".into(),
13237            endpoint: None,
13238            subject: None,
13239            slot: Some("checkout/$orderId".into()),
13240        };
13241        // Drop the conflicting HTTP `cart → payment` edge from the
13242        // fixture so the duplicate-store pair is the only one
13243        // distinguishable on this pair.
13244        s.contratos
13245            .retain(|c| !(c.de == "cart" && c.para == "payment"));
13246        s.contratos.push(store.clone());
13247        s.contratos.push(store);
13248        let err = s.validate().unwrap_err();
13249        assert!(
13250            matches!(
13251                err,
13252                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13253                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
13254            ),
13255            "got {err:?}"
13256        );
13257    }
13258
13259    #[test]
13260    fn rejects_duplicate_capability_contrato() {
13261        // Same gate on the pure-capability axis (no payload selector).
13262        // Two contracts with identical (de, para, wit) and no
13263        // endpoint/subject/slot are duplicate edges; pin so a future
13264        // `target_label` change can't accidentally collapse the
13265        // capability arm into a None-shaped key that compares equal
13266        // to a populated one.
13267        let mut s = three_member_spec();
13268        let capability = WitContract {
13269            de: "cart".into(),
13270            para: "catalog".into(),
13271            wit: "pleme:cap/audit".into(),
13272            endpoint: None,
13273            subject: None,
13274            slot: None,
13275        };
13276        s.contratos.push(capability.clone());
13277        s.contratos.push(capability);
13278        let err = s.validate().unwrap_err();
13279        match err {
13280            AplicacaoError::ContratoDuplicate {
13281                de,
13282                para,
13283                wit,
13284                target,
13285            } => {
13286                assert_eq!(de, "cart");
13287                assert_eq!(para, "catalog");
13288                assert_eq!(wit, "pleme:cap/audit");
13289                assert!(
13290                    target.contains("capability"),
13291                    "capability-edge duplicate diagnostic must surface the \
13292                     no-payload shape (got target = {target:?})"
13293                );
13294            }
13295            other => panic!("expected ContratoDuplicate, got {other:?}"),
13296        }
13297    }
13298
13299    #[test]
13300    fn accepts_distinct_http_paths_between_same_pair() {
13301        // Negative pin: two HTTP contracts cart → catalog at distinct
13302        // endpoints (`/products/:id` and `/search`) are *not*
13303        // duplicates — they're distinct typed edges differing on the
13304        // payload axis. The duplicate-gate must not over-match here,
13305        // since the cart-calls-catalog-on-multiple-paths shape is the
13306        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
13307        // example: cart calls catalog at /products/:id, payment at
13308        // /charge — same shape extends to two paths on one para).
13309        let mut s = three_member_spec();
13310        s.contratos
13311            .push(contract_http("cart", "catalog", "/search"));
13312        s.validate()
13313            .expect("distinct endpoints between same (de, para) must validate");
13314    }
13315
13316    #[test]
13317    fn accepts_same_endpoint_on_different_pairs() {
13318        // Negative pin: the same `/charge` endpoint reused on two
13319        // different (de, para) pairs is two distinct edges, not a
13320        // duplicate. Pinning this shape so the gate's identity key
13321        // includes both `de` and `para` (not just `(wit, endpoint)`).
13322        let mut s = three_member_spec();
13323        s.contratos
13324            .push(contract_http("payment", "catalog", "/charge"));
13325        s.validate()
13326            .expect("same endpoint reused on distinct (de, para) must validate");
13327    }
13328
13329    #[test]
13330    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
13331        // Pin the diagnostic shape: the duplicate-edge error names
13332        // *which* target field carried the conflict, so the author
13333        // doesn't have to re-grep the source caixa.lisp to find it.
13334        // Same self-locating diagnostic discipline as
13335        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
13336        let mut s = three_member_spec();
13337        s.contratos
13338            .push(contract_http("cart", "catalog", "/products/:id"));
13339        let err = s.validate().unwrap_err();
13340        let msg = format!("{err}");
13341        assert!(
13342            msg.contains("\"/products/:id\""),
13343            "duplicate-contrato diagnostic must name the offending \
13344             :endpoint payload (got: {msg:?})"
13345        );
13346        assert!(
13347            msg.contains("cart") && msg.contains("catalog"),
13348            "diagnostic must name both endpoints of the duplicate edge \
13349             (got: {msg:?})"
13350        );
13351    }
13352
13353    #[test]
13354    fn duplicate_contrato_gate_runs_after_membership_check() {
13355        // Order pin: a duplicate contract whose `:de` is *also* not in
13356        // `:membros` surfaces the membership error first — the
13357        // missing-member diagnostic is more locating than the
13358        // duplicate-edge one (the author has to fix the membership
13359        // before the duplicate is meaningful). Same ordering
13360        // discipline as `membros_validation_runs_before_contratos_membership_check`.
13361        let mut s = three_member_spec();
13362        s.contratos.push(contract_http("phantom", "catalog", "/x"));
13363        s.contratos.push(contract_http("phantom", "catalog", "/x"));
13364        let err = s.validate().unwrap_err();
13365        assert!(
13366            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
13367            "membership-missing must fire before duplicate-edge (got {err:?})"
13368        );
13369    }
13370
13371    #[test]
13372    fn duplicate_contrato_gate_runs_after_target_shape_check() {
13373        // Order pin: a contract with a malformed target (e.g. an HTTP
13374        // wit world with an empty :endpoint) surfaces the target-shape
13375        // error first, not the duplicate one. Even when two such
13376        // malformed entries are identical, the per-contract `target()`
13377        // check fires inside the loop *before* the duplicate-key
13378        // insert, so the diagnostic remains the most-locating one.
13379        let mut s = three_member_spec();
13380        let malformed = WitContract {
13381            de: "cart".into(),
13382            para: "catalog".into(),
13383            wit: "wasi:http/proxy".into(),
13384            endpoint: Some(String::new()),
13385            subject: None,
13386            slot: None,
13387        };
13388        s.contratos.push(malformed.clone());
13389        s.contratos.push(malformed);
13390        let err = s.validate().unwrap_err();
13391        assert!(
13392            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
13393            "endpoint-empty must fire before duplicate-edge (got {err:?})"
13394        );
13395    }
13396
13397    #[test]
13398    fn wit_target_label_pins_per_variant_format() {
13399        // Label format is the single source of truth every duplicate-
13400        // `:contratos` diagnostic + every future `feira app graph`
13401        // consumer routes through. Pin the shape per variant so a
13402        // future edit to `WitTarget::label` (e.g. a JSON emitter that
13403        // strips the leading `:`, or a rename from `endpoint` →
13404        // `path`) surfaces as a red-red test rather than as a silent
13405        // downstream diagnostic drift. Together with the exhaustive
13406        // `match` on `WitTarget` inside `label()`, adding a future
13407        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
13408        // peer, per-edge WIT registry variants) is a compile error at
13409        // the label site — not a fall-through into the `Capability`
13410        // "no payload" default the prior raw-field-probe helper
13411        // silently landed on.
13412        assert_eq!(
13413            WitTarget::Http {
13414                endpoint: "/charge",
13415            }
13416            .label(),
13417            "\
13418:endpoint \"/charge\""
13419        );
13420        assert_eq!(
13421            WitTarget::PubSub {
13422                subject: "events.checkout.paid",
13423            }
13424            .label(),
13425            "\
13426:subject \"events.checkout.paid\""
13427        );
13428        assert_eq!(
13429            WitTarget::Store {
13430                slot: "checkout/$order",
13431            }
13432            .label(),
13433            "\
13434:slot \"checkout/$order\""
13435        );
13436        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
13437        // Capability-arm label routes through the lifted
13438        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
13439        // declaration per arm, next to the variant" discipline the
13440        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
13441        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13442        // consts already carry extends to the payload-less arm; the
13443        // byte-string equality pin below plus this label-routes-
13444        // through-the-const pin make a future rebrand on either the
13445        // const declaration or the `label()` template a build error
13446        // here rather than a downstream consumer surprise.
13447        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
13448        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
13449    }
13450
13451    #[test]
13452    fn wit_target_display_routes_through_label_helper() {
13453        // Fail-before-pass-after pin on the fourth (and only remaining)
13454        // typed-shape-discriminator axis to converge onto the
13455        // three-path-convergence discipline the sibling M3
13456        // [`PlacementStrategy`] (0a2f653) and M2
13457        // [`crate::supervisor::RestartStrategy`] /
13458        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
13459        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
13460        // through [`WitTarget::label`], so every consumer reaching for
13461        // `format!("{v}")` on a typed payload target lands on the same
13462        // stable author-facing byte-string [`WitTarget::label`] returns
13463        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
13464        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
13465        // `:contratos` gate seeds via [`WitTarget::label`] at
13466        // aplicacao.rs:5491 already threads through.
13467        //
13468        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
13469        // through to the `Debug` derive's structural output
13470        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
13471        // rather than the [`WitTarget::label`] helper's stable byte-
13472        // string (`:endpoint "/charge"` — the author-facing `:contratos`
13473        // keyword form). Every future consumer that reaches for
13474        // `format!("{target}")` — the canonical shape every user-facing
13475        // pretty-print site on the sibling typed-enum axes
13476        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
13477        // [`crate::supervisor::RestartPolicy`]) already uses — would
13478        // silently land under a different byte-string than the
13479        // [`WitTarget::label`] callers that the duplicate-`:contratos`
13480        // diagnostic already threads through, with the mismatch
13481        // surfacing as a downstream diagnostic / graph / audit line
13482        // reading one spelling while the substrate's own gate emitted
13483        // another.
13484        //
13485        // Pin the routing here so a future
13486        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
13487        // that hand-rolls the per-arm formatting instead of delegating
13488        // to [`WitTarget::label`] fails at caixa-core build time.
13489        for variant in [
13490            WitTarget::Http {
13491                endpoint: "/charge",
13492            },
13493            WitTarget::PubSub {
13494                subject: "events.checkout.paid",
13495            },
13496            WitTarget::Store {
13497                slot: "checkout/$order",
13498            },
13499            WitTarget::Capability,
13500        ] {
13501            assert_eq!(
13502                variant.to_string(),
13503                variant.label(),
13504                "WitTarget::{variant:?} Display must route through \
13505                 WitTarget::label (single source of truth: the lifted \
13506                 payload_pair 4-arm dispatch the label helper already \
13507                 threads through)"
13508            );
13509        }
13510    }
13511
13512    #[test]
13513    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
13514        // Consumer-side pin on the three-path convergence:
13515        // [`std::fmt::Display`] agrees byte-for-byte with the
13516        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
13517        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
13518        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
13519        // Pre-lift the two paths were structurally independent — the
13520        // substrate-side gate reached for `target_view.label()` while a
13521        // future downstream diagnostic / graph / audit line reaching
13522        // for `format!("{target}")` would silently land on the `Debug`
13523        // derive's structural output. Pin the two paths byte-for-byte
13524        // here so any future variant addition (M4 `Rest`/`Grpc` split
13525        // of [`WitTarget::Http`], `Queue`-shaped peer of
13526        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
13527        // match error at [`WitTarget::payload_pair`] rather than a
13528        // silent per-consumer dispatch miss.
13529        for variant in [
13530            WitTarget::Http {
13531                endpoint: "/charge",
13532            },
13533            WitTarget::PubSub {
13534                subject: "events.checkout.paid",
13535            },
13536            WitTarget::Store {
13537                slot: "checkout/$order",
13538            },
13539            WitTarget::Capability,
13540        ] {
13541            assert_eq!(
13542                format!("{variant}"),
13543                variant.label(),
13544                "WitTarget::{variant:?} Display byte-string must match \
13545                 the AplicacaoError::ContratoDuplicate `target:` carrier \
13546                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
13547                 seeds via WitTarget::label — three-path convergence: \
13548                 Display + label + payload_pair all resolve to the same \
13549                 per-arm byte-string"
13550            );
13551        }
13552    }
13553
13554    #[test]
13555    fn wit_target_payload_pair_pins_per_variant() {
13556        // Pin the per-arm `(field-name, payload)` pair single-sourced
13557        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
13558        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
13559        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
13560        // and [`WitTarget::field_name`] (returns the first component)
13561        // route through. Until this lift landed [`WitTarget::label`]
13562        // dispatched on the same three arms with a per-arm
13563        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
13564        // paired [`WitTarget::HTTP_FIELD_NAME`] /
13565        // [`WitTarget::PUBSUB_FIELD_NAME`] /
13566        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
13567        // canonical "same shape, written N times" duplication
13568        // THEORY.md §I.3.5 promotes to a build-time concern. A future
13569        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
13570        // [`WitTarget::Http`], `Queue`-shaped peer of
13571        // [`WitTarget::Store`]) is one match-arm edit at
13572        // [`WitTarget::payload_pair`], visible here as a compile-time
13573        // exhaustiveness error on both this pin and the label-format
13574        // pin above.
13575        assert_eq!(
13576            WitTarget::Http {
13577                endpoint: "/charge"
13578            }
13579            .payload_pair(),
13580            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
13581        );
13582        assert_eq!(
13583            WitTarget::PubSub {
13584                subject: "events.x",
13585            }
13586            .payload_pair(),
13587            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
13588        );
13589        assert_eq!(
13590            WitTarget::Store {
13591                slot: "checkout/$order",
13592            }
13593            .payload_pair(),
13594            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
13595        );
13596        assert_eq!(WitTarget::Capability.payload_pair(), None);
13597    }
13598
13599    #[test]
13600    fn wit_target_field_name_pins_per_variant() {
13601        // Pin the per-arm author-facing `:contratos` payload field
13602        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
13603        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13604        // + returned by [`WitTarget::field_name`]. Every downstream
13605        // consumer (the [`WitContract::target`] gate's `expected:`
13606        // scalar, the [`WitTarget::label`] template's keyword prefix,
13607        // the `feira app graph` verb's `endpoint=…` prefix) routes
13608        // through the same three peer consts, so a rename on the
13609        // author-surface `(defcaixa … :contratos ((:de … :para …
13610        // :wit … :endpoint …)))` field lands in exactly one place.
13611        assert_eq!(
13612            WitTarget::Http {
13613                endpoint: "/charge"
13614            }
13615            .field_name(),
13616            Some(WitTarget::HTTP_FIELD_NAME),
13617        );
13618        assert_eq!(
13619            WitTarget::PubSub {
13620                subject: "events.x",
13621            }
13622            .field_name(),
13623            Some(WitTarget::PUBSUB_FIELD_NAME),
13624        );
13625        assert_eq!(
13626            WitTarget::Store {
13627                slot: "checkout/$order",
13628            }
13629            .field_name(),
13630            Some(WitTarget::STORE_FIELD_NAME),
13631        );
13632        // Capability arm carries no payload field — the diagnostic
13633        // never reports `expected: "capability"` because the gate's
13634        // Capability arm accepts no payload at all (it fires the
13635        // "expected: none" WrongTarget error instead), so the field-
13636        // name method returns None here rather than a placeholder.
13637        assert_eq!(WitTarget::Capability.field_name(), None);
13638
13639        // Peer const scalar values pinned so a rename on either side
13640        // (author-surface field name in the `(defcaixa …)` DSL, or
13641        // the diagnostic's `expected:` scalar) can't drift without
13642        // failing here first.
13643        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
13644        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
13645        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
13646    }
13647
13648    #[test]
13649    fn wit_target_payload_pins_per_variant() {
13650        // Pin the per-arm payload scalar single-sourced onto the
13651        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
13652        // [`WitTarget::payload`] — the peer per-half projection to
13653        // [`WitTarget::field_name`] on the paired sub-selector axis. The
13654        // three payload-carrying arms round-trip their author-declared
13655        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
13656        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
13657        // the payload-less [`WitTarget::Capability`] arm returns `None`.
13658        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
13659        // (c6ec2af) pin on the Component-0 projection axis, extended
13660        // onto the Component-1 projection axis so both per-half readers
13661        // on the paired dispatch carry their own byte-shape pin.
13662        assert_eq!(
13663            WitTarget::Http {
13664                endpoint: "/charge",
13665            }
13666            .payload(),
13667            Some("/charge"),
13668        );
13669        assert_eq!(
13670            WitTarget::PubSub {
13671                subject: "events.x",
13672            }
13673            .payload(),
13674            Some("events.x"),
13675        );
13676        assert_eq!(
13677            WitTarget::Store {
13678                slot: "checkout/$order",
13679            }
13680            .payload(),
13681            Some("checkout/$order"),
13682        );
13683        assert_eq!(WitTarget::Capability.payload(), None);
13684    }
13685
13686    #[test]
13687    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
13688        // Per-variant equivalence pin: for every arm of [`WitTarget`],
13689        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
13690        // byte-for-byte. Guards the drift surface where a future refactor
13691        // that split one accessor off the shared match onto its own
13692        // dispatch — a well-meaning "inline the pair back into per-half
13693        // fields for one crate-internal caller who only wanted one half"
13694        // or a scratch `impl` shadowing the derived projection — would
13695        // silently desynchronize [`WitTarget::payload`] from the
13696        // authoritative [`WitTarget::payload_pair`] dispatch, and every
13697        // downstream consumer that thinks "the payload half of the pair"
13698        // would drift from the diagnostic / graph consumers reading the
13699        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
13700        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
13701        // per-half projection pin (`gitrefspec_ref_pair_projects_
13702        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
13703        // FluxCD source-controller `spec.ref.<field>` axis — same "one
13704        // paired dispatch, both per-half projections agree byte-for-
13705        // byte" discipline extended onto the M3 `:contratos` payload-
13706        // arm surface.
13707        for variant in [
13708            WitTarget::Http {
13709                endpoint: "/charge",
13710            },
13711            WitTarget::PubSub {
13712                subject: "events.checkout.paid",
13713            },
13714            WitTarget::Store {
13715                slot: "checkout/$order",
13716            },
13717            WitTarget::Capability,
13718        ] {
13719            let via_projection = variant.payload();
13720            let via_pair = variant.payload_pair().map(|(_, p)| p);
13721            assert_eq!(
13722                via_projection, via_pair,
13723                "WitTarget::{variant:?} payload() must equal \
13724                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
13725                 regression that splits the two per-half projections off \
13726                 their shared match would silently desynchronize the \
13727                 payload accessor from the paired dispatch every \
13728                 diagnostic / graph consumer reads through",
13729            );
13730        }
13731    }
13732
13733    #[test]
13734    fn wit_target_http_endpoint_pins_per_variant() {
13735        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
13736        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
13737        // substrate-primitive per-arm post-projection accessor every
13738        // L7-HTTP-facing consumer routes through, sibling to the peer
13739        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
13740        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
13741        // arm round-trips its author-declared endpoint verbatim as
13742        // `Some("/charge")`; the three sibling arms
13743        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
13744        // [`WitTarget::Capability`]) each return `None` because they
13745        // carry no HTTP endpoint by definition. Same fail-before-pass-
13746        // after per-variant discipline as the sibling
13747        // `wit_target_payload_pins_per_variant` (5d6dc92) /
13748        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
13749        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
13750        // the peer pan-arm / per-half projection axes — extended onto
13751        // the per-arm HTTP-shape post-projection axis so a future
13752        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
13753        // [`WitTarget::Http`], a `Queue`-shaped peer of
13754        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
13755        // error on the sibling [`WitTarget::http_endpoint`] match arms
13756        // whose payload the L7-HTTP-shape accept-set is meant to bound.
13757        assert_eq!(
13758            WitTarget::Http {
13759                endpoint: "/charge",
13760            }
13761            .http_endpoint(),
13762            Some("/charge"),
13763        );
13764        assert_eq!(
13765            WitTarget::PubSub {
13766                subject: "events.checkout.paid",
13767            }
13768            .http_endpoint(),
13769            None,
13770        );
13771        assert_eq!(
13772            WitTarget::Store {
13773                slot: "checkout/$order",
13774            }
13775            .http_endpoint(),
13776            None,
13777        );
13778        assert_eq!(WitTarget::Capability.http_endpoint(), None);
13779    }
13780
13781    #[test]
13782    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
13783        // Per-variant coherence pin: for every arm of [`WitTarget`],
13784        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
13785        // arm (both project the same author-declared request-path
13786        // scalar), and returns `None` on every sibling arm regardless of
13787        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
13788        // Store carry their own payload the pan-arm accessor surfaces,
13789        // but that payload is not an HTTP endpoint — the per-arm
13790        // accessor must not leak it through the HTTP-shape channel).
13791        // Guards the drift surface where a future refactor that
13792        // conflated the per-arm HTTP projection with the pan-arm
13793        // [`WitTarget::payload`] projection — a well-meaning "one
13794        // accessor for the L7 branch, one for the graph" collapse that
13795        // routes both through the same 4-arm dispatch — would silently
13796        // widen the L7-HTTP-shape accept-set onto pub-sub / store
13797        // payloads at the caixa-mesh L7 emit branch, admitting a
13798        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
13799        // rule with the operator-side apply-time symptom (Cilium's
13800        // eBPF data-plane rejects every ingress edge whose L7 filter
13801        // doesn't match the wire-format HTTP request line) far from
13802        // the source refactor. Sibling to the peer
13803        // `wit_target_payload_matches_payload_pair_second_component_
13804        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
13805        // extended onto the per-arm HTTP specialization axis so both
13806        // the pan-arm and the per-arm projections carry their own
13807        // byte-shape coherence witness against the substrate's typed
13808        // arm-family accept-set.
13809        for variant in [
13810            WitTarget::Http {
13811                endpoint: "/charge",
13812            },
13813            WitTarget::PubSub {
13814                subject: "events.checkout.paid",
13815            },
13816            WitTarget::Store {
13817                slot: "checkout/$order",
13818            },
13819            WitTarget::Capability,
13820        ] {
13821            let per_arm = variant.http_endpoint();
13822            let pan_arm = variant.payload();
13823            if variant.is_http() {
13824                assert_eq!(
13825                    per_arm, pan_arm,
13826                    "WitTarget::{variant:?} http_endpoint() must equal \
13827                     payload() on the Http arm — a per-arm-vs-pan-arm \
13828                     split would silently drift the L7 emit branch's \
13829                     path-scalar source from the graph verb's payload \
13830                     scalar source",
13831                );
13832            } else {
13833                assert_eq!(
13834                    per_arm, None,
13835                    "WitTarget::{variant:?} http_endpoint() must return \
13836                     None on non-Http arms — a leak that surfaced a \
13837                     pub-sub :subject or a key/value :slot through the \
13838                     HTTP-endpoint accessor would silently widen the \
13839                     Cilium L7 HTTP `path:` rule accept-set onto \
13840                     protocol shapes Cilium's eBPF data-plane can't \
13841                     introspect",
13842                );
13843            }
13844        }
13845    }
13846
13847    #[test]
13848    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
13849        // Per-variant coherence pin: for every arm of [`WitTarget`],
13850        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
13851        // drift surface where a future extension of the
13852        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
13853        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
13854        // accessor to cover both peers) landed without a paired
13855        // extension of the [`gen_platform::IsVariant`]-derived
13856        // `is_http()` predicate's accept-set, or vice versa — a
13857        // regression that split the "which arms count as HTTP-shaped
13858        // for L7-path emission?" answer between two dispatch surfaces
13859        // the substrate ships. Sibling to the peer
13860        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
13861        // on the paired dispatch axis — extended onto the per-arm
13862        // predicate-vs-accessor coherence axis so the gen-platform
13863        // IsVariant predicate and the substrate-lifted per-arm
13864        // accessor carry one shared answer to "is this the HTTP arm?".
13865        for variant in [
13866            WitTarget::Http {
13867                endpoint: "/charge",
13868            },
13869            WitTarget::PubSub {
13870                subject: "events.checkout.paid",
13871            },
13872            WitTarget::Store {
13873                slot: "checkout/$order",
13874            },
13875            WitTarget::Capability,
13876        ] {
13877            assert_eq!(
13878                variant.http_endpoint().is_some(),
13879                variant.is_http(),
13880                "WitTarget::{variant:?} http_endpoint().is_some() must \
13881                 equal is_http() — a drift would split the L7 emit \
13882                 branch's arm-set gate from the substrate-derived \
13883                 shape-discrimination predicate on the same axis",
13884            );
13885        }
13886    }
13887
13888    #[test]
13889    fn wit_target_pubsub_subject_pins_per_variant() {
13890        // Fail-before-pass-after pin: the substrate-canonical per-arm
13891        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
13892        // is the single dispatch every future pub-sub-facing consumer
13893        // routes through, sibling to the peer [`WitContract::subject`]
13894        // (63e18a0) pre-projection scalar accessor on the raw-field
13895        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
13896        // post-projection per-arm accessor on the sibling HTTP-shape
13897        // axis. The [`WitTarget::PubSub`] arm round-trips its
13898        // author-declared subject verbatim as
13899        // `Some("events.checkout.paid")`; the three sibling arms each
13900        // return `None` because they carry no NATS-shaped subject by
13901        // definition. Same fail-before-pass-after per-variant discipline
13902        // as the sibling `wit_target_http_endpoint_pins_per_variant`
13903        // pin on the peer per-arm axis — extended onto the per-arm
13904        // pub-sub-shape post-projection axis so a future [`WitTarget`]
13905        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
13906        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
13907        // compile-time exhaustiveness error on the sibling
13908        // [`WitTarget::pubsub_subject`] match arms whose payload the
13909        // pub-sub-shape accept-set is meant to bound.
13910        assert_eq!(
13911            WitTarget::PubSub {
13912                subject: "events.checkout.paid",
13913            }
13914            .pubsub_subject(),
13915            Some("events.checkout.paid"),
13916        );
13917        assert_eq!(
13918            WitTarget::Http {
13919                endpoint: "/charge",
13920            }
13921            .pubsub_subject(),
13922            None,
13923        );
13924        assert_eq!(
13925            WitTarget::Store {
13926                slot: "checkout/$order",
13927            }
13928            .pubsub_subject(),
13929            None,
13930        );
13931        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
13932    }
13933
13934    #[test]
13935    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
13936        // Per-variant coherence pin: for every arm of [`WitTarget`],
13937        // `.pubsub_subject()` equals `.payload()` on the
13938        // [`WitTarget::PubSub`] arm (both project the same
13939        // author-declared subject scalar), and returns `None` on every
13940        // sibling arm regardless of whether [`WitTarget::payload`]
13941        // itself returns `Some` (Http / Store carry their own payload
13942        // the pan-arm accessor surfaces, but that payload is not a
13943        // pub-sub subject — the per-arm accessor must not leak it
13944        // through the pub-sub-shape channel). Sibling to the peer
13945        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
13946        // coherence pin on the per-arm HTTP-shape axis — extended onto
13947        // the per-arm pub-sub specialization axis so both per-arm
13948        // projections carry their own byte-shape coherence witness
13949        // against the substrate's typed arm-family accept-set.
13950        for variant in [
13951            WitTarget::Http {
13952                endpoint: "/charge",
13953            },
13954            WitTarget::PubSub {
13955                subject: "events.checkout.paid",
13956            },
13957            WitTarget::Store {
13958                slot: "checkout/$order",
13959            },
13960            WitTarget::Capability,
13961        ] {
13962            let per_arm = variant.pubsub_subject();
13963            let pan_arm = variant.payload();
13964            if variant.is_pubsub() {
13965                assert_eq!(
13966                    per_arm, pan_arm,
13967                    "WitTarget::{variant:?} pubsub_subject() must equal \
13968                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
13969                     split would silently drift the pub-sub-shape emit \
13970                     branch's subject-scalar source from the graph verb's \
13971                     payload scalar source",
13972                );
13973            } else {
13974                assert_eq!(
13975                    per_arm, None,
13976                    "WitTarget::{variant:?} pubsub_subject() must return \
13977                     None on non-PubSub arms — a leak that surfaced an \
13978                     HTTP :endpoint or a key/value :slot through the \
13979                     pub-sub-subject accessor would silently widen the \
13980                     downstream NATS-shape accept-set onto protocol \
13981                     shapes NATS servers can't route",
13982                );
13983            }
13984        }
13985    }
13986
13987    #[test]
13988    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
13989        // Per-variant coherence pin: for every arm of [`WitTarget`],
13990        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
13991        // drift surface where a future extension of the
13992        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
13993        // without a paired extension of the [`gen_platform::IsVariant`]-
13994        // derived `is_pubsub()` predicate's accept-set, or vice versa
13995        // — a regression that split the "which arms count as pub-sub-
13996        // shaped for subject emission?" answer between two dispatch
13997        // surfaces the substrate ships. Sibling to the peer
13998        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
13999        // pin on the per-arm HTTP-shape axis — extended onto the
14000        // per-arm pub-sub predicate-vs-accessor coherence axis so the
14001        // gen-platform IsVariant predicate and the substrate-lifted
14002        // per-arm accessor carry one shared answer to "is this the
14003        // PubSub arm?".
14004        for variant in [
14005            WitTarget::Http {
14006                endpoint: "/charge",
14007            },
14008            WitTarget::PubSub {
14009                subject: "events.checkout.paid",
14010            },
14011            WitTarget::Store {
14012                slot: "checkout/$order",
14013            },
14014            WitTarget::Capability,
14015        ] {
14016            assert_eq!(
14017                variant.pubsub_subject().is_some(),
14018                variant.is_pubsub(),
14019                "WitTarget::{variant:?} pubsub_subject().is_some() must \
14020                 equal is_pubsub() — a drift would split the pub-sub \
14021                 emit branch's arm-set gate from the substrate-derived \
14022                 shape-discrimination predicate on the same axis",
14023            );
14024        }
14025    }
14026
14027    #[test]
14028    fn wit_target_store_slot_pins_per_variant() {
14029        // Fail-before-pass-after pin: the substrate-canonical per-arm
14030        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
14031        // is the single dispatch every future store-facing consumer
14032        // routes through, sibling to the peer [`WitContract::slot`]
14033        // pre-projection scalar accessor on the raw-field axis and to
14034        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
14035        // [`WitTarget::pubsub_subject`] post-projection per-arm
14036        // accessors on the sibling per-payload-arm axes. The
14037        // [`WitTarget::Store`] arm round-trips its author-declared
14038        // slot verbatim as `Some("checkout/$order")`; the three
14039        // sibling arms each return `None` because they carry no
14040        // WASI-key/value slot by definition. Same fail-before-pass-
14041        // after per-variant discipline as the sibling
14042        // `wit_target_http_endpoint_pins_per_variant` +
14043        // `wit_target_pubsub_subject_pins_per_variant` pins on the
14044        // peer per-arm axes — extended onto the per-arm store-shape
14045        // post-projection axis so a future [`WitTarget`] variant
14046        // addition trips a compile-time exhaustiveness error on the
14047        // sibling [`WitTarget::store_slot`] match arms whose payload
14048        // the store-shape accept-set is meant to bound.
14049        assert_eq!(
14050            WitTarget::Store {
14051                slot: "checkout/$order",
14052            }
14053            .store_slot(),
14054            Some("checkout/$order"),
14055        );
14056        assert_eq!(
14057            WitTarget::Http {
14058                endpoint: "/charge",
14059            }
14060            .store_slot(),
14061            None,
14062        );
14063        assert_eq!(
14064            WitTarget::PubSub {
14065                subject: "events.checkout.paid",
14066            }
14067            .store_slot(),
14068            None,
14069        );
14070        assert_eq!(WitTarget::Capability.store_slot(), None);
14071    }
14072
14073    #[test]
14074    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
14075        // Per-variant coherence pin: for every arm of [`WitTarget`],
14076        // `.store_slot()` equals `.payload()` on the
14077        // [`WitTarget::Store`] arm (both project the same
14078        // author-declared slot scalar), and returns `None` on every
14079        // sibling arm regardless of whether [`WitTarget::payload`]
14080        // itself returns `Some`. Sibling to the peer
14081        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
14082        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
14083        // pins on the per-arm HTTP and PubSub axes — closes the
14084        // per-arm-vs-pan-arm byte-shape coherence trio across all
14085        // three payload arms.
14086        for variant in [
14087            WitTarget::Http {
14088                endpoint: "/charge",
14089            },
14090            WitTarget::PubSub {
14091                subject: "events.checkout.paid",
14092            },
14093            WitTarget::Store {
14094                slot: "checkout/$order",
14095            },
14096            WitTarget::Capability,
14097        ] {
14098            let per_arm = variant.store_slot();
14099            let pan_arm = variant.payload();
14100            if variant.is_store() {
14101                assert_eq!(
14102                    per_arm, pan_arm,
14103                    "WitTarget::{variant:?} store_slot() must equal \
14104                     payload() on the Store arm — a per-arm-vs-pan-arm \
14105                     split would silently drift the store-shape emit \
14106                     branch's slot-scalar source from the graph verb's \
14107                     payload scalar source",
14108                );
14109            } else {
14110                assert_eq!(
14111                    per_arm, None,
14112                    "WitTarget::{variant:?} store_slot() must return \
14113                     None on non-Store arms — a leak that surfaced an \
14114                     HTTP :endpoint or a NATS :subject through the \
14115                     key/value-slot accessor would silently widen the \
14116                     downstream WASI-key/value slot accept-set onto \
14117                     protocol shapes the kv backends can't route",
14118                );
14119            }
14120        }
14121    }
14122
14123    #[test]
14124    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
14125        // Per-variant coherence pin: for every arm of [`WitTarget`],
14126        // `.store_slot().is_some()` iff `.is_store()`. Guards the
14127        // drift surface where a future extension of the
14128        // [`WitTarget::store_slot`] accessor's accept-set landed
14129        // without a paired extension of the [`gen_platform::IsVariant`]-
14130        // derived `is_store()` predicate's accept-set. Sibling to the
14131        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
14132        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
14133        // pins — closes the per-arm predicate-vs-accessor coherence
14134        // trio across all three payload arms so the gen-platform
14135        // IsVariant predicate and the substrate-lifted per-arm
14136        // accessor carry one shared answer to "is this the Store arm?".
14137        for variant in [
14138            WitTarget::Http {
14139                endpoint: "/charge",
14140            },
14141            WitTarget::PubSub {
14142                subject: "events.checkout.paid",
14143            },
14144            WitTarget::Store {
14145                slot: "checkout/$order",
14146            },
14147            WitTarget::Capability,
14148        ] {
14149            assert_eq!(
14150                variant.store_slot().is_some(),
14151                variant.is_store(),
14152                "WitTarget::{variant:?} store_slot().is_some() must \
14153                 equal is_store() — a drift would split the store-shape \
14154                 emit branch's arm-set gate from the substrate-derived \
14155                 shape-discrimination predicate on the same axis",
14156            );
14157        }
14158    }
14159
14160    #[test]
14161    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
14162        // Fail-before-pass-after cross-axis pin on the trio
14163        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
14164        // payload-carrying arm of [`WitTarget`], exactly one per-arm
14165        // accessor returns `Some(payload)` and the two peers return
14166        // `None`; and on the payload-less [`WitTarget::Capability`]
14167        // arm, all three return `None`. Guards the drift surface where
14168        // a future extension of one per-arm accessor's accept-set (e.g.
14169        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
14170        // that widened `http_endpoint` to cover both peers without
14171        // narrowing the peer `pubsub_subject` / `store_slot` accept-
14172        // sets to keep the partition mutually exclusive) landed without
14173        // threading through the peer per-arm accessors — the resulting
14174        // silent overlap would land the same edge's payload on two
14175        // downstream per-shape emit branches at once, or leak a
14176        // pub-sub subject through the store-slot channel, at renderer
14177        // emit time far from the substrate primitive's arm-widening
14178        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
14179        // 3-way pin on the payload-field-name axis — extended onto the
14180        // per-arm-accessor payload-projection axis so the substrate-
14181        // owned partition invariant is load-bearing at every per-arm
14182        // consumer's read site.
14183        let payload_variants = [
14184            (
14185                WitTarget::Http {
14186                    endpoint: "/charge",
14187                },
14188                "http",
14189            ),
14190            (
14191                WitTarget::PubSub {
14192                    subject: "events.checkout.paid",
14193                },
14194                "pubsub",
14195            ),
14196            (
14197                WitTarget::Store {
14198                    slot: "checkout/$order",
14199                },
14200                "store",
14201            ),
14202        ];
14203        for (variant, own_arm_label) in payload_variants {
14204            let own_arm_hit = match own_arm_label {
14205                "http" => variant.is_http(),
14206                "pubsub" => variant.is_pubsub(),
14207                "store" => variant.is_store(),
14208                other => panic!("unknown own-arm label {other:?}"),
14209            };
14210            let per_arm_results = [
14211                ("http_endpoint", variant.http_endpoint()),
14212                ("pubsub_subject", variant.pubsub_subject()),
14213                ("store_slot", variant.store_slot()),
14214            ];
14215            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
14216            assert_eq!(
14217                some_count, 1,
14218                "WitTarget::{variant:?} must land exactly one per-arm \
14219                 post-projection accessor's Some result — the trio \
14220                 (http_endpoint, pubsub_subject, store_slot) must \
14221                 partition the payload arm-set; got {per_arm_results:?}",
14222            );
14223            assert!(
14224                own_arm_hit,
14225                "WitTarget::{variant:?} own-arm gen-platform predicate \
14226                 must return true on its own arm — a partition failure \
14227                 upstream of this pin",
14228            );
14229            assert!(
14230                variant.payload().is_some(),
14231                "WitTarget::{variant:?} pan-arm payload() must return \
14232                 Some on every payload-carrying arm the trio partitions",
14233            );
14234        }
14235        // The payload-less Capability arm must return None on every
14236        // per-arm accessor — the partition's terminal-fallback shape.
14237        let cap = WitTarget::Capability;
14238        assert_eq!(cap.http_endpoint(), None);
14239        assert_eq!(cap.pubsub_subject(), None);
14240        assert_eq!(cap.store_slot(), None);
14241        assert_eq!(
14242            cap.payload(),
14243            None,
14244            "WitTarget::Capability pan-arm payload() must return None — \
14245             the trio's payload-less-arm coherence witness",
14246        );
14247    }
14248
14249    #[test]
14250    fn wit_target_field_names_are_pairwise_distinct() {
14251        // Distinctness pin: if any two of the three payload-field-name
14252        // scalars ever collapse (e.g. an accidental `endpoint` copy-
14253        // paste over the `subject` const), the [`WitContract::target`]
14254        // gate's diagnostic would point authors at the wrong field —
14255        // an "expected `:endpoint`" error on a pub-sub edge would
14256        // silently misroute the fix. Same cross-axis-distinctness
14257        // discipline as the peer M3 `:placement :estrategia` variant-
14258        // discriminator scalar-value pins (cc8f749) applied to the
14259        // payload-field-name axis.
14260        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
14261        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
14262        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
14263    }
14264
14265    #[test]
14266    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
14267        // Fail-before-pass-after pin: the graph-verb payload column's
14268        // per-arm `{field}={payload}` byte-string is derived through the
14269        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
14270        // payload-carrying arms, not through a hand-rolled per-arm match
14271        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
14272        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14273        // inline. A future variant addition — the M4-and-later per-edge
14274        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
14275        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
14276        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
14277        // and both [`WitTarget::label`] (duplicate-`:contratos`
14278        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
14279        // payload column) pick up the new arm from the same dispatch.
14280        // Prior to this lift the graph verb open-coded the 4-arm match
14281        // in caixa-feira, so a variant addition would have to be threaded
14282        // through both projections in lockstep or the graph verb would
14283        // silently drop the new arm to `(capability-only)`.
14284        for variant in [
14285            WitTarget::Http {
14286                endpoint: "/charge",
14287            },
14288            WitTarget::PubSub {
14289                subject: "events.checkout.paid",
14290            },
14291            WitTarget::Store {
14292                slot: "checkout/$order",
14293            },
14294        ] {
14295            let (field, payload) = variant
14296                .payload_pair()
14297                .expect("payload arm must expose (field, payload)");
14298            assert_eq!(
14299                variant.graph_label(),
14300                format!("{field}={payload}"),
14301                "WitTarget::{variant:?} graph_label must route the \
14302                 `{{field}}={{payload}}` template through payload_pair — \
14303                 a regression to a hand-rolled per-arm match at the graph \
14304                 verb would silently disagree with a future variant \
14305                 addition landed only at payload_pair"
14306            );
14307        }
14308    }
14309
14310    #[test]
14311    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
14312        // Fail-before-pass-after pin on the payload-less arm: the graph
14313        // verb's `(capability-only)` byte-string routes through the
14314        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
14315        // [`WitTarget::Capability`] arm, not through an inline
14316        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
14317        // per-`:contratos` payload column. Peer of the sibling
14318        // [`wit_target_label_pins_per_variant_format`] Capability-arm
14319        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
14320        // extended here onto the third payload-less-arm consumer axis
14321        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
14322        // axis and the wrong-target diagnostic axis).
14323        assert_eq!(
14324            WitTarget::Capability.graph_label(),
14325            WitTarget::CAPABILITY_GRAPH_LABEL,
14326        );
14327        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
14328    }
14329
14330    #[test]
14331    fn wit_target_capability_graph_label_distinct_from_capability_label() {
14332        // Cross-consumer-axis distinctness pin: the graph-verb
14333        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
14334        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
14335        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
14336        // payload)`) surface the payload-less arm on two distinct
14337        // consumer axes; a collapse (an accidental rebrand that lands
14338        // one spelling on both consts, a copy-paste that unifies them
14339        // "for consistency") would silently merge the two byte-strings
14340        // and lose the vocabulary distinction the graph verb's
14341        // compact-column form and the diagnostic's descriptive-clause
14342        // form each carry on purpose. Peer of the sibling 4-way
14343        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
14344        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
14345        // extended here onto the cross-consumer-axis distinctness of the
14346        // two payload-less-arm consts.
14347        assert_ne!(
14348            WitTarget::CAPABILITY_GRAPH_LABEL,
14349            WitTarget::CAPABILITY_LABEL,
14350            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
14351             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
14352             diagnostic) must remain distinct — a collapse would silently \
14353             merge two consumer axes onto one spelling"
14354        );
14355    }
14356
14357    #[test]
14358    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
14359        // 4-way distinctness pin extending the sibling
14360        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
14361        // (which covers only the HTTP / PubSub / Store payload arms)
14362        // onto the fourth scalar the shared
14363        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
14364        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
14365        // (`"none"`), the payload-less Capability-arm rejection scalar.
14366        //
14367        // All four [`WitTarget::HTTP_FIELD_NAME`] /
14368        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14369        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
14370        // dispatch surface [`WitContract::target`] writes onto the
14371        // `ContratoWrongTarget::expected` field — the same `&'static
14372        // str` axis authors read as "this WIT world's shape admits
14373        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
14374        // downstream consumers rely on: an `expected: "endpoint"`
14375        // diagnostic on a Capability-shaped edge tells the author to
14376        // add a `:endpoint "…"` slot to a WIT world that admits none,
14377        // silently misrouting the fix. Until this pin landed the three
14378        // payload-arm consts were distinctness-guarded by the sibling
14379        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
14380        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
14381        // author-facing vocabulary shift from `"none"` to `"endpoint"`
14382        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
14383        // into per-shape peers) would have silently landed one
14384        // Capability-arm rejection on a payload-arm's `expected:` byte-
14385        // string and desynchronized the diagnostic from the author's
14386        // typed shape.
14387        //
14388        // Same 4-way pairwise-distinctness pin discipline as the peer
14389        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
14390        // (cc8f749) applies on the sibling M3 closed-set typed-enum
14391        // scalar-value dispatch axis; extends the pin trajectory the
14392        // sibling `wit_target_field_names_are_pairwise_distinct`
14393        // 3-way pin opened to cover the last unguarded corner on the
14394        // `ContratoWrongTarget::expected` scalar-value axis.
14395        //
14396        // Fail-before-pass-after locally verified by mutating
14397        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
14398        // — this pin fires as expected; restoring passes.
14399        let all = [
14400            WitTarget::HTTP_FIELD_NAME,
14401            WitTarget::PUBSUB_FIELD_NAME,
14402            WitTarget::STORE_FIELD_NAME,
14403            WitTarget::CAPABILITY_EXPECTED,
14404        ];
14405        for (i, a) in all.iter().enumerate() {
14406            for (j, b) in all.iter().enumerate() {
14407                if i != j {
14408                    assert_ne!(
14409                        a, b,
14410                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
14411                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
14412                         pairwise distinct — got duplicate {a:?} at indices \
14413                         {i} and {j}; all four scalars thread through the \
14414                         shared `AplicacaoError::ContratoWrongTarget::expected` \
14415                         &'static str axis, so a collapse silently misdirects \
14416                         the diagnostic on which typed shape the WIT world admits",
14417                    );
14418                }
14419            }
14420        }
14421    }
14422
14423    #[test]
14424    fn wit_target_is_variant_predicates_partition_the_arm_set() {
14425        // Fail-before-pass-after pin on the
14426        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
14427        // each of the four variants exactly one of the generated
14428        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
14429        // predicates returns `true` and the other three return
14430        // `false`. Prior to this derive the only production
14431        // arm-discriminator on [`WitTarget`] — the sync-cycle
14432        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
14433        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
14434        // the variant that expressed no compile-time link back to
14435        // the closed-set typed dispatch a future fifth
14436        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
14437        // split of [`WitTarget::PubSub`] into shape-specific peers,
14438        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
14439        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
14440        // to thread through in lockstep or the DFS exclusion would
14441        // silently disagree with the peer diagnostic templates on
14442        // which arms carry sync-versus-async semantics. Peer of the
14443        // sibling [`crate::CaixaKind`] (f5bba80),
14444        // [`PlacementStrategy`] (766ec63),
14445        // [`crate::supervisor::RestartStrategy`],
14446        // [`crate::supervisor::RestartPolicy`], and
14447        // [`crate::upgrade::UpgradeInstruction`] (915a934)
14448        // `IsVariant` derives on the sibling closed-set typed-enum
14449        // discriminator axes — extends the same one-typed-dispatch-
14450        // per-variant discipline onto the last unlifted closed-set
14451        // typed-enum discriminator on the caixa surface (the M3
14452        // mesh-slot per-`:contratos` target-arm axis), closing the
14453        // arm-discriminator convergence trajectory across every
14454        // closed-set typed enum in caixa-core.
14455        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
14456            (
14457                WitTarget::Http { endpoint: "/x" },
14458                [true, false, false, false],
14459            ),
14460            (
14461                WitTarget::PubSub {
14462                    subject: "events.x",
14463                },
14464                [false, true, false, false],
14465            ),
14466            (
14467                WitTarget::Store { slot: "kv/x" },
14468                [false, false, true, false],
14469            ),
14470            (WitTarget::Capability, [false, false, false, true]),
14471        ];
14472        for (variant, expected) in rows {
14473            let observed = [
14474                variant.is_http(),
14475                variant.is_pubsub(),
14476                variant.is_store(),
14477                variant.is_capability(),
14478            ];
14479            assert_eq!(
14480                observed, expected,
14481                "WitTarget::{variant:?} is_* predicates must partition \
14482                 the arm set (http, pubsub, store, capability); got {observed:?}"
14483            );
14484        }
14485    }
14486
14487    #[test]
14488    fn wit_target_is_variant_predicates_are_const_fn() {
14489        // The [`gen_platform::IsVariant`] derive emits `const fn`
14490        // predicates on the peer [`crate::CaixaKind`] +
14491        // [`crate::upgrade::UpgradeInstruction`] +
14492        // [`crate::supervisor::RestartStrategy`] +
14493        // [`crate::supervisor::RestartPolicy`] +
14494        // [`PlacementStrategy`] closed-set typed enums — pin the
14495        // same posture on [`WitTarget`] so a future accidental
14496        // downgrade to non-`const` (an added runtime helper reachable
14497        // only from a non-`const` context, a manual hand-rolled
14498        // `impl` that shadows the derive-generated method) trips at
14499        // caixa-core build time rather than surfacing as a downstream
14500        // `const`-context regression far from the derive declaration.
14501        //
14502        // Unlike the peer unit-variant enums (`CaixaKind` /
14503        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
14504        // whose `const` constructors need no arguments, the three
14505        // payload-carrying [`WitTarget`] arms are const-constructed
14506        // through `&'static str` payloads — the same `'static`
14507        // lifetime the closed-set typed enum's four-arm partition
14508        // pin above already threads through.
14509        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
14510        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
14511        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
14512        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
14513        const IS_HTTP: bool = HTTP.is_http();
14514        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
14515        const IS_STORE: bool = STORE.is_store();
14516        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
14517        assert!(IS_HTTP);
14518        assert!(IS_PUBSUB);
14519        assert!(IS_STORE);
14520        assert!(IS_CAPABILITY);
14521    }
14522
14523    #[test]
14524    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
14525        // Consumer-side pin on the sole production converge site:
14526        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
14527        // edges from the synchronous-subgraph DFS via the lifted
14528        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
14529        // predicate (rebound from the prior raw
14530        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
14531        // variant). Byte-equivalent today (`is_pubsub` is the
14532        // derive-generated `matches!(self, Self::PubSub { .. })` by
14533        // construction, the `#[is_variant(name = "pubsub")]` override
14534        // aliasing the auto-derived `is_pub_sub` back to the sibling
14535        // [`WitContract::is_pubsub`] name); pin the behavior so a
14536        // future accidental drift (a rebind onto a peer arm
14537        // predicate, a manual hand-rolled `impl` that shadows the
14538        // derive-generated method with different semantics, a peer
14539        // arm rename that shifts which variant carries sync-versus-
14540        // async semantics) trips at caixa-core test time rather than
14541        // at some downstream operator's runtime dispatch far from the
14542        // rebind commit.
14543        //
14544        // The fixture constructs a two-Servico Aplicacao with one
14545        // pub-sub edge that would close a sync-cycle if the DFS did
14546        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
14547        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
14548        // edge, which is not a cycle. A regression in the converge
14549        // (a rebind that reads the pub-sub arm as sync) would report
14550        // `AplicacaoError::ContratoCycle`.
14551        let s = AplicacaoSpec {
14552            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
14553            contratos: vec![
14554                // Pub-sub edge: DFS must skip via is_pubsub().
14555                WitContract {
14556                    de: "a".into(),
14557                    para: "b".into(),
14558                    wit: "nats:pub-sub".into(),
14559                    endpoint: None,
14560                    subject: Some("events.x".into()),
14561                    slot: None,
14562                },
14563                // HTTP edge: DFS must include.
14564                WitContract {
14565                    de: "b".into(),
14566                    para: "a".into(),
14567                    wit: "wasi:http/proxy".into(),
14568                    endpoint: Some("/x".into()),
14569                    subject: None,
14570                    slot: None,
14571                },
14572            ],
14573            politicas: MeshPolicy::default(),
14574            placement: Placement {
14575                estrategia: PlacementStrategy::Replicated,
14576                clusters: vec!["rio".into()],
14577                affinity: None,
14578                shard_key: None,
14579            },
14580            entrada: None,
14581        };
14582        s.validate()
14583            .expect("pub-sub edge must be excluded from sync-cycle DFS");
14584    }
14585
14586    #[test]
14587    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
14588        // Consumer-side pin: the same three peer consts thread through
14589        // both the [`WitTarget::label`] template (leading-`:` keyword
14590        // prefix in the duplicate-`:contratos` diagnostic) and the
14591        // [`WitContract::target`] gate's [`AplicacaoError::
14592        // ContratoMissingTarget`] `expected:` scalar (the field the
14593        // author needs to add). Pin both routes at once so a future
14594        // refactor can't accidentally split them onto separate string
14595        // literals — the "one place, everywhere reaches for it"
14596        // invariant the peer const set carries.
14597        let http_label = WitTarget::Http { endpoint: "/x" }.label();
14598        assert!(
14599            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
14600            "label must lead with :{} keyword (got {http_label:?})",
14601            WitTarget::HTTP_FIELD_NAME,
14602        );
14603
14604        let mut s = three_member_spec();
14605        s.contratos.push(WitContract {
14606            de: "cart".into(),
14607            para: "catalog".into(),
14608            wit: "kafka:topic".into(),
14609            endpoint: None,
14610            subject: None,
14611            slot: None,
14612        });
14613        match s.validate().unwrap_err() {
14614            AplicacaoError::ContratoMissingTarget { expected, .. } => {
14615                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
14616            }
14617            other => panic!("expected ContratoMissingTarget, got {other:?}"),
14618        }
14619    }
14620
14621    #[test]
14622    fn duplicate_pubsub_diagnostic_names_offending_subject() {
14623        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
14624        // on the pub-sub target axis: the duplicate-edge diagnostic
14625        // must name the `:subject` payload verbatim (not just the
14626        // `(de, para, wit)` triple). Prior to lifting the label onto
14627        // [`WitTarget::label`] the diagnostic derived the label from
14628        // raw [`WitContract`] `Option<String>` probes — a future
14629        // `WitTarget` variant addition (M4 per-edge WIT registry)
14630        // would silently fall through to the `Capability` "no
14631        // payload" default without a compiler warning. Pinning the
14632        // pub-sub arm's format closes the second of three
14633        // payload-carrying `WitTarget` arms this diagnostic threads
14634        // through.
14635        let mut s = three_member_spec();
14636        let pubsub = WitContract {
14637            de: "payment".into(),
14638            para: "cart".into(),
14639            wit: "nats:pub-sub".into(),
14640            endpoint: None,
14641            subject: Some("events.checkout.paid".into()),
14642            slot: None,
14643        };
14644        s.contratos.push(pubsub.clone());
14645        s.contratos.push(pubsub);
14646        let err = s.validate().unwrap_err();
14647        let msg = format!("{err}");
14648        assert!(
14649            msg.contains(":subject \"events.checkout.paid\""),
14650            "duplicate-pubsub diagnostic must name the offending \
14651             :subject payload (got: {msg:?})"
14652        );
14653    }
14654
14655    #[test]
14656    fn duplicate_store_diagnostic_names_offending_slot() {
14657        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
14658        // key-value target axis: the diagnostic must name the `:slot`
14659        // payload verbatim. Third of three payload-carrying
14660        // `WitTarget` arms this diagnostic threads through, closing
14661        // the per-arm label pin trilogy (`Http` — 6841,
14662        // `PubSub` + `Store` — this test + peer above).
14663        let mut s = three_member_spec();
14664        let store = WitContract {
14665            de: "cart".into(),
14666            para: "payment".into(),
14667            wit: "wasi:keyvalue/store".into(),
14668            endpoint: None,
14669            subject: None,
14670            slot: Some("checkout/$orderId".into()),
14671        };
14672        s.contratos
14673            .retain(|c| !(c.de == "cart" && c.para == "payment"));
14674        s.contratos.push(store.clone());
14675        s.contratos.push(store);
14676        let err = s.validate().unwrap_err();
14677        let msg = format!("{err}");
14678        assert!(
14679            msg.contains(":slot \"checkout/$orderId\""),
14680            "duplicate-store diagnostic must name the offending :slot \
14681             payload (got: {msg:?})"
14682        );
14683    }
14684
14685    #[test]
14686    fn rejects_entrada_path_without_leading_slash() {
14687        let mut s = three_member_spec();
14688        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
14689        let err = s.validate().unwrap_err();
14690        assert!(
14691            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
14692            "got {err:?}"
14693        );
14694    }
14695
14696    #[test]
14697    fn rejects_empty_entrada_path() {
14698        let mut s = three_member_spec();
14699        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
14700        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14701    }
14702
14703    #[test]
14704    fn rejects_duplicate_entrada_paths() {
14705        let mut s = three_member_spec();
14706        s.entrada.as_mut().unwrap().paths = vec![
14707            "/api/cart".into(),
14708            "/api/products".into(),
14709            "/api/cart".into(),
14710        ];
14711        let err = s.validate().unwrap_err();
14712        assert!(
14713            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
14714            "got {err:?}"
14715        );
14716    }
14717
14718    #[test]
14719    fn rejects_zero_entrada_port() {
14720        let mut s = three_member_spec();
14721        s.entrada.as_mut().unwrap().port = 0;
14722        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
14723    }
14724
14725    // ── :entrada :paths value-shape gate ─────────────────────────────
14726    //
14727    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
14728    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
14729    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
14730    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
14731    // time now becomes a caixa-build-time `EntradaPathInvalid` with
14732    // the offending `:paths` entry named verbatim.
14733
14734    #[test]
14735    fn rejects_entrada_path_with_query() {
14736        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
14737        // silently passed validate and the Gateway API webhook
14738        // rejected it at apply time with no source citation.
14739        let mut s = three_member_spec();
14740        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
14741        let err = s.validate().unwrap_err();
14742        assert!(
14743            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14744                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
14745            "got {err:?}"
14746        );
14747    }
14748
14749    #[test]
14750    fn rejects_entrada_path_with_fragment() {
14751        let mut s = three_member_spec();
14752        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
14753        let err = s.validate().unwrap_err();
14754        assert!(
14755            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14756                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
14757            "got {err:?}"
14758        );
14759    }
14760
14761    #[test]
14762    fn rejects_entrada_path_with_space() {
14763        let mut s = three_member_spec();
14764        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
14765        let err = s.validate().unwrap_err();
14766        assert!(
14767            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14768                if path == "/api/my cart" && reason.contains("whitespace")),
14769            "got {err:?}"
14770        );
14771    }
14772
14773    #[test]
14774    fn rejects_entrada_path_with_tab() {
14775        let mut s = three_member_spec();
14776        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
14777        let err = s.validate().unwrap_err();
14778        assert!(
14779            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14780                if path == "/api/\tcart" && reason.contains("whitespace")),
14781            "got {err:?}"
14782        );
14783    }
14784
14785    #[test]
14786    fn rejects_entrada_path_with_control_char() {
14787        // 0x01 (SOH) — a non-whitespace control char surfaces the
14788        // distinct "control character" reason arm, separate from
14789        // the whitespace arm. Pinned so a future refactor that
14790        // collapses the two arms can't accidentally drop the more
14791        // self-locating diagnostic.
14792        let mut s = three_member_spec();
14793        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
14794        let err = s.validate().unwrap_err();
14795        assert!(
14796            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14797                if path == "/api/\x01cart" && reason.contains("control character")),
14798            "got {err:?}"
14799        );
14800    }
14801
14802    #[test]
14803    fn rejects_entrada_path_with_non_ascii() {
14804        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
14805        // unreserved-set rule rejects. The Gateway API webhook
14806        // rejects literal non-ASCII bytes; percent-encoding is the
14807        // only way to author non-ASCII in a path.
14808        let mut s = three_member_spec();
14809        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
14810        let err = s.validate().unwrap_err();
14811        assert!(
14812            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14813                if path == "/api/café" && reason.contains("non-ASCII")),
14814            "got {err:?}"
14815        );
14816    }
14817
14818    #[test]
14819    fn rejects_entrada_path_with_consecutive_slashes() {
14820        let mut s = three_member_spec();
14821        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
14822        let err = s.validate().unwrap_err();
14823        assert!(
14824            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14825                if path == "/api//cart" && reason.contains("consecutive `/`")),
14826            "got {err:?}"
14827        );
14828    }
14829
14830    #[test]
14831    fn rejects_entrada_path_with_dot_segment() {
14832        let mut s = three_member_spec();
14833        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
14834        let err = s.validate().unwrap_err();
14835        assert!(
14836            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14837                if path == "/api/./cart" && reason.contains("`.` segment")),
14838            "got {err:?}"
14839        );
14840    }
14841
14842    #[test]
14843    fn rejects_entrada_path_with_trailing_dot_segment() {
14844        // The bare `/.` and the trailing `/foo/.` are both rejected
14845        // by the Gateway API webhook; pinned separately so a future
14846        // narrowing that catches only the inner form surfaces here.
14847        let mut s = three_member_spec();
14848        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
14849        let err = s.validate().unwrap_err();
14850        assert!(
14851            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14852                if path == "/api/." && reason.contains("`.` segment")),
14853            "got {err:?}"
14854        );
14855    }
14856
14857    #[test]
14858    fn rejects_entrada_path_with_parent_segment() {
14859        let mut s = three_member_spec();
14860        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
14861        let err = s.validate().unwrap_err();
14862        assert!(
14863            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14864                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
14865            "got {err:?}"
14866        );
14867    }
14868
14869    #[test]
14870    fn rejects_entrada_path_with_trailing_parent_segment() {
14871        // Trailing `/..` — symmetric arm of the parent-segment rule,
14872        // pinned separately so a future relaxation that only checks
14873        // the inner form (`/../`) surfaces here.
14874        let mut s = three_member_spec();
14875        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
14876        let err = s.validate().unwrap_err();
14877        assert!(
14878            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14879                if path == "/api/.." && reason.contains("`..` parent-segment")),
14880            "got {err:?}"
14881        );
14882    }
14883
14884    #[test]
14885    fn rejects_entrada_path_too_long() {
14886        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
14887        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
14888        // ASCII-alphanumeric body so only the length rule fires.
14889        let mut s = three_member_spec();
14890        let big = format!("/api/{}", "a".repeat(1020));
14891        assert_eq!(big.len(), 1025);
14892        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
14893        let err = s.validate().unwrap_err();
14894        assert!(
14895            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14896                if path == &big && reason.contains("max length of 1024")),
14897            "got {err:?}"
14898        );
14899    }
14900
14901    #[test]
14902    fn entrada_path_max_length_validates() {
14903        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
14904        // maxLength cap. Boundary pin: drift in the cap surfaces here
14905        // and at `rejects_entrada_path_too_long` simultaneously.
14906        let mut s = three_member_spec();
14907        let big = format!("/api/{}", "a".repeat(1019));
14908        assert_eq!(big.len(), 1024);
14909        s.entrada.as_mut().unwrap().paths = vec![big];
14910        s.validate().unwrap();
14911    }
14912
14913    #[test]
14914    fn entrada_accepts_canonical_paths() {
14915        // Positive-control sweep — every form the Gateway API
14916        // apiserver accepts must round-trip through validate. Covers
14917        // the root catch-all, plain paths, dot-prefixed segments
14918        // (hidden-file-style, distinct from `.` and `..` segments
14919        // which are rejected), digit-bearing segments, the canonical
14920        // route-template `:param` form (`:` is RFC 3986 reserved-set
14921        // valid in paths), trailing-slash form, percent-encoded
14922        // segments, and an interior `..` *substring* (`/foo..bar` is
14923        // not the `..` segment and is allowed).
14924        for path in [
14925            "/",
14926            "/api/cart",
14927            "/healthz",
14928            "/api/.config",
14929            "/v1/products",
14930            "/products/:id",
14931            "/api/cart/",
14932            "/api/caf%C3%A9",
14933            "/foo..bar",
14934            "/...",
14935        ] {
14936            let mut s = three_member_spec();
14937            s.entrada.as_mut().unwrap().paths = vec![path.into()];
14938            s.validate()
14939                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
14940        }
14941    }
14942
14943    #[test]
14944    fn entrada_path_empty_takes_precedence_over_invalid() {
14945        // Ordering pin: `EntradaPathEmpty` is the more self-locating
14946        // diagnostic on `""` and must lead — `validate_entrada_path`
14947        // is only reached after the empty-check fires at the call
14948        // site. (The predicate itself defends against direct
14949        // invocation by returning the same error on `""`.)
14950        let mut s = three_member_spec();
14951        s.entrada.as_mut().unwrap().paths = vec!["".into()];
14952        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14953    }
14954
14955    #[test]
14956    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
14957        // Ordering pin: a path without a leading `/` surfaces the
14958        // narrower `EntradaPathNotAbsolute` diagnostic first; the
14959        // value-shape gate is only consulted on paths that already
14960        // satisfy the absolute-prefix invariant.
14961        let mut s = three_member_spec();
14962        // `bad path` would fire the whitespace rule under the
14963        // value-shape gate, but missing-leading-`/` is the more
14964        // self-locating diagnostic.
14965        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
14966        let err = s.validate().unwrap_err();
14967        assert!(
14968            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
14969            "got {err:?}"
14970        );
14971    }
14972
14973    #[test]
14974    fn entrada_path_invalid_fires_before_duplicate_check() {
14975        // Ordering pin: a malformed path on the *first* entry of a
14976        // would-be duplicate pair fires the value-shape gate before
14977        // the duplicate gate, mirroring the
14978        // `placement_cluster_invalid_fires_before_duplicate_check`
14979        // (6cbb900) pattern on the peer axis.
14980        let mut s = three_member_spec();
14981        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
14982        let err = s.validate().unwrap_err();
14983        assert!(
14984            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
14985            "got {err:?}"
14986        );
14987    }
14988
14989    #[test]
14990    fn entrada_path_diagnostic_carries_offending_path() {
14991        // Diagnostic-shape pin — the offending path + a non-empty
14992        // reason flow through verbatim so the author can grep their
14993        // caixa.lisp for `:paths` and fix it in one edit. Same shape
14994        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
14995        let mut s = three_member_spec();
14996        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
14997        let err = s.validate().unwrap_err();
14998        match err {
14999            AplicacaoError::EntradaPathInvalid { path, reason } => {
15000                assert_eq!(path, "/api?q=1");
15001                assert!(!reason.is_empty(), "reason field must be non-empty");
15002            }
15003            other => panic!("expected EntradaPathInvalid, got {other:?}"),
15004        }
15005    }
15006
15007    #[test]
15008    fn rejects_entrada_path_with_curly_brace_template_form() {
15009        // Per-axis pin on the shared `is_gateway_api_http_path`
15010        // reserved-byte arm: the canonical "I wrote an OpenAPI
15011        // path-template `{id}` instead of the Gateway API `:id` form"
15012        // footgun the K8s apiserver would otherwise catch at admission
15013        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
15014        // landing site, far from the caixa.lisp. Surfaces as
15015        // `EntradaPathInvalid` carrying the offending path verbatim
15016        // plus the canonical `%7B`/`%7D` percent-encoding remediation
15017        // — the substrate-side `gateway_api_http_path_rejects_every_
15018        // reserved_printable_ascii_byte` predicate-level sweep pins the
15019        // full eleven-byte set; this per-axis pin confirms the
15020        // diagnostic flows through to the `EntradaPathInvalid` variant.
15021        let mut s = three_member_spec();
15022        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
15023        let err = s.validate().unwrap_err();
15024        assert!(
15025            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15026                if path == "/api/cart/{id}"
15027                    && reason.contains("reserved character")
15028                    && reason.contains("'{'")
15029                    && reason.contains("%7B")),
15030            "got {err:?}"
15031        );
15032    }
15033
15034    #[test]
15035    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
15036        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
15037        // template_form` on the sibling `:contratos :endpoint` axis.
15038        // Same shared `is_gateway_api_http_path` reserved-byte arm
15039        // fires through `ContratoEndpointInvalid`, with the offending
15040        // endpoint + `:de` + `:para` + reason flowing through verbatim.
15041        // Pins that the lifted predicate's tightening lands on both
15042        // caller axes simultaneously — one source of truth for the
15043        // Gateway API HTTPPathMatch.value accepted set.
15044        let err = contrato_endpoint_err("/api/cart/{id}");
15045        assert!(
15046            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15047                if endpoint == "/api/cart/{id}"
15048                    && reason.contains("reserved character")
15049                    && reason.contains("'{'")
15050                    && reason.contains("%7B")),
15051            "got {err:?}"
15052        );
15053    }
15054
15055    // ── :entrada :host value-shape gate ──────────────────────────────
15056    //
15057    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
15058    // the sibling `:host` axis. Every authoring footgun the K8s
15059    // Gateway API v1 apiserver would catch at admission time becomes
15060    // a caixa-build-time `EntradaHostInvalid` with the offending
15061    // `:host` named verbatim. Same diagnostic shape as
15062    // `MembroVersaoInvalid` (9888b13).
15063
15064    #[test]
15065    fn rejects_entrada_host_with_scheme() {
15066        // Fail-before-pass-after pin — pre-gate codebases silently
15067        // accepted `https://…` and the apiserver rejected it at apply
15068        // time with no source citation.
15069        let mut s = three_member_spec();
15070        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
15071        let err = s.validate().unwrap_err();
15072        assert!(
15073            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15074                if host == "https://checkout.quero.cloud"),
15075            "got {err:?}"
15076        );
15077    }
15078
15079    #[test]
15080    fn rejects_entrada_host_with_port() {
15081        // The `:8080` port suffix is the canonical "I forgot the port
15082        // belongs in `:entrada :port`" footgun. The top-level `:` arm
15083        // (introduced after the per-label loop-only impl silently
15084        // surfaced a deep "label \"cloud:8080\" contains invalid
15085        // character ':'" leak) names the canonical fix verbatim — the
15086        // `:entrada :port` slot.
15087        let mut s = three_member_spec();
15088        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
15089        let err = s.validate().unwrap_err();
15090        assert!(
15091            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15092                if host == "checkout.quero.cloud:8080"
15093                && reason.contains(":entrada :port")),
15094            "got {err:?}"
15095        );
15096    }
15097
15098    #[test]
15099    fn rejects_entrada_host_with_trailing_colon() {
15100        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
15101        // edit) — the per-label loop would land it as a deep
15102        // "label \"com:\" must start and end with an alphanumeric"
15103        // / "contains invalid character ':'" leak. The top-level
15104        // `:` arm pre-empts with the canonical `:port` slot
15105        // diagnostic.
15106        let mut s = three_member_spec();
15107        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
15108        let err = s.validate().unwrap_err();
15109        assert!(
15110            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15111                if host == "checkout.quero.cloud:"
15112                && reason.contains(":entrada :port")),
15113            "got {err:?}"
15114        );
15115    }
15116
15117    #[test]
15118    fn rejects_entrada_host_unbracketed_ipv6_literal() {
15119        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
15120        // literals across the board (peer with `rejects_entrada_host_
15121        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
15122        // Before this top-level `:` arm landed the per-label loop
15123        // surfaced a single-label byte-class diagnostic that named the
15124        // `:` byte but not the IP-literal prohibition. The top-level
15125        // `:` arm names both the `:port` slot and the IP-literal
15126        // prohibition verbatim, so an author whose `:host "2001:..."`
15127        // value lands here gets a self-locating fix either way.
15128        let mut s = three_member_spec();
15129        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
15130        let err = s.validate().unwrap_err();
15131        assert!(
15132            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15133                if host == "2001:db8::1"
15134                && reason.contains("IPv6")),
15135            "got {err:?}"
15136        );
15137    }
15138
15139    #[test]
15140    fn rejects_entrada_host_wildcard_with_port() {
15141        // Wildcard host with port suffix — the `*.` strip and the
15142        // per-label loop on `["foo", "quero", "cloud:8080"]` would
15143        // surface the deep byte-class leak. The top-level `:` arm sits
15144        // upstream of the `*.` strip, so it names the canonical `:port`
15145        // fix verbatim regardless of whether the host is wildcard-led.
15146        let mut s = three_member_spec();
15147        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
15148        let err = s.validate().unwrap_err();
15149        assert!(
15150            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15151                if host == "*.quero.cloud:8080"
15152                && reason.contains(":entrada :port")),
15153            "got {err:?}"
15154        );
15155    }
15156
15157    #[test]
15158    fn rejects_entrada_host_with_path() {
15159        let mut s = three_member_spec();
15160        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
15161        let err = s.validate().unwrap_err();
15162        assert!(
15163            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15164                if host == "checkout.quero.cloud/api"),
15165            "got {err:?}"
15166        );
15167    }
15168
15169    #[test]
15170    fn rejects_entrada_host_with_uppercase() {
15171        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
15172        // rejected, not silently lower-cased.
15173        let mut s = three_member_spec();
15174        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
15175        let err = s.validate().unwrap_err();
15176        assert!(
15177            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15178                if reason.contains("uppercase")),
15179            "got {err:?}"
15180        );
15181    }
15182
15183    #[test]
15184    fn rejects_entrada_host_with_underscore() {
15185        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
15186        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
15187        let mut s = three_member_spec();
15188        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
15189        let err = s.validate().unwrap_err();
15190        assert!(
15191            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15192                if reason.contains('_')),
15193            "got {err:?}"
15194        );
15195    }
15196
15197    #[test]
15198    fn rejects_entrada_host_ipv4_literal() {
15199        // Gateway API v1 explicitly forbids IP literals as Hostnames.
15200        let mut s = three_member_spec();
15201        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
15202        let err = s.validate().unwrap_err();
15203        assert!(
15204            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15205                if reason.contains("IPv4")),
15206            "got {err:?}"
15207        );
15208    }
15209
15210    #[test]
15211    fn rejects_entrada_host_with_trailing_dot() {
15212        // The Gateway API regex anchors at end-of-string with no
15213        // trailing `.` allowance — the FQDN root-dot form is rejected.
15214        let mut s = three_member_spec();
15215        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
15216        let err = s.validate().unwrap_err();
15217        assert!(
15218            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15219                if host == "checkout.quero.cloud."),
15220            "got {err:?}"
15221        );
15222    }
15223
15224    #[test]
15225    fn rejects_entrada_host_with_leading_dot() {
15226        let mut s = three_member_spec();
15227        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
15228        let err = s.validate().unwrap_err();
15229        assert!(
15230            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15231                if reason.contains("empty label")),
15232            "got {err:?}"
15233        );
15234    }
15235
15236    #[test]
15237    fn rejects_entrada_host_with_consecutive_dots() {
15238        let mut s = three_member_spec();
15239        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
15240        let err = s.validate().unwrap_err();
15241        assert!(
15242            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15243                if reason.contains("empty label")),
15244            "got {err:?}"
15245        );
15246    }
15247
15248    #[test]
15249    fn rejects_entrada_host_with_leading_hyphen_label() {
15250        let mut s = three_member_spec();
15251        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
15252        let err = s.validate().unwrap_err();
15253        assert!(
15254            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15255                if reason.contains("alphanumeric")),
15256            "got {err:?}"
15257        );
15258    }
15259
15260    #[test]
15261    fn rejects_entrada_host_with_trailing_hyphen_label() {
15262        let mut s = three_member_spec();
15263        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
15264        let err = s.validate().unwrap_err();
15265        assert!(
15266            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15267                if reason.contains("alphanumeric")),
15268            "got {err:?}"
15269        );
15270    }
15271
15272    #[test]
15273    fn rejects_entrada_host_with_inner_wildcard() {
15274        // Gateway API allows `*` only as the first label (`*.foo`);
15275        // any inner or trailing `*` is rejected.
15276        let mut s = three_member_spec();
15277        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
15278        let err = s.validate().unwrap_err();
15279        assert!(
15280            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15281                if reason.contains("wildcard")),
15282            "got {err:?}"
15283        );
15284    }
15285
15286    #[test]
15287    fn rejects_entrada_host_bare_wildcard() {
15288        // `*.` with no domain is meaningless; Gateway API rejects it.
15289        let mut s = three_member_spec();
15290        s.entrada.as_mut().unwrap().host = "*.".into();
15291        let err = s.validate().unwrap_err();
15292        assert!(
15293            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15294                if reason.contains("wildcard")),
15295            "got {err:?}"
15296        );
15297    }
15298
15299    #[test]
15300    fn rejects_entrada_host_with_whitespace() {
15301        let mut s = three_member_spec();
15302        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15303        let err = s.validate().unwrap_err();
15304        assert!(
15305            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15306                if reason.contains("whitespace")),
15307            "got {err:?}"
15308        );
15309    }
15310
15311    #[test]
15312    fn rejects_entrada_host_space_names_offending_byte() {
15313        // Embedded space in the `:entrada :host` axis surfaces the
15314        // byte-naming diagnostic through the lifted
15315        // `find_ascii_whitespace_byte` predicate. Peer with the
15316        // sibling `parse_rejects_leading_whitespace` pins on
15317        // `supervisor::duration_codec` (a7ae622) — same "the
15318        // diagnostic carries the offending byte's `0x{b:02x}` shape"
15319        // discipline extended from the shared duration codec to the
15320        // Gateway API v1 Hostname axis.
15321        let mut s = three_member_spec();
15322        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15323        let err = s.validate().unwrap_err();
15324        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15325            panic!("expected EntradaHostInvalid, got {err:?}");
15326        };
15327        assert!(
15328            reason.contains("ASCII whitespace byte"),
15329            "expected byte-naming diagnostic, got {reason:?}"
15330        );
15331        assert!(
15332            reason.contains("0x20"),
15333            "expected offending space byte 0x20, got {reason:?}"
15334        );
15335    }
15336
15337    #[test]
15338    fn rejects_entrada_host_tab_names_offending_byte() {
15339        // Embedded tab byte in the `:entrada :host` axis — the
15340        // canonical paste-from-YAML-block-scalar / paste-from-
15341        // indented-doc footgun. Pins that the lifted predicate covers
15342        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
15343        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
15344        // not just the leading-space case the pre-lift `.bytes().any`
15345        // arm's opaque "must not contain whitespace" reason already
15346        // covered. Peer with `parse_rejects_tab_byte` on
15347        // `supervisor::duration_codec` (a7ae622).
15348        let mut s = three_member_spec();
15349        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
15350        let err = s.validate().unwrap_err();
15351        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15352            panic!("expected EntradaHostInvalid, got {err:?}");
15353        };
15354        assert!(
15355            reason.contains("ASCII whitespace byte"),
15356            "expected byte-naming diagnostic, got {reason:?}"
15357        );
15358        assert!(
15359            reason.contains("0x09"),
15360            "expected offending tab byte 0x09, got {reason:?}"
15361        );
15362    }
15363
15364    #[test]
15365    fn rejects_entrada_host_lf_names_offending_byte() {
15366        // Embedded LF byte in the `:entrada :host` axis — the
15367        // canonical paste-from-shell-heredoc / paste-from-multiline-
15368        // doc footgun the caixa-mesh YAML emitter would silently
15369        // reinterpret at the Gateway API v1 HTTPRoute admission
15370        // layer (an embedded LF byte in a YAML plain scalar either
15371        // truncates the value at the emitter or crashes the parser
15372        // on the k8s-apiserver side). Pins the third representative
15373        // of the full ASCII-whitespace set through the shared
15374        // predicate.
15375        let mut s = three_member_spec();
15376        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
15377        let err = s.validate().unwrap_err();
15378        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15379            panic!("expected EntradaHostInvalid, got {err:?}");
15380        };
15381        assert!(
15382            reason.contains("ASCII whitespace byte"),
15383            "expected byte-naming diagnostic, got {reason:?}"
15384        );
15385        assert!(
15386            reason.contains("0x0a"),
15387            "expected offending LF byte 0x0a, got {reason:?}"
15388        );
15389    }
15390
15391    #[test]
15392    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
15393        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
15394        // axis — the canonical paste-from-typography /
15395        // paste-from-word-processor footgun. Before the non-ASCII
15396        // Unicode `White_Space` scan lifted through the shared
15397        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
15398        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
15399        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
15400        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
15401        // with the far-from-source `label "…" must start and end
15402        // with an alphanumeric` diagnostic — burying the
15403        // paste-from-typography origin under a label-shape leak.
15404        // Peer with the sibling non-ASCII-whitespace pins at
15405        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
15406        // — 1b75b38), `limits::parse_duration`,
15407        // `limits::parse_millicores`, and the shared duration codec
15408        // — same "the diagnostic carries the offending Unicode
15409        // codepoint's `U+XXXX` shape" discipline extended from every
15410        // typed-magnitude codec to the Gateway API v1 Hostname axis.
15411        let mut s = three_member_spec();
15412        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
15413        let err = s.validate().unwrap_err();
15414        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15415            panic!("expected EntradaHostInvalid, got {err:?}");
15416        };
15417        assert!(
15418            reason.contains("non-ASCII Unicode whitespace character"),
15419            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15420        );
15421        assert!(
15422            reason.contains("U+00A0"),
15423            "expected offending NBSP codepoint U+00A0, got {reason:?}"
15424        );
15425    }
15426
15427    #[test]
15428    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
15429        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
15430        // `:entrada :host` axis — the canonical paste-from-web-doc /
15431        // paste-from-published-HTML footgun. `char::is_whitespace`
15432        // returns true for `U+2028` per the Unicode `White_Space`
15433        // property, so `str::trim` at any downstream site would
15434        // silently strip it — same drift class as NBSP but on a
15435        // different codepoint region. Pins the second representative
15436        // (non-Latin-1 `char::is_whitespace` member) through the
15437        // shared predicate. Peer with
15438        // `parse_byte_size_rejects_internal_line_separator` on
15439        // `limits::parse_byte_size` (1b75b38).
15440        let mut s = three_member_spec();
15441        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
15442        let err = s.validate().unwrap_err();
15443        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15444            panic!("expected EntradaHostInvalid, got {err:?}");
15445        };
15446        assert!(
15447            reason.contains("non-ASCII Unicode whitespace character"),
15448            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15449        );
15450        assert!(
15451            reason.contains("U+2028"),
15452            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
15453        );
15454    }
15455
15456    #[test]
15457    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
15458        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
15459        // labels in the `:entrada :host` axis — the canonical
15460        // paste-from-CJK-typography footgun (CJK IMEs default to
15461        // full-width whitespace when the space bar is pressed in
15462        // Japanese / Chinese input modes). Pins the third
15463        // representative of the non-ASCII Unicode `White_Space` set
15464        // through the shared predicate: the CJK block, distinct from
15465        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
15466        // SEPARATOR `U+2028` — covering the same axis breadth the
15467        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
15468        // (1b75b38) pins on `limits::parse_byte_size`.
15469        let mut s = three_member_spec();
15470        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
15471        let err = s.validate().unwrap_err();
15472        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15473            panic!("expected EntradaHostInvalid, got {err:?}");
15474        };
15475        assert!(
15476            reason.contains("non-ASCII Unicode whitespace character"),
15477            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15478        );
15479        assert!(
15480            reason.contains("U+3000"),
15481            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
15482        );
15483    }
15484
15485    #[test]
15486    fn rejects_entrada_host_too_long() {
15487        // Total length cap = 253; build a 254-byte host out of two
15488        // 63-byte labels + one 62-byte label + dots.
15489        let mut s = three_member_spec();
15490        let big = format!(
15491            "{}.{}.{}.{}",
15492            "a".repeat(63),
15493            "b".repeat(63),
15494            "c".repeat(63),
15495            "d".repeat(254 - 63 * 3 - 3)
15496        );
15497        assert_eq!(big.len(), 254);
15498        s.entrada.as_mut().unwrap().host = big;
15499        let err = s.validate().unwrap_err();
15500        assert!(
15501            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15502                if reason.contains("max length of 253")),
15503            "got {err:?}"
15504        );
15505    }
15506
15507    #[test]
15508    fn rejects_entrada_host_label_too_long() {
15509        let mut s = three_member_spec();
15510        // 64-byte label — one over the per-label cap.
15511        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
15512        let err = s.validate().unwrap_err();
15513        assert!(
15514            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15515                if reason.contains("label max length of 63")),
15516            "got {err:?}"
15517        );
15518    }
15519
15520    #[test]
15521    fn entrada_host_diagnostic_carries_offending_host() {
15522        // Diagnostic-shape pin — the offending host + a non-empty
15523        // reason flow through verbatim so the author can grep their
15524        // caixa.lisp for `:host "<host>"` and fix it in one edit.
15525        let mut s = three_member_spec();
15526        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
15527        let err = s.validate().unwrap_err();
15528        match err {
15529            AplicacaoError::EntradaHostInvalid { host, reason } => {
15530                assert_eq!(host, "checkout.quero.cloud:8080");
15531                assert!(!reason.is_empty(), "reason field must be non-empty");
15532            }
15533            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15534        }
15535    }
15536
15537    #[test]
15538    fn entrada_host_empty_takes_precedence_over_invalid() {
15539        // Ordering pin: `EmptyEntradaHost` is the more self-locating
15540        // diagnostic on `""` and must lead — `validate_entrada_host`
15541        // is only reached after the empty-check fires at the call
15542        // site. (The predicate itself defends against direct
15543        // invocation by returning the same error on `""`.)
15544        let mut s = three_member_spec();
15545        s.entrada.as_mut().unwrap().host = String::new();
15546        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
15547    }
15548
15549    #[test]
15550    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
15551        // Ordering pin: a missing :para member is the more
15552        // self-locating diagnostic and fires before the host gate.
15553        let mut s = three_member_spec();
15554        let e = s.entrada.as_mut().unwrap();
15555        e.para = "ghost".into();
15556        e.host = "BAD HOST".into();
15557        let err = s.validate().unwrap_err();
15558        assert!(
15559            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
15560            "got {err:?}"
15561        );
15562    }
15563
15564    #[test]
15565    fn entrada_host_invalid_fires_before_port_zero() {
15566        // Ordering pin: the host gate fires before the port gate so
15567        // a malformed host is named even when the port is also wrong.
15568        let mut s = three_member_spec();
15569        let e = s.entrada.as_mut().unwrap();
15570        e.host = "Checkout.quero.cloud".into();
15571        e.port = 0;
15572        let err = s.validate().unwrap_err();
15573        assert!(
15574            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15575                if host == "Checkout.quero.cloud"),
15576            "got {err:?}"
15577        );
15578    }
15579
15580    #[test]
15581    fn entrada_accepts_canonical_hosts() {
15582        // Positive-control sweep — every form the Gateway API
15583        // apiserver accepts must round-trip through validate. Covers
15584        // a plain DNS subdomain, a leading wildcard, a single-label
15585        // host (cluster-internal), a max-length-edge label, a
15586        // hyphen-bearing label, and a Punycode IDN label.
15587        for host in [
15588            "checkout.quero.cloud",
15589            "*.quero.cloud",
15590            "checkout",
15591            // 63-byte label — exactly the per-label cap.
15592            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
15593            "foo-bar.quero.cloud",
15594            // Punycode IDN — valid because the author pre-encoded.
15595            "xn--bcher-kva.example.com",
15596        ] {
15597            let mut s = three_member_spec();
15598            s.entrada.as_mut().unwrap().host = host.into();
15599            s.validate()
15600                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
15601        }
15602    }
15603
15604    #[test]
15605    fn entrada_host_max_length_validates() {
15606        // 253-byte host is the cap exactly — must validate. Build a
15607        // 253-byte host out of three 63-byte labels + one 61-byte
15608        // label + 3 dots = 252 bytes, then pad one byte to 253.
15609        let mut s = three_member_spec();
15610        let host = format!(
15611            "{}.{}.{}.{}",
15612            "a".repeat(63),
15613            "b".repeat(63),
15614            "c".repeat(63),
15615            "d".repeat(253 - 63 * 3 - 3)
15616        );
15617        assert_eq!(host.len(), 253);
15618        s.entrada.as_mut().unwrap().host = host;
15619        s.validate().unwrap();
15620    }
15621
15622    #[test]
15623    fn entrada_host_total_length_cap_threads_lifted_render_const() {
15624        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
15625        // total-length gate now reads the K8s Gateway API v1 Hostname
15626        // `maxLength: 253` cap from the lifted
15627        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
15628        // of truth — the same constant every future Gateway-API-Hostname
15629        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
15630        // materializer's per-host validator, the future per-`Certificate`
15631        // SAN emitter for cert-manager, the multi-`:entrada`
15632        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
15633        // from. Before the lift, the aplicacao-side reader consumed a
15634        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
15635        // 253-byte value as the peer render-side canonical bounds
15636        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
15637        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
15638        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
15639        // module boundary — a future 253-byte drift on either side would
15640        // silently split into two axes' worth of admission-schema mismatch
15641        // without a build-time signal. Pin the cap through a fresh 254-
15642        // byte host that hits the total-length arm, then read the reason
15643        // for the exact byte count the shared constant carries: any future
15644        // regression on the lift (a private alias reintroduced, a hard-
15645        // coded literal at the arm, a mismatch between the aplicacao-side
15646        // and render-side canonicals) surfaces as this pin's diagnostic
15647        // failing to match, not as a per-cluster admission rejection far
15648        // from the caixa.lisp source line.
15649        let mut s = three_member_spec();
15650        let over_cap = format!(
15651            "{}.{}.{}.{}",
15652            "a".repeat(63),
15653            "b".repeat(63),
15654            "c".repeat(63),
15655            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
15656        );
15657        assert_eq!(
15658            over_cap.len(),
15659            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
15660        );
15661        s.entrada.as_mut().unwrap().host = over_cap;
15662        let err = s.validate().unwrap_err();
15663        match err {
15664            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15665                let needle = format!(
15666                    "max length of {} bytes",
15667                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
15668                );
15669                assert!(
15670                    reason.contains(&needle),
15671                    "diagnostic must name the lifted \
15672                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
15673                );
15674            }
15675            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15676        }
15677    }
15678
15679    #[test]
15680    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
15681        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
15682        // on the per-label-cap axis. Before the lift, the aplicacao-side
15683        // per-label arm consumed a private const alias
15684        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
15685        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
15686        // split from it at the module boundary — every `.`-separated
15687        // label in a Gateway API v1 Hostname is a DNS-1123 label under
15688        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
15689        // so the private alias's 63 and the canonical const's 63 were
15690        // pinning the same underlying rule twice. Pin the cap through a
15691        // 64-byte label that hits the per-label arm, then read the reason
15692        // for the exact byte count the shared constant carries: any
15693        // future drift on either side (a private alias reintroduced, a
15694        // hard-coded literal at the arm, a mismatch between the two
15695        // 63-byte pins) surfaces at this pin's diagnostic rather than at
15696        // a per-cluster admission rejection whose "field is invalid"
15697        // opacity misframes the root cause.
15698        let mut s = three_member_spec();
15699        let over_cap_label = format!(
15700            "{}.quero.cloud",
15701            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
15702        );
15703        s.entrada.as_mut().unwrap().host = over_cap_label;
15704        let err = s.validate().unwrap_err();
15705        match err {
15706            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15707                let needle = format!(
15708                    "label max length of {} bytes",
15709                    crate::render::DNS_1123_LABEL_MAX_LEN,
15710                );
15711                assert!(
15712                    reason.contains(&needle),
15713                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
15714                     cap verbatim on the per-label arm, got: {reason:?}",
15715                );
15716            }
15717            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15718        }
15719    }
15720
15721    #[test]
15722    fn entrada_with_empty_paths_validates() {
15723        // Empty `:paths` is the documented "match every path" form;
15724        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
15725        let mut s = three_member_spec();
15726        s.entrada.as_mut().unwrap().paths = vec![];
15727        s.validate().unwrap();
15728    }
15729
15730    #[test]
15731    fn entrada_root_path_validates() {
15732        // The author-supplied bare-root `:entrada :paths` entry is the
15733        // same byte-shape the peer emit-side catch-all constant
15734        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
15735        // the author's `:paths` list is empty — sweeping the test-side
15736        // probe literal onto the lifted const closes the two-axis pin
15737        // (author-side admit + emit-side canonical fallback) around
15738        // one `&'static str`, so a future rebrand of the catch-all
15739        // reaches both consumers by construction. Peer to
15740        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
15741        // on the canonical-literal pin surface.
15742        let mut s = three_member_spec();
15743        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
15744        s.validate().unwrap();
15745    }
15746
15747    #[test]
15748    fn placement_strategy_variants_round_trip() {
15749        for s in [
15750            PlacementStrategy::SingleNode,
15751            PlacementStrategy::Replicated,
15752            PlacementStrategy::Sharded,
15753        ] {
15754            let p = Placement {
15755                estrategia: s,
15756                clusters: vec!["rio".into()],
15757                affinity: None,
15758                // Route the paired `:shard-key` fixture-builder through the
15759                // typed cross-slot invariant predicate
15760                // [`PlacementStrategy::requires_shard_key`] rather than the
15761                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
15762                // arm-identity predicate — the two answer the same
15763                // question under today's closed accept-set but a future
15764                // arm addition that consumed `:shard-key` under a
15765                // non-`Sharded` name would silently mis-attach the
15766                // fixture's `:shard-key` if the builder read through the
15767                // arm-identity predicate. The cross-slot-invariant
15768                // predicate migrates through one caixa-core edit on any
15769                // future arm addition; the fixture keeps producing a
15770                // `validate()`-passing round-trip by construction.
15771                shard_key: if s.requires_shard_key() {
15772                    Some("$key".into())
15773                } else {
15774                    None
15775                },
15776            };
15777            let json = serde_json::to_string(&p).unwrap();
15778            let back: Placement = serde_json::from_str(&json).unwrap();
15779            assert_eq!(back, p);
15780        }
15781    }
15782
15783    #[test]
15784    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
15785        // The fail-before-pass-after pin: pre-lift there was no
15786        // single-source binding between the [`PlacementStrategy`]
15787        // variant name the `Serialize` derive emits and the byte-
15788        // string every downstream cluster-side dispatcher (the
15789        // `lareira-fleet-programs` aggregator's per-entry strategy
15790        // branch, the future `app-operator` reconciler, the M3
15791        // Adaptive compression pass's per-strategy weighting) probes
15792        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
15793        // future `#[serde(rename_all = "kebab-case")]` attribute on
15794        // the enum — or a variant rename in the source — would
15795        // silently rebrand the emitted scalar under one spelling
15796        // while every downstream dispatcher still probed the other,
15797        // with the failure surfacing at the aggregator's dispatch
15798        // step or the operator's reconcile posture (workloads coming
15799        // up under the `default()` `Replicated` arm rather than the
15800        // typed slot's declared strategy) far from the source
15801        // rebrand commit and with no field naming the drift. Pinning
15802        // the two paths (the `Serialize` derive's serialized string
15803        // AND the [`PlacementStrategy::as_str`] helper) to the same
15804        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
15805        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15806        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
15807        // makes any future drift on either endpoint fail here at
15808        // caixa-core build time.
15809        for (variant, expected) in [
15810            (
15811                PlacementStrategy::SingleNode,
15812                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15813            ),
15814            (
15815                PlacementStrategy::Replicated,
15816                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15817            ),
15818            (
15819                PlacementStrategy::Sharded,
15820                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15821            ),
15822        ] {
15823            let json = serde_json::to_string(&variant).unwrap();
15824            assert_eq!(
15825                json,
15826                format!("\"{expected}\""),
15827                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
15828            );
15829            assert_eq!(
15830                variant.as_str(),
15831                expected,
15832                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
15833                 M3_PLACEMENT_ESTRATEGIA_* constant"
15834            );
15835        }
15836    }
15837
15838    #[test]
15839    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
15840        // Cross-arm drift-detection pin on the M3
15841        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
15842        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15843        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
15844        // scalar-value pentad: a future collapse of two canonical
15845        // variant byte-strings onto the same value (an accidental
15846        // copy-paste flip of
15847        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
15848        // read `"SingleNode"`, a per-arm rebrand that lands one const
15849        // without touching its paired peer) would silently reroute
15850        // every downstream operator's per-strategy dispatch onto the
15851        // sibling arm's reconcile branch and pass every
15852        // propagation-probe test that expected only the stale arm's
15853        // value — a `Replicated`-declared Aplicacao would come up
15854        // under the `SingleNode` primary-and-standby reconcile
15855        // posture, so every-cluster active-active workload would
15856        // silently collapse onto one-cluster-runs-at-a-time takeover
15857        // semantics against its declared strategy, with no field
15858        // naming the strategy-value drift root cause. Peer of the
15859        // sibling
15860        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
15861        // (09ffb2d) /
15862        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
15863        // (ccdf955) /
15864        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
15865        // (d739850) distinctness pins on the sibling OTP-shape /
15866        // caixa-kind closed-set typed-enum discriminator axes — the
15867        // fourth (and structurally the M3 mesh-primitive-defining)
15868        // closed-set typed-enum axis to converge on the same
15869        // "pairwise-distinct-by-construction" discipline.
15870        //
15871        // Fail-before-pass-after locally verified by mutating
15872        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
15873        // also read `"SingleNode"` — this pin fires as expected;
15874        // restoring passes.
15875        let all = [
15876            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15877            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15878            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15879        ];
15880        for (i, a) in all.iter().enumerate() {
15881            for (j, b) in all.iter().enumerate() {
15882                if i != j {
15883                    assert_ne!(
15884                        a, b,
15885                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
15886                         distinct — got duplicate {a:?} at indices {i} and {j}",
15887                    );
15888                }
15889            }
15890        }
15891    }
15892
15893    #[test]
15894    fn placement_strategy_display_routes_through_as_str_helper() {
15895        // The fail-before-pass-after pin: pre-lift the sibling
15896        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
15897        // / [`crate::supervisor::RestartPolicy`] both carried a stable
15898        // [`std::fmt::Display`] surface via their
15899        // `#[discriminant(also_display)]` gen-platform derive, but
15900        // [`PlacementStrategy`] did not — every consumer reaching for
15901        // a strategy byte-string past the wire format had to pick
15902        // between three paths ([`PlacementStrategy::as_str`], the
15903        // `Serialize` derive's serialized string, or `format!("{v:?}")`
15904        // on the `Debug` derive), any two of which a future variant
15905        // rename or `#[serde(rename_all = "kebab-case")]` attribute
15906        // would silently desynchronize. Wiring [`std::fmt::Display`]
15907        // through [`PlacementStrategy::as_str`] closes the third path:
15908        // every `format!("{v}")` call reaches the same lifted
15909        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
15910        // and the [`PlacementStrategy::as_str`] helper already route
15911        // through, so a future variant rename lands at exactly one
15912        // place. Pin the routing here so a future
15913        // `impl std::fmt::Display for PlacementStrategy` reimplementation
15914        // that hand-rolls the arms instead of delegating to
15915        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
15916        for variant in [
15917            PlacementStrategy::SingleNode,
15918            PlacementStrategy::Replicated,
15919            PlacementStrategy::Sharded,
15920        ] {
15921            assert_eq!(
15922                variant.to_string(),
15923                variant.as_str(),
15924                "PlacementStrategy::{variant:?} Display must route through \
15925                 PlacementStrategy::as_str (single source of truth: the lifted \
15926                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
15927            );
15928        }
15929    }
15930
15931    #[test]
15932    fn placement_strategy_display_matches_serialized_wire_byte_string() {
15933        // The fail-before-pass-after pin on the second half of the
15934        // three-path convergence: `Display` (user-facing text) agrees
15935        // byte-for-byte with the `Serialize` derive's wire format
15936        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
15937        // scalar) on every variant. Pre-lift the two paths were
15938        // structurally independent — a future
15939        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
15940        // would silently rebrand the emitted wire scalar
15941        // (`single-node`, `replicated`, `sharded`) while every consumer
15942        // that pretty-prints the strategy (the M3 diagnostic templates,
15943        // the future `feira app graph` per-Aplicacao strategy line,
15944        // the future M4 CR materializer's admission-webhook rejection
15945        // body) would still emit the TitleCase form the `as_str` /
15946        // `Display` route returns, with the mismatch surfacing at
15947        // consumer parse time / operator dispatch time far from the
15948        // source rebrand commit. Pin the two paths byte-for-byte here
15949        // so any future serde-attribute or variant-rename drift is a
15950        // caixa-core-build-time test failure at this call, not a
15951        // silent per-consumer dispatch miss.
15952        for variant in [
15953            PlacementStrategy::SingleNode,
15954            PlacementStrategy::Replicated,
15955            PlacementStrategy::Sharded,
15956        ] {
15957            let wire = serde_json::to_string(&variant).unwrap();
15958            // Strip the outer `"…"` the JSON string form carries — the
15959            // wire scalar the K8s / YAML apiserver consumes is the
15960            // enclosed byte-string, not the quote wrapper.
15961            let unquoted = wire
15962                .strip_prefix('"')
15963                .and_then(|s| s.strip_suffix('"'))
15964                .expect("serialized PlacementStrategy is a JSON string");
15965            assert_eq!(
15966                variant.to_string(),
15967                unquoted,
15968                "PlacementStrategy::{variant:?} Display byte-string must match the \
15969                 Serialize derive's wire byte-string (three-path convergence: \
15970                 Display + as_str + Serialize all resolve to the same \
15971                 M3_PLACEMENT_ESTRATEGIA_* const)"
15972            );
15973        }
15974    }
15975
15976    #[test]
15977    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
15978        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
15979        // derive on [`PlacementStrategy`]: for each of the three variants
15980        // exactly one of the generated `is_single_node` / `is_replicated`
15981        // / `is_sharded` predicates returns `true` and the other two
15982        // return `false`. Prior to this derive the three per-arm
15983        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
15984        // (the `placement_strategy_variants_round_trip` fixture, the
15985        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
15986        // fixture, and the
15987        // `validate_placement_reads_through_lifted_estrategia_accessor`
15988        // fixture) each open-coded a per-arm PartialEq compare against
15989        // the enum variant — three sites that expressed no compile-time
15990        // link back to the closed-set typed dispatch a future fourth
15991        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
15992        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
15993        // would have to thread through in lockstep or one fixture would
15994        // silently disagree with the others on which arms consume the
15995        // `:shard-key` axis. Peer of the sibling
15996        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
15997        // / [`crate::supervisor::RestartPolicy`] /
15998        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
15999        // the sibling closed-set typed-enum discriminator axes — extends
16000        // the same one-typed-dispatch-per-variant discipline onto the
16001        // fifth (and only remaining) closed-set typed-enum discriminator
16002        // on the caixa surface, closing the axis on the M3 mesh-slot
16003        // family.
16004        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
16005            (PlacementStrategy::SingleNode, [true, false, false]),
16006            (PlacementStrategy::Replicated, [false, true, false]),
16007            (PlacementStrategy::Sharded, [false, false, true]),
16008        ];
16009        for (variant, expected) in rows {
16010            let observed = [
16011                variant.is_single_node(),
16012                variant.is_replicated(),
16013                variant.is_sharded(),
16014            ];
16015            assert_eq!(
16016                observed, expected,
16017                "PlacementStrategy::{variant:?} is_* predicates must partition \
16018                 the arm set (single_node, replicated, sharded); got {observed:?}"
16019            );
16020        }
16021    }
16022
16023    #[test]
16024    fn placement_strategy_is_variant_predicates_are_const_fn() {
16025        // The [`gen_platform::IsVariant`] derive emits `const fn`
16026        // predicates on the peer [`crate::CaixaKind`] +
16027        // [`crate::upgrade::UpgradeInstruction`] +
16028        // [`crate::supervisor::RestartStrategy`] +
16029        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
16030        // pin the same posture on [`PlacementStrategy`] so a future
16031        // accidental downgrade to non-`const` (an added runtime helper
16032        // reachable only from a non-`const` context, a manual hand-rolled
16033        // `impl` that shadows the derive-generated method) trips at
16034        // caixa-core build time rather than surfacing as a downstream
16035        // `const`-context regression far from the derive declaration.
16036        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
16037        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
16038        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
16039        assert!(IS_SINGLE_NODE);
16040        assert!(IS_REPLICATED);
16041        assert!(IS_SHARDED);
16042    }
16043
16044    #[test]
16045    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
16046        // Fail-before-pass-after pin on the substrate-lifted
16047        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
16048        // per-arm predicate: for each variant in the closed accept-set the
16049        // predicate returns `true` iff the variant consumes the paired
16050        // [`Placement::shard_key`] axis under
16051        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
16052        // partition. Today the accept-set is the singleton `{Sharded}` —
16053        // `Sharded` is the Akka-style hash-keyed distribution arm
16054        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
16055        // §II.1) and `Replicated` (active-active) refuse the axis through
16056        // [`AplicacaoError::ShardKeyOnNonSharded`].
16057        //
16058        // Pins the per-arm truth-table so a future arm addition (an
16059        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
16060        // roadmap names, a `WeightedShard` promotion the future M5
16061        // adaptive-placement engine acknowledges) that landed a variant
16062        // without extending this predicate's arm-set would surface as a
16063        // caixa-core build-time exhaustiveness error at the
16064        // `match self { … }` arm-fan below rather than a silent per-consumer
16065        // mis-classification at renderer emit time. The paired
16066        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
16067        // predicate stays a distinct question — arm-identity (which the
16068        // sibling
16069        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
16070        // pin already locks) is not cross-slot-invariant consumption; today
16071        // they trip on the same singleton but the pair migrates through
16072        // one caixa-core edit on any future arm addition.
16073        //
16074        // Peer of the sibling per-arm classifier pins
16075        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
16076        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
16077        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
16078        // derived paired predicate on the post-projection typed-view axis
16079        // — same "per-arm semantic-classification predicate paired with
16080        // the arm-identity predicate the derive already emits" discipline
16081        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
16082        // `:placement :shard-key` cross-slot-invariant axis.
16083        let rows: [(PlacementStrategy, bool); 3] = [
16084            (PlacementStrategy::SingleNode, false),
16085            (PlacementStrategy::Replicated, false),
16086            (PlacementStrategy::Sharded, true),
16087        ];
16088        for (variant, expected) in rows {
16089            assert_eq!(
16090                variant.requires_shard_key(),
16091                expected,
16092                "PlacementStrategy::{variant:?}.requires_shard_key() must \
16093                 be {expected} (the substrate-canonical cross-slot invariant \
16094                 on the :placement :shard-key axis; today `Sharded` is the \
16095                 singleton consuming arm — MESH-COMPOSITION §II.4)",
16096            );
16097        }
16098    }
16099
16100    #[test]
16101    fn placement_strategy_requires_shard_key_is_const_fn() {
16102        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
16103        // invariant per-arm predicate is declared `#[must_use] pub const
16104        // fn` — pin the `const`-eval posture here so a future accidental
16105        // downgrade to non-`const` (an added runtime helper reachable
16106        // only from a non-`const` context, a manual hand-rolled `impl`
16107        // that shadows the current three-arm `match self { … }` dispatch)
16108        // trips at caixa-core build time rather than surfacing as a
16109        // downstream `const`-context regression far from the declaration.
16110        // Same shape as the sibling
16111        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
16112        // the peer [`gen_platform::IsVariant`]-derived arm-identity
16113        // predicate axis, but here the load-bearing assertions live in
16114        // module-scope `const _: () = assert!(…)` items so a violation
16115        // fails at compile time (const-eval trip) rather than test time —
16116        // strictly stronger than the runtime `assert!(CONST)` pattern the
16117        // sibling pin uses, and side-steps the
16118        // `clippy::assertions_on_constants` lint the runtime pattern
16119        // otherwise accumulates on the module baseline.
16120        //
16121        // The test body simply witnesses that the module-scope items
16122        // compiled and the runtime dispatch agrees with the const-eval
16123        // dispatch on every arm — the runtime read gives the test a
16124        // failure surface (rather than an empty test body clippy would
16125        // flag as a no-op).
16126        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
16127        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
16128        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
16129        assert_eq!(
16130            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
16131            [
16132                PlacementStrategy::SingleNode.requires_shard_key(),
16133                PlacementStrategy::Replicated.requires_shard_key(),
16134                PlacementStrategy::Sharded.requires_shard_key(),
16135            ],
16136            "runtime and const-eval dispatch on \
16137             PlacementStrategy::requires_shard_key must agree on every arm",
16138        );
16139    }
16140
16141    #[test]
16142    fn placement_estrategia_accessor_is_const_fn() {
16143        // The [`Placement::estrategia`] per-`:placement` distribution-
16144        // strategy `Copy`-return scalar accessor is declared
16145        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
16146        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
16147        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
16148        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
16149        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
16150        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
16151        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
16152        // [`RateLimit`], every one a `pub const fn`). Pin the
16153        // `const`-eval posture here so a future accidental downgrade to
16154        // non-`const` (an added runtime helper reachable only from a
16155        // non-`const` context, a slot promotion to a non-`Copy` return
16156        // that would silently drop the `const` qualifier, a manual
16157        // hand-rolled shadow) trips at caixa-core build time rather
16158        // than surfacing as a downstream `const`-context regression far
16159        // from the declaration.
16160        //
16161        // Same shape as the sibling
16162        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
16163        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
16164        // predicate axis — the load-bearing witness lives in the
16165        // module-scope `const fn` wrapper `estrategia_via_const_fn`
16166        // below: a body that calls [`Placement::estrategia`] under a
16167        // `const fn` signature is well-formed only when the callee is
16168        // itself `const fn`, so any future accidental downgrade of
16169        // [`Placement::estrategia`] to non-`const` fails at caixa-core
16170        // build time (const-eval E0015 / E0658 depending on the arm),
16171        // strictly stronger than a runtime `assert!(CONST)` and
16172        // side-stepping the destructor-in-const restriction that
16173        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
16174        // items on `Placement`'s `Vec<String>` / `Option<String>`
16175        // carriers.
16176        //
16177        // The runtime body witnesses that the const-eval-shaped
16178        // wrapper agrees with a direct call on every closed-set arm.
16179        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
16180            p.estrategia()
16181        }
16182        for estrategia in [
16183            PlacementStrategy::SingleNode,
16184            PlacementStrategy::Replicated,
16185            PlacementStrategy::Sharded,
16186        ] {
16187            let placement = Placement {
16188                estrategia,
16189                clusters: Vec::new(),
16190                affinity: None,
16191                shard_key: None,
16192            };
16193            assert_eq!(
16194                estrategia_via_const_fn(&placement),
16195                placement.estrategia(),
16196                "const-fn-wrapped and direct dispatch on \
16197                 Placement::estrategia must agree for {estrategia:?}",
16198            );
16199        }
16200    }
16201
16202    #[test]
16203    fn entrada_port_accessor_is_const_fn() {
16204        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
16205        // scalar accessor is declared `#[must_use] pub const fn` —
16206        // matching the peer M3 mesh-slot `Copy`-return accessor family
16207        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
16208        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
16209        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
16210        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
16211        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
16212        // [`RateLimit::window`] on the sibling [`RateLimit`], the
16213        // sibling per-`:placement` [`Placement::estrategia`] pinned by
16214        // [`placement_estrategia_accessor_is_const_fn`] above — every
16215        // one a `pub const fn`). Pin the `const`-eval posture here so
16216        // a future accidental downgrade to non-`const` (an added
16217        // runtime helper reachable only from a non-`const` context, an
16218        // `Option<u16>`-shape migration once the substrate grows
16219        // per-`:membros` heterogeneous listener ports that would
16220        // silently drop the `const` qualifier, a manual hand-rolled
16221        // shadow) trips at caixa-core build time rather than surfacing
16222        // as a downstream `const`-context regression far from the
16223        // declaration.
16224        //
16225        // Same shape as the sibling
16226        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
16227        // load-bearing witness lives in the module-scope `const fn`
16228        // wrapper `port_via_const_fn`: a body that calls
16229        // [`Entrada::port`] under a `const fn` signature is well-formed
16230        // only when the callee is itself `const fn`, side-stepping the
16231        // destructor-in-const restriction that would otherwise block a
16232        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
16233        // `String` / `Vec<String>` carriers.
16234        //
16235        // The runtime body sweeps a representative port set spanning
16236        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
16237        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
16238        // ceiling — the const-fn-wrapped call must agree with a direct
16239        // call on every fixture (a violation trips the test) and every
16240        // returned scalar must byte-equal the input `port` (a violation
16241        // means the accessor stopped being a raw field-return copy).
16242        const fn port_via_const_fn(e: &Entrada) -> u16 {
16243            e.port()
16244        }
16245        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
16246            let entrada = Entrada {
16247                host: String::new(),
16248                para: String::new(),
16249                port,
16250                paths: Vec::new(),
16251            };
16252            assert_eq!(
16253                port_via_const_fn(&entrada),
16254                entrada.port(),
16255                "const-fn-wrapped and direct dispatch on Entrada::port \
16256                 must agree for port={port}",
16257            );
16258            assert_eq!(
16259                entrada.port(),
16260                port,
16261                "Entrada::port must return the storage-side u16 verbatim \
16262                 for port={port}",
16263            );
16264        }
16265    }
16266
16267    #[test]
16268    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
16269        // Load-bearing cross-slot-partition pin closing the loop between
16270        // the substrate-lifted
16271        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
16272        // the closed-set typed enum and the actual
16273        // [`AplicacaoSpec::validate_placement`] runtime behavior across
16274        // the paired `:placement :shard-key` axis: every validated
16275        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
16276        // satisfies `placement.shard_key().is_some() ==
16277        // placement.estrategia().requires_shard_key()`. The four-cell
16278        // shape witness sweeps every combination of (variant in the
16279        // closed accept-set, `:shard-key` Some/None) and pins:
16280        //
16281        //   * variant.requires_shard_key() && shard_key.is_some() →
16282        //     validate() passes; the paired shape is the sole
16283        //     `requires_shard_key` arm-family accepted shape.
16284        //   * variant.requires_shard_key() && shard_key.is_none() →
16285        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
16286        //     the paired shape is the refused missing-key shape on
16287        //     Sharded-family arms.
16288        //   * !variant.requires_shard_key() && shard_key.is_some() →
16289        //     validate() fails with
16290        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
16291        //     is the refused declared-but-inert shape on non-Sharded-
16292        //     family arms.
16293        //   * !variant.requires_shard_key() && shard_key.is_none() →
16294        //     validate() passes; the paired shape is the sole
16295        //     non-`requires_shard_key` arm-family accepted shape.
16296        //
16297        // The compile-time-exhaustive `match p.estrategia()` dispatch at
16298        // [`AplicacaoSpec::validate_placement`] preserves its structural
16299        // arm-fan (a future arm addition still surfaces a build-time
16300        // exhaustiveness error there); this pin closes the semantic loop
16301        // between the arm-fan's shape-gate cascades and the substrate-
16302        // canonical predicate every downstream consumer of the paired
16303        // shape reads through. Fail-before-pass-after locally verified by
16304        // mutating the predicate's `Sharded => true` arm to `false` — the
16305        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
16306        // `validate() must pass` assertion; restoring passes. Same "close
16307        // the loop between the typed predicate and the runtime behavior"
16308        // discipline as the sibling
16309        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
16310        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
16311        // per-arm classifier axis.
16312        for variant in [
16313            PlacementStrategy::SingleNode,
16314            PlacementStrategy::Replicated,
16315            PlacementStrategy::Sharded,
16316        ] {
16317            for present in [false, true] {
16318                let mut spec = three_member_spec();
16319                spec.placement.estrategia = variant;
16320                spec.placement.shard_key = present.then(|| "tenantId".into());
16321                let expects_ok = variant.requires_shard_key() == present;
16322                let result = spec.validate();
16323                match (expects_ok, &result) {
16324                    (true, Ok(())) => {}
16325                    (false, Err(err)) => {
16326                        // Cross-check the refusal diagnostic names the
16327                        // right cell of the four-cell shape witness — the
16328                        // `requires_shard_key && !present` cell must trip
16329                        // [`AplicacaoError::ShardedWithoutKey`]; the
16330                        // `!requires_shard_key && present` cell must trip
16331                        // [`AplicacaoError::ShardKeyOnNonSharded`].
16332                        match (variant.requires_shard_key(), present, err) {
16333                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
16334                            (
16335                                false,
16336                                true,
16337                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
16338                            ) => {
16339                                assert_eq!(
16340                                    *e, variant,
16341                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
16342                                     the paired PlacementStrategy",
16343                                );
16344                            }
16345                            _ => panic!(
16346                                "unexpected refusal for estrategia={variant:?} \
16347                                 present={present}: {err:?}"
16348                            ),
16349                        }
16350                    }
16351                    (true, Err(err)) => panic!(
16352                        "validate() must pass for estrategia={variant:?} \
16353                         present={present} (requires_shard_key={} == present={present}), \
16354                         got {err:?}",
16355                        variant.requires_shard_key(),
16356                    ),
16357                    (false, Ok(())) => panic!(
16358                        "validate() must fail for estrategia={variant:?} \
16359                         present={present} (requires_shard_key={} != present={present})",
16360                        variant.requires_shard_key(),
16361                    ),
16362                }
16363            }
16364        }
16365    }
16366
16367    #[test]
16368    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
16369        // Pin the M3 diagnostic template routes through the typed
16370        // [`PlacementStrategy`] Display byte-string (rebound from the
16371        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
16372        // routes emitted identical bytes (the `Debug` derive on a
16373        // unit variant emits the variant name verbatim, exactly what
16374        // `as_str` returns), but the two paths were structurally
16375        // independent — a future `#[serde(rename_all = "…")]`
16376        // attribute or variant rename would coordinate the wire /
16377        // `Display` / `as_str` triple through the lifted const but
16378        // leave the `Debug` route on the compiler-derived variant name,
16379        // silently desynchronizing the diagnostic byte-string from the
16380        // wire byte-string. Rebinding the template onto `Display`
16381        // ties the diagnostic to the same lifted
16382        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
16383        // emits — drift becomes structurally impossible. Pin the
16384        // byte-string here so a future edit that reverts the template
16385        // to `{estrategia:?}` is caught at caixa-core test time, not
16386        // at consumer dispatch time.
16387        for (variant, expected_scalar) in [
16388            (
16389                PlacementStrategy::SingleNode,
16390                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16391            ),
16392            (
16393                PlacementStrategy::Replicated,
16394                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16395            ),
16396            (
16397                PlacementStrategy::Sharded,
16398                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16399            ),
16400        ] {
16401            let err = AplicacaoError::PlacementWithoutClusters {
16402                estrategia: variant,
16403            };
16404            let msg = err.to_string();
16405            assert!(
16406                msg.starts_with(&format!(":placement {expected_scalar} requires")),
16407                "PlacementWithoutClusters diagnostic for {variant:?} must open \
16408                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16409            );
16410        }
16411    }
16412
16413    #[test]
16414    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
16415        // Peer of
16416        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
16417        // on the second M3 diagnostic that carries the typed
16418        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
16419        // diagnostics now route the strategy scalar through the same
16420        // [`std::fmt::Display`] surface, tying the diagnostic
16421        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
16422        // const set the wire format also emits. The two non-Sharded
16423        // arms are exercised here (the diagnostic exists to flag a
16424        // `:shard-key` slot the current strategy will never consume);
16425        // the peer `Sharded` arm never reaches this diagnostic (the
16426        // `Sharded` strategy consumes `:shard-key` — the
16427        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
16428        // slot instead).
16429        for (variant, expected_scalar) in [
16430            (
16431                PlacementStrategy::SingleNode,
16432                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16433            ),
16434            (
16435                PlacementStrategy::Replicated,
16436                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16437            ),
16438        ] {
16439            let err = AplicacaoError::ShardKeyOnNonSharded {
16440                estrategia: variant,
16441                shard_key: "$tenantId".into(),
16442            };
16443            let msg = err.to_string();
16444            assert!(
16445                msg.starts_with(&format!(":placement {expected_scalar} carries")),
16446                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
16447                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16448            );
16449        }
16450    }
16451
16452    #[test]
16453    fn placement_strategy_all_enumerates_every_variant_once() {
16454        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
16455        // exhaustive-iteration surface: every variant appears exactly
16456        // once, and the slice length matches the arm count of the
16457        // closed set. Every consumer that walks the accepted-strategy
16458        // set (a future `feira app placement --list` CLI-side surfacing,
16459        // a future M4 admission-webhook's rejection body naming the
16460        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
16461        // reverse-projection consumers that iterate the accept-set for
16462        // a "did you mean" hint) reads through this slice, so a future
16463        // variant addition (an `Anycast` mesh-anycast arm the
16464        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
16465        // grows the enum but forgets to grow [`Self::ALL`] silently
16466        // truncates every downstream consumer's accept-set at the same
16467        // pre-addition boundary — this pin fails at caixa-core build
16468        // time on the pairwise-distinct + arm-count invariants.
16469        //
16470        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
16471        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
16472        // pins on the peer closed-set typed-enum axes.
16473        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
16474        assert_eq!(
16475            all.len(),
16476            3,
16477            "PlacementStrategy::ALL must enumerate every variant of the \
16478             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
16479        );
16480        for (i, a) in all.iter().enumerate() {
16481            for (j, b) in all.iter().enumerate() {
16482                if i != j {
16483                    assert_ne!(
16484                        a, b,
16485                        "PlacementStrategy::ALL must carry every variant exactly \
16486                         once — got duplicate {a:?} at indices {i} and {j}"
16487                    );
16488                }
16489            }
16490        }
16491        for variant in [
16492            PlacementStrategy::SingleNode,
16493            PlacementStrategy::Replicated,
16494            PlacementStrategy::Sharded,
16495        ] {
16496            assert!(
16497                all.contains(&variant),
16498                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
16499                 addition that grows the enum but forgets to grow the ALL slice \
16500                 silently truncates every downstream consumer's accept-set at the \
16501                 pre-addition boundary"
16502            );
16503        }
16504    }
16505
16506    #[test]
16507    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
16508        // Fail-before-pass-after pin on the forward accept-set of the
16509        // [`PlacementStrategy::from_wire`] reverse projection: every
16510        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
16511        // constant the [`PlacementStrategy::as_str`] emitter walks
16512        // parses back to its paired variant. Any future arm addition
16513        // that grows the emitter's `as_str` match but forgets to grow
16514        // the parser's `from_str` match silently splits the two halves
16515        // of the round-trip — the wire byte-string one non-serde
16516        // consumer parses from the one the emitter wrote — with the
16517        // failure surfacing at parse time far from the rebrand commit.
16518        // Pinning the three-arm accept-set here catches the drift at
16519        // caixa-core build time.
16520        //
16521        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
16522        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
16523        // closed-set typed-enum `str → Self` axes.
16524        for (wire, expected) in [
16525            (
16526                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16527                PlacementStrategy::SingleNode,
16528            ),
16529            (
16530                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16531                PlacementStrategy::Replicated,
16532            ),
16533            (
16534                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16535                PlacementStrategy::Sharded,
16536            ),
16537        ] {
16538            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16539                panic!(
16540                    "PlacementStrategy::from_wire({wire:?}) must accept every \
16541                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
16542                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
16543                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
16544                )
16545            });
16546            assert_eq!(
16547                parsed, expected,
16548                "PlacementStrategy::from_wire({wire:?}) must return \
16549                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
16550            );
16551        }
16552    }
16553
16554    #[test]
16555    fn placement_strategy_from_wire_round_trips_through_as_str() {
16556        // Fail-before-pass-after pin on the closed round-trip between
16557        // the forward [`PlacementStrategy::as_str`] emitter and the
16558        // reverse [`PlacementStrategy::from_wire`] parser: for every
16559        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
16560        // output must return exactly the same variant. Any per-arm
16561        // divergence — a future arm added to `as_str` but not
16562        // `from_str`, an accidental copy-paste flip in one but not the
16563        // other — silently splits the emit and parse halves and the
16564        // failure surfaces at consumer parse time far from the drift
16565        // site. The `ALL`-iterating shape means a future variant
16566        // addition picks up the coverage by construction.
16567        //
16568        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
16569        // [`crate::CaixaKind::from_wire`] and the
16570        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
16571        // sibling round-trip pin on [`RateLimitUnit`].
16572        for &variant in PlacementStrategy::ALL {
16573            let wire = variant.as_str();
16574            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16575                panic!(
16576                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16577                     must be Some({variant:?}) — the two halves of the round-trip \
16578                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
16579                     got None on wire byte-string {wire:?}"
16580                )
16581            });
16582            assert_eq!(
16583                parsed, variant,
16584                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16585                 must round-trip to the same variant; got {parsed:?}"
16586            );
16587        }
16588    }
16589
16590    #[test]
16591    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
16592        // Fail-before-pass-after pin on the closed-set refusal
16593        // discipline of [`PlacementStrategy::from_wire`]: every
16594        // byte-string outside the three-arm accept-set returns `None`
16595        // rather than silently collapsing onto the [`Default`]
16596        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
16597        // exercised here sweeps the load-bearing drift shapes: the
16598        // empty string (a stripped serde-attribute drift), an all-
16599        // whitespace string (the canonical text-editor accidental
16600        // padding shape), the lowercased kebab-case forms a future
16601        // `#[serde(rename_all = "kebab-case")]` attribute would emit
16602        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
16603        // coincidentally match the accepted canonical scalars, so only
16604        // `"single-node"` fires as a refusal, but pinning the case-
16605        // sensitivity of the accepted arms via the peer [`SingleNode`]
16606        // assertion in the round-trip pin makes the discipline
16607        // structurally clear), the lowercased single-word forms
16608        // (`"singlenode"`), the padded canonical scalar
16609        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
16610        // (`"Sharded\n"`), and a pointer-different `&'static str` that
16611        // happens to alias a canonical byte-string by content but not
16612        // by identity (validated implicitly by the emitter's routing
16613        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
16614        // identity a paired [`crate::assert_str_reexport_identity`] pin
16615        // in caixa-core's per-const declaration surface would catch).
16616        //
16617        // Peer of the sibling
16618        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
16619        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
16620        for bad in [
16621            "",
16622            " ",
16623            "\n",
16624            "\t",
16625            "single-node",
16626            "singlenode",
16627            "SingleNodes",
16628            "single_node",
16629            "single node",
16630            "SINGLENODE",
16631            "SingleNode ",
16632            " SingleNode",
16633            " Sharded ",
16634            "Sharded\n",
16635            "replicated ",
16636            "sharded",
16637            "REPLICATED",
16638            "Anycast",
16639            "Global",
16640            "?",
16641        ] {
16642            assert!(
16643                PlacementStrategy::from_wire(bad).is_none(),
16644                "PlacementStrategy::from_wire({bad:?}) must return None — the \
16645                 parser's accept-set is exactly the three PlacementStrategy::as_str \
16646                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
16647                 is outside that closed set"
16648            );
16649        }
16650    }
16651
16652    #[test]
16653    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
16654        // Fail-before-pass-after pin on the third path of the four-path
16655        // convergence: `from_str` (the reverse projection) inverts the
16656        // `Serialize` derive's wire byte-string on every variant.
16657        // Together with the pre-existing three-path convergence
16658        // (`Display` + `as_str` + `Serialize` all resolve to the same
16659        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
16660        // the peer
16661        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
16662        // this closes the round-trip: the wire byte-string the
16663        // `Serialize` derive emits parses back to the same variant
16664        // through `from_str`, so any future serde-attribute or variant-
16665        // rename drift on the emit half now surfaces as a matched drift
16666        // on the parse half at caixa-core build time — the two halves
16667        // migrate as a unit through the lifted consts on any future
16668        // rename, and the round-trip cannot silently split.
16669        //
16670        // Peer of the sibling
16671        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
16672        // wire-format pin — extends the three-path convergence
16673        // (`Display` + `as_str` + `Serialize`) onto the fourth path
16674        // (`from_str`), closing the `str ↔ Self` round-trip on the
16675        // M3 `:placement :estrategia` closed-set axis.
16676        for &variant in PlacementStrategy::ALL {
16677            let wire = serde_json::to_string(&variant).unwrap();
16678            let unquoted = wire
16679                .strip_prefix('"')
16680                .and_then(|s| s.strip_suffix('"'))
16681                .expect("serialized PlacementStrategy is a JSON string");
16682            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
16683                panic!(
16684                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
16685                     Serialize derive's wire byte-string for \
16686                     PlacementStrategy::{variant:?} — the four-path convergence \
16687                     (Display + as_str + Serialize + from_str) resolves through \
16688                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
16689                )
16690            });
16691            assert_eq!(
16692                parsed, variant,
16693                "PlacementStrategy::from_wire of the Serialize derive's wire \
16694                 byte-string for PlacementStrategy::{variant:?} must round-trip \
16695                 to the same variant; got {parsed:?}"
16696            );
16697        }
16698    }
16699
16700    #[test]
16701    fn rejects_zero_policy_timeout() {
16702        let mut s = three_member_spec();
16703        s.politicas.timeout = Some(Duration::ZERO);
16704        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
16705    }
16706
16707    #[test]
16708    fn rejects_zero_policy_retries() {
16709        let mut s = three_member_spec();
16710        s.politicas.retries = Some(0);
16711        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
16712    }
16713
16714    #[test]
16715    fn rejects_policy_retries_above_cap() {
16716        // The fail-before-pass-after pin: `Some(11)` is structurally
16717        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
16718        // passed validate on every pre-gate codebase because the
16719        // typed slot's only check was the zero-floor arm. The
16720        // thundering-herd amplification vector only surfaced at the
16721        // runtime substrate (Envoy / Cilium L7 retry overlay)
16722        // far from the source caixa.lisp with no field naming the
16723        // offending policy.
16724        let mut s = three_member_spec();
16725        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
16726        assert_eq!(
16727            s.validate().unwrap_err(),
16728            AplicacaoError::PolicyRetriesExceedsCap {
16729                retries: POLICY_RETRIES_MAX + 1
16730            }
16731        );
16732    }
16733
16734    #[test]
16735    fn rejects_policy_retries_far_above_cap() {
16736        // The `u32::MAX` worst case — the four-billion-retry policy
16737        // a typo (`(:retries 4294967295)`) or struct-literal
16738        // copy-paste lands in the slot. Pin the cap arm's coverage
16739        // explicitly across the full `u32` overflow so a future
16740        // relaxation that drops the upper bound surfaces here.
16741        let mut s = three_member_spec();
16742        s.politicas.retries = Some(u32::MAX);
16743        assert_eq!(
16744            s.validate().unwrap_err(),
16745            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
16746        );
16747    }
16748
16749    #[test]
16750    fn accepts_policy_retries_at_cap() {
16751        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
16752        // must validate. The cap is inclusive on the top edge,
16753        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16754        // discipline on the sibling [`crate::LimitsSpec::memory`]
16755        // axis. Pin the boundary explicitly so a future off-by-one
16756        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
16757        // surfaces here as a test failure rather than a silent
16758        // contract narrowing.
16759        let mut s = three_member_spec();
16760        s.politicas.retries = Some(POLICY_RETRIES_MAX);
16761        s.validate()
16762            .expect("retries == POLICY_RETRIES_MAX must validate");
16763    }
16764
16765    #[test]
16766    fn accepts_policy_retries_typical_values() {
16767        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
16768        // every value in the validated set must pass. The
16769        // Envoy / Istio production-playbook recommendation band
16770        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
16771        // (`maxRetries ≤ 10`) both lie within this set.
16772        for r in 1..=POLICY_RETRIES_MAX {
16773            let mut s = three_member_spec();
16774            s.politicas.retries = Some(r);
16775            s.validate()
16776                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
16777        }
16778    }
16779
16780    #[test]
16781    fn policy_retries_zero_takes_precedence_over_cap() {
16782        // The cross-arm ordering pin: `Some(0)` is structurally
16783        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
16784        // (cap), but the zero-floor diagnostic is the more
16785        // self-locating one (it directly names the omit-axis
16786        // remediation), so the validate gate must fire on zero
16787        // first. Pin the order so a future refactor that reorders
16788        // the arms surfaces here as a test failure rather than a
16789        // silent diagnostic regression. Same shape every other
16790        // zero-then-shape ordering on this surface uses
16791        // ([`AplicacaoError::PolicyTimeoutZero`] then
16792        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
16793        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
16794        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
16795        let mut s = three_member_spec();
16796        s.politicas.retries = Some(0);
16797        assert_eq!(
16798            s.validate().unwrap_err(),
16799            AplicacaoError::PolicyRetriesZero,
16800            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
16801        );
16802    }
16803
16804    #[test]
16805    fn policy_retries_cap_diagnostic_carries_offending_value() {
16806        // The diagnostic-shape pin: the offending `u32` is carried
16807        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
16808        // variant so the surfaced error message names the value the
16809        // author wrote (`":politicas :retries (47) exceeds the
16810        // mesh-policy ceiling …"`), not just the cap. Same
16811        // self-locating diagnostic shape every other typed-cap arm
16812        // on this surface carries
16813        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16814        // offending byte count verbatim).
16815        let mut s = three_member_spec();
16816        s.politicas.retries = Some(47);
16817        let err = s.validate().unwrap_err();
16818        assert!(
16819            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
16820            "got {err:?}"
16821        );
16822        let msg = err.to_string();
16823        assert!(
16824            msg.contains("47"),
16825            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
16826        );
16827    }
16828
16829    #[test]
16830    fn policy_retries_cap_is_aws_app_mesh_aligned() {
16831        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
16832        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
16833        // schema cap — the only upstream mesh-policy schema that
16834        // documents an explicit hard cap. Pinning the literal value
16835        // here surfaces a future drift (a relaxation to 20, a
16836        // tightening to 5) as a deliberate test edit, not a silent
16837        // contract narrowing.
16838        assert_eq!(POLICY_RETRIES_MAX, 10);
16839    }
16840
16841    #[test]
16842    fn rejects_circuit_breaker_zero_max_failures() {
16843        let mut s = three_member_spec();
16844        s.politicas.circuit_breaker = Some(CircuitBreaker {
16845            max_failures: 0,
16846            window: Duration::from_secs(60),
16847        });
16848        assert_eq!(
16849            s.validate().unwrap_err(),
16850            AplicacaoError::PolicyBreakerZeroFailures
16851        );
16852    }
16853
16854    #[test]
16855    fn rejects_circuit_breaker_max_failures_above_cap() {
16856        // The fail-before-pass-after pin: `1001` is structurally one
16857        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
16858        // silently passed validate on every pre-gate codebase
16859        // because the typed slot's only check was the zero-floor
16860        // arm. The breaker-no-op vector only surfaced at the runtime
16861        // substrate (Envoy / Cilium L7 outlier-detection overlay)
16862        // far from the source caixa.lisp with no field naming the
16863        // offending policy.
16864        let mut s = three_member_spec();
16865        s.politicas.circuit_breaker = Some(CircuitBreaker {
16866            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16867            window: Duration::from_secs(60),
16868        });
16869        assert_eq!(
16870            s.validate().unwrap_err(),
16871            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16872                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16873            }
16874        );
16875    }
16876
16877    #[test]
16878    fn rejects_circuit_breaker_max_failures_far_above_cap() {
16879        // The `u32::MAX` worst case — the four-billion-failure
16880        // threshold a typo (`(:max-failures 4294967295)`) or a
16881        // struct-literal copy-paste lands in the slot. Pin the cap
16882        // arm's coverage explicitly across the full `u32` overflow
16883        // so a future relaxation that drops the upper bound surfaces
16884        // here.
16885        let mut s = three_member_spec();
16886        s.politicas.circuit_breaker = Some(CircuitBreaker {
16887            max_failures: u32::MAX,
16888            window: Duration::from_secs(60),
16889        });
16890        assert_eq!(
16891            s.validate().unwrap_err(),
16892            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16893                max_failures: u32::MAX,
16894            }
16895        );
16896    }
16897
16898    #[test]
16899    fn accepts_circuit_breaker_max_failures_at_cap() {
16900        // The boundary value — exactly
16901        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
16902        // cap is inclusive on the top edge, matching the
16903        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16904        // discipline on the sibling capped axes. Pin the boundary
16905        // explicitly so a future off-by-one tightening
16906        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
16907        // surfaces here as a test failure rather than a silent
16908        // contract narrowing.
16909        let mut s = three_member_spec();
16910        s.politicas.circuit_breaker = Some(CircuitBreaker {
16911            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
16912            window: Duration::from_secs(60),
16913        });
16914        s.validate()
16915            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
16916    }
16917
16918    #[test]
16919    fn accepts_circuit_breaker_max_failures_typical_values() {
16920        // The documented production-playbook band positive-control
16921        // sweep — every value Hystrix / Istio / Envoy / Polly /
16922        // Resilience4j recommend (5..=50) must pass, plus a sweep
16923        // through the hyperscale band (100, 500, 1000) the cap
16924        // accepts. Pin the inclusive validated set explicitly so a
16925        // future tightening of the ceiling surfaces here.
16926        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
16927            let mut s = three_member_spec();
16928            s.politicas.circuit_breaker = Some(CircuitBreaker {
16929                max_failures: n,
16930                window: Duration::from_secs(60),
16931            });
16932            s.validate()
16933                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
16934        }
16935    }
16936
16937    #[test]
16938    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
16939        // The cross-arm ordering pin: `0` is structurally outside
16940        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
16941        // (cap), but the zero-floor diagnostic is the more
16942        // self-locating one (it directly names the omit-axis
16943        // remediation), so the validate gate must fire on zero
16944        // first. Same shape every other zero-then-shape ordering on
16945        // this surface uses
16946        // ([`AplicacaoError::PolicyRetriesZero`] then
16947        // [`AplicacaoError::PolicyRetriesExceedsCap`];
16948        // [`AplicacaoError::PolicyTimeoutZero`] then
16949        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
16950        let mut s = three_member_spec();
16951        s.politicas.circuit_breaker = Some(CircuitBreaker {
16952            max_failures: 0,
16953            window: Duration::from_secs(60),
16954        });
16955        assert_eq!(
16956            s.validate().unwrap_err(),
16957            AplicacaoError::PolicyBreakerZeroFailures,
16958            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
16959        );
16960    }
16961
16962    #[test]
16963    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
16964        // The cross-arm ordering pin between the cap and the
16965        // sibling `:window` gates (zero-window, canonical-window).
16966        // A breaker carrying both an over-cap `max_failures` AND a
16967        // structurally invalid window (zero, sub-ms) must surface
16968        // the cap diagnostic first — the cap arm is wired
16969        // immediately after the zero-failure arm and strictly
16970        // before the window arms, so the offending value the
16971        // diagnostic names matches the order the author would
16972        // discover the gates by reading top-to-bottom through
16973        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
16974        // future refactor that reorders the arms surfaces here as a
16975        // test failure rather than a silent diagnostic regression.
16976        let mut s = three_member_spec();
16977        s.politicas.circuit_breaker = Some(CircuitBreaker {
16978            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16979            window: Duration::ZERO,
16980        });
16981        assert_eq!(
16982            s.validate().unwrap_err(),
16983            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16984                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16985            },
16986            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
16987        );
16988    }
16989
16990    #[test]
16991    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
16992        // The diagnostic-shape pin: the offending `u32` is carried
16993        // verbatim into the
16994        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
16995        // variant so the surfaced error message names the value the
16996        // author wrote (`":politicas :circuit-breaker :max-failures
16997        // (50000) exceeds the mesh-policy ceiling …"`), not just
16998        // the cap. Same self-locating diagnostic shape every other
16999        // typed-cap arm on this surface carries
17000        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
17001        // offending retry count verbatim,
17002        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
17003        // offending byte count verbatim).
17004        let mut s = three_member_spec();
17005        s.politicas.circuit_breaker = Some(CircuitBreaker {
17006            max_failures: 50_000,
17007            window: Duration::from_secs(60),
17008        });
17009        let err = s.validate().unwrap_err();
17010        assert!(
17011            matches!(
17012                err,
17013                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17014                    max_failures: 50_000
17015                }
17016            ),
17017            "got {err:?}"
17018        );
17019        let msg = err.to_string();
17020        assert!(
17021            msg.contains("50000"),
17022            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
17023        );
17024    }
17025
17026    #[test]
17027    fn policy_breaker_max_failures_cap_pins_canonical_value() {
17028        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
17029        // value at 1000 — an order of magnitude above every
17030        // documented production-playbook recommendation band
17031        // (Hystrix `requestVolumeThreshold` default 20, Istio
17032        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
17033        // `outlier_detection.consecutive_5xx` default 5, Polly /
17034        // Resilience4j typical 5..=50) and below the
17035        // clearly-pathological "effectively no protection" floor
17036        // (10_000, 100_000, u32::MAX). Pinning the literal value
17037        // here surfaces a future drift (a relaxation to 10_000, a
17038        // tightening to 100) as a deliberate test edit, not a
17039        // silent contract narrowing.
17040        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
17041    }
17042
17043    #[test]
17044    fn rejects_circuit_breaker_zero_window() {
17045        let mut s = three_member_spec();
17046        s.politicas.circuit_breaker = Some(CircuitBreaker {
17047            max_failures: 5,
17048            window: Duration::ZERO,
17049        });
17050        assert_eq!(
17051            s.validate().unwrap_err(),
17052            AplicacaoError::PolicyBreakerZeroWindow
17053        );
17054    }
17055
17056    #[test]
17057    fn rejects_zero_rate_limit() {
17058        let mut s = three_member_spec();
17059        s.politicas.rate_limit = Some(RateLimit {
17060            rate: 0,
17061            window: Duration::from_secs(1),
17062        });
17063        assert_eq!(
17064            s.validate().unwrap_err(),
17065            AplicacaoError::PolicyRateLimitZero
17066        );
17067    }
17068
17069    #[test]
17070    fn rejects_rate_limit_zero_window() {
17071        // `RateLimit { rate: 100, window: Duration::ZERO }` is
17072        // constructible programmatically (the typed `Duration` field
17073        // imposes no nonzero invariant) but renders through
17074        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
17075        // codec's `parse` rejects as `unknown rate-limit window unit
17076        // "0s"`. Until this validate-time gate landed the typed slot
17077        // accepted the value silently and the round-trip break only
17078        // surfaced at deserialize time (potentially in a downstream
17079        // consumer that never re-validates). Pin the rejection at
17080        // `AplicacaoSpec::validate` so the typed slot's valid set
17081        // matches the codec's round-trippable set structurally.
17082        let mut s = three_member_spec();
17083        s.politicas.rate_limit = Some(RateLimit {
17084            rate: 100,
17085            window: Duration::ZERO,
17086        });
17087        assert_eq!(
17088            s.validate().unwrap_err(),
17089            AplicacaoError::PolicyRateLimitWindowNotCanonical {
17090                window: Duration::ZERO
17091            }
17092        );
17093    }
17094
17095    #[test]
17096    fn rejects_rate_limit_arbitrary_seconds_window() {
17097        // 45 seconds is a valid `Duration` but not one of the three
17098        // canonical rate-limit windows the codec round-trips
17099        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
17100        // refuses on round-trip — same round-trip-break shape the
17101        // zero-window arm above pins, with a non-zero magnitude to
17102        // guard against a future "reject only zero" half-measure.
17103        let mut s = three_member_spec();
17104        let window = Duration::from_secs(45);
17105        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
17106        assert_eq!(
17107            s.validate().unwrap_err(),
17108            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17109        );
17110    }
17111
17112    #[test]
17113    fn rejects_rate_limit_two_minute_window() {
17114        // 120 seconds = 2 minutes is a "looks-canonical" but
17115        // not-canonical window: it's a clean integer multiple of the
17116        // minute unit, but the codec only round-trips the
17117        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
17118        // A `Duration::from_secs(120)` window renders as `"100/120s"`
17119        // which the parser rejects. Pinning this case rules out a
17120        // future "accept any clean multiple of s/m/h" relaxation
17121        // that would silently break the codec contract.
17122        let mut s = three_member_spec();
17123        let window = Duration::from_secs(120);
17124        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
17125        assert_eq!(
17126            s.validate().unwrap_err(),
17127            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17128        );
17129    }
17130
17131    #[test]
17132    fn rejects_rate_limit_subsecond_window() {
17133        // A sub-second window (e.g. 500ms) is a valid `Duration` but
17134        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
17135        // Pin the rejection so a future relaxation can't silently
17136        // admit fractional-second windows that the codec can't
17137        // round-trip.
17138        let mut s = three_member_spec();
17139        let window = Duration::from_millis(500);
17140        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
17141        assert_eq!(
17142            s.validate().unwrap_err(),
17143            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17144        );
17145    }
17146
17147    #[test]
17148    fn rejects_policy_rate_limit_above_cap() {
17149        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
17150        // is structurally one past the cap and silently passed
17151        // validate on every pre-gate codebase because the typed slot's
17152        // only `rate` check was the zero-floor arm. The no-op-limiter
17153        // shape only surfaced at the runtime substrate (Envoy's
17154        // `local_rate_limit.token_bucket.max_tokens`, the future
17155        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
17156        // with no field naming the offending policy.
17157        let mut s = three_member_spec();
17158        s.politicas.rate_limit = Some(RateLimit {
17159            rate: POLICY_RATE_LIMIT_MAX + 1,
17160            window: Duration::from_secs(1),
17161        });
17162        assert_eq!(
17163            s.validate().unwrap_err(),
17164            AplicacaoError::PolicyRateLimitExceedsCap {
17165                rate: POLICY_RATE_LIMIT_MAX + 1
17166            }
17167        );
17168    }
17169
17170    #[test]
17171    fn rejects_policy_rate_limit_far_above_cap() {
17172        // The `u32::MAX` worst case — the four-billion-token rate-limit
17173        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
17174        // copy-paste lands in the slot. Pin the cap arm's coverage
17175        // explicitly across the full `u32` overflow so a future
17176        // relaxation that drops the upper bound surfaces here. Peer to
17177        // `rejects_policy_retries_far_above_cap` on the sibling
17178        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
17179        // on the sibling `:max-failures` axis.
17180        let mut s = three_member_spec();
17181        s.politicas.rate_limit = Some(RateLimit {
17182            rate: u32::MAX,
17183            window: Duration::from_secs(1),
17184        });
17185        assert_eq!(
17186            s.validate().unwrap_err(),
17187            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
17188        );
17189    }
17190
17191    #[test]
17192    fn accepts_policy_rate_limit_at_cap() {
17193        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
17194        // must validate. The cap is inclusive on the top edge, matching
17195        // every other typed upper bound in this crate
17196        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
17197        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
17198        // across all three canonical windows so a future off-by-one
17199        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
17200        // window-conditional cap surfaces here as a test failure rather
17201        // than a silent contract narrowing.
17202        for secs in [1u64, 60, 3600] {
17203            let mut s = three_member_spec();
17204            s.politicas.rate_limit = Some(RateLimit {
17205                rate: POLICY_RATE_LIMIT_MAX,
17206                window: Duration::from_secs(secs),
17207            });
17208            s.validate().unwrap_or_else(|e| {
17209                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
17210            });
17211        }
17212    }
17213
17214    #[test]
17215    fn accepts_policy_rate_limit_typical_values() {
17216        // The documented production-playbook recommendation band —
17217        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
17218        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
17219        // Enterprise ~1M per-hour. Every value in the validated set
17220        // must pass; pin the band explicitly so a future tightening
17221        // surfaces here.
17222        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
17223            for secs in [1u64, 60, 3600] {
17224                let mut s = three_member_spec();
17225                s.politicas.rate_limit = Some(RateLimit {
17226                    rate,
17227                    window: Duration::from_secs(secs),
17228                });
17229                s.validate().unwrap_or_else(|e| {
17230                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
17231                });
17232            }
17233        }
17234    }
17235
17236    #[test]
17237    fn policy_rate_limit_zero_takes_precedence_over_cap() {
17238        // The cross-arm ordering pin: `rate == 0` is structurally
17239        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
17240        // (cap), but the zero-floor diagnostic is the more
17241        // self-locating one (it directly names the omit-axis
17242        // remediation). Pin the order so a future refactor that
17243        // reorders the arms surfaces here as a test failure rather
17244        // than a silent diagnostic regression. Same shape every other
17245        // zero-then-cap ordering on this surface uses
17246        // ([`AplicacaoError::PolicyRetriesZero`] then
17247        // [`AplicacaoError::PolicyRetriesExceedsCap`];
17248        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17249        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17250        let mut s = three_member_spec();
17251        s.politicas.rate_limit = Some(RateLimit {
17252            rate: 0,
17253            window: Duration::from_secs(1),
17254        });
17255        assert_eq!(
17256            s.validate().unwrap_err(),
17257            AplicacaoError::PolicyRateLimitZero,
17258            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
17259        );
17260    }
17261
17262    #[test]
17263    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
17264        // Two-axis-bad pin: rate above cap *and* window non-canonical.
17265        // The validate gate must fire on the rate cap first — the
17266        // amplification-shape (no-op limiter) diagnostic is the more
17267        // fundamental one; the window-canonical diagnostic is the
17268        // narrower codec-round-trip shape. Pin the ordering so a future
17269        // refactor that reorders the rate-then-window check arms
17270        // surfaces here as a test failure rather than a silent
17271        // diagnostic regression.
17272        let mut s = three_member_spec();
17273        s.politicas.rate_limit = Some(RateLimit {
17274            rate: POLICY_RATE_LIMIT_MAX + 1,
17275            window: Duration::from_secs(45),
17276        });
17277        assert_eq!(
17278            s.validate().unwrap_err(),
17279            AplicacaoError::PolicyRateLimitExceedsCap {
17280                rate: POLICY_RATE_LIMIT_MAX + 1
17281            },
17282            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
17283        );
17284    }
17285
17286    #[test]
17287    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
17288        // The diagnostic-shape pin: the offending `u32` is carried
17289        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
17290        // variant so the surfaced error message names the value the
17291        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
17292        // the mesh-policy ceiling …"`), not just the cap. Same
17293        // self-locating diagnostic shape every other typed-cap arm on
17294        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
17295        // carries the offending retries count verbatim,
17296        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
17297        // the offending failure count verbatim).
17298        let mut s = three_member_spec();
17299        s.politicas.rate_limit = Some(RateLimit {
17300            rate: 5_000_000,
17301            window: Duration::from_secs(1),
17302        });
17303        let err = s.validate().unwrap_err();
17304        assert!(
17305            matches!(
17306                err,
17307                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
17308            ),
17309            "got {err:?}"
17310        );
17311        let msg = err.to_string();
17312        assert!(
17313            msg.contains("5000000"),
17314            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
17315        );
17316    }
17317
17318    #[test]
17319    fn policy_rate_limit_cap_pins_canonical_value() {
17320        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
17321        // 1_000_000 — two-to-three orders of magnitude above every
17322        // documented production-playbook recommendation band (Envoy /
17323        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
17324        // Gateway 10_000..=100_000 per-minute) and below the
17325        // clearly-pathological "paste-from-binary blob" floor
17326        // (100_000_000, u32::MAX). Pinning the literal value here
17327        // surfaces a future drift (a relaxation to 10_000_000, a
17328        // tightening to 100_000) as a deliberate test edit, not a
17329        // silent contract narrowing.
17330        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
17331    }
17332
17333    #[test]
17334    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
17335        // Both axes are invalid here: rate == 0 *and* window is
17336        // non-canonical. The validate gate must fire on rate first
17337        // (matching the existing `rejects_zero_rate_limit` ordering),
17338        // so the existing diagnostic continues to lead with the
17339        // simpler "zero rate" framing. Pinning the order of checks
17340        // so a future refactor that reorders the arms surfaces here
17341        // as a test failure rather than a silent diagnostic
17342        // regression.
17343        let mut s = three_member_spec();
17344        s.politicas.rate_limit = Some(RateLimit {
17345            rate: 0,
17346            window: Duration::from_secs(45),
17347        });
17348        assert_eq!(
17349            s.validate().unwrap_err(),
17350            AplicacaoError::PolicyRateLimitZero
17351        );
17352    }
17353
17354    #[test]
17355    fn rate_limit_canonical_windows_validate() {
17356        // The three canonical windows the codec round-trips
17357        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
17358        // unchanged. Pin the full canonical set as a positive case
17359        // (the existing `rate_limit_round_trip_seconds` /
17360        // `rate_limit_round_trip_minutes` tests pin the
17361        // serialize-then-deserialize property at the codec layer; this
17362        // test pins the validate-side complement so a future tightening
17363        // of the canonical set — e.g. dropping `:hour` — surfaces here
17364        // as a test failure rather than a silent contract narrowing).
17365        for secs in [1u64, 60, 3600] {
17366            let mut s = three_member_spec();
17367            s.politicas.rate_limit = Some(RateLimit {
17368                rate: 100,
17369                window: Duration::from_secs(secs),
17370            });
17371            s.validate().expect("canonical window must validate");
17372        }
17373    }
17374
17375    #[test]
17376    fn rate_limit_validated_value_round_trips_through_codec() {
17377        // The structural property the validate gate enforces:
17378        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
17379        // losslessly through the `rate_limit_codec` (serialize → string
17380        // → deserialize → equal value). Pin this end-to-end so a future
17381        // change to either side (the validate gate's accepted window
17382        // set, the codec's parse/render unit set) that breaks the
17383        // alignment surfaces here. The previous-state shape (typed
17384        // slot accepts arbitrary `Duration`, codec only round-trips
17385        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
17386        // window — the validate gate now forecloses that.
17387        for secs in [1u64, 60, 3600] {
17388            let mut s = three_member_spec();
17389            s.politicas.rate_limit = Some(RateLimit {
17390                rate: 250,
17391                window: Duration::from_secs(secs),
17392            });
17393            s.validate().unwrap();
17394            let json = serde_json::to_string(&s.politicas).unwrap();
17395            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17396            assert_eq!(
17397                back.rate_limit, s.politicas.rate_limit,
17398                "every validated :rate-limit must round-trip losslessly through the codec"
17399            );
17400        }
17401    }
17402
17403    #[test]
17404    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
17405        // The hour-window canonical form (`"<n>/h"`) was missing from
17406        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
17407        // pair. Now that the validate gate pins 3600s as part of the
17408        // canonical set, pin its serialize-side render shape too so
17409        // the third leg of the s/m/h tripod is explicitly tested.
17410        let policy = MeshPolicy {
17411            rate_limit: Some(RateLimit {
17412                rate: 10000,
17413                window: Duration::from_secs(3600),
17414            }),
17415            ..Default::default()
17416        };
17417        let json = serde_json::to_string(&policy).unwrap();
17418        assert!(
17419            json.contains("\"10000/h\""),
17420            "hour-window canonical form must render with `h` suffix (got: {json})"
17421        );
17422        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17423        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
17424    }
17425
17426    #[test]
17427    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
17428        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
17429        // typed accessor's accepted-window set against the codec's
17430        // accepted set explicitly. A future addition to the codec
17431        // (e.g. accepting `:day`/`:week` as authoring units) must be
17432        // accompanied by a parallel addition here, and a regression
17433        // that drops one of the three canonical units from either
17434        // side surfaces as a test failure. The accessor is the
17435        // single source of truth for the canonical-window set —
17436        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
17437        // gate and [`rate_limit_codec::render`]'s canonical arm both
17438        // read through it — this test enshrines that its
17439        // `Duration → Option<RateLimitUnit>` projection matches the
17440        // codec's parse / render arms' accepted-window set exactly.
17441        //
17442        // Predecessor: this pin previously read the module-private
17443        // free helper `is_canonical_rate_limit_window` — a delegate
17444        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
17445        // — but the helper had no production consumers left after the
17446        // validate-gate migration onto [`RateLimit::canonical_unit`]
17447        // and was deleted; the closed-set arm-window bijection now
17448        // lives on exactly one typed dispatch on the substrate
17449        // primitive.
17450        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
17451            RateLimit { rate: 1, window }.canonical_unit()
17452        };
17453        assert!(canonical_unit(Duration::from_secs(1)).is_some());
17454        assert!(canonical_unit(Duration::from_secs(60)).is_some());
17455        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
17456        // Non-canonical windows the accessor rejects.
17457        assert!(canonical_unit(Duration::ZERO).is_none());
17458        assert!(canonical_unit(Duration::from_secs(2)).is_none());
17459        assert!(canonical_unit(Duration::from_secs(30)).is_none());
17460        assert!(canonical_unit(Duration::from_secs(120)).is_none());
17461        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
17462        // Sub-second windows: even `Duration::from_millis(1000)` is
17463        // exactly 1s and accepted; `Duration::from_millis(500)` is
17464        // sub-second and rejected.
17465        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
17466        assert!(canonical_unit(Duration::from_millis(500)).is_none());
17467        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
17468    }
17469
17470    #[test]
17471    fn rate_limit_unit_table_projections_are_mutual_inverses() {
17472        // Bidirection pin against the closed-set typed enum
17473        // [`RateLimitUnit`] arm-table (the canonical
17474        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
17475        // of the rate-limit unit surface reads from). The two
17476        // projection directions [`RateLimitUnit::from_suffix`] /
17477        // [`RateLimitUnit::window`] (str → Duration, exposed as one
17478        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
17479        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
17480        // (Duration → str, exposed as one typed dispatch through
17481        // [`RateLimit::canonical_unit`] composed with
17482        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
17483        // codec's parse arm ([`rate_limit_codec::parse`] via
17484        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
17485        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
17486        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
17487        // via [`RateLimit::canonical_unit`]) all key off. A future
17488        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
17489        // sub-second window) is one variant + one arm per method on the
17490        // closed-set enum; the compiler-enforced exhaustiveness on
17491        // every consumer's `match self` arms picks it up by
17492        // construction. This pin enshrines that both projection
17493        // directions agree on every canonical arm row and neither
17494        // leaks a spurious entry the other doesn't recognize.
17495        //
17496        // Predecessor: this test previously read the two vestigial
17497        // module-private free helpers `rate_limit_window_unit` and
17498        // `rate_limit_window_from_unit` on the `Duration → &str` and
17499        // `&str → Duration` axes; the former was deleted after its
17500        // sole production consumer ([`rate_limit_codec::render`])
17501        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
17502        // the latter is folded here into the substrate primitive
17503        // [`RateLimitUnit::window_from_suffix`] so both projection
17504        // directions live on the closed-set enum's arm-table.
17505        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
17506            let window = super::RateLimitUnit::window_from_suffix(unit)
17507                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
17508            assert_eq!(
17509                window,
17510                Duration::from_secs(secs),
17511                "unit {unit:?} must resolve to {secs}s"
17512            );
17513            let projected_suffix = RateLimit { rate: 1, window }
17514                .canonical_unit()
17515                .map(super::RateLimitUnit::as_suffix);
17516            assert_eq!(
17517                projected_suffix,
17518                Some(unit),
17519                "Duration({secs}s) must render as {unit:?} \
17520                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
17521            );
17522        }
17523        // Non-table units yield None on the `unit → Duration`
17524        // projection — a future `"d"` addition to the table would
17525        // flip this arm; today it pins the current three-row table's
17526        // rejection semantics.
17527        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
17528        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
17529        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
17530        // Non-table Durations yield None on the `Duration → unit`
17531        // projection — pins that the two projections agree on the
17532        // "not in the table" semantic too, so a drift where the
17533        // parse-side accepts a value the render-side can't emit is
17534        // a build error at the two-arm pair, not a silent codec
17535        // round-trip break.
17536        let projected_suffix = |window: Duration| -> Option<&'static str> {
17537            RateLimit { rate: 1, window }
17538                .canonical_unit()
17539                .map(super::RateLimitUnit::as_suffix)
17540        };
17541        assert!(projected_suffix(Duration::from_secs(2)).is_none());
17542        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
17543        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
17544    }
17545
17546    #[test]
17547    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
17548        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
17549        // substrate-primitive `&str → Duration` associated method the
17550        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
17551        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
17552        // to the same [`Duration`] the two-step composition
17553        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
17554        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
17555        // `"MIN"`) must project to [`None`] on both paths. A future
17556        // implementation of `window_from_suffix` that took a shortcut
17557        // through a per-suffix `match` table (bypassing the arm-table's
17558        // `Self::from_suffix` scan and the arm-table's `Self::window`
17559        // dispatch) would silently split the accept-set — the parse
17560        // arm would accept a suffix the enum's arm-table doesn't know,
17561        // or reject a suffix the enum's arm-table does; this pin
17562        // surfaces that drift at caixa-core build time rather than at a
17563        // downstream serde round-trip audit on a live `MeshPolicy`.
17564        //
17565        // Same byte-parity discipline the sibling
17566        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
17567        // pin carries on the peer `Duration → RateLimitUnit` axis via
17568        // [`RateLimit::canonical_unit`], and the peer
17569        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17570        // carries on the bidirectional arm-table axis — extended here
17571        // onto the fifth (and last unlifted) projection axis on the
17572        // closed-set enum's arm-table.
17573        let composition = |suffix: &str| -> Option<Duration> {
17574            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
17575        };
17576        for suffix in ["s", "m", "h"] {
17577            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17578            let via_composition = composition(suffix);
17579            assert_eq!(
17580                via_method, via_composition,
17581                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17582                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
17583                 method must delegate to the arm-table's two typed dispatches, \
17584                 not shortcut through a per-suffix match table"
17585            );
17586            assert!(
17587                via_method.is_some(),
17588                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
17589                 RateLimitUnit::window_from_suffix"
17590            );
17591        }
17592        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
17593            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17594            let via_composition = composition(suffix);
17595            assert_eq!(
17596                via_method, via_composition,
17597                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17598                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
17599                 axis too"
17600            );
17601            assert!(
17602                via_method.is_none(),
17603                "non-arm suffix {suffix:?} must project to None via \
17604                 RateLimitUnit::window_from_suffix — a future extension that \
17605                 accepted this suffix without a corresponding arm on the enum \
17606                 would split the codec's parse-accepted set from the enum's \
17607                 arm-table"
17608            );
17609        }
17610        // And the codec's parse arm now reads through this method: a
17611        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
17612        // the same `Duration` the method returns for its unit, closing
17613        // the two-consumer drift surface (the codec's parse arm and the
17614        // enum's arm-table) with one typed dispatch on the substrate
17615        // primitive.
17616        for suffix in ["s", "m", "h"] {
17617            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
17618            let mp: MeshPolicy = serde_json::from_str(&wire)
17619                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
17620            let parsed = mp.rate_limit().expect("rate_limit payload present");
17621            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
17622                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
17623            assert_eq!(
17624                parsed.window(),
17625                via_method,
17626                "codec parse arm on {wire:?} must resolve the window through \
17627                 RateLimitUnit::window_from_suffix, not a divergent path"
17628            );
17629        }
17630    }
17631
17632    #[test]
17633    fn rate_limit_unit_all_enumerates_every_arm_once() {
17634        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
17635        // enumerate every arm of the closed-set enum exactly once, in
17636        // the canonical shortest-to-longest window order (Second before
17637        // Minute before Hour) — the same order the sibling
17638        // [`crate::supervisor::RestartStrategy`] /
17639        // [`crate::supervisor::RestartPolicy`] /
17640        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
17641        // typed enums carry (the arm declared first is the arm listed
17642        // first). A future variant addition that extends the enum
17643        // without appending to [`RateLimitUnit::ALL`] leaves the
17644        // exhaustive iteration surface silently short one arm — the
17645        // codec's parse arm would then reject the new suffix even
17646        // though the enum knows it. This pin closes the drift.
17647        assert_eq!(
17648            super::RateLimitUnit::ALL,
17649            &[
17650                super::RateLimitUnit::Second,
17651                super::RateLimitUnit::Minute,
17652                super::RateLimitUnit::Hour,
17653            ],
17654            "RateLimitUnit::ALL must enumerate every arm exactly once, \
17655             in canonical shortest-to-longest window order"
17656        );
17657    }
17658
17659    #[test]
17660    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
17661        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
17662        // every arm's [`RateLimitUnit::as_suffix`] output must parse
17663        // back through [`RateLimitUnit::from_suffix`] to the same
17664        // variant. A future arm addition that lands `as_suffix` but
17665        // forgets `from_suffix` (`from_suffix` iterates
17666        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
17667        // is the load-bearing carrier of the round-trip; the sibling
17668        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
17669        // the `ALL` half) trips here at caixa-core build time rather
17670        // than surfacing as a codec round-trip miss (a `render` emit
17671        // that lands a suffix the paired `parse` cannot decode).
17672        for unit in super::RateLimitUnit::ALL {
17673            let suffix = unit.as_suffix();
17674            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
17675                panic!(
17676                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
17677                     RateLimitUnit::as_suffix output — got None for {unit:?}"
17678                )
17679            });
17680            assert_eq!(
17681                parsed, *unit,
17682                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
17683                 must return RateLimitUnit::{unit:?}"
17684            );
17685        }
17686    }
17687
17688    #[test]
17689    fn rate_limit_unit_from_window_and_window_round_trip() {
17690        // Total round-trip pin on the `(from_window, window)` pair:
17691        // every arm's [`RateLimitUnit::window`] output must parse back
17692        // through [`RateLimitUnit::from_window`] to the same variant.
17693        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
17694        // on the peer `Duration` axis — the two round-trip pins
17695        // together enshrine that both projections of the typed
17696        // canonical-unit bijection are total on the arm-set.
17697        for unit in super::RateLimitUnit::ALL {
17698            let window = unit.window();
17699            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
17700                panic!(
17701                    "RateLimitUnit::from_window({window:?}) must accept every \
17702                     RateLimitUnit::window output — got None for {unit:?}"
17703                )
17704            });
17705            assert_eq!(
17706                parsed, *unit,
17707                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17708                 must return RateLimitUnit::{unit:?}"
17709            );
17710        }
17711    }
17712
17713    #[test]
17714    fn rate_limit_unit_from_window_accessor_is_const_fn() {
17715        // Fail-before-pass-after pin: witnesses the
17716        // [`RateLimitUnit::from_window`] `const`-eval posture via a
17717        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
17718        // -> Option<RateLimitUnit>` whose body calls
17719        // `RateLimitUnit::from_window(window)`, well-formed only when
17720        // the callee is itself `const fn` (any future downgrade to
17721        // non-`const` fails at caixa-core build time with E0015 `cannot
17722        // call non-const function`, strictly stronger than a runtime
17723        // `assert!`, side-stepping the destructor-in-const restriction
17724        // that blocks direct `const _: Option<RateLimitUnit> =
17725        // RateLimitUnit::from_window(...)` items on `Duration`'s
17726        // carrier). The runtime body sweeps every closed-set
17727        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
17728        // rejection sample (`Duration::from_millis(500)` sub-second
17729        // residue) and asserts the wrapped and direct dispatches agree
17730        // — a violation means the wrapper stopped compiling under a
17731        // future `const`-posture downgrade, or the reverse resolver's
17732        // arm-set silently split from the peer `Self::window` emitter's
17733        // arm-set. Peer of the sibling
17734        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
17735        // (152c868) /
17736        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
17737        // (152c868) /
17738        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
17739        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
17740        // `const`-eval-surface pins on the peer M2 / M3 substrate-
17741        // primitive `Copy`-return accessor axes, extended onto the
17742        // reverse `Duration → RateLimitUnit` projection axis on the
17743        // M3 mesh-slot rate-limit closed-set typed enum.
17744        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
17745            super::RateLimitUnit::from_window(window)
17746        }
17747        for unit in super::RateLimitUnit::ALL {
17748            let window = unit.window();
17749            let via_wrapper = from_window_via_const_fn(window);
17750            let direct = super::RateLimitUnit::from_window(window);
17751            assert_eq!(
17752                via_wrapper, direct,
17753                "RateLimitUnit::from_window({window:?}) via const fn \
17754                 wrapper must agree with direct dispatch for {unit:?}"
17755            );
17756            assert_eq!(
17757                via_wrapper,
17758                Some(*unit),
17759                "RateLimitUnit::from_window({window:?}) via const fn \
17760                 wrapper must return Some({unit:?}) for the peer \
17761                 window() output"
17762            );
17763        }
17764        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
17765        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
17766    }
17767
17768    #[test]
17769    fn rate_limit_unit_from_window_composes_through_window_accessor() {
17770        // Composition-witness pin on the routing-through-peer discipline:
17771        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
17772        // through the peer `pub const fn` [`RateLimitUnit::window`]
17773        // canonical-`Duration` projection rather than a hand-authored
17774        // per-arm second-magnitude literal — a future arm-magnitude edit
17775        // on the sibling `window()` accessor (a `Second → 2s` typo, a
17776        // `Hour → 3599s` off-by-one) must therefore reach this reverse
17777        // resolver by construction. A pin that hard-coded the three
17778        // second-magnitudes here would silently split from the peer
17779        // emitter on any such edit; instead, this pin asserts the
17780        // composition invariant `from_window(u.window()) == Some(u)`
17781        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
17782        // arm — a violation means either the peer `Self::window`
17783        // accessor drifted (breaking every downstream consumer that
17784        // reads through it), or the reverse resolver stopped routing
17785        // through the peer (introducing a hand-authored literal that
17786        // silently disagrees with the emitter). Either failure is a
17787        // caixa-core-build-time surface, not a downstream renderer
17788        // round-trip regression.
17789        //
17790        // Peer of the sibling
17791        // [`crate::render::assert_str_reexport_identity`] discipline on
17792        // the substrate-primitive `&'static str` re-export axis and the
17793        // [`rate_limit_unit_from_window_and_window_round_trip`]
17794        // round-trip pin on the peer projection direction; extends the
17795        // one-canonical-dispatch-per-projection discipline onto the
17796        // reverse-resolver's per-arm probe axis.
17797        for unit in super::RateLimitUnit::ALL {
17798            let window_via_peer = unit.window();
17799            let resolved = super::RateLimitUnit::from_window(window_via_peer);
17800            assert_eq!(
17801                resolved,
17802                Some(*unit),
17803                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17804                 must return Some({unit:?}) — the reverse resolver's per-arm \
17805                 probes must route through the peer `Self::window` accessor \
17806                 so any future arm-magnitude edit reaches both projection \
17807                 directions by construction"
17808            );
17809        }
17810    }
17811
17812    #[test]
17813    fn rate_limit_canonical_unit_accessor_is_const_fn() {
17814        // Fail-before-pass-after pin: witnesses the
17815        // [`RateLimit::canonical_unit`] `const`-eval posture via a
17816        // `const fn` wrapper
17817        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
17818        // whose body calls `rl.canonical_unit()`, well-formed only when
17819        // the callee is itself `const fn` (any future downgrade to
17820        // non-`const` fails at caixa-core build time with E0015 `cannot
17821        // call non-const method`). The runtime body sweeps every
17822        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
17823        // constructs a typed [`RateLimit`] with the peer `Self::window`
17824        // canonical `Duration`, then asserts both the wrapper and the
17825        // direct dispatch agree and both return `Some(unit)`. Composes
17826        // with the sibling
17827        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
17828        // typed [`RateLimit`] projection layer's `const`-posture is
17829        // load-bearing on the reverse resolver's `const`-posture, and
17830        // both must migrate together (a downgrade of either surface
17831        // splits the paired `const`-eval-surface pass on the M3
17832        // mesh-slot rate-limit `Duration ↔ Self` bijection).
17833        const fn canonical_unit_via_const_fn(
17834            rl: &super::RateLimit,
17835        ) -> Option<super::RateLimitUnit> {
17836            rl.canonical_unit()
17837        }
17838        for unit in super::RateLimitUnit::ALL {
17839            let rl = super::RateLimit {
17840                rate: 1,
17841                window: unit.window(),
17842            };
17843            let via_wrapper = canonical_unit_via_const_fn(&rl);
17844            let direct = rl.canonical_unit();
17845            assert_eq!(
17846                via_wrapper, direct,
17847                "RateLimit::canonical_unit() via const fn wrapper must \
17848                 agree with direct dispatch for {unit:?}"
17849            );
17850            assert_eq!(
17851                via_wrapper,
17852                Some(*unit),
17853                "RateLimit::canonical_unit() via const fn wrapper must \
17854                 return Some({unit:?}) for a RateLimit whose window is \
17855                 the peer RateLimitUnit::{unit:?}.window() output"
17856            );
17857        }
17858    }
17859
17860    #[test]
17861    fn rate_limit_unit_projections_are_pairwise_distinct() {
17862        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
17863        // [`RateLimitUnit::window`] outputs must be pairwise distinct
17864        // across every arm — an accidental copy-paste flip that
17865        // reroutes one arm's suffix or window to also match another
17866        // silently collapses two arms onto one, so
17867        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
17868        // (both using `find` on `Self::ALL`) would return whichever
17869        // arm the linear scan lands on first — a match-arm-ordering-
17870        // dependent outcome the closed-set typed-enum shape is meant
17871        // to rule out structurally. Peer of the sibling
17872        // `caixa_kind_wire_consts_are_pairwise_distinct` /
17873        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
17874        // other closed-set typed-enum discriminator axes.
17875        let all = super::RateLimitUnit::ALL;
17876        for (i, a) in all.iter().enumerate() {
17877            for (j, b) in all.iter().enumerate() {
17878                if i != j {
17879                    assert_ne!(
17880                        a.as_suffix(),
17881                        b.as_suffix(),
17882                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
17883                         must be distinct — a collision silently collapses two \
17884                         arms onto one under from_suffix's linear scan"
17885                    );
17886                    assert_ne!(
17887                        a.window(),
17888                        b.window(),
17889                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
17890                         must be distinct — a collision silently collapses two \
17891                         arms onto one under from_window's linear scan"
17892                    );
17893                }
17894            }
17895        }
17896    }
17897
17898    #[test]
17899    fn rate_limit_unit_display_routes_through_as_suffix() {
17900        // Route pin: [`std::fmt::Display`] must byte-equal
17901        // [`RateLimitUnit::as_suffix`] on every arm — the single
17902        // source of truth for the canonical suffix. A future
17903        // reimplementation that hand-rolls the arms instead of
17904        // delegating to [`RateLimitUnit::as_suffix`] would silently
17905        // desynchronize `format!("{u}")` from the codec's parse arm
17906        // (which uses `as_suffix` to compare suffixes). Peer of the
17907        // sibling `caixa_kind_display_routes_through_as_str_helper` /
17908        // `placement_strategy_display_routes_through_as_str_helper`
17909        // pins on the peer closed-set typed-enum Display axes.
17910        for unit in super::RateLimitUnit::ALL {
17911            assert_eq!(
17912                unit.to_string(),
17913                unit.as_suffix(),
17914                "RateLimitUnit::{unit:?} Display must route through \
17915                 as_suffix (single source of truth: the canonical suffix \
17916                 the codec parses and renders)"
17917            );
17918        }
17919    }
17920
17921    #[test]
17922    fn rate_limit_unit_from_window_rejects_non_canonical() {
17923        // Rejection pin on the parser's accept-set: any Duration
17924        // outside the three-arm [`RateLimitUnit::window`] output set
17925        // (sub-second residue, or a second-magnitude outside `{1, 60,
17926        // 3600}`) must return `None`. A future accidental widening of
17927        // the accept-set (rounding down sub-second residue to the
17928        // nearest arm, admitting `Duration::from_secs(30)` as a
17929        // half-minute unit) would silently drift the parser's accept-
17930        // set from the emitter's — a validated slot with a
17931        // non-canonical window would then round-trip through the
17932        // codec to a canonical form the author never wrote.
17933        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
17934        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
17935        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
17936        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
17937        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
17938        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
17939        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
17940    }
17941
17942    #[test]
17943    fn rate_limit_unit_from_suffix_rejects_unknown() {
17944        // Rejection pin on the suffix parser's accept-set: any string
17945        // outside the three-arm [`RateLimitUnit::as_suffix`] output
17946        // set must return `None`. Peer of the sibling
17947        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
17948        // the [`crate::CaixaKind`] `from_wire` accept-set.
17949        for bad in [
17950            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
17951            " s",
17952        ] {
17953            assert!(
17954                super::RateLimitUnit::from_suffix(bad).is_none(),
17955                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
17956                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
17957                 outputs"
17958            );
17959        }
17960    }
17961
17962    #[test]
17963    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
17964        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
17965        // every canonical `:window` magnitude the validate gate
17966        // accepts must map to the paired [`RateLimitUnit`] arm through
17967        // this accessor. A future validate-gate rebrand that widened
17968        // the accepted-window set without extending [`RateLimitUnit`]
17969        // would silently split the accessor's `Some`-return set from
17970        // the validate gate's accept-set — a slot that satisfies
17971        // validate would land at the accessor with `None`, so a
17972        // consumer past validate that pattern-matches on the returned
17973        // `Some` would silently miss the newly-accepted magnitude.
17974        for (window_secs, expected) in [
17975            (1u64, super::RateLimitUnit::Second),
17976            (60, super::RateLimitUnit::Minute),
17977            (3600, super::RateLimitUnit::Hour),
17978        ] {
17979            let rl = RateLimit {
17980                rate: 100,
17981                window: Duration::from_secs(window_secs),
17982            };
17983            assert_eq!(
17984                rl.canonical_unit(),
17985                Some(expected),
17986                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
17987                 must return Some({expected:?})"
17988            );
17989        }
17990        // Non-canonical windows the validate gate rejects also return
17991        // None here — the accessor is the typed-enum projection of
17992        // the sibling `is_canonical_rate_limit_window` predicate.
17993        let bad = RateLimit {
17994            rate: 100,
17995            window: Duration::from_secs(30),
17996        };
17997        assert!(
17998            bad.canonical_unit().is_none(),
17999            "RateLimit with a non-canonical window must return None from \
18000             canonical_unit — the validate gate rejects the same set"
18001        );
18002    }
18003
18004    #[test]
18005    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
18006        // Fail-before-pass-after byte-parity pin: for every canonical
18007        // window the [`rate_limit_codec::render`] arm's emitted string
18008        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
18009        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
18010        // the vestigial free helper [`rate_limit_window_unit`] (a
18011        // `find_map`-walked `Duration → &'static str` delegate) onto the
18012        // substrate primitive [`RateLimit::canonical_unit`] typed method
18013        // (a closed-set `match self.window` arm on
18014        // [`RateLimitUnit::from_window`], projected through
18015        // [`RateLimitUnit::as_suffix`] via the enum's
18016        // [`std::fmt::Display`] impl). A future re-routing of the render
18017        // arm through a differently-computed unit projection would break
18018        // this pin at build time rather than as a silent per-consumer
18019        // codec round-trip drift far from the substrate primitive edit.
18020        //
18021        // Sibling to the peer
18022        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
18023        // on the free-helper axis: that pin locks the two projections
18024        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
18025        // on the closed-set arm table; this pin locks the codec's render
18026        // arm reads through the typed accessor rather than the free
18027        // helper. Two production consumers of the canonical-unit axis
18028        // now key off one typed dispatch on the substrate primitive.
18029        for (window_secs, unit) in [
18030            (1u64, super::RateLimitUnit::Second),
18031            (60, super::RateLimitUnit::Minute),
18032            (3600, super::RateLimitUnit::Hour),
18033        ] {
18034            let rl = RateLimit {
18035                rate: 42,
18036                window: Duration::from_secs(window_secs),
18037            };
18038            let policy = MeshPolicy {
18039                rate_limit: Some(rl),
18040                ..Default::default()
18041            };
18042            let json = serde_json::to_string(&policy).unwrap();
18043            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
18044            assert!(
18045                json.contains(&expected),
18046                "rate_limit_codec::render must emit {expected} (via \
18047                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
18048                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
18049            );
18050            // And the accessor route resolves to the same typed unit
18051            // the render arm's Display formatting is asked to produce —
18052            // so a future edit that split the two paths (one through
18053            // the accessor, one through a re-introduced free helper)
18054            // trips this pin.
18055            assert_eq!(
18056                rl.canonical_unit(),
18057                Some(unit),
18058                "RateLimit::canonical_unit must return Some({unit:?}) for a \
18059                 {window_secs}s window; the codec render arm reads the same \
18060                 typed unit through this accessor"
18061            );
18062        }
18063    }
18064
18065    #[test]
18066    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
18067        // Fail-before-pass-after byte-parity pin on the validate gate's
18068        // canonical-window shape probe: every non-canonical `:window`
18069        // the free-helper predicate [`is_canonical_rate_limit_window`]
18070        // rejects is also rejected by the substrate primitive
18071        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
18072        // gate now reads through, and vice versa on the accepted set
18073        // (the three canonical windows). Locks the migration from the
18074        // free helper onto the substrate primitive: a future re-routing
18075        // of one of the two paths through a differently-computed unit
18076        // projection would silently split the codec's accepted set from
18077        // the validate gate's accepted set — a two-consumer drift the
18078        // codec-round-trip pin
18079        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
18080        // above closes on the render arm and this pin closes on the
18081        // validate arm.
18082        for canonical_window_secs in [1u64, 60, 3600] {
18083            let mut s = three_member_spec();
18084            let rl = RateLimit {
18085                rate: 100,
18086                window: Duration::from_secs(canonical_window_secs),
18087            };
18088            s.politicas.rate_limit = Some(rl);
18089            assert!(
18090                s.validate().is_ok(),
18091                "canonical {canonical_window_secs}s window must pass \
18092                 validate_politicas — the validate gate now reads \
18093                 RateLimit::canonical_unit().is_none() and the accessor \
18094                 returns Some on every canonical arm"
18095            );
18096            assert!(
18097                rl.canonical_unit().is_some(),
18098                "canonical {canonical_window_secs}s window must resolve to \
18099                 Some on RateLimit::canonical_unit — the validate gate reads \
18100                 this accessor directly"
18101            );
18102        }
18103        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
18104            let mut s = three_member_spec();
18105            let rl = RateLimit {
18106                rate: 100,
18107                window: Duration::from_secs(non_canonical_window_secs),
18108            };
18109            s.politicas.rate_limit = Some(rl);
18110            assert_eq!(
18111                s.validate().unwrap_err(),
18112                AplicacaoError::PolicyRateLimitWindowNotCanonical {
18113                    window: rl.window(),
18114                },
18115                "non-canonical {non_canonical_window_secs}s window must be \
18116                 rejected by validate_politicas — the validate gate now \
18117                 keys off RateLimit::canonical_unit().is_none()"
18118            );
18119            assert!(
18120                rl.canonical_unit().is_none(),
18121                "non-canonical {non_canonical_window_secs}s window must \
18122                 resolve to None on RateLimit::canonical_unit — the two \
18123                 paths (the free helper the validate gate previously read \
18124                 and the substrate primitive the validate gate now reads) \
18125                 must agree on the same rejected set"
18126            );
18127        }
18128        // And the substrate-primitive [`RateLimit::canonical_unit`]
18129        // accessor's accepted-window set matches the codec's parse arm's
18130        // accepted-suffix set on every canonical / non-canonical shape,
18131        // so a future silent drift between the codec's accepted set and
18132        // the validate gate's accepted set is a build error at test time
18133        // (both consumers key off the same closed-set enum's `match self`
18134        // arms). The predecessor free helper `is_canonical_rate_limit_window`
18135        // — a delegate that composed [`RateLimitUnit::from_window`] with
18136        // `.is_some()` — was deleted after this migration; the
18137        // canonical-window set now lives on exactly one typed dispatch
18138        // on the substrate primitive.
18139        for (secs, expected) in [
18140            (1u64, true),
18141            (60, true),
18142            (3600, true),
18143            (2, false),
18144            (30, false),
18145            (86_400, false),
18146        ] {
18147            let window = Duration::from_secs(secs);
18148            let rl = RateLimit { rate: 1, window };
18149            assert_eq!(
18150                rl.canonical_unit().is_some(),
18151                expected,
18152                "RateLimit::canonical_unit().is_some() must agree with the \
18153                 codec-accepted canonical-window set on {secs}s"
18154            );
18155            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
18156                1 => "s",
18157                60 => "m",
18158                3600 => "h",
18159                _ => return,
18160            })
18161            .is_some_and(|d| d == window);
18162            if expected {
18163                assert!(
18164                    suffix_from_axis,
18165                    "the codec's `&str → Duration` axis \
18166                     ({secs}s) must round-trip to the same Duration the \
18167                     substrate primitive's accessor returns Some on"
18168                );
18169            }
18170        }
18171    }
18172
18173    #[test]
18174    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
18175        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
18176        // derive: for each of the three variants, exactly one of the
18177        // generated `is_second` / `is_minute` / `is_hour` predicates
18178        // returns `true` and the other two return `false`. Peer of
18179        // the sibling
18180        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
18181        // sibling `IsVariant`-derived closed-set typed-enum pins.
18182        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
18183            (super::RateLimitUnit::Second, [true, false, false]),
18184            (super::RateLimitUnit::Minute, [false, true, false]),
18185            (super::RateLimitUnit::Hour, [false, false, true]),
18186        ];
18187        for (variant, expected) in rows {
18188            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
18189            assert_eq!(
18190                observed, expected,
18191                "RateLimitUnit::{variant:?} is_* predicates must partition \
18192                 the arm set (second, minute, hour); got {observed:?}"
18193            );
18194        }
18195    }
18196
18197    #[test]
18198    fn rejects_policy_timeout_sub_millisecond() {
18199        // A purely sub-millisecond `Duration` (`from_micros(500)` =
18200        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
18201        // arm passes — but `as_millis() == 0`, so the shared codec's
18202        // `render` arm returns the literal `"0s"`, which the
18203        // codec's `parse` arm then deserializes as `Duration::ZERO`
18204        // and the `PolicyTimeoutZero` zero-floor gate would reject
18205        // on re-validate. Pin the rejection at the typed slot's
18206        // canonical-floor gate so the round-trip break surfaces at
18207        // validate time, naming the offending `Duration`, rather
18208        // than at the next serialize → deserialize round-trip far
18209        // from the source `caixa.lisp`.
18210        let mut s = three_member_spec();
18211        let timeout = Duration::from_micros(500);
18212        s.politicas.timeout = Some(timeout);
18213        assert_eq!(
18214            s.validate().unwrap_err(),
18215            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
18216        );
18217    }
18218
18219    #[test]
18220    fn rejects_policy_timeout_non_integer_millisecond() {
18221        // A `Duration` with non-integer-millisecond residue
18222        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
18223        // through the shared codec's `render` arm as `"1ms"` (the
18224        // `as_millis()` floor truncates), which the codec's `parse`
18225        // arm then deserializes as `Duration::from_millis(1)` =
18226        // 1_000_000 ns — silently *different* from the original.
18227        // Pin the rejection so this round-trip break surfaces at
18228        // validate time, where the offending `Duration` is named,
18229        // rather than as a silent value-laundered round-trip on the
18230        // next codec round-trip.
18231        let mut s = three_member_spec();
18232        let timeout = Duration::from_micros(1500);
18233        s.politicas.timeout = Some(timeout);
18234        assert_eq!(
18235            s.validate().unwrap_err(),
18236            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
18237        );
18238    }
18239
18240    #[test]
18241    fn accepts_policy_timeout_integer_millisecond_forms() {
18242        // The codec's accepted set — integer multiples of 1ms — is
18243        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
18244        // `1h` all pass the canonical gate. Pin the canonical-forms
18245        // sweep so a future tightening of the codec's grammar (e.g.
18246        // dropping `:ms`) surfaces here as a test failure rather
18247        // than a silent contract narrowing on the typed slot.
18248        for timeout in [
18249            Duration::from_millis(1),
18250            Duration::from_millis(500),
18251            Duration::from_millis(1500),
18252            Duration::from_secs(30),
18253            Duration::from_secs(120),
18254            Duration::from_secs(3600),
18255        ] {
18256            let mut s = three_member_spec();
18257            s.politicas.timeout = Some(timeout);
18258            s.validate()
18259                .expect("integer-millisecond :timeout must validate");
18260        }
18261    }
18262
18263    #[test]
18264    fn policy_timeout_zero_takes_precedence_over_canonical() {
18265        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
18266        // pass the canonical-millisecond gate; the more self-locating
18267        // `PolicyTimeoutZero` arm (which names the omit-axis
18268        // remediation directly) must fire first. Pin the ordering so
18269        // a future refactor that reorders the arms surfaces here as a
18270        // test failure rather than a silent diagnostic regression.
18271        let mut s = three_member_spec();
18272        s.politicas.timeout = Some(Duration::ZERO);
18273        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
18274    }
18275
18276    #[test]
18277    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
18278        // The diagnostic envelope carries the offending `Duration`
18279        // verbatim so the author can grep their `caixa.lisp` for
18280        // `:timeout "<value>"` and fix it in one edit. Same
18281        // diagnostic shape every other typed-slot canonical-form
18282        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
18283        // peer `:rate-limit :window` axis.
18284        let mut s = three_member_spec();
18285        let timeout = Duration::from_nanos(1_000_001);
18286        s.politicas.timeout = Some(timeout);
18287        match s.validate().unwrap_err() {
18288            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
18289                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
18290            }
18291            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
18292        }
18293    }
18294
18295    #[test]
18296    fn rejects_policy_timeout_above_cap() {
18297        // The fail-before-pass-after pin: 3601s = 1h + 1s is
18298        // structurally one canonical-tick past the
18299        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
18300        // integer-millisecond magnitude the canonical-form arm above
18301        // accepts cleanly, that the codec round-trips losslessly as
18302        // `"3601s"`, and that silently passed validate on every
18303        // pre-gate codebase because the typed slot's only checks were
18304        // the zero-floor and canonical-form arms. The mesh-level
18305        // deadline degenerates only at the runtime substrate (Envoy
18306        // / Cilium L7 timeout overlay) far from the source
18307        // `caixa.lisp` with no field naming the offending policy.
18308        let mut s = three_member_spec();
18309        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
18310        s.politicas.timeout = Some(timeout);
18311        assert_eq!(
18312            s.validate().unwrap_err(),
18313            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18314        );
18315    }
18316
18317    #[test]
18318    fn rejects_policy_timeout_one_millisecond_above_cap() {
18319        // Boundary case: exactly 1ms past the cap (the granularity
18320        // the canonical-form gate enforces). Catches a future
18321        // "strictly less than" half-measure and pins the diagnostic
18322        // to name the offending `Duration` verbatim. Peer of
18323        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
18324        // boundary pin on the sibling `:limits :memory` top edge.
18325        let mut s = three_member_spec();
18326        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
18327        s.politicas.timeout = Some(timeout);
18328        assert_eq!(
18329            s.validate().unwrap_err(),
18330            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18331        );
18332    }
18333
18334    #[test]
18335    fn rejects_policy_timeout_far_above_cap() {
18336        // The "obvious authoring footgun" case: a `(:timeout "24h")`
18337        // or `(:timeout "86400s")` — values the canonical-form arm
18338        // accepts as integer-millisecond magnitudes, the codec
18339        // round-trips losslessly through serde, but the mesh-level
18340        // policy cannot honor (a 24-hour synchronous-`:contratos`
18341        // deadline is operationally indistinguishable from
18342        // omit-the-axis). Until this gate landed validate accepted
18343        // it. Pin both common above-cap values (24h, 7d) so a future
18344        // relaxation that drops the upper bound surfaces here.
18345        for timeout in [
18346            Duration::from_secs(86_400),    // 24h
18347            Duration::from_secs(604_800),   // 7d
18348            Duration::from_secs(1_000_000), // ~11.5 days
18349        ] {
18350            let mut s = three_member_spec();
18351            s.politicas.timeout = Some(timeout);
18352            assert_eq!(
18353                s.validate().unwrap_err(),
18354                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18355            );
18356        }
18357    }
18358
18359    #[test]
18360    fn accepts_policy_timeout_at_cap() {
18361        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
18362        // must validate. The cap is inclusive on the top edge,
18363        // matching the [`POLICY_RETRIES_MAX`] /
18364        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
18365        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18366        // sibling capped axes. Pin the boundary explicitly so a
18367        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
18368        // instead of `>`) surfaces here as a test failure rather
18369        // than a silent contract narrowing.
18370        let mut s = three_member_spec();
18371        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
18372        s.validate()
18373            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
18374    }
18375
18376    #[test]
18377    fn accepts_policy_timeout_typical_values() {
18378        // The documented production-playbook band positive-control
18379        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
18380        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
18381        // plus a sweep through the long-running-workflow band
18382        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
18383        // validated set explicitly so a future tightening of the
18384        // ceiling surfaces here as a deliberate test edit, not a
18385        // silent contract narrowing.
18386        for timeout in [
18387            Duration::from_millis(1),
18388            Duration::from_millis(500),
18389            Duration::from_secs(1),
18390            Duration::from_secs(10),
18391            Duration::from_secs(15), // Envoy default
18392            Duration::from_secs(30),
18393            Duration::from_secs(60), // AWS App Mesh typical
18394            Duration::from_secs(300),
18395            Duration::from_secs(900),
18396            Duration::from_secs(1800),
18397            Duration::from_secs(3600), // exactly 1h, the cap
18398        ] {
18399            let mut s = three_member_spec();
18400            s.politicas.timeout = Some(timeout);
18401            s.validate()
18402                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
18403        }
18404    }
18405
18406    #[test]
18407    fn policy_timeout_zero_takes_precedence_over_cap() {
18408        // The cross-arm ordering pin: `Duration::ZERO` is
18409        // structurally outside both `>= 1ms` (zero-floor) and
18410        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
18411        // diagnostic is the more self-locating one (it directly
18412        // names the omit-axis remediation), so the validate gate
18413        // must fire on zero first. Same shape every other
18414        // zero-then-shape ordering on this surface uses
18415        // ([`AplicacaoError::PolicyRetriesZero`] then
18416        // [`AplicacaoError::PolicyRetriesExceedsCap`];
18417        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18418        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18419        let mut s = three_member_spec();
18420        s.politicas.timeout = Some(Duration::ZERO);
18421        assert_eq!(
18422            s.validate().unwrap_err(),
18423            AplicacaoError::PolicyTimeoutZero,
18424            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18425        );
18426    }
18427
18428    #[test]
18429    fn policy_timeout_canonical_takes_precedence_over_cap() {
18430        // The cross-arm ordering pin: a `Duration` that is *both*
18431        // sub-millisecond (non-canonical-form) and structurally
18432        // above the cap surfaces the canonical-form diagnostic
18433        // first, because the round-trip-shape break is the more
18434        // fundamental issue (the value can't even round-trip
18435        // through the codec, so the cap diagnostic naming
18436        // `1ms..=1h` would be misleading — there's no integer-ms
18437        // form of the offending value). Pin the order so a future
18438        // refactor that reorders the arms surfaces here as a test
18439        // failure rather than a silent diagnostic regression.
18440        let mut s = three_member_spec();
18441        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
18442        // *and* total magnitude above the 1h cap.
18443        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
18444        s.politicas.timeout = Some(timeout);
18445        assert_eq!(
18446            s.validate().unwrap_err(),
18447            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
18448            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18449        );
18450    }
18451
18452    #[test]
18453    fn policy_timeout_cap_diagnostic_carries_offending_value() {
18454        // The diagnostic-shape pin: the offending `Duration` is
18455        // carried verbatim into the
18456        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
18457        // surfaced error message names the value the author wrote
18458        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
18459        // exceeds the mesh-policy ceiling …"`), not just the cap.
18460        // Same self-locating diagnostic shape every other typed-cap
18461        // arm on this surface carries
18462        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
18463        // offending retry count verbatim).
18464        let mut s = three_member_spec();
18465        let timeout = Duration::from_secs(7200); // 2h
18466        s.politicas.timeout = Some(timeout);
18467        let err = s.validate().unwrap_err();
18468        assert!(
18469            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
18470            "got {err:?}"
18471        );
18472        let msg = err.to_string();
18473        assert!(
18474            msg.contains("7200"),
18475            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
18476        );
18477    }
18478
18479    #[test]
18480    fn policy_timeout_cap_pins_canonical_value() {
18481        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
18482        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
18483        // the shared duration codec emits as a clean canonical
18484        // string (`"<n>h"`). Pinning the literal value here surfaces
18485        // a future drift (a relaxation to 24h, a tightening to 5m)
18486        // as a deliberate test edit, not a silent contract
18487        // narrowing. Same shape every other typed-cap value pin on
18488        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
18489        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
18490        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
18491    }
18492
18493    #[test]
18494    fn policy_timeout_cap_value_round_trips_through_codec() {
18495        // The codec round-trip property the cap arm preserves: the
18496        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
18497        // the shared duration codec — every value at the cap renders
18498        // to a clean canonical string (`"1h"`) and parses back to
18499        // the same `Duration`. Pin this so a future drift between
18500        // the cap constant and the codec's largest emitted unit
18501        // surfaces here. Same shape every other typed boundary pin
18502        // on this surface uses
18503        // (`wasm32_memory_cap_matches_parsed_4_gib`).
18504        let policy = MeshPolicy {
18505            timeout: Some(POLICY_TIMEOUT_MAX),
18506            ..Default::default()
18507        };
18508        let json = serde_json::to_string(&policy).unwrap();
18509        // The codec emits `"1h"` for the canonical 1-hour magnitude.
18510        assert!(
18511            json.contains("\"1h\""),
18512            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
18513        );
18514        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18515        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
18516    }
18517
18518    #[test]
18519    fn rejects_circuit_breaker_window_sub_millisecond() {
18520        // Peer of the `:timeout` sub-millisecond arm on the second
18521        // typed-`Duration` `:politicas` axis: a purely sub-ms
18522        // `Duration` (`from_micros(500)`) renders through the shared
18523        // codec as `"0s"`, which the codec parses back to
18524        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
18525        // zero-floor gate then rejects on re-validate.
18526        let mut s = three_member_spec();
18527        let window = Duration::from_micros(500);
18528        s.politicas.circuit_breaker = Some(CircuitBreaker {
18529            max_failures: 5,
18530            window,
18531        });
18532        assert_eq!(
18533            s.validate().unwrap_err(),
18534            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18535        );
18536    }
18537
18538    #[test]
18539    fn rejects_circuit_breaker_window_non_integer_millisecond() {
18540        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
18541        // with non-integer-millisecond residue renders through the
18542        // shared codec as the truncated `"<n>ms"` form, parsing back
18543        // to a *different* `Duration` on the next round-trip.
18544        let mut s = three_member_spec();
18545        let window = Duration::from_micros(1500);
18546        s.politicas.circuit_breaker = Some(CircuitBreaker {
18547            max_failures: 5,
18548            window,
18549        });
18550        assert_eq!(
18551            s.validate().unwrap_err(),
18552            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18553        );
18554    }
18555
18556    #[test]
18557    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
18558        // The canonical-forms sweep on the breaker axis: every
18559        // integer-ms multiple the codec round-trips losslessly
18560        // passes the canonical gate.
18561        for window in [
18562            Duration::from_millis(1),
18563            Duration::from_millis(500),
18564            Duration::from_millis(1500),
18565            Duration::from_secs(30),
18566            Duration::from_secs(60),
18567            Duration::from_secs(3600),
18568        ] {
18569            let mut s = three_member_spec();
18570            s.politicas.circuit_breaker = Some(CircuitBreaker {
18571                max_failures: 5,
18572                window,
18573            });
18574            s.validate()
18575                .expect("integer-millisecond :circuit-breaker :window must validate");
18576        }
18577    }
18578
18579    #[test]
18580    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
18581        // `Duration::ZERO` would pass the canonical-ms gate (the
18582        // sub-ns residue is zero) but must surface the narrower
18583        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
18584        // remediation.
18585        let mut s = three_member_spec();
18586        s.politicas.circuit_breaker = Some(CircuitBreaker {
18587            max_failures: 5,
18588            window: Duration::ZERO,
18589        });
18590        assert_eq!(
18591            s.validate().unwrap_err(),
18592            AplicacaoError::PolicyBreakerZeroWindow
18593        );
18594    }
18595
18596    #[test]
18597    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
18598        // Both axes invalid: max_failures == 0 *and* window is
18599        // sub-ms. The validate gate must fire on max_failures first
18600        // (matching the existing ordering pin
18601        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
18602        // the existing diagnostic continues to lead with the simpler
18603        // "zero threshold" framing.
18604        let mut s = three_member_spec();
18605        s.politicas.circuit_breaker = Some(CircuitBreaker {
18606            max_failures: 0,
18607            window: Duration::from_micros(500),
18608        });
18609        assert_eq!(
18610            s.validate().unwrap_err(),
18611            AplicacaoError::PolicyBreakerZeroFailures
18612        );
18613    }
18614
18615    #[test]
18616    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
18617        let mut s = three_member_spec();
18618        let window = Duration::from_nanos(60_000_000_001);
18619        s.politicas.circuit_breaker = Some(CircuitBreaker {
18620            max_failures: 5,
18621            window,
18622        });
18623        match s.validate().unwrap_err() {
18624            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
18625                assert_eq!(w, window, "diagnostic must carry the offending Duration");
18626            }
18627            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
18628        }
18629    }
18630
18631    #[test]
18632    fn rejects_circuit_breaker_window_above_cap() {
18633        // The fail-before-pass-after pin: 3601s = 1h + 1s is
18634        // structurally one canonical-tick past the
18635        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
18636        // integer-millisecond magnitude the canonical-form arm above
18637        // accepts cleanly, that the codec round-trips losslessly as
18638        // `"3601s"`, and that silently passed validate on every
18639        // pre-gate codebase because the typed slot's only checks were
18640        // the zero-floor and canonical-form arms. The
18641        // rolling-window-to-lifetime-counter degeneration surfaces
18642        // only at the runtime substrate (Envoy's outlier_detection
18643        // interval, the future CiliumClusterwideEnvoyConfig overlay)
18644        // far from the source `caixa.lisp` with no field naming the
18645        // offending policy.
18646        let mut s = three_member_spec();
18647        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18648        s.politicas.circuit_breaker = Some(CircuitBreaker {
18649            max_failures: 5,
18650            window,
18651        });
18652        assert_eq!(
18653            s.validate().unwrap_err(),
18654            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18655        );
18656    }
18657
18658    #[test]
18659    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
18660        // Boundary case: exactly 1ms past the cap (the granularity the
18661        // canonical-form gate enforces). Catches a future "strictly
18662        // less than" half-measure and pins the diagnostic to name the
18663        // offending `Duration` verbatim. Peer of
18664        // `rejects_policy_timeout_one_millisecond_above_cap` on the
18665        // sibling duration-typed `:politicas :timeout` top edge.
18666        let mut s = three_member_spec();
18667        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
18668        s.politicas.circuit_breaker = Some(CircuitBreaker {
18669            max_failures: 5,
18670            window,
18671        });
18672        assert_eq!(
18673            s.validate().unwrap_err(),
18674            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18675        );
18676    }
18677
18678    #[test]
18679    fn rejects_circuit_breaker_window_far_above_cap() {
18680        // The "obvious authoring footgun" case: a `(:window "24h")` or
18681        // `(:window "86400s")` — values the canonical-form arm
18682        // accepts as integer-millisecond magnitudes, the codec
18683        // round-trips losslessly through serde, but the
18684        // rolling-window breaker contract cannot honor (a 24-hour
18685        // rolling failure window is operationally a lifetime counter).
18686        // Until this gate landed validate accepted it. Pin both common
18687        // above-cap values (24h, 7d) so a future relaxation that
18688        // drops the upper bound surfaces here.
18689        for window in [
18690            Duration::from_secs(86_400),    // 24h
18691            Duration::from_secs(604_800),   // 7d
18692            Duration::from_secs(1_000_000), // ~11.5 days
18693        ] {
18694            let mut s = three_member_spec();
18695            s.politicas.circuit_breaker = Some(CircuitBreaker {
18696                max_failures: 5,
18697                window,
18698            });
18699            assert_eq!(
18700                s.validate().unwrap_err(),
18701                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18702            );
18703        }
18704    }
18705
18706    #[test]
18707    fn accepts_circuit_breaker_window_at_cap() {
18708        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
18709        // (1h) — must validate. The cap is inclusive on the top edge,
18710        // matching the [`POLICY_TIMEOUT_MAX`] /
18711        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
18712        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18713        // sibling capped axes. Pin the boundary explicitly so a
18714        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
18715        // instead of `>`) surfaces here as a test failure rather than
18716        // a silent contract narrowing.
18717        let mut s = three_member_spec();
18718        s.politicas.circuit_breaker = Some(CircuitBreaker {
18719            max_failures: 5,
18720            window: POLICY_BREAKER_WINDOW_MAX,
18721        });
18722        s.validate()
18723            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
18724    }
18725
18726    #[test]
18727    fn accepts_circuit_breaker_window_typical_values() {
18728        // The documented production-playbook band positive-control
18729        // sweep — every value Hystrix / resilience4j / Istio / Envoy
18730        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
18731        // through the long-tail failure-detection band (15m, 30m, 1h)
18732        // the cap accepts. Pin the inclusive validated set explicitly
18733        // so a future tightening of the ceiling surfaces here as a
18734        // deliberate test edit, not a silent contract narrowing.
18735        for window in [
18736            Duration::from_millis(1),
18737            Duration::from_millis(500),
18738            Duration::from_secs(1),
18739            Duration::from_secs(10), // Hystrix / Istio / Envoy default
18740            Duration::from_secs(30),
18741            Duration::from_secs(60),  // resilience4j typical
18742            Duration::from_secs(300), // AWS App Mesh typical
18743            Duration::from_secs(900),
18744            Duration::from_secs(1800),
18745            Duration::from_secs(3600), // exactly 1h, the cap
18746        ] {
18747            let mut s = three_member_spec();
18748            s.politicas.circuit_breaker = Some(CircuitBreaker {
18749                max_failures: 5,
18750                window,
18751            });
18752            s.validate()
18753                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
18754        }
18755    }
18756
18757    #[test]
18758    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
18759        // The cross-arm ordering pin: `Duration::ZERO` is structurally
18760        // outside both `>= 1ms` (zero-floor) and
18761        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
18762        // diagnostic is the more self-locating one (it directly names
18763        // the omit-axis remediation), so the validate gate must fire
18764        // on zero first. Same shape every other zero-then-cap
18765        // ordering on this surface uses
18766        // ([`AplicacaoError::PolicyTimeoutZero`] then
18767        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
18768        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18769        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18770        let mut s = three_member_spec();
18771        s.politicas.circuit_breaker = Some(CircuitBreaker {
18772            max_failures: 5,
18773            window: Duration::ZERO,
18774        });
18775        assert_eq!(
18776            s.validate().unwrap_err(),
18777            AplicacaoError::PolicyBreakerZeroWindow,
18778            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18779        );
18780    }
18781
18782    #[test]
18783    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
18784        // The cross-arm ordering pin: a `Duration` that is *both*
18785        // sub-millisecond (non-canonical-form) and structurally above
18786        // the cap surfaces the canonical-form diagnostic first,
18787        // because the round-trip-shape break is the more fundamental
18788        // issue (the value can't even round-trip through the codec, so
18789        // the cap diagnostic naming `1ms..=1h` would be misleading —
18790        // there's no integer-ms form of the offending value). Pin the
18791        // order so a future refactor that reorders the arms surfaces
18792        // here as a test failure rather than a silent diagnostic
18793        // regression. Peer of
18794        // `policy_timeout_canonical_takes_precedence_over_cap` on the
18795        // sibling duration-typed `:politicas :timeout` axis.
18796        let mut s = three_member_spec();
18797        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
18798        s.politicas.circuit_breaker = Some(CircuitBreaker {
18799            max_failures: 5,
18800            window,
18801        });
18802        assert_eq!(
18803            s.validate().unwrap_err(),
18804            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
18805            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18806        );
18807    }
18808
18809    #[test]
18810    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
18811        // The cross-arm ordering pin between the two breaker axes: a
18812        // `CircuitBreaker` whose *both* `max_failures` is above its
18813        // cap *and* `window` is above its cap surfaces the
18814        // max-failures cap diagnostic first, because the validate
18815        // gate visits the failures arm before the window arm. Pin the
18816        // order so a future refactor that reorders the breaker arms
18817        // surfaces here.
18818        let mut s = three_member_spec();
18819        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18820        s.politicas.circuit_breaker = Some(CircuitBreaker {
18821            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18822            window,
18823        });
18824        assert_eq!(
18825            s.validate().unwrap_err(),
18826            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18827                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
18828            },
18829            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
18830        );
18831    }
18832
18833    #[test]
18834    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
18835        // The diagnostic-shape pin: the offending `Duration` is
18836        // carried verbatim into the
18837        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
18838        // the surfaced error message names the value the author wrote
18839        // (`":politicas :circuit-breaker :window (Duration { secs:
18840        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
18841        // just the cap. Same self-locating diagnostic shape every
18842        // other typed-cap arm on this surface carries
18843        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
18844        // offending `Duration` verbatim).
18845        let mut s = three_member_spec();
18846        let window = Duration::from_secs(7200); // 2h
18847        s.politicas.circuit_breaker = Some(CircuitBreaker {
18848            max_failures: 5,
18849            window,
18850        });
18851        let err = s.validate().unwrap_err();
18852        assert!(
18853            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
18854            "got {err:?}"
18855        );
18856        let msg = err.to_string();
18857        assert!(
18858            msg.contains("7200"),
18859            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
18860        );
18861    }
18862
18863    #[test]
18864    fn circuit_breaker_window_cap_pins_canonical_value() {
18865        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
18866        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
18867        // shared duration codec emits as a clean canonical string
18868        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
18869        // the sibling duration-typed `:politicas :timeout` axis (the
18870        // two duration-typed `:politicas` axes share a uniform top
18871        // edge). Pinning the literal value here surfaces a future
18872        // drift (a relaxation to 24h, a tightening to 5m) as a
18873        // deliberate test edit, not a silent contract narrowing. Same
18874        // shape every other typed-cap value pin on this surface uses
18875        // (`policy_timeout_cap_pins_canonical_value`).
18876        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
18877        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
18878        assert_eq!(
18879            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
18880            "the two duration-typed `:politicas` caps share the same top edge"
18881        );
18882    }
18883
18884    #[test]
18885    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
18886        // The codec round-trip property the cap arm preserves: the
18887        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
18888        // through the shared duration codec — every value at the cap
18889        // renders to a clean canonical string (`"1h"`) and parses back
18890        // to the same `Duration`. Pin this so a future drift between
18891        // the cap constant and the codec's largest emitted unit
18892        // surfaces here. Same shape every other typed boundary pin on
18893        // this surface uses
18894        // (`policy_timeout_cap_value_round_trips_through_codec`).
18895        let policy = MeshPolicy {
18896            circuit_breaker: Some(CircuitBreaker {
18897                max_failures: 5,
18898                window: POLICY_BREAKER_WINDOW_MAX,
18899            }),
18900            ..Default::default()
18901        };
18902        let json = serde_json::to_string(&policy).unwrap();
18903        // The codec emits `"1h"` for the canonical 1-hour magnitude.
18904        assert!(
18905            json.contains("\"1h\""),
18906            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
18907        );
18908        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18909        assert_eq!(
18910            back.circuit_breaker.unwrap().window,
18911            POLICY_BREAKER_WINDOW_MAX
18912        );
18913    }
18914
18915    #[test]
18916    fn is_integer_millisecond_duration_predicate_tracks_codec() {
18917        // Pin the predicate's accepted set against the codec's
18918        // accepted set explicitly. The codec parses
18919        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
18920        // accepted value is an integer-millisecond multiple — so the
18921        // predicate must accept exactly that set. Same shape every
18922        // other predicate-on-the-typed-slot helper carries
18923        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
18924        // Read directly from the codec-owned predicate — the crate's
18925        // single source of truth every typed-`Duration` axis now routes
18926        // through via
18927        // [`crate::render::require_positive_canonical_bounded_duration`].
18928        use super::supervisor::duration_codec::is_integer_millisecond_duration;
18929        assert!(is_integer_millisecond_duration(Duration::ZERO));
18930        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
18931        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
18932        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
18933        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
18934        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
18935        // Non-integer-millisecond residue: rejected.
18936        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
18937        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
18938        assert!(!is_integer_millisecond_duration(Duration::from_micros(
18939            1500
18940        )));
18941        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
18942        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
18943            999_999
18944        )));
18945        // The 1-ns-past-1ms boundary: rejected (no longer a clean
18946        // integer-millisecond multiple).
18947        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
18948            1_000_001
18949        )));
18950    }
18951
18952    #[test]
18953    fn policy_timeout_validated_value_round_trips_through_codec() {
18954        // The structural property the canonical-ms gate enforces:
18955        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
18956        // round-trips losslessly through the shared `duration_codec`
18957        // (serialize → string → deserialize → equal value). Pin this
18958        // end-to-end so a future change to either side (the validate
18959        // gate's accepted granularity, the codec's parse/render unit
18960        // set) that breaks the alignment surfaces here. The
18961        // previous-state shape (typed slot accepts arbitrary
18962        // `Duration`, codec only round-trips integer-ms) would fail
18963        // this test for any `Duration::from_micros(1500)` timeout —
18964        // the validate gate now forecloses that.
18965        for timeout in [
18966            Duration::from_millis(1),
18967            Duration::from_millis(1500),
18968            Duration::from_secs(30),
18969            Duration::from_secs(3600),
18970        ] {
18971            let mut s = three_member_spec();
18972            s.politicas.timeout = Some(timeout);
18973            s.validate().unwrap();
18974            let json = serde_json::to_string(&s.politicas).unwrap();
18975            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18976            assert_eq!(
18977                back.timeout, s.politicas.timeout,
18978                "every validated :timeout must round-trip losslessly through the codec"
18979            );
18980        }
18981    }
18982
18983    #[test]
18984    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
18985        // Peer of the `:timeout` round-trip property on the breaker
18986        // axis.
18987        for window in [
18988            Duration::from_millis(1),
18989            Duration::from_millis(1500),
18990            Duration::from_secs(30),
18991            Duration::from_secs(3600),
18992        ] {
18993            let mut s = three_member_spec();
18994            s.politicas.circuit_breaker = Some(CircuitBreaker {
18995                max_failures: 5,
18996                window,
18997            });
18998            s.validate().unwrap();
18999            let json = serde_json::to_string(&s.politicas).unwrap();
19000            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19001            assert_eq!(
19002                back.circuit_breaker.unwrap().window,
19003                window,
19004                "every validated :circuit-breaker :window must round-trip losslessly"
19005            );
19006        }
19007    }
19008
19009    #[test]
19010    fn empty_politicas_validates() {
19011        // Omitting every policy axis is fine — defaults express "no
19012        // policy on this axis", not "policy = 0". The fixture's typical
19013        // values continue to validate; this test pins that
19014        // MeshPolicy::default() is a clean pass through validate().
19015        let mut s = three_member_spec();
19016        s.politicas = MeshPolicy::default();
19017        s.validate().unwrap();
19018    }
19019
19020    #[test]
19021    fn typical_politicas_validates_with_every_axis_set() {
19022        // The full §III.1 example block (timeout + retries + breaker +
19023        // mtls + rate-limit) — every axis nonzero — must remain a
19024        // clean pass.
19025        let mut s = three_member_spec();
19026        s.politicas = MeshPolicy {
19027            timeout: Some(Duration::from_secs(30)),
19028            retries: Some(3),
19029            circuit_breaker: Some(CircuitBreaker {
19030                max_failures: 5,
19031                window: Duration::from_secs(60),
19032            }),
19033            mtls_required: Some(true),
19034            rate_limit: Some(RateLimit {
19035                rate: 100,
19036                window: Duration::from_secs(1),
19037            }),
19038        };
19039        s.validate().unwrap();
19040    }
19041
19042    #[test]
19043    fn rejects_empty_cluster_name() {
19044        let mut s = three_member_spec();
19045        s.placement.clusters = vec!["rio".into(), "".into()];
19046        assert_eq!(
19047            s.validate().unwrap_err(),
19048            AplicacaoError::PlacementClusterEmpty
19049        );
19050    }
19051
19052    #[test]
19053    fn rejects_duplicate_cluster_names() {
19054        let mut s = three_member_spec();
19055        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
19056        let err = s.validate().unwrap_err();
19057        assert!(
19058            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
19059            "got {err:?}"
19060        );
19061    }
19062
19063    #[test]
19064    fn rejects_placement_cluster_with_uppercase() {
19065        // The canonical "I copied the cluster's display name verbatim"
19066        // typo — K8s context names are lowercase per DNS-1123 label
19067        // rule, but org docs often round-trip a TitleCase identifier
19068        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
19069        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
19070        // on the peer name axis.
19071        let mut s = three_member_spec();
19072        s.placement.clusters = vec!["Rio".into(), "mar".into()];
19073        let err = s.validate().unwrap_err();
19074        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19075            panic!("expected PlacementClusterInvalid, got other variant");
19076        };
19077        assert_eq!(cluster, "Rio");
19078        assert!(
19079            reason.contains("uppercase"),
19080            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19081        );
19082        assert!(
19083            reason.contains("\"rio\""),
19084            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19085        );
19086    }
19087
19088    #[test]
19089    fn rejects_placement_cluster_with_underscore() {
19090        // The canonical "I'm thinking of an env var / hostname slug"
19091        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
19092        // schema. K8s context filtering on `my_cluster` silently misses
19093        // the cluster the author intended; the gate moves it to caixa-
19094        // build time. Same shape as `rejects_membro_caixa_with_underscore`
19095        // (3f9d7a0).
19096        let mut s = three_member_spec();
19097        s.placement.clusters = vec!["my_cluster".into()];
19098        let err = s.validate().unwrap_err();
19099        assert!(
19100            matches!(
19101                err,
19102                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19103                    if cluster == "my_cluster" && reason.contains('_')
19104            ),
19105            "got {err:?}"
19106        );
19107    }
19108
19109    #[test]
19110    fn rejects_placement_cluster_with_dot() {
19111        // A `:placement :clusters` entry is a single DNS-1123 *label*,
19112        // not a subdomain — even though K8s context names sometimes
19113        // carry a dotted form via kubeconfig conventions, the strictest
19114        // floor among the use sites (DNS-1035 cluster.x-k8s.io
19115        // `metadata.name`, Cilium identity label values) wins. The "I
19116        // want to namespace my cluster names with `.`" intent is
19117        // expressed via `-` (`mar-east`).
19118        let mut s = three_member_spec();
19119        s.placement.clusters = vec!["team.rio".into()];
19120        let err = s.validate().unwrap_err();
19121        assert!(
19122            matches!(
19123                err,
19124                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19125                    if cluster == "team.rio" && reason.contains('.')
19126            ),
19127            "got {err:?}"
19128        );
19129    }
19130
19131    #[test]
19132    fn rejects_placement_cluster_with_leading_hyphen() {
19133        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
19134        // with an alphanumeric. The K8s apiserver rejects `-rio`
19135        // outright; the rendered fan-out would emit a `metadata.name:
19136        // "-rio"` that fails admission far from the source caixa.lisp.
19137        let mut s = three_member_spec();
19138        s.placement.clusters = vec!["-rio".into()];
19139        let err = s.validate().unwrap_err();
19140        assert!(
19141            matches!(
19142                err,
19143                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19144                    if cluster == "-rio" && reason.contains("start and end")
19145            ),
19146            "got {err:?}"
19147        );
19148    }
19149
19150    #[test]
19151    fn rejects_placement_cluster_with_trailing_hyphen() {
19152        // The symmetric arm of the boundary rule. Pin separately so
19153        // both ends are covered against a future relaxation that only
19154        // checks one boundary (parallel to
19155        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
19156        let mut s = three_member_spec();
19157        s.placement.clusters = vec!["rio-".into()];
19158        let err = s.validate().unwrap_err();
19159        assert!(
19160            matches!(
19161                err,
19162                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19163                    if cluster == "rio-"
19164            ),
19165            "got {err:?}"
19166        );
19167    }
19168
19169    #[test]
19170    fn rejects_placement_cluster_with_unicode() {
19171        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19172        // before it reaches K8s. The byte-by-byte ASCII validity check
19173        // rejects multi-byte UTF-8 sequences by the first byte that
19174        // fails `[a-z0-9-]`.
19175        let mut s = three_member_spec();
19176        s.placement.clusters = vec!["rió".into()];
19177        let err = s.validate().unwrap_err();
19178        assert!(
19179            matches!(
19180                err,
19181                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19182                    if cluster == "rió"
19183            ),
19184            "got {err:?}"
19185        );
19186    }
19187
19188    #[test]
19189    fn rejects_placement_cluster_with_whitespace() {
19190        // Whitespace is the canonical "I pasted from a sketch / doc"
19191        // footgun. The apiserver rejects every cluster `metadata.name`
19192        // value carrying whitespace.
19193        let mut s = three_member_spec();
19194        s.placement.clusters = vec!["rio cluster".into()];
19195        let err = s.validate().unwrap_err();
19196        assert!(
19197            matches!(
19198                err,
19199                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19200                    if cluster == "rio cluster"
19201            ),
19202            "got {err:?}"
19203        );
19204    }
19205
19206    #[test]
19207    fn rejects_placement_cluster_too_long() {
19208        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
19209        // pin. The diagnostic names both the cap (63) and the actual
19210        // length so the author can shorten in one edit. Mirrors
19211        // `rejects_membro_caixa_too_long` (3f9d7a0).
19212        let mut s = three_member_spec();
19213        let too_long = "a".repeat(64);
19214        s.placement.clusters = vec![too_long.clone()];
19215        let err = s.validate().unwrap_err();
19216        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19217            panic!("expected PlacementClusterInvalid");
19218        };
19219        assert_eq!(cluster, too_long);
19220        assert!(
19221            reason.contains("63") && reason.contains("64"),
19222            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19223        );
19224    }
19225
19226    #[test]
19227    fn placement_cluster_max_length_validates() {
19228        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
19229        // future tightening (e.g. dropping to 62) surfaces here as a
19230        // regression, mirroring `membro_caixa_max_length_validates`
19231        // (3f9d7a0).
19232        let mut s = three_member_spec();
19233        s.placement.clusters = vec!["a".repeat(63)];
19234        s.validate().unwrap();
19235    }
19236
19237    #[test]
19238    fn accepts_canonical_placement_cluster_forms() {
19239        // The DNS-1123 label shapes a caixa author is realistically
19240        // going to write for cluster names: single-word lowercase
19241        // (`rio`), regional hyphen-joined (`mar-east`), single
19242        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
19243        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
19244        // Pin every leg so a future tightening that bans (e.g.) digit-
19245        // start identifiers surfaces here.
19246        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
19247            let mut s = three_member_spec();
19248            s.placement.clusters = vec![form.into()];
19249            s.validate().unwrap_or_else(|e| {
19250                panic!("canonical cluster form {form:?} must validate, got {e:?}")
19251            });
19252        }
19253    }
19254
19255    #[test]
19256    fn placement_cluster_empty_takes_precedence_over_invalid() {
19257        // Order pin: the existing `PlacementClusterEmpty` diagnostic
19258        // (which doesn't try to parse) fires before the new
19259        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
19260        // `:clusters` entry keeps its narrower error message — the new
19261        // gate would also reject `""`, but the empty-string arm is the
19262        // more self-locating diagnostic. Mirrors the
19263        // `membro_caixa_empty_takes_precedence_over_invalid` pin
19264        // (3f9d7a0).
19265        let mut s = three_member_spec();
19266        s.placement.clusters = vec!["rio".into(), "".into()];
19267        let err = s.validate().unwrap_err();
19268        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
19269    }
19270
19271    #[test]
19272    fn placement_cluster_invalid_fires_before_duplicate_check() {
19273        // Order pin: a malformed-shape `:clusters` entry surfaces *its
19274        // own* diagnostic, even when a later entry would otherwise
19275        // collapse onto a duplicate name. The per-entry shape gate runs
19276        // inline before the duplicate-key insert, parallel to
19277        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
19278        let mut s = three_member_spec();
19279        s.placement.clusters = vec!["Rio".into(), "rio".into()];
19280        let err = s.validate().unwrap_err();
19281        assert!(
19282            matches!(
19283                err,
19284                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
19285            ),
19286            "got {err:?}"
19287        );
19288    }
19289
19290    #[test]
19291    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
19292        // The diagnostic-shape pin: the error names the offending
19293        // `:clusters` value verbatim so the author can grep their
19294        // caixa.lisp without re-running the build, and carries a
19295        // non-empty `reason` naming the specific violation. Same shape
19296        // every typed-shape gate enshrines
19297        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
19298        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
19299        let mut s = three_member_spec();
19300        s.placement.clusters = vec!["BAD_CLUSTER".into()];
19301        let err = s.validate().unwrap_err();
19302        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19303            panic!("expected PlacementClusterInvalid");
19304        };
19305        assert_eq!(cluster, "BAD_CLUSTER");
19306        assert!(
19307            !reason.is_empty(),
19308            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
19309        );
19310    }
19311
19312    #[test]
19313    fn rejects_sharded_with_empty_clusters() {
19314        // §III.1: Sharded uses :clusters as the shard pool. An empty
19315        // pool means "shard across no clusters" — meaningless, same as
19316        // Replicated with no hosts.
19317        let mut s = three_member_spec();
19318        s.placement.estrategia = PlacementStrategy::Sharded;
19319        s.placement.shard_key = Some("$tenantId".into());
19320        s.placement.clusters = vec![];
19321        assert!(matches!(
19322            s.validate().unwrap_err(),
19323            AplicacaoError::PlacementWithoutClusters {
19324                estrategia: PlacementStrategy::Sharded
19325            }
19326        ));
19327    }
19328
19329    #[test]
19330    fn rejects_sharded_with_empty_shard_key() {
19331        let mut s = three_member_spec();
19332        s.placement.estrategia = PlacementStrategy::Sharded;
19333        s.placement.shard_key = Some("".into());
19334        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
19335    }
19336
19337    #[test]
19338    fn rejects_shard_key_under_replicated_strategy() {
19339        // The fail-before-pass-after pin: a `:placement (:estrategia
19340        // Replicated :shard-key "tenantId")` manifest carries the
19341        // hash-keyed-distribution slot on a strategy that never consumes
19342        // it. Before the gate the typed slot's value silently vanished
19343        // at the renderer layer (caixa-mesh emits `placement.shardKey`
19344        // verbatim regardless of strategy; the Akka-style cluster-
19345        // sharding reconciler keys off `estrategia == Sharded` and
19346        // ignores the slot otherwise), with no diagnostic. Lifting the
19347        // rejection to a build-time gate makes the
19348        // `shard_key.is_some() == matches!(estrategia, Sharded)`
19349        // partition a structural property of every validated
19350        // [`Placement`].
19351        let mut s = three_member_spec();
19352        // The fixture already uses Replicated; just add a shard-key.
19353        s.placement.shard_key = Some("$tenantId".into());
19354        let err = s.validate().unwrap_err();
19355        let AplicacaoError::ShardKeyOnNonSharded {
19356            estrategia,
19357            shard_key,
19358        } = err
19359        else {
19360            panic!("expected ShardKeyOnNonSharded, got {err:?}");
19361        };
19362        assert_eq!(estrategia, PlacementStrategy::Replicated);
19363        assert_eq!(shard_key, "$tenantId");
19364    }
19365
19366    #[test]
19367    fn rejects_shard_key_under_singlenode_strategy() {
19368        // Peer of the Replicated case above on the SingleNode arm: OTP
19369        // distributed-app takeover (one cluster runs at a time) has no
19370        // hash-keyed routing axis to consume `:shard-key` either, so
19371        // the rejection fires on both non-Sharded arms uniformly.
19372        let mut s = three_member_spec();
19373        s.placement.estrategia = PlacementStrategy::SingleNode;
19374        s.placement.shard_key = Some("$tenantId".into());
19375        let err = s.validate().unwrap_err();
19376        let AplicacaoError::ShardKeyOnNonSharded {
19377            estrategia,
19378            shard_key,
19379        } = err
19380        else {
19381            panic!("expected ShardKeyOnNonSharded, got {err:?}");
19382        };
19383        assert_eq!(estrategia, PlacementStrategy::SingleNode);
19384        assert_eq!(shard_key, "$tenantId");
19385    }
19386
19387    #[test]
19388    fn rejects_empty_shard_key_under_replicated_strategy() {
19389        // The `Some("")` case under non-Sharded is rejected by
19390        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
19391        // fires before the empty-value gate), not
19392        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
19393        // the `Sharded` arm). Pin the partition so a future reorder of
19394        // the validate_placement match arms doesn't silently swap which
19395        // diagnostic the author sees — both are author errors, but
19396        // ShardKeyOnNonSharded names which strategy is the actual fix
19397        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
19398        // only says "pick a non-empty key".
19399        let mut s = three_member_spec();
19400        s.placement.shard_key = Some(String::new());
19401        let err = s.validate().unwrap_err();
19402        assert!(
19403            matches!(
19404                err,
19405                AplicacaoError::ShardKeyOnNonSharded {
19406                    estrategia: PlacementStrategy::Replicated,
19407                    ref shard_key,
19408                } if shard_key.is_empty()
19409            ),
19410            "got {err:?}"
19411        );
19412    }
19413
19414    #[test]
19415    fn replicated_without_shard_key_validates() {
19416        // The complement of the rejection: `:placement :estrategia
19417        // Replicated` with `:shard-key None` is the canonical happy
19418        // path on every existing fixture. Pin the no-shard-key case so
19419        // the new gate doesn't accidentally fire on `None`.
19420        let mut s = three_member_spec();
19421        assert!(matches!(
19422            s.placement.estrategia,
19423            PlacementStrategy::Replicated
19424        ));
19425        s.placement.shard_key = None;
19426        s.validate().unwrap();
19427    }
19428
19429    #[test]
19430    fn singlenode_without_shard_key_validates() {
19431        // Peer of the Replicated no-shard-key case on the SingleNode
19432        // arm — both non-Sharded strategies must validate cleanly when
19433        // the slot is omitted.
19434        let mut s = three_member_spec();
19435        s.placement.estrategia = PlacementStrategy::SingleNode;
19436        s.placement.shard_key = None;
19437        s.validate().unwrap();
19438    }
19439
19440    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
19441        // Fixture builder for the `:placement :shard-key` shape gate
19442        // tests: a three-member Aplicacao on the `Sharded` strategy
19443        // with the supplied `:shard-key` slot. Co-locates the
19444        // arm-construction so every test below carries one line of
19445        // setup (the offending `:shard-key` value) and the assertion.
19446        let mut s = three_member_spec();
19447        s.placement.estrategia = PlacementStrategy::Sharded;
19448        s.placement.shard_key = Some(key.into());
19449        s
19450    }
19451
19452    #[test]
19453    fn rejects_shard_key_with_embedded_space() {
19454        // The canonical paste-from-aligned-doc footgun:
19455        // `:shard-key "$tenant Id"` — the Akka-style entity-id
19456        // extractor reads the slot as a single-token reference, and an
19457        // embedded space breaks the token boundary at the runtime
19458        // hash-extractor pass with no diagnostic naming the offending
19459        // entry.
19460        let s = sharded_spec_with_key("$tenant Id");
19461        let err = s.validate().unwrap_err();
19462        assert!(
19463            matches!(
19464                err,
19465                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19466                    if shard_key == "$tenant Id" && reason.contains("space")
19467            ),
19468            "got {err:?}"
19469        );
19470    }
19471
19472    #[test]
19473    fn rejects_shard_key_with_leading_space() {
19474        // Leading-space arm of the embedded-whitespace footgun — the
19475        // paste-from-aligned-doc / paste-from-CSV-cell variant where
19476        // the leading column-padding leaked into the slot.
19477        let s = sharded_spec_with_key(" $tenantId");
19478        let err = s.validate().unwrap_err();
19479        assert!(
19480            matches!(
19481                err,
19482                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
19483                    if shard_key == " $tenantId"
19484            ),
19485            "got {err:?}"
19486        );
19487    }
19488
19489    #[test]
19490    fn rejects_shard_key_with_trailing_newline() {
19491        // The canonical paste-from-shell-heredoc footgun — every
19492        // `<<EOF` heredoc terminator paste leaves a trailing newline
19493        // the YAML emitter then folds away inconsistently across
19494        // emitter implementations.
19495        let s = sharded_spec_with_key("$tenantId\n");
19496        let err = s.validate().unwrap_err();
19497        assert!(
19498            matches!(
19499                err,
19500                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19501                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
19502            ),
19503            "got {err:?}"
19504        );
19505    }
19506
19507    #[test]
19508    fn rejects_shard_key_with_embedded_tab() {
19509        // The paste-from-aligned-doc tab-stop variant — tabs land
19510        // alongside spaces in copy-paste from formatted columns.
19511        let s = sharded_spec_with_key("$tenant\tId");
19512        let err = s.validate().unwrap_err();
19513        assert!(
19514            matches!(
19515                err,
19516                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19517                    if shard_key == "$tenant\tId" && reason.contains("tab")
19518            ),
19519            "got {err:?}"
19520        );
19521    }
19522
19523    #[test]
19524    fn rejects_shard_key_with_control_character() {
19525        // The paste-from-binary / paste-from-screen-cleared-terminal
19526        // footgun — an embedded `\x01` (SOH) byte that some YAML
19527        // emitters silently strip and others escape as ``,
19528        // breaking round-trip across emitter implementations.
19529        let s = sharded_spec_with_key("$tenant\u{0001}Id");
19530        let err = s.validate().unwrap_err();
19531        assert!(
19532            matches!(
19533                err,
19534                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19535                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
19536            ),
19537            "got {err:?}"
19538        );
19539    }
19540
19541    #[test]
19542    fn rejects_shard_key_with_non_ascii() {
19543        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
19544        // footgun — non-ASCII bytes normalize differently between the
19545        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
19546        // YAML parser, the same entity ID can silently map to two
19547        // distinct shards on a re-render.
19548        let s = sharded_spec_with_key("$tenàntId");
19549        let err = s.validate().unwrap_err();
19550        assert!(
19551            matches!(
19552                err,
19553                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19554                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
19555            ),
19556            "got {err:?}"
19557        );
19558    }
19559
19560    #[test]
19561    fn rejects_shard_key_too_long() {
19562        // Length cap pin: 64 bytes — one byte over the
19563        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
19564        // here is a paste-from-doc multi-line blob landing in
19565        // `:shard-key` instead of a single-token extractor expression.
19566        let too_long = "a".repeat(64);
19567        let s = sharded_spec_with_key(&too_long);
19568        let err = s.validate().unwrap_err();
19569        let AplicacaoError::ShardKeyInvalid {
19570            ref shard_key,
19571            ref reason,
19572        } = err
19573        else {
19574            panic!("expected ShardKeyInvalid, got {err:?}");
19575        };
19576        assert_eq!(shard_key, &too_long);
19577        assert!(
19578            reason.contains("63") && reason.contains("64"),
19579            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19580        );
19581    }
19582
19583    #[test]
19584    fn shard_key_max_length_validates() {
19585        // Boundary pin: 63 bytes exactly — the
19586        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
19587        // dropping to 62) surfaces here as a regression, mirroring
19588        // `placement_cluster_max_length_validates` /
19589        // `placement_affinity_max_length_validates` on the peer
19590        // identifier-shaped slots.
19591        let s = sharded_spec_with_key(&"a".repeat(63));
19592        s.validate().unwrap();
19593    }
19594
19595    #[test]
19596    fn accepts_canonical_shard_key_forms() {
19597        // The Akka-style entity-id extractor shapes a caixa author is
19598        // realistically going to write — pin every leg so a future
19599        // tightening that bans (e.g.) the `${...}` interpolation
19600        // variant or the `metadata.<field>` JSONPath form surfaces
19601        // here as a regression. The canonical forms span:
19602        //
19603        //   - bare property name (`tenantId`, `customerId`)
19604        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
19605        //   - JSONPath-style nested reference (`metadata.tenantId`,
19606        //     `$.user.id`)
19607        //   - interpolation-style template (`${tenant}`)
19608        //   - snake_case property name (`customer_id`)
19609        //   - kebab-case property name (`customer-id` — accepted
19610        //     because the slot is a printable-ASCII single-token
19611        //     reference, not a DNS-1123 label like
19612        //     `:placement :affinity` / `:clusters`)
19613        //   - single character (`a`, `$` — boundary)
19614        for form in [
19615            "tenantId",
19616            "customerId",
19617            "$tenantId",
19618            "metadata.tenantId",
19619            "$.user.id",
19620            "${tenant}",
19621            "customer_id",
19622            "customer-id",
19623            "a",
19624            "$",
19625        ] {
19626            let s = sharded_spec_with_key(form);
19627            s.validate().unwrap_or_else(|e| {
19628                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
19629            });
19630        }
19631    }
19632
19633    #[test]
19634    fn shard_key_empty_takes_precedence_over_invalid() {
19635        // Order pin: the existing `ShardedKeyEmpty` diagnostic
19636        // (reserved for the `Sharded` `Some("")` arm) fires before the
19637        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
19638        // `:shard-key` keeps its narrower error message — the new gate
19639        // would also reject `""` defensively, but the empty-string arm
19640        // is the more self-locating diagnostic. Mirrors the
19641        // `placement_cluster_empty_takes_precedence_over_invalid` pin
19642        // on the peer identifier-shaped slot.
19643        let s = sharded_spec_with_key("");
19644        let err = s.validate().unwrap_err();
19645        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
19646    }
19647
19648    #[test]
19649    fn shard_key_invalid_diagnostic_carries_offending_value() {
19650        // The diagnostic-shape pin: the error names the offending
19651        // `:shard-key` value verbatim so the author can grep their
19652        // caixa.lisp without re-running the build, and carries a
19653        // parser-shaped `reason:` naming the specific violation —
19654        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19655        // on the peer identifier-shaped slot.
19656        let s = sharded_spec_with_key("$tenant Id");
19657        let err = s.validate().unwrap_err();
19658        let AplicacaoError::ShardKeyInvalid {
19659            ref shard_key,
19660            ref reason,
19661        } = err
19662        else {
19663            panic!("expected ShardKeyInvalid, got {err:?}");
19664        };
19665        assert_eq!(shard_key, "$tenant Id");
19666        assert!(
19667            !reason.is_empty(),
19668            "reason must name the specific violation, got empty string"
19669        );
19670    }
19671
19672    #[test]
19673    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
19674        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
19675        // `:shard-key` carried on non-Sharded strategies) fires before
19676        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
19677        // a `Replicated` strategy surfaces the more self-locating
19678        // strategy-mismatch diagnostic (naming the actual fix — drop
19679        // the slot, or switch to Sharded) rather than the shape
19680        // diagnostic. The strategy-mismatch arm is the more actionable
19681        // diagnostic: a malformed shard-key on Replicated is "you
19682        // shouldn't have a :shard-key here at all", not "your
19683        // :shard-key value is malformed".
19684        let mut s = three_member_spec();
19685        // Replicated is the default fixture strategy.
19686        s.placement.shard_key = Some("$tenant Id".into());
19687        let err = s.validate().unwrap_err();
19688        assert!(
19689            matches!(
19690                err,
19691                AplicacaoError::ShardKeyOnNonSharded {
19692                    estrategia: PlacementStrategy::Replicated,
19693                    ..
19694                }
19695            ),
19696            "got {err:?}"
19697        );
19698    }
19699
19700    #[test]
19701    fn rejects_empty_affinity_hint() {
19702        let mut s = three_member_spec();
19703        s.placement.affinity = Some("".into());
19704        assert_eq!(
19705            s.validate().unwrap_err(),
19706            AplicacaoError::PlacementAffinityEmpty
19707        );
19708    }
19709
19710    #[test]
19711    fn placement_without_affinity_validates() {
19712        // Omitting :affinity is fine — the placement engine falls back
19713        // to the default heuristic. Pin the no-hint case so the
19714        // affinity-empty rejection doesn't accidentally fire on `None`.
19715        let mut s = three_member_spec();
19716        s.placement.affinity = None;
19717        s.validate().unwrap();
19718    }
19719
19720    #[test]
19721    fn rejects_placement_affinity_with_uppercase() {
19722        // The canonical "I copied the ADR's display name verbatim" typo
19723        // — placement hints land verbatim in K8s label-selector
19724        // territory, where the apiserver enforces the DNS-1123 label
19725        // rule (lowercase-only) on every identity-keyed admission axis.
19726        // Mirrors `rejects_placement_cluster_with_uppercase` on the
19727        // sibling slot.
19728        let mut s = three_member_spec();
19729        s.placement.affinity = Some("DataLocality".into());
19730        let err = s.validate().unwrap_err();
19731        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19732            panic!("expected PlacementAffinityInvalid, got other variant");
19733        };
19734        assert_eq!(affinity, "DataLocality");
19735        assert!(
19736            reason.contains("uppercase"),
19737            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19738        );
19739        assert!(
19740            reason.contains("\"datalocality\""),
19741            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19742        );
19743    }
19744
19745    #[test]
19746    fn rejects_placement_affinity_with_underscore() {
19747        // The canonical "I'm thinking of an env var / Python identifier"
19748        // leak — `_` is forbidden by every DNS-1123 label schema. Same
19749        // shape as `rejects_placement_cluster_with_underscore` on the
19750        // sibling slot.
19751        let mut s = three_member_spec();
19752        s.placement.affinity = Some("data_locality".into());
19753        let err = s.validate().unwrap_err();
19754        assert!(
19755            matches!(
19756                err,
19757                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19758                    if affinity == "data_locality" && reason.contains('_')
19759            ),
19760            "got {err:?}"
19761        );
19762    }
19763
19764    #[test]
19765    fn rejects_placement_affinity_with_dot() {
19766        // A `:placement :affinity` value is a single DNS-1123 *label*
19767        // (it lands as a K8s label value selector key), not a subdomain.
19768        // The "I want to namespace my hint with `.`" intent is expressed
19769        // via `-` (`data-locality-east`).
19770        let mut s = three_member_spec();
19771        s.placement.affinity = Some("data.locality".into());
19772        let err = s.validate().unwrap_err();
19773        assert!(
19774            matches!(
19775                err,
19776                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19777                    if affinity == "data.locality" && reason.contains('.')
19778            ),
19779            "got {err:?}"
19780        );
19781    }
19782
19783    #[test]
19784    fn rejects_placement_affinity_with_unicode() {
19785        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19786        // before it reaches K8s. The byte-by-byte ASCII validity check
19787        // rejects multi-byte UTF-8 sequences by the first byte that
19788        // fails `[a-z0-9-]`.
19789        let mut s = three_member_spec();
19790        s.placement.affinity = Some("data-localité".into());
19791        let err = s.validate().unwrap_err();
19792        assert!(
19793            matches!(
19794                err,
19795                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19796                    if affinity == "data-localité"
19797            ),
19798            "got {err:?}"
19799        );
19800    }
19801
19802    #[test]
19803    fn rejects_placement_affinity_with_leading_hyphen() {
19804        // DNS-1123 boundary rule: labels must start with an
19805        // alphanumeric. Pin separately from the trailing-hyphen arm so
19806        // a future relaxation that only checks one boundary surfaces
19807        // here as a regression (parallel to
19808        // `rejects_placement_cluster_with_leading_hyphen`).
19809        let mut s = three_member_spec();
19810        s.placement.affinity = Some("-data-locality".into());
19811        let err = s.validate().unwrap_err();
19812        assert!(
19813            matches!(
19814                err,
19815                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19816                    if affinity == "-data-locality" && reason.contains("start and end")
19817            ),
19818            "got {err:?}"
19819        );
19820    }
19821
19822    #[test]
19823    fn rejects_placement_affinity_with_trailing_hyphen() {
19824        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
19825        // ends are covered against a future relaxation.
19826        let mut s = three_member_spec();
19827        s.placement.affinity = Some("data-locality-".into());
19828        let err = s.validate().unwrap_err();
19829        assert!(
19830            matches!(
19831                err,
19832                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19833                    if affinity == "data-locality-"
19834            ),
19835            "got {err:?}"
19836        );
19837    }
19838
19839    #[test]
19840    fn rejects_placement_affinity_with_whitespace() {
19841        // Whitespace is the canonical "I pasted from a sketch / doc"
19842        // footgun. The apiserver rejects every label-selector value
19843        // carrying whitespace.
19844        let mut s = three_member_spec();
19845        s.placement.affinity = Some("data locality".into());
19846        let err = s.validate().unwrap_err();
19847        assert!(
19848            matches!(
19849                err,
19850                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19851                    if affinity == "data locality"
19852            ),
19853            "got {err:?}"
19854        );
19855    }
19856
19857    #[test]
19858    fn rejects_placement_affinity_too_long() {
19859        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
19860        // pin. The diagnostic names both the cap (63) and the actual
19861        // length so the author can shorten in one edit. Mirrors
19862        // `rejects_placement_cluster_too_long`.
19863        let mut s = three_member_spec();
19864        let too_long = "a".repeat(64);
19865        s.placement.affinity = Some(too_long.clone());
19866        let err = s.validate().unwrap_err();
19867        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19868            panic!("expected PlacementAffinityInvalid");
19869        };
19870        assert_eq!(affinity, too_long);
19871        assert!(
19872            reason.contains("63") && reason.contains("64"),
19873            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19874        );
19875    }
19876
19877    #[test]
19878    fn placement_affinity_max_length_validates() {
19879        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
19880        // future tightening (e.g. dropping to 62) surfaces here as a
19881        // regression, mirroring `placement_cluster_max_length_validates`.
19882        let mut s = three_member_spec();
19883        s.placement.affinity = Some("a".repeat(63));
19884        s.validate().unwrap();
19885    }
19886
19887    #[test]
19888    fn accepts_canonical_placement_affinity_forms() {
19889        // The DNS-1123 label shapes a caixa author is realistically
19890        // going to write for placement hints: the M3 canonical examples
19891        // (`data-locality`, `low-latency`, `anti-affinity`), the
19892        // single-token form (`affinity`), the single-character boundary
19893        // (`a`), the digit-start (DNS-1123 allows this, unlike
19894        // DNS-1035), and a regional-suffixed form. Pin every leg so a
19895        // future tightening that bans (e.g.) digit-start identifiers
19896        // surfaces here.
19897        for form in [
19898            "data-locality",
19899            "low-latency",
19900            "anti-affinity",
19901            "affinity",
19902            "a",
19903            "3-tier",
19904            "locality-east",
19905        ] {
19906            let mut s = three_member_spec();
19907            s.placement.affinity = Some(form.into());
19908            s.validate().unwrap_or_else(|e| {
19909                panic!("canonical affinity form {form:?} must validate, got {e:?}")
19910            });
19911        }
19912    }
19913
19914    #[test]
19915    fn placement_affinity_empty_takes_precedence_over_invalid() {
19916        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
19917        // (which doesn't try to parse) fires before the new
19918        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
19919        // `:affinity` keeps its narrower error message — the new gate
19920        // would also reject `""`, but the empty-string arm is the more
19921        // self-locating diagnostic. Mirrors the
19922        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
19923        let mut s = three_member_spec();
19924        s.placement.affinity = Some(String::new());
19925        let err = s.validate().unwrap_err();
19926        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
19927    }
19928
19929    #[test]
19930    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
19931        // The diagnostic shape pin: every rejection carries the offending
19932        // `affinity:` verbatim plus a parser-shaped `reason:` so the
19933        // author can grep their caixa.lisp for `:affinity "<hint>"` and
19934        // fix it in one edit. Mirrors the
19935        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19936        // pin on the sibling slot.
19937        let mut s = three_member_spec();
19938        s.placement.affinity = Some("Data_Locality".into());
19939        let err = s.validate().unwrap_err();
19940        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19941            panic!("expected PlacementAffinityInvalid");
19942        };
19943        assert_eq!(affinity, "Data_Locality");
19944        assert!(
19945            !reason.is_empty(),
19946            "diagnostic reason must not be empty (got: {reason:?})"
19947        );
19948    }
19949
19950    #[test]
19951    fn singlenode_with_takeover_candidates_validates() {
19952        // OTP distributed-application convention (MESH-COMPOSITION
19953        // §II.1): SingleNode runs on one cluster at a time but the
19954        // :clusters list enumerates the takeover candidates. Multiple
19955        // entries are not a contradiction — they are the failover pool.
19956        let mut s = three_member_spec();
19957        s.placement.estrategia = PlacementStrategy::SingleNode;
19958        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
19959        s.validate().unwrap();
19960    }
19961
19962    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
19963
19964    #[test]
19965    fn mesh_policy_default_is_empty() {
19966        // The Default impl carries None on every axis — the typed
19967        // analog of an unset `:politicas (())` slot. Renderers that
19968        // overlay the policy onto a cluster artifact key off this
19969        // predicate to skip the slot entirely; pinning so a future
19970        // axis added to MeshPolicy can't silently break the contract
19971        // (a new field whose Default is non-None would flip is_empty
19972        // to false on every existing caixa, surfacing here).
19973        assert!(MeshPolicy::default().is_empty());
19974    }
19975
19976    #[test]
19977    fn mesh_policy_with_only_timeout_is_not_empty() {
19978        let p = MeshPolicy {
19979            timeout: Some(Duration::from_secs(30)),
19980            ..Default::default()
19981        };
19982        assert!(!p.is_empty());
19983    }
19984
19985    #[test]
19986    fn mesh_policy_with_only_retries_is_not_empty() {
19987        let p = MeshPolicy {
19988            retries: Some(3),
19989            ..Default::default()
19990        };
19991        assert!(!p.is_empty());
19992    }
19993
19994    #[test]
19995    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
19996        let p = MeshPolicy {
19997            circuit_breaker: Some(CircuitBreaker {
19998                max_failures: 5,
19999                window: Duration::from_secs(60),
20000            }),
20001            ..Default::default()
20002        };
20003        assert!(!p.is_empty());
20004    }
20005
20006    #[test]
20007    fn mesh_policy_with_only_mtls_required_is_not_empty() {
20008        // Even `mtls_required: Some(false)` (an explicit opt-out) is
20009        // not empty — the author *named* the axis, the renderer needs
20010        // to honor that vs. fall back to the cluster default.
20011        let p = MeshPolicy {
20012            mtls_required: Some(false),
20013            ..Default::default()
20014        };
20015        assert!(!p.is_empty());
20016    }
20017
20018    #[test]
20019    fn mesh_policy_with_only_rate_limit_is_not_empty() {
20020        let p = MeshPolicy {
20021            rate_limit: Some(RateLimit {
20022                rate: 100,
20023                window: Duration::from_secs(1),
20024            }),
20025            ..Default::default()
20026        };
20027        assert!(!p.is_empty());
20028    }
20029
20030    #[test]
20031    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
20032        // The three-member happy-path fixture sets timeout + retries +
20033        // mtls_required — every populated axis must read non-empty.
20034        // Pin the round-trip so the M3.x per-:politicas emitter (the
20035        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
20036        // on is_empty() to decide whether to emit at all without
20037        // re-deriving the contract from inline field probes.
20038        assert!(!three_member_spec().politicas.is_empty());
20039    }
20040
20041    // ── shared duration codec: cross-slot integer-magnitude gate ──
20042    //
20043    // The integer-magnitude discipline applied to
20044    // `supervisor::duration_codec::parse` lifts onto every typed slot
20045    // that routes through the shared codec — `MeshPolicy::timeout`
20046    // (`:politicas :timeout`) and `CircuitBreaker::window`
20047    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
20048    // These cross-slot tests pin that the gate fires at the serde
20049    // layer for both typed slots, not just for the supervisor side.
20050
20051    #[test]
20052    fn policy_timeout_serde_rejects_fractional_seconds() {
20053        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
20054        // so the shared codec's integer-magnitude gate applies on
20055        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
20056        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
20057        // deserialize with the canonical-form diagnostic naming the
20058        // offending `"1.5"` and the remediation `"1500ms"`.
20059        let payload = r#"{"timeout":"1.5s"}"#;
20060        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20061        let msg = err.to_string();
20062        assert!(
20063            msg.contains("not a non-negative integer"),
20064            "expected integer-magnitude diagnostic in {msg:?}"
20065        );
20066        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
20067        assert!(
20068            msg.contains("\"1500ms\""),
20069            "missing canonical-form remediation in {msg:?}"
20070        );
20071    }
20072
20073    #[test]
20074    fn policy_timeout_serde_rejects_leading_plus_sign() {
20075        // Pin the leading-`+` arm cross-slot — the prior f64 parser
20076        // accepted `"+30s"` silently and round-tripped to `"30s"`.
20077        let payload = r#"{"timeout":"+30s"}"#;
20078        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20079        let msg = err.to_string();
20080        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
20081    }
20082
20083    #[test]
20084    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
20085        // `CircuitBreaker::window` uses `with =
20086        // "supervisor::duration_codec_required"` (the required-Duration
20087        // variant that delegates to the same shared parser). `"0.5m"`
20088        // parsed to 30s and round-tripped to `"30s"` on next emit —
20089        // DRIFT closed.
20090        let payload = format!(
20091            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
20092            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
20093            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
20094        );
20095        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
20096        let msg = err.to_string();
20097        assert!(
20098            msg.contains("not a non-negative integer"),
20099            "expected integer-magnitude diagnostic in {msg:?}"
20100        );
20101        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
20102        assert!(
20103            msg.contains("\"30s\""),
20104            "missing canonical-form remediation in {msg:?}"
20105        );
20106    }
20107
20108    #[test]
20109    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
20110        // Pin the happy-path on the cross-slot side: every canonical
20111        // author shape `render` ever emits parses cleanly through the
20112        // shared codec on the `CircuitBreaker` slot. The
20113        // codec's accepted set (post-gate) is exactly its emitted set
20114        // for the integer-magnitude class.
20115        for window_lit in ["30s", "500ms", "2m", "1h"] {
20116            let payload = format!(
20117                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
20118                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
20119                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
20120            );
20121            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
20122                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
20123            });
20124            assert_eq!(cb.max_failures, 5);
20125        }
20126    }
20127
20128    // ── rate_limit_codec: integer-magnitude gate ──
20129    //
20130    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
20131    // / 737a676 / d53c922 trajectory landed on every typed-duration /
20132    // typed-byte-size codec in caixa-core lifts onto the fifth typed
20133    // codec — `rate_limit_codec` — through the digit-only magnitude
20134    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
20135    // These tests pin the gate at the serde layer for `:politicas
20136    // :rate-limit` (the only typed slot the codec backs), and at the
20137    // codec-internal `parse` layer for the canonical positive cases.
20138
20139    #[test]
20140    fn rate_limit_serde_rejects_fractional_rate() {
20141        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
20142        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
20143        // wording, which didn't name the canonical-form remediation or
20144        // the round-trip drift the next emit would produce. Now refused
20145        // at deserialize with the canonical-form diagnostic naming the
20146        // offending `"1.5"` magnitude and the round-trip drift wording.
20147        let payload = r#"{"rateLimit":"1.5/s"}"#;
20148        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20149        let msg = err.to_string();
20150        assert!(
20151            msg.contains("not a non-negative integer"),
20152            "expected integer-magnitude diagnostic in {msg:?}"
20153        );
20154        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
20155        assert!(
20156            msg.contains("THEORY.md"),
20157            "missing render-determinism contract citation in {msg:?}"
20158        );
20159    }
20160
20161    #[test]
20162    fn rate_limit_serde_rejects_leading_plus_sign() {
20163        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
20164        // permissive-`+` parse), so `"+100/s"` silently parsed to
20165        // `RateLimit { 100, 1s }` and round-tripped through `render` to
20166        // `"100/s"` — a *different* canonical string on the next emit,
20167        // breaking the THEORY.md Part V render-determinism contract
20168        // exactly the way the peer duration codecs' `"+30s"` case did.
20169        // This is the load-bearing class the digit-only gate closes
20170        // beyond what `u32::from_str`'s strictness covers on its own.
20171        let payload = r#"{"rateLimit":"+100/s"}"#;
20172        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20173        let msg = err.to_string();
20174        assert!(
20175            msg.contains("not a non-negative integer"),
20176            "expected integer-magnitude diagnostic in {msg:?}"
20177        );
20178        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
20179    }
20180
20181    #[test]
20182    fn rate_limit_serde_rejects_leading_minus_sign() {
20183        // The signed-negative arm: `"-1/s"` lands on the
20184        // non-canonical-but-numeric branch via the `i64` fallback (the
20185        // `f64` parse also succeeds), surfacing the canonical-form
20186        // diagnostic. Replaces the prior value-laundered "not a u32"
20187        // wording with the unified diagnostic across signs.
20188        let payload = r#"{"rateLimit":"-1/s"}"#;
20189        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20190        let msg = err.to_string();
20191        assert!(
20192            msg.contains("not a non-negative integer"),
20193            "expected integer-magnitude diagnostic in {msg:?}"
20194        );
20195        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
20196    }
20197
20198    #[test]
20199    fn rate_limit_serde_rejects_decimal_shaped_integer() {
20200        // `"100.0/s"` is integer-valued numerically but not in the
20201        // codec's accepted set — `render` emits `"100/s"`, so the
20202        // round-trip would drift. Lifted to the canonical-form
20203        // diagnostic peer with the duration codec's `"1.0s"` case
20204        // (1c55a2a).
20205        let payload = r#"{"rateLimit":"100.0/s"}"#;
20206        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20207        let msg = err.to_string();
20208        assert!(
20209            msg.contains("not a non-negative integer"),
20210            "expected integer-magnitude diagnostic in {msg:?}"
20211        );
20212        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
20213    }
20214
20215    #[test]
20216    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
20217        // Non-numeric, non-digit-only input lands on the existing
20218        // narrower `"not a u32"` arm (preserved for diagnostic-shape
20219        // stability on the parser-shape footgun case). Pin this so a
20220        // future relaxation of the numeric-fallback predicate doesn't
20221        // silently collapse garbage onto the canonical-form arm — same
20222        // partition the peer duration codecs draw between
20223        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
20224        let payload = r#"{"rateLimit":"abc/s"}"#;
20225        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20226        let msg = err.to_string();
20227        assert!(
20228            msg.contains("not a u32"),
20229            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
20230        );
20231        assert!(
20232            !msg.contains("not a non-negative integer"),
20233            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
20234        );
20235    }
20236
20237    #[test]
20238    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
20239        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
20240        // u32's range. The digit-only gate passes; `u32::from_str`
20241        // fails on overflow. Surface that with the overflow-shaped
20242        // diagnostic naming the offending magnitude verbatim, peer
20243        // with `supervisor::duration_codec`'s overflow arm. Pinning
20244        // the wording so a future refactor doesn't silently collapse
20245        // overflow onto the canonical-form arm.
20246        let payload = r#"{"rateLimit":"4294967296/s"}"#;
20247        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20248        let msg = err.to_string();
20249        assert!(
20250            msg.contains("overflows u32"),
20251            "expected overflow diagnostic in {msg:?}"
20252        );
20253        assert!(
20254            msg.contains("\"4294967296\""),
20255            "missing offending magnitude in {msg:?}"
20256        );
20257    }
20258
20259    #[test]
20260    fn rate_limit_serde_rejects_leading_zero_magnitude() {
20261        // `"0100/s"` is digit-only, so the existing
20262        // non-digit-only / sign / fractional arm doesn't catch it —
20263        // `u32::from_str("0100")` returns `Ok(100)`, so before this
20264        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
20265        // round-tripped through `render` to `"100/s"` — a *different*
20266        // canonical string on the next emit, breaking the THEORY.md
20267        // Part V render-determinism contract exactly the way the
20268        // peer `"+100/s"` case did before the leading-`+` arm landed.
20269        // This is the load-bearing class the leading-zero gate closes
20270        // beyond what the existing digit-only / sign / fractional
20271        // gates cover, and the peer arm to the leading-`+` test
20272        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
20273        // canonical-form-drift axis.
20274        let payload = r#"{"rateLimit":"0100/s"}"#;
20275        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20276        let msg = err.to_string();
20277        assert!(
20278            msg.contains("non-canonical leading zero"),
20279            "expected leading-zero diagnostic in {msg:?}"
20280        );
20281        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
20282        assert!(
20283            msg.contains("THEORY.md"),
20284            "missing render-determinism contract citation in {msg:?}"
20285        );
20286    }
20287
20288    #[test]
20289    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
20290        // `"00/s"` is the degenerate leading-zero case — every byte
20291        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
20292        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
20293        // a *different* canonical string, same render-determinism
20294        // violation. The single-byte `"0/s"` itself is in the
20295        // accepted set (round-trips losslessly through `render`,
20296        // refused downstream by `PolicyRateLimitZero`); the
20297        // multi-byte `"00/s"` is not. Pins the boundary between the
20298        // accepted single-`0` and the rejected leading-zero class.
20299        let payload = r#"{"rateLimit":"00/s"}"#;
20300        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20301        let msg = err.to_string();
20302        assert!(
20303            msg.contains("non-canonical leading zero"),
20304            "expected leading-zero diagnostic in {msg:?}"
20305        );
20306        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
20307    }
20308
20309    #[test]
20310    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
20311        // Cross-window pin — the gate is window-agnostic; the
20312        // leading-zero class is a property of the magnitude, not the
20313        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
20314        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
20315        // single-window coverage extended across the three canonical
20316        // windows the codec accepts.
20317        let payload = r#"{"rateLimit":"007/h"}"#;
20318        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20319        let msg = err.to_string();
20320        assert!(
20321            msg.contains("non-canonical leading zero"),
20322            "expected leading-zero diagnostic in {msg:?}"
20323        );
20324        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
20325    }
20326
20327    #[test]
20328    fn rate_limit_serde_rejects_leading_whitespace() {
20329        // `" 100/s"` — the canonical paste-from-aligned-doc /
20330        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
20331        // the top-level `s.trim()` silently ate the leading space and
20332        // parsed the value to `RateLimit { 100, 1s }`, which then
20333        // round-tripped through `render` to `"100/s"` (a *different*
20334        // canonical string on the next emit) — the exact
20335        // canonical-form-drift class the leading-`+` / leading-zero
20336        // arms already close, extended to the whitespace byte class.
20337        let payload = r#"{"rateLimit":" 100/s"}"#;
20338        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20339        let msg = err.to_string();
20340        assert!(
20341            msg.contains("contains whitespace byte"),
20342            "expected whitespace diagnostic in {msg:?}"
20343        );
20344        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20345        assert!(
20346            msg.contains("THEORY.md"),
20347            "missing render-determinism contract citation in {msg:?}"
20348        );
20349    }
20350
20351    #[test]
20352    fn rate_limit_serde_rejects_trailing_whitespace() {
20353        // `"100/s "` — the canonical shell-history / trailing-space
20354        // paste footgun. Before this gate the top-level `s.trim()`
20355        // silently ate the trailing space and parsed to
20356        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
20357        // next emit — same canonical-form drift as the leading-space
20358        // sibling, closed on the same whitespace-byte arm.
20359        let payload = r#"{"rateLimit":"100/s "}"#;
20360        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20361        let msg = err.to_string();
20362        assert!(
20363            msg.contains("contains whitespace byte"),
20364            "expected whitespace diagnostic in {msg:?}"
20365        );
20366        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20367    }
20368
20369    #[test]
20370    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
20371        // `"100 / s"` — the canonical typographically-spaced author
20372        // shape (the same idiom every prose reference to a rate limit
20373        // renders as, mistakenly retained when the value is pasted
20374        // into a codec-shaped slot). Before this gate the per-part
20375        // `rate_str.trim()` / `unit.trim()` calls silently ate both
20376        // spaces on either side of `/` and parsed to
20377        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
20378        // codec's *internal* whitespace-tolerance vector, orthogonal
20379        // to the leading / trailing surface but the same canonical-
20380        // form-drift class. Pins the arm as strictly stronger than the
20381        // pre-existing top-level `s.trim()` behavior: it fires on
20382        // whitespace anywhere in the value, not just at the string
20383        // boundary.
20384        let payload = r#"{"rateLimit":"100 / s"}"#;
20385        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20386        let msg = err.to_string();
20387        assert!(
20388            msg.contains("contains whitespace byte"),
20389            "expected whitespace diagnostic in {msg:?}"
20390        );
20391        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20392    }
20393
20394    #[test]
20395    fn rate_limit_serde_rejects_tab_byte() {
20396        // `"\t100/s"` — the canonical paste-from-indented-doc /
20397        // paste-from-YAML-block-scalar footgun where a tab byte leads
20398        // the magnitude. Pins that the gate covers tab (`0x09`) as
20399        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
20400        // members and both would be silently swallowed by `s.trim()`
20401        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
20402        // space alone to the full ASCII-whitespace set (space `0x20`,
20403        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
20404        // the tab arm as a representative of the non-space members.
20405        let payload = r#"{"rateLimit":"\t100/s"}"#;
20406        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20407        let msg = err.to_string();
20408        assert!(
20409            msg.contains("contains whitespace byte"),
20410            "expected whitespace diagnostic in {msg:?}"
20411        );
20412        assert!(
20413            msg.contains("0x09"),
20414            "missing offending tab byte in {msg:?}"
20415        );
20416    }
20417
20418    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
20419    //
20420    // Successor to the ASCII-whitespace arm (1ad7755) on
20421    // `rate_limit_codec` — closes the strictly-complementary class the
20422    // byte-scan cannot see, through the lifted
20423    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
20424
20425    #[test]
20426    fn rate_limit_serde_rejects_leading_nbsp() {
20427        // NBSP prefix — paste-from-typography footgun. Byte-scan
20428        // misses, `str::trim` silently strips it, value drifts to
20429        // `"100/s"` on next serialize.
20430        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
20431        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20432        let msg = err.to_string();
20433        assert!(
20434            msg.contains("non-ASCII Unicode whitespace character"),
20435            "expected non-ASCII whitespace diagnostic in {msg:?}"
20436        );
20437        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
20438    }
20439
20440    #[test]
20441    fn rate_limit_serde_rejects_internal_em_space() {
20442        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
20443        // paste-from-typography footgun on the `<integer>/<unit>`
20444        // shape.
20445        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
20446        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20447        let msg = err.to_string();
20448        assert!(
20449            msg.contains("non-ASCII Unicode whitespace character"),
20450            "expected non-ASCII whitespace diagnostic in {msg:?}"
20451        );
20452        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
20453    }
20454
20455    #[test]
20456    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
20457        // Positive-control pin: every ASCII-only canonical form the
20458        // renderer emits stays accepted through the new arm.
20459        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
20460            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
20461            let p: MeshPolicy = serde_json::from_str(&payload)
20462                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
20463            assert!(p.rate_limit.is_some());
20464        }
20465    }
20466
20467    #[test]
20468    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
20469        // The boundary case — `"0/s"` is the canonical form
20470        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
20471        // it at the parse layer; the downstream
20472        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
20473        // `rate == 0` at the typed-validate layer above. Pins the
20474        // partition: the leading-zero gate at the codec layer does
20475        // not poach the rate-zero semantic-validation arm at the
20476        // typed-validate layer above (a future stricter codec must
20477        // not reject `"0/s"` here, or it'd collapse the diagnostic
20478        // partitioning that lets `PolicyRateLimitZero` name the
20479        // offending typed slot).
20480        let payload = r#"{"rateLimit":"0/s"}"#;
20481        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
20482            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
20483        });
20484        let rl = policy.rate_limit.expect("rate_limit must be Some");
20485        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
20486        assert_eq!(
20487            rl.window,
20488            Duration::from_secs(1),
20489            "single-`0` magnitude with `s` unit must parse to window=1s"
20490        );
20491    }
20492
20493    #[test]
20494    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
20495        // The complementary boundary pin — every magnitude
20496        // `render` emits starts with `[1-9]` (or is the single byte
20497        // `"0"`), so the canonical-form predicate is `(len == 1) ||
20498        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
20499        // '1'` case explicitly so a future tightening of the gate
20500        // (e.g. an over-eager "no leading digit < 5" rule, or a
20501        // mistakenly anchored start-of-magnitude byte check) lands
20502        // here before the canonical-forms-iterating test would catch
20503        // it.
20504        let payload = r#"{"rateLimit":"100/s"}"#;
20505        let policy: MeshPolicy = serde_json::from_str(payload)
20506            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
20507        let rl = policy.rate_limit.expect("rate_limit must be Some");
20508        assert_eq!(
20509            rl.rate, 100,
20510            "canonical-100 magnitude must parse to rate=100"
20511        );
20512    }
20513
20514    #[test]
20515    fn rate_limit_serde_accepts_integer_canonical_forms() {
20516        // Pin the happy-path: every canonical author shape `render`
20517        // ever emits parses cleanly through the codec post-gate. The
20518        // codec's accepted set (post-gate) is exactly its emitted set
20519        // for the integer-magnitude class — same property
20520        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
20521        // gates guarantee on the peer codecs. Iterating across rate
20522        // magnitudes (including `"0"`, which the codec accepts even
20523        // though `validate_politicas` rejects `rate == 0` at the typed
20524        // layer above) closes the codec contract at the parse layer
20525        // independently of the validate layer.
20526        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
20527            for unit_lit in ["s", "m", "h"] {
20528                let lit = format!("{rate_lit}/{unit_lit}");
20529                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
20530                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
20531                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
20532                });
20533                let rl = policy.rate_limit.expect("rate_limit must be Some");
20534                assert_eq!(
20535                    rl.rate,
20536                    rate_lit.parse::<u32>().unwrap(),
20537                    "rate mismatch for {lit:?}"
20538                );
20539            }
20540        }
20541    }
20542
20543    #[test]
20544    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
20545        // The structural property the gate enforces: serialize ∘
20546        // deserialize is the identity on every canonical author shape.
20547        // Peer of `parse_byte_size`'s and `parse_duration`'s
20548        // `_round_trips_through_render_for_every_canonical_form` tests
20549        // on the rate-limit axis. Before the gate, `"+100/s"` violated
20550        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
20551        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
20552        for rate in [1u32, 100, 5000, 1_000_000] {
20553            for (window, unit) in [
20554                (Duration::from_secs(1), "s"),
20555                (Duration::from_secs(60), "m"),
20556                (Duration::from_secs(3600), "h"),
20557            ] {
20558                let policy = MeshPolicy {
20559                    rate_limit: Some(RateLimit { rate, window }),
20560                    ..Default::default()
20561                };
20562                let json = serde_json::to_string(&policy).unwrap();
20563                let expected = format!("\"{rate}/{unit}\"");
20564                assert!(
20565                    json.contains(&expected),
20566                    "expected {expected:?} in {json:?}"
20567                );
20568                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20569                assert_eq!(
20570                    back.rate_limit, policy.rate_limit,
20571                    "round-trip for {json:?}"
20572                );
20573            }
20574        }
20575    }
20576
20577    // ── self-membership cross-slot gate ──────────────────────────────
20578
20579    #[test]
20580    fn validate_no_self_membership_rejects_self_named_membro() {
20581        // An Aplicacao whose `:membros` lists its own `:nome` is a
20582        // one-node lacre-closure recursion — rejected, naming the parent.
20583        let membros = vec![
20584            membro("catalog", "^0.1"),
20585            membro("checkout", "^0.1"),
20586            membro("cart", "^0.1"),
20587        ];
20588        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
20589        assert!(
20590            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
20591            "got {err:?}"
20592        );
20593    }
20594
20595    #[test]
20596    fn validate_no_self_membership_accepts_distinct_membros() {
20597        // Positive control: distinct member names (including a member
20598        // that is itself an Aplicacao — recursive composition is valid,
20599        // MESH-COMPOSITION §V) pass the gate.
20600        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
20601        validate_no_self_membership(&membros, "checkout").unwrap();
20602    }
20603
20604    #[test]
20605    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
20606        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
20607        // `NoMembros` arm (the more-fundamental "graph must have nodes"
20608        // gate), not by this cross-slot self-edge gate. Keeping the
20609        // self-membership predicate vacuously-ok on the empty input
20610        // matches its supervisor-axis peer
20611        // (`validate_no_self_supervision_empty_children_is_ok`) and
20612        // makes the gate composable from any future call site (an M4
20613        // CR materializer's per-membros validator) without re-checking
20614        // emptiness.
20615        validate_no_self_membership(&[], "checkout").unwrap();
20616    }
20617
20618    #[test]
20619    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
20620        // Pinning the Display: the self-membership diagnostic must name
20621        // the offending caixa verbatim + the "lists itself" framing the
20622        // author can grep for, so the cluster-far failure surfaces at
20623        // build time with one-line remediation. Same diagnostic shape
20624        // as the supervisor-axis `ChildSupervisesSelf` peer.
20625        let membros = vec![membro("orquestra", "^0.1")];
20626        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
20627        let msg = err.to_string();
20628        assert!(
20629            msg.contains("orquestra"),
20630            "diagnostic must name the offending caixa nome (got: {msg:?})"
20631        );
20632        assert!(
20633            msg.contains("lists itself"),
20634            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
20635        );
20636    }
20637
20638    #[test]
20639    fn default_servico_port_constant_pins_canonical_8080_literal() {
20640        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
20641        // at the verbatim `8080` literal both consumers (the
20642        // `Entrada::port` serde default via [`default_port`] and the
20643        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
20644        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
20645        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
20646        // discipline (a085b26) on the per-renderer canonical-K8s-axis
20647        // string-constant axis: a future refactor that drifts the
20648        // constant out from under either consumer surfaces here ahead
20649        // of every per-renderer's first emission. The literal value
20650        // matches the well-known HTTP-alt port the `pleme-computeunit`
20651        // library chart already emits as its `trigger.service.port`
20652        // default — by construction the same value the substrate
20653        // assumes about every Servico's in-cluster L4 listener.
20654        assert_eq!(
20655            DEFAULT_SERVICO_PORT, 8080,
20656            "canonical Servico port literal must remain `8080` verbatim — \
20657             this is the value both the `Entrada::port` serde default and the \
20658             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
20659        );
20660    }
20661
20662    #[test]
20663    fn default_port_helper_returns_canonical_servico_port_constant() {
20664        // The bridge-arm — pins that the [`default_port`] helper
20665        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
20666        // attribute hooks routes through the lifted
20667        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
20668        // literal. A future refactor that re-introduces the `8080`
20669        // literal at the helper's return site (silently re-opening
20670        // the drift footgun this lift closed) surfaces here ahead of
20671        // every author-side `(:entrada (:host … :para …))` slot
20672        // without an explicit `:port`. Peer with the
20673        // `default_namespace_re_export_points_at_caixa_core_canonical`
20674        // pin on the caixa-mesh-side re-export axis.
20675        assert_eq!(
20676            default_port(),
20677            DEFAULT_SERVICO_PORT,
20678            "the serde-default helper must route through the lifted constant"
20679        );
20680    }
20681
20682    #[test]
20683    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
20684        // The end-to-end pin — an author-surface `(:entrada (:host …
20685        // :para …))` without an explicit `:port` slot deserializes to
20686        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
20687        // verbatim. Routes the canonical lifted constant through both
20688        // the serde-default machinery (the `#[serde(default =
20689        // "default_port")]` attribute) and the typed-value-shape
20690        // contract (the resulting [`Entrada::port`] value). A future
20691        // refactor that drifts either axis — replacing the serde
20692        // hook's helper, changing the typed slot's wire shape — would
20693        // surface here before any per-renderer's CNP / Gateway /
20694        // HTTPRoute emission consumed the drifted default.
20695        let entrada: Entrada =
20696            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
20697        assert_eq!(
20698            entrada.port, DEFAULT_SERVICO_PORT,
20699            "the serde default must materialize as the lifted canonical Servico port"
20700        );
20701    }
20702
20703    #[test]
20704    fn servico_port_min_pins_canonical_accept_set_floor() {
20705        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
20706        // verbatim `1` literal every typed `:entrada :port` acceptance
20707        // gate keys off. Peer with the
20708        // [`default_servico_port_constant_pins_canonical_8080_literal`]
20709        // discipline on the canonical-Servico-port-constant axis: a
20710        // future refactor that drifts the accept-set floor out from
20711        // under the sole consumer at [`AplicacaoSpec::validate`]'s
20712        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
20713        // every per-`:entrada` `EntradaPortZero` diagnostic. The
20714        // literal value matches the IANA-registered TCP/UDP port
20715        // space floor (`1..=65535` — port `0` is the "any ephemeral"
20716        // sentinel, not a well-defined destination the substrate's
20717        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
20718        // axis can honor).
20719        assert_eq!(
20720            SERVICO_PORT_MIN, 1,
20721            "canonical Servico port accept-set floor must remain `1` verbatim — \
20722             this is the value the `AplicacaoSpec::validate` gate at \
20723             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
20724        );
20725    }
20726
20727    #[test]
20728    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
20729        // The cross-const invariant pin — the substrate's canonical
20730        // default port must satisfy its own accept-set floor by
20731        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
20732        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
20733        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
20734        // override the operator pins through a future
20735        // `:placement :default-port` slot that lands out-of-range, a
20736        // per-edition Servico-port migration that lifted the floor
20737        // above the previous default without coordinating the pair —
20738        // would silently invalidate the serde-default emission at
20739        // every author-side `(:entrada (:host … :para …))` slot
20740        // without an explicit `:port`: the default port would fall
20741        // below the accept-set floor, the `AplicacaoSpec::validate`
20742        // gate would reject every default-carrying Aplicacao as
20743        // `EntradaPortZero`, and the substrate's typed
20744        // `(defcaixa … :kind Aplicacao)` surface would fail validate
20745        // on every Aplicacao whose author omitted `:entrada :port`
20746        // for the substrate's chosen default — a class of authoring-
20747        // surface footguns the compile-time pin structurally closes.
20748        // Peer with the
20749        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
20750        // (27f9b34) cross-const invariant pin discipline on the peer
20751        // canonical-Helm-per-values-block child-chart-enablement-toggle
20752        // axis pair.
20753        assert!(
20754            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
20755            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
20756             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
20757             every default-carrying `(:entrada (:host … :para …))` slot without an \
20758             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
20759             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
20760        );
20761    }
20762
20763    #[test]
20764    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
20765        // The gate-site pin — asserts the `AplicacaoSpec::validate`
20766        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
20767        // `EntradaPortZero` diagnostic on the below-floor input
20768        // `port: 0` (the only below-floor value the `u16` field can
20769        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
20770        // is the singleton `{0}`). A future refactor that drifts the
20771        // gate off the lifted const (silently re-introducing an
20772        // inline `if e.port == 0` byte-check) surfaces here — the
20773        // pin cannot distinguish `< 1` from `== 0` on the current
20774        // floor, but it *does* pin that the diagnostic fires on `0`
20775        // through whichever gate is wired, so any future accept-set
20776        // floor migration (a hypothetical unprivileged-only
20777        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
20778        // update this test alongside the const declaration —
20779        // structurally guaranteeing the gate + accept-set + pin
20780        // trio move together. Peer with the
20781        // [`rejects_zero_entrada_port`] behavioral pin on the same
20782        // per-`:entrada :port` axis — that pin asserts the pre-lift
20783        // behavioral contract (`port: 0` → `EntradaPortZero`); this
20784        // pin adds the structural link to the lifted floor const.
20785        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
20786        let mut s = three_member_spec();
20787        s.entrada.as_mut().unwrap().port = 0;
20788        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
20789    }
20790
20791    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
20792
20793    #[test]
20794    fn membro_serde_keys_match_lifted_membro_key_consts() {
20795        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
20796        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
20797        // name the exact camelCase JSON keys the
20798        // `#[serde(rename_all = "camelCase")]` attribute on
20799        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
20800        // that each canonical byte-sequence appears verbatim in the
20801        // JSON — a future accidental `rename_all = "snake_case"` /
20802        // `"kebab-case"` / verbatim-field-name flip at the derive
20803        // attribute (any of which would silently break every downstream
20804        // JSON consumer that reaches for one of the two consts via
20805        // `Value::get(...)`) surfaces here as a build-time test failure
20806        // at `aplicacao.rs`, not as an apply-time
20807        // `.get(<stale-canonical-const>)` returning `None` far from the
20808        // derive-attr drift's commit. Peer with the sibling
20809        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
20810        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
20811        // same discipline the SupervisorSpec top-level lift established,
20812        // extended here to the M3 [`Membro`] per-`:membros` axis.
20813        let m = Membro {
20814            caixa: "catalog".into(),
20815            versao: "^0.1".into(),
20816        };
20817        let json = serde_json::to_string(&m).unwrap();
20818        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
20819            let quoted = format!("\"{key}\"");
20820            assert!(
20821                json.contains(&quoted),
20822                "serialized Membro must carry the lifted MEMBRO_KEY_* \
20823                 byte-sequence {quoted} verbatim in the JSON emission \
20824                 (got: {json})",
20825            );
20826        }
20827    }
20828
20829    #[test]
20830    fn membro_key_consts_are_pairwise_distinct() {
20831        // Cross-axis drift-detection pin: a future collapse of the two
20832        // canonical [`Membro`] per-entry byte-strings onto the same
20833        // value (e.g. an accidental copy-paste flip of
20834        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
20835        // silently reroute every downstream probe on one axis onto the
20836        // sibling axis's overlay entry and pass every propagation-probe
20837        // test that expected only the stale axis's value. Peer of the
20838        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
20839        // (40cc4e5).
20840        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
20841        for (i, a) in all.iter().enumerate() {
20842            for b in all.iter().skip(i + 1) {
20843                assert_ne!(
20844                    a, b,
20845                    "MEMBRO_KEY_* consts must be pairwise-distinct \
20846                     canonical byte-sequences — got `{a}` == `{b}`",
20847                );
20848            }
20849        }
20850    }
20851
20852    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
20853    //    URL-path fallback resolver every HTTPRoute-aware renderer
20854    //    reaching for a per-rule path-list resolution routes through.
20855    //    The four pin tests below fix the four-way accept-set the
20856    //    resolver must always honor: (:paths-non-empty-verbatim,
20857    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
20858    //    :paths-preserves-order-across-multiple-entries) — drift on any
20859    //    arm surfaces at caixa-core build time rather than at cluster-
20860    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
20861    //    sibling `:politicas` typed-primitive dispatch axis.
20862
20863    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
20864        Entrada {
20865            host: "example.com".into(),
20866            para: "cart".into(),
20867            paths: paths.into_iter().map(String::from).collect(),
20868            port: DEFAULT_SERVICO_PORT,
20869        }
20870    }
20871
20872    #[test]
20873    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
20874        // The typed `:entrada :paths` slot carries an author-declared
20875        // list — the resolver returns each entry verbatim, no
20876        // catch-all substitution. The canonical "author declared
20877        // paths, honor them verbatim" arm of the path-list dispatch.
20878        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
20879        assert_eq!(
20880            e.resolved_paths(),
20881            vec!["/api/cart", "/api/products"],
20882            "resolved_paths must return each `:entrada :paths` entry \
20883             verbatim when the typed slot is non-empty (got {:?})",
20884            e.resolved_paths(),
20885        );
20886    }
20887
20888    #[test]
20889    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
20890        // Empty `:entrada :paths` slot — the resolver substitutes the
20891        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
20892        // catch-all fallback verbatim. Pins the empty-arm of the
20893        // resolver's four-way accept-set against a future silent
20894        // detour that returned an empty Vec (which would emit an
20895        // HTTPRoute with zero rules — silently dropping every
20896        // external `:entrada` flow at admission time), routed to a
20897        // different fallback shape, or dropped the catch-all
20898        // altogether.
20899        let e = entrada_with_paths(vec![]);
20900        assert_eq!(
20901            e.resolved_paths(),
20902            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
20903            "resolved_paths on empty `:entrada :paths` must fall back \
20904             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
20905             all — got {:?}",
20906            e.resolved_paths(),
20907        );
20908    }
20909
20910    #[test]
20911    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
20912        // Single-entry `:entrada :paths` — the resolver returns the
20913        // single declared path verbatim, NOT the catch-all fallback
20914        // (author declared a path, honor it — the empty-arm and the
20915        // len-1 arm are semantically distinct axes of the resolver's
20916        // accept-set). Pins that the resolver treats "author declared
20917        // one path" as authored input, not as the empty case.
20918        let e = entrada_with_paths(vec!["/api/only"]);
20919        assert_eq!(
20920            e.resolved_paths(),
20921            vec!["/api/only"],
20922            "resolved_paths on single-entry `:entrada :paths` must \
20923             return the declared path verbatim, NOT the catch-all \
20924             fallback (got {:?})",
20925            e.resolved_paths(),
20926        );
20927    }
20928
20929    #[test]
20930    fn resolved_paths_preserves_author_declared_order() {
20931        // The `:entrada :paths` list is author-ordered — the resolver
20932        // preserves the author's declaration order verbatim, since
20933        // per-rule dispatch order at the K8s Gateway API HTTPRoute
20934        // consumer is significant (first-match-wins under the
20935        // path-prefix matcher). Pins against a future silent
20936        // re-sort / dedup / normalize detour that reordered author
20937        // input.
20938        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
20939        assert_eq!(
20940            e.resolved_paths(),
20941            vec!["/z/last", "/a/first", "/m/mid"],
20942            "resolved_paths must preserve author-declared `:entrada \
20943             :paths` order verbatim — got {:?}",
20944            e.resolved_paths(),
20945        );
20946    }
20947
20948    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
20949    //    slot `&[String]` slice accessor every per-`:entrada` consumer
20950    //    that must see the author's declaration verbatim (not the
20951    //    fallback-applied projection the sibling `resolved_paths`
20952    //    returns) routes through. The three pin tests below fix the
20953    //    accept-set the accessor must honor: (:non-empty-byte-equal,
20954    //    :empty-projects-empty-slice, :preserves-author-declared-order)
20955    //    — drift on any arm surfaces at caixa-core build time rather
20956    //    than at cluster-apply time. Peer discipline with the sibling
20957    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
20958    //    peer M3 mesh-slot `Vec<String>`-carry axis.
20959
20960    #[test]
20961    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
20962        // Byte-equal pin: [`Entrada::paths`] must project the raw
20963        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
20964        // slice borrowed from the typed slot's own [`Vec<String>`]
20965        // storage — no re-ordering, no dedup, no per-entry normalization,
20966        // no fallback substitution (the fallback-applying projection is
20967        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
20968        // a future silent detour that re-normalized the list, dropped
20969        // duplicates the [`AplicacaoSpec::validate`]
20970        // `EntradaPathDuplicate` refusal already rejects at build time,
20971        // or (most severe) accidentally routed through the fallback-
20972        // applying sibling and returned the substrate catch-all when
20973        // the author declared an empty list — collapsing the raw-slot
20974        // and fallback-applied axes into one and breaking the
20975        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
20976        //
20977        // Peer of the sibling
20978        // [`Placement::clusters`]-shape byte-equal pin
20979        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20980        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
20981        let fixtures: Vec<Vec<String>> = vec![
20982            Vec::new(),
20983            vec!["/api/cart".into()],
20984            vec!["/api/cart".into(), "/api/products".into()],
20985            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
20986        ];
20987        for paths in fixtures {
20988            let e = Entrada {
20989                host: "example.com".into(),
20990                para: "cart".into(),
20991                paths: paths.clone(),
20992                port: DEFAULT_SERVICO_PORT,
20993            };
20994            assert_eq!(
20995                e.paths(),
20996                paths.as_slice(),
20997                "Entrada::paths must return :entrada :paths verbatim \
20998                 (got {:?}, expected {:?})",
20999                e.paths(),
21000                paths.as_slice(),
21001            );
21002            assert_eq!(
21003                e.paths(),
21004                e.paths.as_slice(),
21005                "Entrada::paths accessor and .paths.as_slice() field \
21006                 access must byte-equal — the accessor is the substrate-\
21007                 primitive typed dispatch every downstream per-`:entrada` \
21008                 raw-slot path-list consumer must route through",
21009            );
21010            assert_eq!(
21011                e.paths().len(),
21012                e.paths.len(),
21013                "Entrada::paths().len() must byte-equal self.paths.len() \
21014                 — a length drift would silently split the paired \
21015                 pre-flight cascade-head `.is_empty()` probe input in \
21016                 the sibling [`Entrada::resolved_paths`] resolver from \
21017                 the per-entry validate loop's traversal input in \
21018                 [`AplicacaoSpec::validate`]",
21019            );
21020        }
21021    }
21022
21023    #[test]
21024    fn resolved_paths_reads_through_lifted_paths_accessor() {
21025        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
21026        // pre-flight `.paths().is_empty()` cascade-head probe (which
21027        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
21028        // catch-all fallback arm when the accessor projects the empty
21029        // slice) and the per-entry `.paths().iter().map(String::as_str)`
21030        // projection (which must reach every entry in the same order
21031        // the accessor projects, so the sibling
21032        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
21033        // per-entry projection stay in lockstep by construction) must
21034        // both key off the lifted accessor. Pins the two-site coherence
21035        // by exercising each production consumer end-to-end: (1) the
21036        // catch-all-fallback arm under the empty slice, (2) the
21037        // author-declared-verbatim arm under a two-entry cohort whose
21038        // per-entry projection must byte-equal the input's per-entry
21039        // author-declared paths in the author's declared order.
21040        //
21041        // Peer of the sibling M3
21042        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
21043        // `validate_placement_reads_through_lifted_clusters_accessor`
21044        // on the sibling `Placement::clusters` reader-site convergence.
21045        let empty = entrada_with_paths(vec![]);
21046        assert_eq!(
21047            empty.resolved_paths(),
21048            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
21049            "resolved_paths on empty :entrada :paths must trip the \
21050             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
21051             catch-all fallback — routing through the lifted paths() \
21052             accessor must not silently drop the fallback arm",
21053        );
21054
21055        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
21056        assert_eq!(
21057            declared.resolved_paths(),
21058            vec!["/api/cart", "/api/products"],
21059            "resolved_paths on non-empty :entrada :paths must return each \
21060             entry verbatim in the author's declared order — routing \
21061             through the lifted paths() accessor must not silently \
21062             reorder or drop entries",
21063        );
21064        // Byte-equal pin against the raw-slot accessor to keep the
21065        // fallback-applying resolver's per-entry projection input in
21066        // lockstep with the raw-slot accessor's projection.
21067        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
21068        assert_eq!(
21069            declared.resolved_paths(),
21070            raw_projected,
21071            "resolved_paths non-empty projection must byte-equal the \
21072             lifted paths() accessor's per-entry String::as_str projection \
21073             — the two projections share the same input slice by \
21074             construction, so any drift here would surface a silent \
21075             re-ordering / dedup / normalization detour in the resolver",
21076        );
21077    }
21078
21079    #[test]
21080    fn validate_reads_through_lifted_entrada_paths_accessor() {
21081        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
21082        // per-entry value-shape gate's `for p in e.paths()` traversal
21083        // (which must reach every entry in the same order the accessor
21084        // projects, so both the per-entry `EntradaPathEmpty` /
21085        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
21086        // the duplicate-detection HashSet insert that trips
21087        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
21088        // projection) must route through the lifted accessor. Pins the
21089        // coherence by exercising each production consumer end-to-end:
21090        // (1) the `EntradaPathEmpty` refusal fires on the second entry
21091        // of a two-entry cohort whose head is valid but tail is empty
21092        // (which requires the loop to reach the second entry through
21093        // the accessor), and (2) the `EntradaPathDuplicate` refusal
21094        // fires on the second entry of a two-entry cohort that shares
21095        // a path (which requires the loop to reach both entries — a
21096        // first-entry-only projection would silently pass since the
21097        // dedup HashSet has room for the first insert).
21098        //
21099        // Peer of the sibling
21100        // `validate_placement_reads_through_lifted_clusters_accessor`
21101        // on the sibling `Placement::clusters` reader-site convergence.
21102        let base = crate::AplicacaoSpec {
21103            membros: vec![crate::Membro {
21104                caixa: "cart".into(),
21105                versao: "^0.1".into(),
21106            }],
21107            contratos: Vec::new(),
21108            politicas: crate::MeshPolicy::default(),
21109            placement: crate::Placement {
21110                estrategia: crate::PlacementStrategy::SingleNode,
21111                clusters: vec!["rio".into()],
21112                shard_key: None,
21113                affinity: None,
21114            },
21115            entrada: Some(Entrada {
21116                host: "example.com".into(),
21117                para: "cart".into(),
21118                paths: vec!["/api/cart".into(), String::new()],
21119                port: DEFAULT_SERVICO_PORT,
21120            }),
21121        };
21122        assert_eq!(
21123            base.validate(),
21124            Err(crate::AplicacaoError::EntradaPathEmpty),
21125            "validate must trip EntradaPathEmpty on the second entry of \
21126             a two-entry cohort — routing through the lifted paths() \
21127             accessor must not silently short-circuit the loop at the \
21128             valid head entry",
21129        );
21130
21131        let mut dup = base;
21132        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
21133        assert_eq!(
21134            dup.validate(),
21135            Err(crate::AplicacaoError::EntradaPathDuplicate {
21136                path: "/api/cart".into(),
21137            }),
21138            "validate must trip EntradaPathDuplicate on the second entry \
21139             of a two-entry cohort that shares a path — routing through \
21140             the lifted paths() accessor must not silently short-circuit \
21141             the dedup HashSet insert at the first entry",
21142        );
21143    }
21144
21145    // ── Entrada::hostname / Entrada::hostnames — the substrate-
21146    //    canonical per-`:entrada` DNS-hostname resolver pair every
21147    //    Gateway-API-aware renderer reaching for a per-listener
21148    //    singular `hostname:` filter (Gateway) or a per-route plural
21149    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
21150    //    The three pin tests below fix the two-way accept-set the pair
21151    //    must always honor: (:singular-byte-equal-to-host,
21152    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
21153    //    on any arm surfaces at caixa-core build time rather than at
21154    //    cluster-apply time when the API server refuses the HTTPRoute
21155    //    for non-intersecting hostname filters. Peer discipline with
21156    //    the sibling `resolved_paths` accept-set pin block above on the
21157    //    per-`:entrada` path-list resolver axis.
21158
21159    fn entrada_with_host(host: &str) -> Entrada {
21160        Entrada {
21161            host: host.into(),
21162            para: "cart".into(),
21163            paths: Vec::new(),
21164            port: DEFAULT_SERVICO_PORT,
21165        }
21166    }
21167
21168    #[test]
21169    fn hostname_returns_entrada_host_byte_equal() {
21170        // The canonical singular-axis pin: [`Entrada::hostname`] must
21171        // return the `:entrada :host` field byte-for-byte, borrowed
21172        // from the typed slot's own [`String`] storage. Pins against a
21173        // future silent detour that re-normalized the host (an
21174        // accidental `.to_lowercase()` — validate_entrada_host already
21175        // enforces lowercase, so any re-normalization is redundant + a
21176        // drift surface between the validator and the accessor), a
21177        // trailing-`.` fully-qualified DNS shape substitution, or a
21178        // Punycode round-trip that lowered a Unicode host through IDNA.
21179        let e = entrada_with_host("checkout.quero.cloud");
21180        assert_eq!(
21181            e.hostname(),
21182            "checkout.quero.cloud",
21183            "Entrada::hostname must return :entrada :host verbatim \
21184             (got {:?})",
21185            e.hostname(),
21186        );
21187        assert_eq!(
21188            e.hostname(),
21189            e.host.as_str(),
21190            "Entrada::hostname must byte-equal the .host field access",
21191        );
21192    }
21193
21194    #[test]
21195    fn hostnames_returns_singleton_of_hostname_accessor() {
21196        // The pair-invariant pin: [`Entrada::hostnames`] must always
21197        // return exactly `vec![hostname()]` — the singleton list whose
21198        // sole entry is the substrate's canonical per-`:entrada`
21199        // singular hostname. Pins the two-consumer coherence axis: the
21200        // Gateway listener's singular `hostname:` filter and the
21201        // HTTPRoute's plural `spec.hostnames[]` filter list must
21202        // agree, else the Gateway API v1.x conformance layer rejects
21203        // the HTTPRoute at attach time with
21204        // `Accepted:False/NoMatchingParent` (the parent Gateway's
21205        // listener hostname doesn't intersect the route's hostname
21206        // filter list) — a divergence whose apply-time symptom is far
21207        // from any single-site commit and never surfaces in the
21208        // emitted YAML. Pinning the pair-invariant here makes any
21209        // future accidental split (an accidental `.to_string() + "."`
21210        // trailing-`.` on the plural side that didn't land on the
21211        // singular side, an accidental prefix stripping on one axis,
21212        // an accidental wildcard prepend the SNI fan-out overlay
21213        // authors on the plural side without a paired singular
21214        // migration) trip at caixa-core build time.
21215        let e = entrada_with_host("checkout.quero.cloud");
21216        assert_eq!(
21217            e.hostnames(),
21218            vec![e.hostname()],
21219            "Entrada::hostnames must return `vec![hostname()]` under \
21220             the pair-invariant — got {:?} vs. singleton {:?}",
21221            e.hostnames(),
21222            vec![e.hostname()],
21223        );
21224    }
21225
21226    #[test]
21227    fn hostnames_is_singleton_under_single_host_author_surface() {
21228        // The singleton-shape pin: under today's single-hostname-per-
21229        // `:entrada` author surface (the `:host` slot is a single
21230        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
21231        // must always return a list of length exactly one. Pins
21232        // against a future silent detour that returned an empty list
21233        // (which would emit an HTTPRoute with `spec.hostnames: []` —
21234        // matching every incoming Host header regardless of the
21235        // Aplicacao's declared ingress apex, silently over-matching
21236        // every foreign VirtualHost the parent Gateway also fronts) or
21237        // a duplicated entry (which the Gateway API v1.x parser
21238        // accepts as a `[]-length-2 list of equal hostnames]` but
21239        // whose semantics differ from the intended singleton). The
21240        // author-surface extension point ("a future `:entrada
21241        // :alt-hosts` list overlay" the docstring names) is the sole
21242        // future axis that flips this pin — that migration will re-
21243        // author this test to pin the new plural cardinality.
21244        let e = entrada_with_host("checkout.quero.cloud");
21245        assert_eq!(
21246            e.hostnames().len(),
21247            1,
21248            "Entrada::hostnames must be a singleton under today's \
21249             single-hostname-per-`:entrada` author surface — got \
21250             length {}: {:?}",
21251            e.hostnames().len(),
21252            e.hostnames(),
21253        );
21254    }
21255
21256    // ── Entrada::destination — the substrate-canonical per-`:entrada`
21257    //    destination-Servico scalar accessor every Gateway-API
21258    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
21259    //    discriminator arg (HTTPRoute name composer) or a per-rule
21260    //    `backendRefs[0].name` axis routes through. The two pin tests
21261    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
21262    //    either arm surfaces at caixa-core build time rather than at
21263    //    cluster-apply time when an HTTPRoute's `metadata.name` and
21264    //    `backendRefs[]` silently disagree on which destination Servico
21265    //    the ingress fronts. Peer discipline with the sibling
21266    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
21267    //    blocks above on the per-`:entrada` path-list / DNS-hostname
21268    //    resolver axes.
21269
21270    #[test]
21271    fn destination_returns_entrada_para_byte_equal() {
21272        // The canonical destination-scalar pin: [`Entrada::destination`]
21273        // must return the `:entrada :para` field byte-for-byte, borrowed
21274        // from the typed slot's own [`String`] storage. Pins against a
21275        // future silent detour that re-normalized the destination (an
21276        // accidental `.to_lowercase()` — the destination Servico is
21277        // already validated as a DNS-1123 label upstream, so any
21278        // re-normalization is redundant + a drift surface between the
21279        // validator and the accessor), a namespace-prefix rewrite (an
21280        // accidental `format!("{namespace}/{para}")` per-CR fully-
21281        // qualified rewrite that didn't land on the peer axis), or a
21282        // per-cluster suffix stamp the operator authors on one
21283        // consumer without the other.
21284        for para in ["cart", "checkout", "catalog", "orders-v2"] {
21285            let e = Entrada {
21286                host: "checkout.quero.cloud".into(),
21287                para: para.into(),
21288                paths: Vec::new(),
21289                port: DEFAULT_SERVICO_PORT,
21290            };
21291            assert_eq!(
21292                e.destination(),
21293                para,
21294                "Entrada::destination must return :entrada :para verbatim \
21295                 (got {:?}, expected {para:?})",
21296                e.destination(),
21297            );
21298            assert_eq!(
21299                e.destination(),
21300                e.para.as_str(),
21301                "Entrada::destination must byte-equal the .para field access",
21302            );
21303        }
21304    }
21305
21306    #[test]
21307    fn destination_borrows_from_entrada_para_storage() {
21308        // The borrow-not-copy pin: [`Entrada::destination`] must
21309        // return a `&str` slice that borrows from the typed slot's
21310        // own [`String`] storage — same-address invariant with
21311        // `entrada.para.as_str()`. Pins against a future silent detour
21312        // that allocated a fresh `String` (`self.para.clone()` in the
21313        // body would type-check but silently drop the borrow, and
21314        // every downstream consumer that assumed the returned slice
21315        // outlives `&self` would break on a stale-reference use-after-
21316        // free). Peer with the sibling `hostname_returns_entrada_
21317        // host_byte_equal` on the singular-DNS-hostname axis.
21318        let e = entrada_with_host("checkout.quero.cloud");
21319        let dest = e.destination();
21320        let para_slice = e.para.as_str();
21321        assert_eq!(
21322            dest.as_ptr(),
21323            para_slice.as_ptr(),
21324            "Entrada::destination must borrow from the .para String's \
21325             backing storage — a fresh allocation here means the \
21326             accessor no longer names the substrate-primitive typed \
21327             dispatch and every downstream consumer would silently \
21328             carry a detached copy",
21329        );
21330        assert_eq!(
21331            dest.len(),
21332            para_slice.len(),
21333            "Entrada::destination and .para.as_str() must byte-equal in \
21334             length as well as in address",
21335        );
21336    }
21337
21338    #[test]
21339    fn port_returns_entrada_port_verbatim_across_permutations() {
21340        // The canonical L4-port-scalar pin: [`Entrada::port`] must
21341        // return the `:entrada :port` field verbatim as a `u16` across
21342        // every author-declared value in the validated accept-set
21343        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
21344        // silent detour that clamped the port (an accidental
21345        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
21346        // land on the peer [`AplicacaoSpec::port_for_destination`]
21347        // resolver), rewrote it through a per-cluster port-remap table
21348        // the operator authors on one consumer without the other, or
21349        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
21350        // serde-default value (which would silently collapse the
21351        // distinction between "author explicitly declared `:port 8080`"
21352        // and "author omitted the slot and inherited the default" the
21353        // future per-cluster override slot depends on). Peer with the
21354        // sibling `destination_returns_entrada_para_byte_equal` +
21355        // `hostname_returns_entrada_host_byte_equal` pins on the
21356        // per-`:entrada` `&str` scalar axes.
21357        for port in [
21358            SERVICO_PORT_MIN,
21359            DEFAULT_SERVICO_PORT,
21360            8443u16,
21361            9090u16,
21362            u16::MAX,
21363        ] {
21364            let e = Entrada {
21365                host: "checkout.quero.cloud".into(),
21366                para: "cart".into(),
21367                paths: Vec::new(),
21368                port,
21369            };
21370            assert_eq!(
21371                e.port(),
21372                port,
21373                "Entrada::port must return :entrada :port verbatim \
21374                 (got {}, expected {port})",
21375                e.port(),
21376            );
21377            assert_eq!(
21378                e.port(),
21379                e.port,
21380                "Entrada::port accessor and .port field access must \
21381                 byte-equal — the accessor is the substrate-primitive \
21382                 typed dispatch every downstream L4-port consumer must \
21383                 route through",
21384            );
21385        }
21386    }
21387
21388    #[test]
21389    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
21390        // Two-consumer coherence pin: the
21391        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
21392        // (which reads through [`Entrada::port`] to compare against
21393        // [`SERVICO_PORT_MIN`]) and the
21394        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
21395        // through [`Entrada::port`] to emit the per-destination
21396        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
21397        // lifted accessor, so any future rebrand on the typed slot's
21398        // reader shape lands at exactly one place. Pins the two-site
21399        // coherence by exercising a below-floor port through validate
21400        // (which must reject) and a validated in-accept-set port through
21401        // port_for_destination (which must emit the same value the
21402        // accessor returns).
21403        let mut spec = three_member_spec();
21404        if let Some(e) = spec.entrada.as_mut() {
21405            e.port = 0;
21406        }
21407        assert_eq!(
21408            spec.validate().unwrap_err(),
21409            AplicacaoError::EntradaPortZero,
21410            "validate must reject `:entrada :port 0` through the lifted \
21411             Entrada::port accessor — port zero lies below \
21412             SERVICO_PORT_MIN and the validator routes through port() \
21413             to name the floor",
21414        );
21415
21416        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
21417            let mut spec = three_member_spec();
21418            if let Some(e) = spec.entrada.as_mut() {
21419                e.port = port;
21420            }
21421            spec.validate().expect(
21422                "entrada with in-accept-set :port must validate — the \
21423                 structural-floor gate reads through Entrada::port",
21424            );
21425            let entrada_ref = spec.entrada().expect(":entrada present");
21426            assert_eq!(
21427                spec.port_for_destination(entrada_ref.destination()),
21428                entrada_ref.port(),
21429                "port_for_destination(entrada.destination()) must equal \
21430                 entrada.port() — the two consumers of the per-:entrada \
21431                 L4-port axis (validator, per-destination resolver) both \
21432                 route through Entrada::port",
21433            );
21434        }
21435    }
21436
21437    #[test]
21438    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
21439        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
21440        // must return the `:contratos :de` field byte-for-byte, borrowed
21441        // from the typed slot's own [`String`] storage. Peer of the
21442        // sibling `destination_returns_entrada_para_byte_equal` pin on
21443        // the per-`:entrada` axis — same "the substrate-primitive
21444        // accessor must byte-equal the raw field access verbatim across
21445        // every author-declared value" discipline extended to the
21446        // per-`:contratos` caller arm. Pins against a future silent
21447        // detour that re-normalized the caller (an accidental
21448        // `.to_lowercase()` — every `:contratos :de` is validated as a
21449        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
21450        // re-normalization is redundant + a drift surface between the
21451        // validator and the accessor), a namespace-prefix rewrite (an
21452        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
21453        // rewrite that didn't land on the peer axis), or a per-cluster
21454        // suffix stamp the operator authors on one consumer without the
21455        // other.
21456        for de in ["cart", "checkout", "catalog", "orders-v2"] {
21457            let c = WitContract {
21458                de: de.into(),
21459                para: "downstream".into(),
21460                wit: "wasi:http/proxy".into(),
21461                endpoint: Some("/lookup".into()),
21462                subject: None,
21463                slot: None,
21464            };
21465            assert_eq!(
21466                c.source(),
21467                de,
21468                "WitContract::source must return :contratos :de verbatim \
21469                 (got {:?}, expected {de:?})",
21470                c.source(),
21471            );
21472            assert_eq!(
21473                c.source(),
21474                c.de.as_str(),
21475                "WitContract::source must byte-equal the .de field access",
21476            );
21477        }
21478    }
21479
21480    #[test]
21481    fn wit_contract_source_borrows_from_de_storage() {
21482        // The borrow-not-copy pin: [`WitContract::source`] must return a
21483        // `&str` slice that borrows from the typed slot's own [`String`]
21484        // storage — same-address invariant with `c.de.as_str()`. Pins
21485        // against a future silent detour that allocated a fresh `String`
21486        // (`self.de.clone()` in the body would type-check but silently
21487        // drop the borrow, and every downstream consumer that assumed
21488        // the returned slice outlives `&self` would break on a stale-
21489        // reference use-after-free). Peer of the sibling
21490        // `destination_borrows_from_entrada_para_storage` on the
21491        // per-`:entrada` axis.
21492        let c = WitContract {
21493            de: "cart".into(),
21494            para: "catalog".into(),
21495            wit: "wasi:http/proxy".into(),
21496            endpoint: Some("/lookup".into()),
21497            subject: None,
21498            slot: None,
21499        };
21500        let src = c.source();
21501        let de_slice = c.de.as_str();
21502        assert_eq!(
21503            src.as_ptr(),
21504            de_slice.as_ptr(),
21505            "WitContract::source must borrow from the .de String's \
21506             backing storage — a fresh allocation here means the \
21507             accessor no longer names the substrate-primitive typed \
21508             dispatch and every downstream consumer would silently \
21509             carry a detached copy",
21510        );
21511        assert_eq!(
21512            src.len(),
21513            de_slice.len(),
21514            "WitContract::source and .de.as_str() must byte-equal in \
21515             length as well as in address",
21516        );
21517    }
21518
21519    #[test]
21520    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
21521        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
21522        // must return the `:contratos :para` field byte-for-byte,
21523        // borrowed from the typed slot's own [`String`] storage. Peer of
21524        // the sibling `destination_returns_entrada_para_byte_equal` on
21525        // the per-`:entrada` axis — both accessors name "the destination-
21526        // Servico byte-string" concept on their respective mesh-slot
21527        // atoms (per-ingress apex vs. per-typed-edge callee) and both
21528        // must project the underlying `.para` field verbatim so every
21529        // downstream renderer that composes them with peer accessors
21530        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
21531        // per-edge L4 port emit site) reads the same byte-string the
21532        // author declared.
21533        for para in ["catalog", "payment", "orders", "inventory-v3"] {
21534            let c = WitContract {
21535                de: "cart".into(),
21536                para: para.into(),
21537                wit: "wasi:http/proxy".into(),
21538                endpoint: Some("/lookup".into()),
21539                subject: None,
21540                slot: None,
21541            };
21542            assert_eq!(
21543                c.destination(),
21544                para,
21545                "WitContract::destination must return :contratos :para \
21546                 verbatim (got {:?}, expected {para:?})",
21547                c.destination(),
21548            );
21549            assert_eq!(
21550                c.destination(),
21551                c.para.as_str(),
21552                "WitContract::destination must byte-equal the .para \
21553                 field access",
21554            );
21555        }
21556    }
21557
21558    #[test]
21559    fn wit_contract_destination_borrows_from_para_storage() {
21560        // The borrow-not-copy pin: [`WitContract::destination`] must
21561        // return a `&str` slice that borrows from the typed slot's own
21562        // [`String`] storage — same-address invariant with
21563        // `c.para.as_str()`. Peer of the sibling
21564        // `destination_borrows_from_entrada_para_storage` on the
21565        // per-`:entrada` axis.
21566        let c = WitContract {
21567            de: "cart".into(),
21568            para: "catalog".into(),
21569            wit: "wasi:http/proxy".into(),
21570            endpoint: Some("/lookup".into()),
21571            subject: None,
21572            slot: None,
21573        };
21574        let dest = c.destination();
21575        let para_slice = c.para.as_str();
21576        assert_eq!(
21577            dest.as_ptr(),
21578            para_slice.as_ptr(),
21579            "WitContract::destination must borrow from the .para \
21580             String's backing storage — a fresh allocation here means \
21581             the accessor no longer names the substrate-primitive typed \
21582             dispatch and every downstream consumer would silently \
21583             carry a detached copy",
21584        );
21585        assert_eq!(
21586            dest.len(),
21587            para_slice.len(),
21588            "WitContract::destination and .para.as_str() must byte-equal \
21589             in length as well as in address",
21590        );
21591    }
21592
21593    #[test]
21594    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
21595        // The canonical per-`:contratos` WIT-world-reference scalar pin:
21596        // [`WitContract::world_ref`] must return the `:contratos :wit`
21597        // field byte-for-byte, borrowed from the typed slot's own
21598        // [`String`] storage. Sibling of the peer per-`:contratos`
21599        // [`WitContract::source`] / [`WitContract::destination`]
21600        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
21601        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
21602        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
21603        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
21604        // "the substrate-primitive accessor must byte-equal the raw
21605        // field access verbatim across every author-declared value"
21606        // discipline extended to the per-`:contratos` WIT-world arm.
21607        // Pins against a future silent detour that re-canonicalized the
21608        // WIT world reference (an accidental `.to_lowercase()` pass that
21609        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
21610        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
21611        // gate is already lowercase-prefixed so any re-normalization is
21612        // redundant + a drift surface between the validator and the
21613        // accessor), an M4-promotion-shape rewrite that formatted a
21614        // typed WIT-world enum through [`Display`] and silently drifted
21615        // the printer output from the source `caixa.lisp`, or a per-
21616        // cluster WIT-alias rewrite that didn't land on the peer field-
21617        // access sites. Five values sweep the shape-dispatch accept-set
21618        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
21619        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
21620        // `wasi:keyvalue/`).
21621        for (wit, endpoint, subject, slot) in [
21622            ("wasi:http/proxy", Some("/lookup"), None, None),
21623            ("http:proxy", Some("/health"), None, None),
21624            ("nats:pub-sub", None, Some("orders.paid"), None),
21625            ("kafka:events", None, Some("checkout-events"), None),
21626            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
21627        ] {
21628            let c = WitContract {
21629                de: "cart".into(),
21630                para: "downstream".into(),
21631                wit: wit.into(),
21632                endpoint: endpoint.map(str::to_string),
21633                subject: subject.map(str::to_string),
21634                slot: slot.map(str::to_string),
21635            };
21636            assert_eq!(
21637                c.world_ref(),
21638                wit,
21639                "WitContract::world_ref must return :contratos :wit \
21640                 verbatim (got {:?}, expected {wit:?})",
21641                c.world_ref(),
21642            );
21643            assert_eq!(
21644                c.world_ref(),
21645                c.wit.as_str(),
21646                "WitContract::world_ref must byte-equal the .wit field \
21647                 access",
21648            );
21649        }
21650    }
21651
21652    #[test]
21653    fn wit_contract_world_ref_borrows_from_wit_storage() {
21654        // The borrow-not-copy pin: [`WitContract::world_ref`] must
21655        // return a `&str` slice that borrows from the typed slot's own
21656        // [`String`] storage — same-address invariant with
21657        // `c.wit.as_str()`. Pins against a future silent detour that
21658        // allocated a fresh `String` (`self.wit.clone()` in the body
21659        // would type-check but silently drop the borrow, and every
21660        // downstream consumer that assumed the returned slice outlives
21661        // `&self` would break on a stale-reference use-after-free — the
21662        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
21663        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
21664        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
21665        // / [`is_pubsub`][WitContract::is_pubsub] /
21666        // [`is_store`][WitContract::is_store] methods route through —
21667        // each borrow from the WitContract's own storage and each would
21668        // silently misbehave if this accessor produced a detached copy).
21669        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
21670        // [`WitContract::destination`] and per-`:entrada`
21671        // [`Entrada::destination`] / [`Entrada::hostname`] and
21672        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
21673        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
21674        let c = WitContract {
21675            de: "cart".into(),
21676            para: "catalog".into(),
21677            wit: "wasi:http/proxy".into(),
21678            endpoint: Some("/lookup".into()),
21679            subject: None,
21680            slot: None,
21681        };
21682        let world = c.world_ref();
21683        let wit_slice = c.wit.as_str();
21684        assert_eq!(
21685            world.as_ptr(),
21686            wit_slice.as_ptr(),
21687            "WitContract::world_ref must borrow from the .wit String's \
21688             backing storage — a fresh allocation here means the \
21689             accessor no longer names the substrate-primitive typed \
21690             dispatch and every downstream consumer would silently carry \
21691             a detached copy",
21692        );
21693        assert_eq!(
21694            world.len(),
21695            wit_slice.len(),
21696            "WitContract::world_ref and .wit.as_str() must byte-equal in \
21697             length as well as in address",
21698        );
21699    }
21700
21701    #[test]
21702    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
21703        // Sibling-triple invariant pin composing all three per-`:contratos`
21704        // substrate-primitive typed dispatches — [`WitContract::source`]
21705        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
21706        // [`WitContract::world_ref`] — at the joint
21707        // `(source(), destination(), world_ref())` call shape every
21708        // renderer that fans on per-edge caller-callee-shape identity
21709        // keys off. The invariant, evaluated per-contract:
21710        //
21711        //   (c.source(), c.destination(), c.world_ref())
21712        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
21713        //
21714        // Closes the last unlifted per-`:contratos` scalar axis — every
21715        // downstream consumer that reads the triple now routes through
21716        // exactly three typed dispatches on the substrate primitive,
21717        // not two typed + one open-coded field access. A future refactor
21718        // that silently split any one accessor's projection (an
21719        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
21720        // canonicalization that didn't reach the peer `source`/
21721        // `destination` arms, an accidental `source()` per-cluster
21722        // caller-alias rewrite that didn't land on the `world_ref` peer)
21723        // surfaces at caixa-core build time. Peer of the sibling per-
21724        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
21725        // per-`:entrada` `(hostname(), destination())` (6db982c /
21726        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
21727        // axes, extended to the per-`:contratos` triple.
21728        for (de, para, wit, endpoint, subject, slot) in [
21729            (
21730                "cart",
21731                "catalog",
21732                "wasi:http/proxy",
21733                Some("/lookup"),
21734                None,
21735                None,
21736            ),
21737            (
21738                "checkout",
21739                "orders",
21740                "nats:pub-sub",
21741                None,
21742                Some("orders.paid"),
21743                None,
21744            ),
21745            (
21746                "cart",
21747                "kv",
21748                "wasi:keyvalue/store",
21749                None,
21750                None,
21751                Some("carts/{cart_id}"),
21752            ),
21753            (
21754                "orders-v2",
21755                "inventory-v3",
21756                "http:proxy",
21757                Some("/reserve"),
21758                None,
21759                None,
21760            ),
21761        ] {
21762            let c = WitContract {
21763                de: de.into(),
21764                para: para.into(),
21765                wit: wit.into(),
21766                endpoint: endpoint.map(str::to_string),
21767                subject: subject.map(str::to_string),
21768                slot: slot.map(str::to_string),
21769            };
21770            assert_eq!(
21771                (c.source(), c.destination(), c.world_ref()),
21772                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
21773                "(WitContract::source, ::destination, ::world_ref) must \
21774                 project (.de, .para, .wit) verbatim across every author-\
21775                 declared triple (got ({:?}, {:?}, {:?}), expected \
21776                 ({de:?}, {para:?}, {wit:?}))",
21777                c.source(),
21778                c.destination(),
21779                c.world_ref(),
21780            );
21781        }
21782    }
21783
21784    #[test]
21785    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
21786        // The canonical per-`:contratos` owned-form caller-callee-pair
21787        // pin: [`WitContract::edge_pair`] must return the
21788        // `(source(), destination())` tuple in owned form byte-for-byte,
21789        // projected through the lifted [`WitContract::source`] /
21790        // [`WitContract::destination`] scalar accessors. Pins the
21791        // composite-projection invariant on the per-`:contratos`
21792        // mesh-slot atom — every author-declared `(de, para)` pair must
21793        // round-trip verbatim through the substrate primitive's typed
21794        // dispatch, so the nine [`AplicacaoError`] diagnostic-
21795        // construction sites the accessor now feeds
21796        // ([`AplicacaoError::EmptyWit`],
21797        // [`AplicacaoError::ContratoEndpointEmpty`],
21798        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
21799        // [`AplicacaoError::ContratoEndpointInvalid`],
21800        // [`AplicacaoError::ContratoSubjectEmpty`],
21801        // [`AplicacaoError::ContratoSubjectInvalid`],
21802        // [`AplicacaoError::ContratoSlotEmpty`],
21803        // [`AplicacaoError::ContratoSlotInvalid`],
21804        // [`AplicacaoError::ContratoDuplicate`]) all read the same
21805        // `(de, para)` label pair every author sees at the source
21806        // `caixa.lisp`. Pins against a future silent detour that swapped
21807        // the `.0` / `.1` arms (an accidental `(destination(),
21808        // source())` re-order in the body would silently invert every
21809        // downstream diagnostic's `de:` / `para:` label pair, silently
21810        // reversing the direction of every operator-facing typed error
21811        // arrow), a fresh-allocation shape drift (an accidental
21812        // `.to_string()` on one arm but not the other would leave the
21813        // owned/borrowed pair mismatched vs. the sibling `source()` /
21814        // `destination()` returns), or an M4 per-cluster caller/callee-
21815        // alias rewrite that landed on `source()` without reaching
21816        // `destination()` (or vice versa). Peer of the sibling per-
21817        // `:contratos` `(source, destination, world_ref)` triple
21818        // pin above on the mesh-slot-atom scalar-value axes, extended
21819        // to the owned-form pair-projection axis.
21820        for (de, para, wit, endpoint, subject, slot) in [
21821            (
21822                "cart",
21823                "catalog",
21824                "wasi:http/proxy",
21825                Some("/lookup"),
21826                None,
21827                None,
21828            ),
21829            (
21830                "checkout",
21831                "orders",
21832                "nats:pub-sub",
21833                None,
21834                Some("orders.paid"),
21835                None,
21836            ),
21837            (
21838                "cart",
21839                "kv",
21840                "wasi:keyvalue/store",
21841                None,
21842                None,
21843                Some("carts/{cart_id}"),
21844            ),
21845            (
21846                "orders-v2",
21847                "inventory-v3",
21848                "http:proxy",
21849                Some("/reserve"),
21850                None,
21851                None,
21852            ),
21853        ] {
21854            let c = WitContract {
21855                de: de.into(),
21856                para: para.into(),
21857                wit: wit.into(),
21858                endpoint: endpoint.map(str::to_string),
21859                subject: subject.map(str::to_string),
21860                slot: slot.map(str::to_string),
21861            };
21862            assert_eq!(
21863                c.edge_pair(),
21864                (de.to_string(), para.to_string()),
21865                "WitContract::edge_pair must return (:contratos :de, \
21866                 :contratos :para) as an owned tuple verbatim (got {:?}, \
21867                 expected ({de:?}, {para:?}))",
21868                c.edge_pair(),
21869            );
21870        }
21871    }
21872
21873    #[test]
21874    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
21875        // The composition pin: [`WitContract::edge_pair`] must return
21876        // exactly `(source().to_string(), destination().to_string())` —
21877        // the owned form of the sibling accessor pair — so any future
21878        // refactor that silently re-authored the caller-arm / callee-arm
21879        // projection to bypass the lifted scalar accessors (an accidental
21880        // `(self.de.clone(), self.para.clone())` regression back to the
21881        // raw field-access shape, an M4-typed-caller-enum `Display`
21882        // re-canonicalization on `source()` that didn't reach
21883        // `edge_pair()`, a per-cluster alias rewrite the operator lands
21884        // on `destination()` without reaching this composite projection)
21885        // trips at caixa-core build time. Pins the "typed dispatch
21886        // composes with typed dispatch, not with raw field access"
21887        // discipline every downstream diagnostic-construction site now
21888        // routes through — a `de:` / `para:` label pair whose
21889        // projection silently drifted off the substrate primitive's
21890        // scalar accessors would silently split the diagnostic's self-
21891        // locating signal from the source `caixa.lisp` author's view.
21892        // Peer of the sibling per-`:politicas` `is_empty` /
21893        // `validate_politicas` accessor-routing-pin family on the M3
21894        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
21895        let c = WitContract {
21896            de: "cart".into(),
21897            para: "catalog".into(),
21898            wit: "wasi:http/proxy".into(),
21899            endpoint: Some("/lookup".into()),
21900            subject: None,
21901            slot: None,
21902        };
21903        assert_eq!(
21904            c.edge_pair(),
21905            (c.source().to_string(), c.destination().to_string()),
21906            "WitContract::edge_pair must compose exactly \
21907             (source().to_string(), destination().to_string()) — a \
21908             bypass of either sibling accessor here would silently \
21909             decouple the composite-projection axis from the \
21910             substrate-primitive scalar accessors every downstream \
21911             consumer routes through",
21912        );
21913    }
21914
21915    #[test]
21916    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
21917     {
21918        // The canonical per-`:contratos` owned-form
21919        // caller-callee-world-ref-triple pin:
21920        // [`WitContract::edge_triple`] must return the
21921        // `(source(), destination(), world_ref())` tuple in owned form
21922        // byte-for-byte, projected through the lifted
21923        // [`WitContract::source`] / [`WitContract::destination`] /
21924        // [`WitContract::world_ref`] scalar accessors. Pins the
21925        // composite-projection invariant on the per-`:contratos`
21926        // mesh-slot atom — every author-declared `(de, para, wit)`
21927        // triple must round-trip verbatim through the substrate
21928        // primitive's typed dispatch, so the nine
21929        // [`AplicacaoError`] diagnostic-construction sites the
21930        // accessor now feeds (the [`WitTarget`]-dispatch's eight
21931        // wrong-target / missing-target / invalid-wit / capability-
21932        // with-payload arms in [`WitContract::target`], plus the
21933        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
21934        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
21935        // read the same `(de, para, wit)` triple every author sees at
21936        // the source `caixa.lisp`. Pins against a future silent
21937        // detour that swapped any two arms (an accidental `(destination(),
21938        // source(), world_ref())` re-order in the body would silently
21939        // invert every downstream diagnostic's `de:` / `para:` label
21940        // pair, silently reversing the direction of every operator-
21941        // facing typed error arrow), a fresh-allocation shape drift
21942        // (an accidental `.to_string()` skipped on one arm would leave
21943        // the owned/borrowed triple mismatched vs. the sibling
21944        // `source()` / `destination()` / `world_ref()` returns), or an
21945        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
21946        // canonicalization pass that landed on one accessor without
21947        // reaching the peers. Peer of the sibling per-`:contratos`
21948        // caller-callee-pair
21949        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
21950        // pin on the mesh-slot-atom composite-projection axis,
21951        // extended to the triple-projection axis.
21952        for (de, para, wit, endpoint, subject, slot) in [
21953            (
21954                "cart",
21955                "catalog",
21956                "wasi:http/proxy",
21957                Some("/lookup"),
21958                None,
21959                None,
21960            ),
21961            (
21962                "checkout",
21963                "orders",
21964                "nats:pub-sub",
21965                None,
21966                Some("orders.paid"),
21967                None,
21968            ),
21969            (
21970                "cart",
21971                "kv",
21972                "wasi:keyvalue/store",
21973                None,
21974                None,
21975                Some("carts/{cart_id}"),
21976            ),
21977            (
21978                "orders-v2",
21979                "inventory-v3",
21980                "http:proxy",
21981                Some("/reserve"),
21982                None,
21983                None,
21984            ),
21985        ] {
21986            let c = WitContract {
21987                de: de.into(),
21988                para: para.into(),
21989                wit: wit.into(),
21990                endpoint: endpoint.map(str::to_string),
21991                subject: subject.map(str::to_string),
21992                slot: slot.map(str::to_string),
21993            };
21994            assert_eq!(
21995                c.edge_triple(),
21996                (de.to_string(), para.to_string(), wit.to_string()),
21997                "WitContract::edge_triple must return (:contratos :de, \
21998                 :contratos :para, :contratos :wit) as an owned triple \
21999                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
22000                c.edge_triple(),
22001            );
22002        }
22003    }
22004
22005    #[test]
22006    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
22007        // The composition pin: [`WitContract::edge_triple`] must return
22008        // exactly `(source().to_string(), destination().to_string(),
22009        // world_ref().to_string())` — the owned form of the sibling
22010        // scalar-accessor triple — so any future refactor that silently
22011        // re-authored one arm's projection to bypass the lifted scalar
22012        // accessors (an accidental `(self.de.clone(), self.para.clone(),
22013        // self.wit.clone())` regression back to the raw field-access
22014        // shape the internal `edge` closure and the ContratoDuplicate
22015        // diagnostic both carried before this lift landed, an
22016        // M4-typed-caller-enum `Display` re-canonicalization on
22017        // `source()` that didn't reach `edge_triple()`, a per-cluster
22018        // alias rewrite the operator lands on `destination()` /
22019        // `world_ref()` without reaching this composite projection)
22020        // trips at caixa-core build time. Pins the "typed dispatch
22021        // composes with typed dispatch, not with raw field access"
22022        // discipline every downstream diagnostic-construction site now
22023        // routes through — a `de:` / `para:` / `wit:` triple whose
22024        // projection silently drifted off the substrate primitive's
22025        // scalar accessors would silently split the diagnostic's self-
22026        // locating signal from the source `caixa.lisp` author's view.
22027        // Peer of the sibling per-`:contratos` edge_pair composition-
22028        // pin above on the mesh-slot-atom composite-projection axis.
22029        let c = WitContract {
22030            de: "cart".into(),
22031            para: "catalog".into(),
22032            wit: "wasi:http/proxy".into(),
22033            endpoint: Some("/lookup".into()),
22034            subject: None,
22035            slot: None,
22036        };
22037        assert_eq!(
22038            c.edge_triple(),
22039            (
22040                c.source().to_string(),
22041                c.destination().to_string(),
22042                c.world_ref().to_string(),
22043            ),
22044            "WitContract::edge_triple must compose exactly \
22045             (source().to_string(), destination().to_string(), \
22046             world_ref().to_string()) — a bypass of any sibling accessor \
22047             here would silently decouple the composite-projection axis \
22048             from the substrate-primitive scalar accessors every \
22049             downstream consumer routes through",
22050        );
22051    }
22052
22053    #[test]
22054    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
22055        // The canonical semantics-pin: [`WitContract::edge_triple`] must
22056        // project the full `(de, para, wit)` identity of a `:contratos`
22057        // edge — the sub-triple every triple-carrying
22058        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
22059        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
22060        // missing-target, capability-with-payload, invalid-wit, and the
22061        // duplicate-gate). Rejects a drift in shape (an accidental
22062        // silent detour that returned a `(de, para)` pair or added an
22063        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
22064        // would trip here because the return type would no longer
22065        // pattern-match the eight `let (de, para, wit) = edge();`
22066        // destructures the [`WitContract::target`] dispatch feeds off
22067        // + the paired duplicate-gate `let (de, para, wit) =
22068        // c.edge_triple();` destructure in
22069        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
22070        // `:contratos` caller-callee-pair pin above extended to the
22071        // triple projection surface: closes the "one composite
22072        // accessor per typed diagnostic-construction sub-tuple"
22073        // discipline on the per-`:contratos` mesh-slot-atom axis.
22074        let c = WitContract {
22075            de: "checkout".into(),
22076            para: "orders".into(),
22077            wit: "nats:pub-sub".into(),
22078            endpoint: None,
22079            subject: Some("orders.paid".into()),
22080            slot: None,
22081        };
22082        let (de, para, wit) = c.edge_triple();
22083        assert_eq!(de, "checkout");
22084        assert_eq!(para, "orders");
22085        assert_eq!(wit, "nats:pub-sub");
22086    }
22087
22088    #[test]
22089    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
22090     {
22091        // The composition pin: [`WitContract::identity`] must return
22092        // exactly `(source(), destination(), world_ref(), endpoint(),
22093        // subject(), slot())` — the borrowed form of the six-scalar-
22094        // accessor identity axis. Any future refactor that silently
22095        // re-authored one arm's projection to bypass a scalar accessor
22096        // (a `self.de.as_str()` regression back to raw field access on
22097        // any of the three required arms, a `self.endpoint.as_deref()`
22098        // regression on any of the three optional arms, an M4 per-
22099        // cluster caller/callee-alias rewrite the operator lands on
22100        // `source()` / `destination()` without reaching this composite
22101        // projection) trips at caixa-core build time. Sweeps four
22102        // permutations of the WIT-shape × payload lattice — HTTP with
22103        // endpoint, pub-sub with subject, store with slot, payload-less
22104        // capability — so every payload arm is exercised. Peer of the
22105        // sibling per-`:contratos`
22106        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
22107        // composition pin on the mesh-slot-atom composite-projection
22108        // axis; extends the discipline from the (de, para, wit) prefix
22109        // onto the full-identity axis carrying the three payload arms.
22110        for (de, para, wit, endpoint, subject, slot) in [
22111            (
22112                "cart",
22113                "catalog",
22114                "wasi:http/proxy",
22115                Some("/lookup"),
22116                None,
22117                None,
22118            ),
22119            (
22120                "checkout",
22121                "orders",
22122                "nats:pub-sub",
22123                None,
22124                Some("orders.paid"),
22125                None,
22126            ),
22127            (
22128                "cart",
22129                "kv",
22130                "wasi:keyvalue/store",
22131                None,
22132                None,
22133                Some("carts/{cart_id}"),
22134            ),
22135            ("audit", "sink", "wasi:logging", None, None, None),
22136        ] {
22137            let c = WitContract {
22138                de: de.into(),
22139                para: para.into(),
22140                wit: wit.into(),
22141                endpoint: endpoint.map(str::to_owned),
22142                subject: subject.map(str::to_owned),
22143                slot: slot.map(str::to_owned),
22144            };
22145            assert_eq!(
22146                c.identity(),
22147                (
22148                    c.source(),
22149                    c.destination(),
22150                    c.world_ref(),
22151                    c.endpoint(),
22152                    c.subject(),
22153                    c.slot(),
22154                ),
22155                "WitContract::identity must compose exactly \
22156                 (source(), destination(), world_ref(), endpoint(), \
22157                 subject(), slot()) — a bypass of any sibling accessor \
22158                 here would silently decouple the identity-projection \
22159                 axis from the substrate-primitive scalar accessors \
22160                 every dedup-key consumer routes through",
22161            );
22162        }
22163    }
22164
22165    #[test]
22166    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
22167        // The canonical semantics-pin: [`WitContract::identity`] must
22168        // project the six-axis (de, para, wit, endpoint, subject, slot)
22169        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22170        // gate keys off — two `WitContract`s that agree on all six axes
22171        // are the same typed edge declared twice, the graph-edge
22172        // analogue of duplicate `:membros` / `:placement :clusters` /
22173        // `:entrada :paths` entries. Rejects a shape drift (an
22174        // accidental silent detour that returned a prefix tuple or
22175        // added an extra field) by pattern-matching the six-arm shape.
22176        // Peer of the sibling per-`:contratos`
22177        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
22178        // pin extended from the (de, para, wit) prefix onto the full
22179        // six-axis identity that the dedup key rides.
22180        let c = WitContract {
22181            de: "cart".into(),
22182            para: "catalog".into(),
22183            wit: "wasi:http/proxy".into(),
22184            endpoint: Some("/products/:id".into()),
22185            subject: None,
22186            slot: None,
22187        };
22188        let (de, para, wit, endpoint, subject, slot) = c.identity();
22189        assert_eq!(de, "cart");
22190        assert_eq!(para, "catalog");
22191        assert_eq!(wit, "wasi:http/proxy");
22192        assert_eq!(endpoint, Some("/products/:id"));
22193        assert_eq!(subject, None);
22194        assert_eq!(slot, None);
22195
22196        // Two byte-identical contracts must produce equal identities —
22197        // the dedup key's foundational invariant.
22198        let c2 = c.clone();
22199        assert_eq!(c.identity(), c2.identity());
22200
22201        // Any change on any of the six axes must break the identity —
22202        // sweeps by mutating one axis at a time.
22203        let mut mutated = c.clone();
22204        mutated.de = "search".into();
22205        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
22206        let mut mutated = c.clone();
22207        mutated.para = "warehouse".into();
22208        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
22209        let mut mutated = c.clone();
22210        mutated.wit = "http:legacy".into();
22211        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
22212        let mut mutated = c.clone();
22213        mutated.endpoint = Some("/search".into());
22214        assert_ne!(
22215            c.identity(),
22216            mutated.identity(),
22217            "endpoint axis must partition"
22218        );
22219        let mut mutated = c.clone();
22220        mutated.subject = Some("orders.paid".into());
22221        assert_ne!(
22222            c.identity(),
22223            mutated.identity(),
22224            "subject axis must partition"
22225        );
22226        let mut mutated = c;
22227        mutated.slot = Some("carts/{id}".into());
22228        assert_ne!(mutated.identity().5, None, "slot axis must partition");
22229    }
22230
22231    #[test]
22232    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
22233        // The canonical per-`:contratos` structural-self-edge pin:
22234        // [`WitContract::is_self_loop`] must return `true` when the
22235        // `:de` and `:para` fields agree byte-for-byte, across every
22236        // WIT-shape variant the per-edge shape family carries. Pins
22237        // the shape-agnostic identity-space partition the
22238        // [`AplicacaoSpec::validate`] self-edge gate at
22239        // caixa-core/src/aplicacao.rs:5559 fires against — all four
22240        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
22241        // under the same one predicate. Four permutations sweep the
22242        // accept-set: HTTP with endpoint, pub-sub with subject, KV
22243        // store with slot, and payload-less capability.
22244        for (nome, wit, endpoint, subject, slot) in [
22245            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
22246            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
22247            (
22248                "kv",
22249                "wasi:keyvalue/store",
22250                None,
22251                None,
22252                Some("carts/{cart_id}"),
22253            ),
22254            ("audit", "wasi:logging", None, None, None),
22255        ] {
22256            let c = WitContract {
22257                de: nome.into(),
22258                para: nome.into(),
22259                wit: wit.into(),
22260                endpoint: endpoint.map(str::to_string),
22261                subject: subject.map(str::to_string),
22262                slot: slot.map(str::to_string),
22263            };
22264            assert!(
22265                c.is_self_loop(),
22266                "WitContract::is_self_loop must return true when \
22267                 :contratos :de == :contratos :para (got false on \
22268                 {nome:?} under {wit:?})",
22269            );
22270        }
22271    }
22272
22273    #[test]
22274    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
22275        // The complement pin: [`WitContract::is_self_loop`] must return
22276        // `false` on every well-shaped inter-Servico contract (the
22277        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
22278        // names — "Servico A calls Servico B" between two distinct
22279        // graph nodes). Pins against a future silent detour that
22280        // inverted the predicate (an accidental `!= ` swap for `==`
22281        // would silently reject every legitimate inter-Servico edge
22282        // and admit every self-edge — the exact inversion of the
22283        // author-intended shape). Four permutations sweep the same
22284        // WIT-shape accept-set the sibling positive-arm test carries.
22285        for (de, para, wit, endpoint, subject, slot) in [
22286            (
22287                "cart",
22288                "catalog",
22289                "wasi:http/proxy",
22290                Some("/lookup"),
22291                None,
22292                None,
22293            ),
22294            (
22295                "checkout",
22296                "orders",
22297                "nats:pub-sub",
22298                None,
22299                Some("orders.paid"),
22300                None,
22301            ),
22302            (
22303                "cart",
22304                "kv",
22305                "wasi:keyvalue/store",
22306                None,
22307                None,
22308                Some("carts/{cart_id}"),
22309            ),
22310            ("audit", "sink", "wasi:logging", None, None, None),
22311        ] {
22312            let c = WitContract {
22313                de: de.into(),
22314                para: para.into(),
22315                wit: wit.into(),
22316                endpoint: endpoint.map(str::to_string),
22317                subject: subject.map(str::to_string),
22318                slot: slot.map(str::to_string),
22319            };
22320            assert!(
22321                !c.is_self_loop(),
22322                "WitContract::is_self_loop must return false when \
22323                 :contratos :de differs from :contratos :para (got true \
22324                 on {de:?} → {para:?} under {wit:?})",
22325            );
22326        }
22327    }
22328
22329    #[test]
22330    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
22331        // The composition pin: [`WitContract::is_self_loop`] must
22332        // resolve to exactly `self.source() == self.destination()` —
22333        // the equality probe of the sibling scalar-accessor pair — so
22334        // any future refactor that silently re-authored the predicate
22335        // to bypass the lifted scalar accessors (an accidental
22336        // `self.de == self.para` regression back to the raw field-
22337        // access shape, an M4-typed-caller-enum identity-comparison
22338        // rule that landed on `source()` without reaching
22339        // `destination()`, a per-cluster alias rewrite the operator
22340        // pins on `destination()` without reaching this predicate)
22341        // trips at caixa-core build time. Pins the "typed dispatch
22342        // composes with typed dispatch, not with raw field access"
22343        // discipline the sibling [`WitContract::edge_pair`] /
22344        // [`WitContract::edge_triple`] composite-projection accessors
22345        // already carry, extended onto the per-edge endpoint-equality
22346        // predicate axis. Positive and complement arms both fire.
22347        let self_edge = WitContract {
22348            de: "cart".into(),
22349            para: "cart".into(),
22350            wit: "wasi:http/proxy".into(),
22351            endpoint: Some("/lookup".into()),
22352            subject: None,
22353            slot: None,
22354        };
22355        assert_eq!(
22356            self_edge.is_self_loop(),
22357            self_edge.source() == self_edge.destination(),
22358            "WitContract::is_self_loop must compose exactly \
22359             `source() == destination()` — a bypass of either sibling \
22360             accessor here would silently decouple the endpoint-\
22361             equality predicate from the substrate-primitive scalar \
22362             accessors every downstream consumer routes through",
22363        );
22364        let inter_edge = WitContract {
22365            de: "cart".into(),
22366            para: "catalog".into(),
22367            wit: "wasi:http/proxy".into(),
22368            endpoint: Some("/lookup".into()),
22369            subject: None,
22370            slot: None,
22371        };
22372        assert_eq!(
22373            inter_edge.is_self_loop(),
22374            inter_edge.source() == inter_edge.destination(),
22375            "WitContract::is_self_loop must compose exactly \
22376             `source() == destination()` on the complement arm too",
22377        );
22378    }
22379
22380    #[test]
22381    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
22382        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
22383        // pin: [`WitContract::endpoint`] must return the `:contratos
22384        // :endpoint` field byte-for-byte, borrowed from the typed slot's
22385        // own `Option<String>` storage. Peer of the sibling
22386        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
22387        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
22388        // mesh-slot `Option<String>` optional-scalar axes — same "the
22389        // substrate-primitive accessor must byte-equal the raw field
22390        // access verbatim across every author-declared value" discipline
22391        // extended to the per-`:contratos` HTTP-payload-carrier arm.
22392        // Pins against a future silent detour that re-canonicalized the
22393        // endpoint (an accidental percent-encoding pass that didn't
22394        // reach the peer field-access site at the dedup key, a per-CR
22395        // fully-qualified prefix rewrite the operator authors on one
22396        // consumer without the other, or an M4 typed-path-template
22397        // `Display` re-canonicalization that silently drifted the
22398        // printer output from the source `caixa.lisp`). Four values
22399        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
22400        // gate upstream admits (short root-path, dashed, param-shaped,
22401        // deep-hierarchy).
22402        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
22403            let c = WitContract {
22404                de: "cart".into(),
22405                para: "catalog".into(),
22406                wit: "wasi:http/proxy".into(),
22407                endpoint: Some(endpoint.into()),
22408                subject: None,
22409                slot: None,
22410            };
22411            assert_eq!(
22412                c.endpoint(),
22413                Some(endpoint),
22414                "WitContract::endpoint must return :contratos :endpoint \
22415                 verbatim (got {:?}, expected Some({endpoint:?}))",
22416                c.endpoint(),
22417            );
22418            assert_eq!(
22419                c.endpoint(),
22420                c.endpoint.as_deref(),
22421                "WitContract::endpoint must byte-equal the .endpoint \
22422                 field's `.as_deref()` projection",
22423            );
22424        }
22425    }
22426
22427    #[test]
22428    fn wit_contract_endpoint_none_when_field_is_none() {
22429        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
22430        // payload-carrier accessor pin: when the typed slot is absent —
22431        // the canonical shape under a non-HTTP `:wit` world per the
22432        // [`WitContract::target`]-enforced shape ↔ target partition
22433        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
22434        // carries `:slot`, [`WitTarget::Capability`] carries none) —
22435        // [`WitContract::endpoint`] must return `None`. Pins against a
22436        // future silent detour that projected the absent slot to a
22437        // `Some("")` empty-string default (the canonical `Option<String>`
22438        // → `String` collapse footgun the sibling M2
22439        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22440        // emptiness predicates already guard on the peer M2 typed-slot
22441        // surfaces), a `Some("None")` stringified-None round-trip, or a
22442        // `Some` arm whose contents were derived from a sibling slot (an
22443        // accidental fallback to the `:subject` / `:slot` payload that
22444        // read the pub-sub / store payload into the endpoint axis).
22445        // Three contracts sweep the accept-set every non-HTTP `:wit`
22446        // world lands on — pub-sub NATS, key/value, and payload-less
22447        // capability.
22448        for (wit, subject, slot) in [
22449            ("nats:pub-sub", Some("orders.paid"), None),
22450            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22451            ("wasi:cli/environment", None, None),
22452        ] {
22453            let c = WitContract {
22454                de: "cart".into(),
22455                para: "downstream".into(),
22456                wit: wit.into(),
22457                endpoint: None,
22458                subject: subject.map(str::to_string),
22459                slot: slot.map(str::to_string),
22460            };
22461            assert!(
22462                c.endpoint().is_none(),
22463                "WitContract::endpoint must return None when the typed \
22464                 slot is absent under :wit {wit:?} (got {:?})",
22465                c.endpoint(),
22466            );
22467            assert_eq!(
22468                c.endpoint(),
22469                c.endpoint.as_deref(),
22470                "WitContract::endpoint must byte-equal the .endpoint \
22471                 field's `.as_deref()` projection in the absent arm",
22472            );
22473        }
22474    }
22475
22476    #[test]
22477    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
22478        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
22479        // an `Option<&str>` whose `Some` arm borrows from the typed
22480        // slot's own [`String`] storage — same-address invariant with
22481        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
22482        // detour that allocated a fresh `String`
22483        // (`self.endpoint.clone().map(...)` in the body would type-check
22484        // but silently drop the borrow, and every downstream consumer
22485        // that assumed the returned slice outlives `&self` would break
22486        // on a stale-reference use-after-free — the [`WitContract::target`]
22487        // Http-arm payload extraction rebinds the returned `Option<&str>`
22488        // through `.ok_or_else(...)` and threads the `&str` payload into
22489        // [`WitTarget::Http { endpoint: &'a str }`], the
22490        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
22491        // [`ContratoIdentity`] dedup key threads the returned
22492        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
22493        // from the WitContract's own storage and each would silently
22494        // misbehave if this accessor produced a detached copy). Peer of
22495        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
22496        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22497        // shaped optional-scalar axes — first extension of the
22498        // `Option<&str>` borrow-not-copy discipline onto the
22499        // per-`:contratos` HTTP-shaped payload-carrier axis.
22500        let c = WitContract {
22501            de: "cart".into(),
22502            para: "catalog".into(),
22503            wit: "wasi:http/proxy".into(),
22504            endpoint: Some("/lookup".into()),
22505            subject: None,
22506            slot: None,
22507        };
22508        let ep = c.endpoint().expect("Some arm");
22509        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
22510        assert_eq!(
22511            ep.as_ptr(),
22512            storage_slice.as_ptr(),
22513            "WitContract::endpoint must borrow from the .endpoint \
22514             String's backing storage — a fresh allocation here means \
22515             the accessor no longer names the substrate-primitive typed \
22516             dispatch and every downstream consumer would silently \
22517             carry a detached copy",
22518        );
22519        assert_eq!(
22520            ep.len(),
22521            storage_slice.len(),
22522            "WitContract::endpoint and .endpoint.as_deref() must byte-\
22523             equal in length as well as in address",
22524        );
22525    }
22526
22527    #[test]
22528    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
22529        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
22530        // pin: [`WitContract::subject`] must return the `:contratos
22531        // :subject` field byte-for-byte, borrowed from the typed slot's
22532        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
22533        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
22534        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22535        // optional-scalar axis — same "the substrate-primitive accessor
22536        // must byte-equal the raw field access verbatim across every
22537        // author-declared value" discipline extended to the pub-sub arm.
22538        // Pins against a future silent detour that re-canonicalized the
22539        // subject (an accidental `.to_lowercase()` normalization that
22540        // didn't reach the peer field-access site at the dedup key, a
22541        // per-CR fully-qualified prefix rewrite the operator authors on
22542        // one consumer without the other, or an M4 typed-subject-template
22543        // `Display` re-canonicalization that silently drifted the printer
22544        // output from the source `caixa.lisp`). Four values sweep the
22545        // NATS accept-set every pub-sub author-declared subject lands on
22546        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
22547        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
22548            let c = WitContract {
22549                de: "cart".into(),
22550                para: "notifier".into(),
22551                wit: "nats:pub-sub".into(),
22552                endpoint: None,
22553                subject: Some(subject.into()),
22554                slot: None,
22555            };
22556            assert_eq!(
22557                c.subject(),
22558                Some(subject),
22559                "WitContract::subject must return :contratos :subject \
22560                 verbatim (got {:?}, expected Some({subject:?}))",
22561                c.subject(),
22562            );
22563            assert_eq!(
22564                c.subject(),
22565                c.subject.as_deref(),
22566                "WitContract::subject must byte-equal the .subject \
22567                 field's `.as_deref()` projection",
22568            );
22569        }
22570    }
22571
22572    #[test]
22573    fn wit_contract_subject_none_when_field_is_none() {
22574        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
22575        // shaped payload-carrier accessor pin: when the typed slot is
22576        // absent — the canonical shape under a non-pub-sub `:wit` world
22577        // per the [`WitContract::target`]-enforced shape ↔ target
22578        // partition ([`WitTarget::Http`] carries `:endpoint`,
22579        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
22580        // carries none) — [`WitContract::subject`] must return `None`.
22581        // Pins against a future silent detour that projected the absent
22582        // slot to a `Some("")` empty-string default (the canonical
22583        // `Option<String>` → `String` collapse footgun the sibling M2
22584        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22585        // emptiness predicates already guard on the peer M2 typed-slot
22586        // surfaces), a `Some("None")` stringified-None round-trip, or a
22587        // `Some` arm whose contents were derived from a sibling slot (an
22588        // accidental fallback to the `:endpoint` / `:slot` payload that
22589        // read the HTTP / store payload into the subject axis). Three
22590        // contracts sweep the accept-set every non-pub-sub `:wit` world
22591        // lands on — HTTP proxy, key/value store, and payload-less
22592        // capability.
22593        for (wit, endpoint, slot) in [
22594            ("wasi:http/proxy", Some("/lookup"), None),
22595            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22596            ("wasi:cli/environment", None, None),
22597        ] {
22598            let c = WitContract {
22599                de: "cart".into(),
22600                para: "downstream".into(),
22601                wit: wit.into(),
22602                endpoint: endpoint.map(str::to_string),
22603                subject: None,
22604                slot: slot.map(str::to_string),
22605            };
22606            assert!(
22607                c.subject().is_none(),
22608                "WitContract::subject must return None when the typed \
22609                 slot is absent under :wit {wit:?} (got {:?})",
22610                c.subject(),
22611            );
22612            assert_eq!(
22613                c.subject(),
22614                c.subject.as_deref(),
22615                "WitContract::subject must byte-equal the .subject \
22616                 field's `.as_deref()` projection in the absent arm",
22617            );
22618        }
22619    }
22620
22621    #[test]
22622    fn wit_contract_subject_borrows_from_subject_storage() {
22623        // The borrow-not-copy pin: [`WitContract::subject`] must return
22624        // an `Option<&str>` whose `Some` arm borrows from the typed
22625        // slot's own [`String`] storage — same-address invariant with
22626        // `c.subject.as_deref().unwrap()`. Pins against a future silent
22627        // detour that allocated a fresh `String`
22628        // (`self.subject.clone().map(...)` in the body would type-check
22629        // but silently drop the borrow, and every downstream consumer
22630        // that assumed the returned slice outlives `&self` would break
22631        // on a stale-reference use-after-free — the [`WitContract::target`]
22632        // PubSub-arm payload extraction rebinds the returned
22633        // `Option<&str>` through `.ok_or_else(...)` and threads the
22634        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
22635        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22636        // [`ContratoIdentity`] dedup key threads the returned
22637        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
22638        // from the WitContract's own storage and each would silently
22639        // misbehave if this accessor produced a detached copy). Peer of
22640        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
22641        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22642        // shaped optional-scalar axis — second extension of the
22643        // `Option<&str>` borrow-not-copy discipline onto the
22644        // per-`:contratos` payload-carrier family, this time on the
22645        // pub-sub arm.
22646        let c = WitContract {
22647            de: "cart".into(),
22648            para: "notifier".into(),
22649            wit: "nats:pub-sub".into(),
22650            endpoint: None,
22651            subject: Some("orders.paid".into()),
22652            slot: None,
22653        };
22654        let sub = c.subject().expect("Some arm");
22655        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
22656        assert_eq!(
22657            sub.as_ptr(),
22658            storage_slice.as_ptr(),
22659            "WitContract::subject must borrow from the .subject \
22660             String's backing storage — a fresh allocation here means \
22661             the accessor no longer names the substrate-primitive typed \
22662             dispatch and every downstream consumer would silently \
22663             carry a detached copy",
22664        );
22665        assert_eq!(
22666            sub.len(),
22667            storage_slice.len(),
22668            "WitContract::subject and .subject.as_deref() must byte-\
22669             equal in length as well as in address",
22670        );
22671    }
22672
22673    #[test]
22674    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
22675        // The canonical per-`:contratos` key/value-store-shaped
22676        // `:slot`-scalar pin: [`WitContract::slot`] must return the
22677        // `:contratos :slot` field byte-for-byte, borrowed from the
22678        // typed slot's own `Option<String>` storage. Peer of the
22679        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
22680        // [`WitContract::subject`] (90de675) accessor pins on the M3
22681        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22682        // optional-scalar axis — same "the substrate-primitive
22683        // accessor must byte-equal the raw field access verbatim
22684        // across every author-declared value" discipline extended to
22685        // the store arm. Pins against a future silent detour that
22686        // re-canonicalized the slot template (an accidental
22687        // `.to_lowercase()` bucket-prefix normalization that didn't
22688        // reach the peer field-access site at the dedup key, a per-CR
22689        // fully-qualified prefix rewrite the operator authors on one
22690        // consumer without the other, or an M4 typed-key-template
22691        // `Display` re-canonicalization that silently drifted the
22692        // printer output from the source `caixa.lisp`). Four values
22693        // sweep the wasi:keyvalue accept-set every store-shaped
22694        // author-declared slot lands on (flat bucket, single-param
22695        // template, multi-param template, nested-hierarchy template).
22696        for slot in [
22697            "sessions",
22698            "carts/{cart_id}",
22699            "orders/{tenant}/{order_id}",
22700            "cache/tenant-a/orders/{id}",
22701        ] {
22702            let c = WitContract {
22703                de: "cart".into(),
22704                para: "kv".into(),
22705                wit: "wasi:keyvalue/store".into(),
22706                endpoint: None,
22707                subject: None,
22708                slot: Some(slot.into()),
22709            };
22710            assert_eq!(
22711                c.slot(),
22712                Some(slot),
22713                "WitContract::slot must return :contratos :slot \
22714                 verbatim (got {:?}, expected Some({slot:?}))",
22715                c.slot(),
22716            );
22717            assert_eq!(
22718                c.slot(),
22719                c.slot.as_deref(),
22720                "WitContract::slot must byte-equal the .slot field's \
22721                 `.as_deref()` projection",
22722            );
22723        }
22724    }
22725
22726    #[test]
22727    fn wit_contract_slot_none_when_field_is_none() {
22728        // The absent-`:slot` arm of the per-`:contratos` store-shaped
22729        // payload-carrier accessor pin: when the typed slot is absent —
22730        // the canonical shape under a non-store `:wit` world per the
22731        // [`WitContract::target`]-enforced shape ↔ target partition
22732        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
22733        // carries `:subject`, [`WitTarget::Capability`] carries none) —
22734        // [`WitContract::slot`] must return `None`. Pins against a
22735        // future silent detour that projected the absent slot to a
22736        // `Some("")` empty-string default (the canonical
22737        // `Option<String>` → `String` collapse footgun the sibling M2
22738        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22739        // emptiness predicates already guard on the peer M2 typed-slot
22740        // surfaces), a `Some("None")` stringified-None round-trip, or
22741        // a `Some` arm whose contents were derived from a sibling
22742        // slot (an accidental fallback to the `:endpoint` / `:subject`
22743        // payload that read the HTTP / pub-sub payload into the store
22744        // axis). Three contracts sweep the accept-set every non-store
22745        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
22746        // payload-less capability.
22747        for (wit, endpoint, subject) in [
22748            ("wasi:http/proxy", Some("/lookup"), None),
22749            ("nats:pub-sub", None, Some("orders.paid")),
22750            ("wasi:cli/environment", None, None),
22751        ] {
22752            let c = WitContract {
22753                de: "cart".into(),
22754                para: "downstream".into(),
22755                wit: wit.into(),
22756                endpoint: endpoint.map(str::to_string),
22757                subject: subject.map(str::to_string),
22758                slot: None,
22759            };
22760            assert!(
22761                c.slot().is_none(),
22762                "WitContract::slot must return None when the typed \
22763                 slot is absent under :wit {wit:?} (got {:?})",
22764                c.slot(),
22765            );
22766            assert_eq!(
22767                c.slot(),
22768                c.slot.as_deref(),
22769                "WitContract::slot must byte-equal the .slot field's \
22770                 `.as_deref()` projection in the absent arm",
22771            );
22772        }
22773    }
22774
22775    #[test]
22776    fn wit_contract_slot_borrows_from_slot_storage() {
22777        // The borrow-not-copy pin: [`WitContract::slot`] must return
22778        // an `Option<&str>` whose `Some` arm borrows from the typed
22779        // slot's own [`String`] storage — same-address invariant with
22780        // `c.slot.as_deref().unwrap()`. Pins against a future silent
22781        // detour that allocated a fresh `String`
22782        // (`self.slot.clone().map(...)` in the body would type-check
22783        // but silently drop the borrow, and every downstream consumer
22784        // that assumed the returned slice outlives `&self` would
22785        // break on a stale-reference use-after-free — the
22786        // [`WitContract::target`] Store-arm payload extraction rebinds
22787        // the returned `Option<&str>` through `.ok_or_else(...)` and
22788        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
22789        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22790        // [`ContratoIdentity`] dedup key threads the returned
22791        // `Option<&str>` into the six-tuple's store arm — each borrow
22792        // from the WitContract's own storage and each would silently
22793        // misbehave if this accessor produced a detached copy). Peer
22794        // of the sibling per-`:contratos` [`WitContract::endpoint`]
22795        // (7020470) / [`WitContract::subject`] (90de675)
22796        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
22797        // shaped optional-scalar axis — third and final extension of
22798        // the `Option<&str>` borrow-not-copy discipline onto the
22799        // per-`:contratos` payload-carrier family, this time on the
22800        // store arm.
22801        let c = WitContract {
22802            de: "cart".into(),
22803            para: "kv".into(),
22804            wit: "wasi:keyvalue/store".into(),
22805            endpoint: None,
22806            subject: None,
22807            slot: Some("carts/{cart_id}".into()),
22808        };
22809        let slot = c.slot().expect("Some arm");
22810        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
22811        assert_eq!(
22812            slot.as_ptr(),
22813            storage_slice.as_ptr(),
22814            "WitContract::slot must borrow from the .slot String's \
22815             backing storage — a fresh allocation here means the \
22816             accessor no longer names the substrate-primitive typed \
22817             dispatch and every downstream consumer would silently \
22818             carry a detached copy",
22819        );
22820        assert_eq!(
22821            slot.len(),
22822            storage_slice.len(),
22823            "WitContract::slot and .slot.as_deref() must byte-equal \
22824             in length as well as in address",
22825        );
22826    }
22827
22828    #[test]
22829    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
22830        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
22831        // [`Membro::nome`] must return the `:membros :caixa` field
22832        // byte-for-byte, borrowed from the typed slot's own [`String`]
22833        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
22834        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22835        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
22836        // slot-atom scalar-value axes — same "the substrate-primitive
22837        // accessor must byte-equal the raw field access verbatim across
22838        // every author-declared value" discipline extended to the
22839        // per-`:membros` member-identity arm. Pins against a future
22840        // silent detour that re-normalized the member identity (an
22841        // accidental `.to_lowercase()` — every `:membros :caixa` is
22842        // validated as a DNS-1123 label upstream via
22843        // [`validate_membro_caixa`], so any re-normalization is
22844        // redundant + a drift surface between the validator and the
22845        // accessor), a namespace-prefix rewrite (an accidental
22846        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
22847        // rewrite that didn't land on the peer axes), or a per-cluster
22848        // alias stamp the operator authors on one consumer without the
22849        // other. Four values sweep the accept-set the DNS-1123 gate
22850        // upstream admits (short single-word / dashed / v-suffixed
22851        // member names).
22852        for name in ["cart", "checkout", "catalog", "orders-v2"] {
22853            let m = Membro {
22854                caixa: name.into(),
22855                versao: "^0.1".into(),
22856            };
22857            assert_eq!(
22858                m.nome(),
22859                name,
22860                "Membro::nome must return :membros :caixa verbatim \
22861                 (got {:?}, expected {name:?})",
22862                m.nome(),
22863            );
22864            assert_eq!(
22865                m.nome(),
22866                m.caixa.as_str(),
22867                "Membro::nome must byte-equal the .caixa field access",
22868            );
22869        }
22870    }
22871
22872    #[test]
22873    fn membro_nome_borrows_from_caixa_storage() {
22874        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
22875        // slice that borrows from the typed slot's own [`String`]
22876        // storage — same-address invariant with `m.caixa.as_str()`. Pins
22877        // against a future silent detour that allocated a fresh `String`
22878        // (`self.caixa.clone()` in the body would type-check but
22879        // silently drop the borrow, and every downstream consumer that
22880        // assumed the returned slice outlives `&self` would break on a
22881        // stale-reference use-after-free — the `HashSet<&str>` collector
22882        // at [`AplicacaoSpec::validate`]'s `names` seed, the
22883        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
22884        // [`AplicacaoSpec::detect_sync_cycles`], the
22885        // [`crate::render::insert_first_seen`] dedup key at
22886        // [`AplicacaoSpec::validate_membros`] — each borrow from the
22887        // Membro's own storage and each would silently misbehave if
22888        // this accessor produced a detached copy). Peer of the sibling
22889        // per-`:contratos` [`WitContract::source`] /
22890        // [`WitContract::destination`] and per-`:entrada`
22891        // [`Entrada::destination`] borrow-invariant pins on the mesh-
22892        // slot-atom scalar-value axes.
22893        let m = Membro {
22894            caixa: "checkout".into(),
22895            versao: "^0.1".into(),
22896        };
22897        let name = m.nome();
22898        let caixa_slice = m.caixa.as_str();
22899        assert_eq!(
22900            name.as_ptr(),
22901            caixa_slice.as_ptr(),
22902            "Membro::nome must borrow from the .caixa String's backing \
22903             storage — a fresh allocation here means the accessor no \
22904             longer names the substrate-primitive typed dispatch and \
22905             every downstream consumer would silently carry a detached \
22906             copy",
22907        );
22908        assert_eq!(
22909            name.len(),
22910            caixa_slice.len(),
22911            "Membro::nome and .caixa.as_str() must byte-equal in length \
22912             as well as in address",
22913        );
22914    }
22915
22916    #[test]
22917    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
22918        // The canonical per-`:membros` member-`:versao`-scalar pin:
22919        // [`Membro::versao_requirement`] must return the
22920        // `:membros :versao` field byte-for-byte, borrowed from the typed
22921        // slot's own [`String`] storage. Sibling of the peer
22922        // `membro_nome_returns_caixa_byte_equal_across_permutations`
22923        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
22924        // — same "the substrate-primitive accessor must byte-equal the
22925        // raw field access verbatim across every author-declared value"
22926        // discipline extended to the per-`:membros` member-`:versao`
22927        // requirement-string arm. Pins against a future silent detour
22928        // that re-canonicalized the requirement (an accidental
22929        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
22930        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
22931        // drifted the printer output away from the source `caixa.lisp`,
22932        // an accidental whitespace trim on `"^ 0.1"` that no consumer
22933        // ever produced from the field-access side, an accidental
22934        // per-cluster lacre-projected concrete-version rewrite that
22935        // didn't land on the peer field-access sites). Five values sweep
22936        // the accept-set the shared
22937        // [`crate::render::require_valid_versao_requirement`] gate
22938        // admits (caret / tilde / exact / wildcard / bare-major).
22939        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
22940            let m = Membro {
22941                caixa: "cart".into(),
22942                versao: req.into(),
22943            };
22944            assert_eq!(
22945                m.versao_requirement(),
22946                req,
22947                "Membro::versao_requirement must return :membros :versao \
22948                 verbatim (got {:?}, expected {req:?})",
22949                m.versao_requirement(),
22950            );
22951            assert_eq!(
22952                m.versao_requirement(),
22953                m.versao.as_str(),
22954                "Membro::versao_requirement must byte-equal the .versao \
22955                 field access",
22956            );
22957        }
22958    }
22959
22960    #[test]
22961    fn membro_versao_requirement_borrows_from_versao_storage() {
22962        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
22963        // return a `&str` slice that borrows from the typed slot's own
22964        // [`String`] storage — same-address invariant with
22965        // `m.versao.as_str()`. Pins against a future silent detour that
22966        // allocated a fresh `String` (`self.versao.clone()` in the body
22967        // would type-check but silently drop the borrow, and every
22968        // downstream consumer that assumed the returned slice outlives
22969        // `&self` would break on a stale-reference use-after-free). Peer
22970        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
22971        // per-`:contratos` [`WitContract::source`] /
22972        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22973        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
22974        // the mesh-slot-atom scalar-value axes.
22975        let m = Membro {
22976            caixa: "checkout".into(),
22977            versao: "^0.1".into(),
22978        };
22979        let req = m.versao_requirement();
22980        let versao_slice = m.versao.as_str();
22981        assert_eq!(
22982            req.as_ptr(),
22983            versao_slice.as_ptr(),
22984            "Membro::versao_requirement must borrow from the .versao \
22985             String's backing storage — a fresh allocation here means \
22986             the accessor no longer names the substrate-primitive typed \
22987             dispatch and every downstream consumer would silently carry \
22988             a detached copy",
22989        );
22990        assert_eq!(
22991            req.len(),
22992            versao_slice.len(),
22993            "Membro::versao_requirement and .versao.as_str() must byte-\
22994             equal in length as well as in address",
22995        );
22996    }
22997
22998    #[test]
22999    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
23000        // Sibling-pair invariant pin composing both per-`:membros`
23001        // substrate-primitive typed dispatches — [`Membro::nome`]
23002        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
23003        // `(nome(), versao_requirement())` call shape every renderer
23004        // that fans on per-member identity + version pin keys off. The
23005        // invariant, evaluated per-member:
23006        //
23007        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
23008        //
23009        // Closes the last unlifted per-`:membros` scalar axis — every
23010        // downstream consumer that reads the pair now routes through
23011        // exactly two typed dispatches on the substrate primitive, not
23012        // one typed + one open-coded field access. A future refactor
23013        // that silently split either accessor's projection (an
23014        // accidental `nome()` namespace-prefix rewrite that didn't
23015        // reach the peer, an accidental `versao_requirement()` lacre-
23016        // projected concrete-version rewrite that didn't land on the
23017        // `nome()` peer) surfaces at caixa-core build time. Peer of the
23018        // sibling per-`:entrada` `(hostname(), destination())` and
23019        // per-`:contratos` `(source(), destination())` pair invariants
23020        // on the mesh-slot-atom scalar-value axes.
23021        for (caixa, versao) in [
23022            ("cart", "^0.1"),
23023            ("checkout", "~0.1.2"),
23024            ("catalog", "0.1.0"),
23025            ("orders-v2", "*"),
23026        ] {
23027            let m = Membro {
23028                caixa: caixa.into(),
23029                versao: versao.into(),
23030            };
23031            assert_eq!(
23032                (m.nome(), m.versao_requirement()),
23033                (m.caixa.as_str(), m.versao.as_str()),
23034                "(Membro::nome, Membro::versao_requirement) must project \
23035                 (.caixa, .versao) verbatim across every author-declared \
23036                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
23037                m.nome(),
23038                m.versao_requirement(),
23039            );
23040        }
23041    }
23042
23043    #[test]
23044    fn validate_membros_empty_gate_routes_through_nome_accessor() {
23045        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
23046        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
23047        // not the raw `.caixa` field access. Structurally: setting
23048        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
23049        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
23050        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
23051        // (i.e. the empty string) — so the emptiness predicate the
23052        // refusal arm reaches under is the accessor-projected value,
23053        // not a peer field that would silently drift under a future
23054        // accessor-side rewrite.
23055        //
23056        // Pins against a future silent detour that (a) re-derived the
23057        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
23058        // instead of `self.nome().is_empty()`, silently disagreeing with
23059        // every peer consumer (the `validate_membro_caixa(m.nome())`
23060        // call one line below, the dedup-key `insert_first_seen(&mut
23061        // seen, m.nome(), …)` two lines below, the emit-side per-
23062        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
23063        // (b) accessor-side introduced a per-tenant alias arm the
23064        // caller was unaware of, silently rewriting an author-declared
23065        // `:caixa "checkout"` to `""` — the raw-field-access gate
23066        // would fail-open while the accessor-routed peer consumers
23067        // would fail-closed, splitting the diagnostic from the actual
23068        // failure surface.
23069        //
23070        // Peer of the sibling
23071        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
23072        // (c0110f1) composition pin — same "the shape-gate predicate
23073        // must route through the substrate-primitive typed dispatch"
23074        // discipline extended onto the per-`:membros` empty-`:caixa`
23075        // refusal-arm axis. Closes the last unlifted `.caixa` production-
23076        // code read site on `Membro` — after this converge every
23077        // caixa-core `.caixa` field access outside the accessor's own
23078        // body is either a test-side field-setter (in-module tests
23079        // constructing invalid-shape inputs) or a doc-comment reference.
23080        let mut s = three_member_spec();
23081        s.membros[1].caixa = String::new();
23082        assert!(
23083            s.membros[1].nome().is_empty(),
23084            "Membro::nome must byte-equal the .caixa field access — an \
23085             accessor-side detour that no longer projects the raw field \
23086             would silently split this drift-detection test from the \
23087             validate() refusal arm",
23088        );
23089        assert_eq!(
23090            s.membros[1].nome(),
23091            s.membros[1].caixa.as_str(),
23092            "Membro::nome and .caixa.as_str() must byte-equal on an \
23093             empty-`:caixa` entry — the emptiness gate keys off the \
23094             accessor by construction",
23095        );
23096        assert_eq!(
23097            s.validate().unwrap_err(),
23098            AplicacaoError::MembroCaixaEmpty,
23099            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
23100             on an entry whose accessor-projected `nome()` is empty",
23101        );
23102    }
23103
23104    #[test]
23105    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
23106        // The canonical per-`:placement` Akka-cluster-sharding
23107        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
23108        // the `:placement :shard-key` field byte-for-byte, borrowed
23109        // from the typed slot's own `Option<String>` storage. Peer of
23110        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
23111        // per-`:contratos` [`WitContract::source`] /
23112        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
23113        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
23114        // slot-atom scalar-value axes — same "the substrate-primitive
23115        // accessor must byte-equal the raw field access verbatim across
23116        // every author-declared value" discipline extended to the
23117        // per-`:placement` Akka-cluster-sharding key extractor arm.
23118        // Pins against a future silent detour that re-normalized the
23119        // key (an accidental `.to_lowercase()` — every non-empty
23120        // `:shard-key` is validated as a printable-ASCII single-token
23121        // reference upstream via [`validate_placement_shard_key`], so
23122        // any re-normalization is redundant + a drift surface between
23123        // the validator and the accessor), a per-cluster alias rewrite
23124        // the operator authors on one consumer without the other, or an
23125        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
23126        // that didn't land on the peer field-access sites. Four values
23127        // sweep the accept-set the shape gate admits — bare identifier,
23128        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
23129        // the four canonical Akka-style entity-id extractor shapes the
23130        // future M4 cluster-sharding reconciler hashes.
23131        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
23132            let p = Placement {
23133                estrategia: PlacementStrategy::Sharded,
23134                clusters: vec!["rio".into()],
23135                affinity: None,
23136                shard_key: Some(key.into()),
23137            };
23138            assert_eq!(
23139                p.shard_key(),
23140                Some(key),
23141                "Placement::shard_key must return :placement :shard-key \
23142                 verbatim (got {:?}, expected Some({key:?}))",
23143                p.shard_key(),
23144            );
23145            assert_eq!(
23146                p.shard_key(),
23147                p.shard_key.as_deref(),
23148                "Placement::shard_key must byte-equal the .shard_key \
23149                 field's `.as_deref()` projection",
23150            );
23151        }
23152    }
23153
23154    #[test]
23155    fn placement_shard_key_none_when_field_is_none() {
23156        // The absent-`:shard-key` arm of the per-`:placement`
23157        // Akka-cluster-sharding accessor pin: when the typed slot is
23158        // absent — the canonical shape under `:estrategia Replicated` /
23159        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
23160        // enforced `shard_key.is_some() == matches!(estrategia,
23161        // Sharded)` partition — [`Placement::shard_key`] must return
23162        // `None`. Pins against a future silent detour that projected
23163        // the absent slot to a `Some("")` empty-string default (the
23164        // canonical `Option<String>` → `String` collapse footgun the
23165        // sibling M2 [`crate::LimitsSpec::is_empty`] /
23166        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
23167        // already guard on the peer M2 typed-slot surfaces), a
23168        // `Some("None")` stringified-None round-trip, or a `Some` arm
23169        // whose contents were derived from a sibling slot (an
23170        // accidental fallback to `estrategia.as_str()` that read the
23171        // strategy discriminator into the key axis). Two placements
23172        // sweep the accept-set every `validate`-passing non-`Sharded`
23173        // shape lands on — `Replicated` (Erlang/OTP distributed-app
23174        // takeover) and `SingleNode` (single-node hosting).
23175        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
23176            let p = Placement {
23177                estrategia,
23178                clusters: vec!["rio".into()],
23179                affinity: None,
23180                shard_key: None,
23181            };
23182            assert!(
23183                p.shard_key().is_none(),
23184                "Placement::shard_key must return None when the typed \
23185                 slot is absent under :estrategia {estrategia:?} (got {:?})",
23186                p.shard_key(),
23187            );
23188            assert_eq!(
23189                p.shard_key(),
23190                p.shard_key.as_deref(),
23191                "Placement::shard_key must byte-equal the .shard_key \
23192                 field's `.as_deref()` projection in the absent arm",
23193            );
23194        }
23195    }
23196
23197    #[test]
23198    fn placement_shard_key_borrows_from_shard_key_storage() {
23199        // The borrow-not-copy pin: [`Placement::shard_key`] must return
23200        // an `Option<&str>` whose `Some` arm borrows from the typed
23201        // slot's own [`String`] storage — same-address invariant with
23202        // `p.shard_key.as_deref().unwrap()`. Pins against a future
23203        // silent detour that allocated a fresh `String`
23204        // (`self.shard_key.clone().map(...)` in the body would type-
23205        // check but silently drop the borrow, and every downstream
23206        // consumer that assumed the returned slice outlives `&self`
23207        // would break on a stale-reference use-after-free — the
23208        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
23209        // gate's `Some(k)`-bound match arm reads `k: &str` under the
23210        // accessor's return type and would silently misbehave if this
23211        // accessor produced a detached copy). Peer of the sibling
23212        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
23213        // [`WitContract::source`] / [`WitContract::destination`]
23214        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
23215        // (6db982c) borrow-invariant pins on the mesh-slot-atom
23216        // scalar-value axes — first extension of the discipline onto
23217        // an `Option<String>`-shaped optional-scalar axis.
23218        let p = Placement {
23219            estrategia: PlacementStrategy::Sharded,
23220            clusters: vec!["rio".into()],
23221            affinity: None,
23222            shard_key: Some("tenantId".into()),
23223        };
23224        let key = p.shard_key().expect("Some arm");
23225        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
23226        assert_eq!(
23227            key.as_ptr(),
23228            storage_slice.as_ptr(),
23229            "Placement::shard_key must borrow from the .shard_key \
23230             String's backing storage — a fresh allocation here means \
23231             the accessor no longer names the substrate-primitive typed \
23232             dispatch and every downstream consumer would silently \
23233             carry a detached copy",
23234        );
23235        assert_eq!(
23236            key.len(),
23237            storage_slice.len(),
23238            "Placement::shard_key and .shard_key.as_deref() must byte-\
23239             equal in length as well as in address",
23240        );
23241    }
23242
23243    #[test]
23244    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
23245        // The canonical per-`:placement` M3-Adaptive-compression-hint
23246        // scalar pin: [`Placement::affinity`] must return the
23247        // `:placement :affinity` field byte-for-byte, borrowed from the
23248        // typed slot's own `Option<String>` storage. Peer of the sibling
23249        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
23250        // pin on the sibling `Option<&str>` optional-scalar axis — same
23251        // "the substrate-primitive accessor must byte-equal the raw
23252        // field access verbatim across every author-declared value"
23253        // discipline extended to the peer per-`:placement` M3-Adaptive-
23254        // compression-hint arm. Pins against a future silent detour
23255        // that re-normalized the hint (an accidental `.to_lowercase()`
23256        // — every `:affinity` is already validated as a DNS-1123 label
23257        // upstream via [`validate_placement_affinity`], so any re-
23258        // normalization is redundant + a drift surface between the
23259        // validator and the accessor), a per-cluster alias rewrite the
23260        // operator authors on one consumer without the other, or an
23261        // accidental hint-family collapse (`low-latency` → `latency`
23262        // that dropped the qualifier prefix). Four values sweep the
23263        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
23264        // canonical adaptive-compression-weight biases the future M4
23265        // placement engine reads.
23266        for hint in [
23267            "data-locality",
23268            "low-latency",
23269            "high-throughput",
23270            "cost-optimized",
23271        ] {
23272            let p = Placement {
23273                estrategia: PlacementStrategy::Replicated,
23274                clusters: vec!["rio".into()],
23275                affinity: Some(hint.into()),
23276                shard_key: None,
23277            };
23278            assert_eq!(
23279                p.affinity(),
23280                Some(hint),
23281                "Placement::affinity must return :placement :affinity \
23282                 verbatim (got {:?}, expected Some({hint:?}))",
23283                p.affinity(),
23284            );
23285            assert_eq!(
23286                p.affinity(),
23287                p.affinity.as_deref(),
23288                "Placement::affinity must byte-equal the .affinity \
23289                 field's `.as_deref()` projection",
23290            );
23291        }
23292    }
23293
23294    #[test]
23295    fn placement_affinity_none_when_field_is_none() {
23296        // The absent-`:affinity` arm of the per-`:placement`
23297        // M3-Adaptive-compression-hint accessor pin: when the typed
23298        // slot is absent — the canonical shape of an Aplicacao that
23299        // leaves the compression weighting up to the placement engine's
23300        // cluster-default arm — [`Placement::affinity`] must return
23301        // `None`. Pins against a future silent detour that projected
23302        // the absent slot to a `Some("")` empty-string default (the
23303        // canonical `Option<String>` → `String` collapse footgun the
23304        // sibling M2 [`crate::LimitsSpec::is_empty`] /
23305        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
23306        // already guard on the peer M2 typed-slot surfaces), a
23307        // `Some("None")` stringified-None round-trip, a `Some` arm
23308        // whose contents were derived from a sibling slot (an
23309        // accidental fallback to `estrategia.as_str()` that read the
23310        // strategy discriminator into the hint axis), or a
23311        // `Some("default")` implicit-default that would silently biases
23312        // the routing without the author having written one. Three
23313        // placements sweep the accept-set every `validate`-passing
23314        // `:affinity None` shape lands on — one per PlacementStrategy
23315        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
23316        // with a shard-key), since `:affinity` is orthogonal to
23317        // `:estrategia` in the typed grammar.
23318        for (estrategia, shard_key) in [
23319            (PlacementStrategy::SingleNode, None),
23320            (PlacementStrategy::Replicated, None),
23321            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
23322        ] {
23323            let p = Placement {
23324                estrategia,
23325                clusters: vec!["rio".into()],
23326                affinity: None,
23327                shard_key,
23328            };
23329            assert!(
23330                p.affinity().is_none(),
23331                "Placement::affinity must return None when the typed \
23332                 slot is absent under :estrategia {estrategia:?} (got {:?})",
23333                p.affinity(),
23334            );
23335            assert_eq!(
23336                p.affinity(),
23337                p.affinity.as_deref(),
23338                "Placement::affinity must byte-equal the .affinity \
23339                 field's `.as_deref()` projection in the absent arm",
23340            );
23341        }
23342    }
23343
23344    #[test]
23345    fn placement_affinity_borrows_from_affinity_storage() {
23346        // The borrow-not-copy pin: [`Placement::affinity`] must return
23347        // an `Option<&str>` whose `Some` arm borrows from the typed
23348        // slot's own [`String`] storage — same-address invariant with
23349        // `p.affinity.as_deref().unwrap()`. Pins against a future
23350        // silent detour that allocated a fresh `String`
23351        // (`self.affinity.clone().map(...)` in the body would type-
23352        // check but silently drop the borrow, and every downstream
23353        // consumer that assumed the returned slice outlives `&self`
23354        // would break on a stale-reference use-after-free — the
23355        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
23356        // gate reads the accessor's `&str` return through the
23357        // [`validate_placement_affinity`] `&str` parameter and would
23358        // silently misbehave if this accessor produced a detached
23359        // copy). Peer of the sibling per-`:placement`
23360        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
23361        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
23362        // extends the discipline onto the sibling per-`:placement`
23363        // M3-Adaptive-compression-hint arm.
23364        let p = Placement {
23365            estrategia: PlacementStrategy::Replicated,
23366            clusters: vec!["rio".into()],
23367            affinity: Some("data-locality".into()),
23368            shard_key: None,
23369        };
23370        let hint = p.affinity().expect("Some arm");
23371        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
23372        assert_eq!(
23373            hint.as_ptr(),
23374            storage_slice.as_ptr(),
23375            "Placement::affinity must borrow from the .affinity \
23376             String's backing storage — a fresh allocation here means \
23377             the accessor no longer names the substrate-primitive typed \
23378             dispatch and every downstream consumer would silently \
23379             carry a detached copy",
23380        );
23381        assert_eq!(
23382            hint.len(),
23383            storage_slice.len(),
23384            "Placement::affinity and .affinity.as_deref() must byte-\
23385             equal in length as well as in address",
23386        );
23387    }
23388
23389    #[test]
23390    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
23391        // The canonical per-`:placement` distribution-strategy-scalar
23392        // pin: [`Placement::estrategia`] must return the `:placement
23393        // :estrategia` field verbatim as a [`PlacementStrategy`],
23394        // `Copy`-projected from the typed slot's own `PlacementStrategy`
23395        // storage across every variant in the closed accept-set
23396        // (`SingleNode` — Erlang/OTP distributed-app takeover;
23397        // `Replicated` — active-active across every named cluster;
23398        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
23399        // against a future silent detour that re-derived the strategy
23400        // from a peer axis (an accidental fallback to
23401        // `if shard_key.is_some() { Sharded } else { Replicated }`
23402        // collapse that read the shard-key axis into the strategy
23403        // discriminator), a variant remap the operator authors on one
23404        // consumer without the other, or a stale-derive detour that
23405        // substituted [`PlacementStrategy::default`] when the field
23406        // held any explicit variant (which would silently collapse the
23407        // distinction between "author explicitly declared `:estrategia
23408        // Replicated`" and "author omitted the slot and inherited the
23409        // default" the future per-cluster override slot depends on).
23410        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
23411        // pin on the `Copy`-return `u16` scalar axis — same "the
23412        // substrate-primitive accessor must byte-equal the raw field
23413        // access verbatim across every author-declared value" discipline
23414        // extended onto the per-`:placement` distribution-strategy
23415        // `Copy`-composite-enum scalar axis.
23416        for estrategia in [
23417            PlacementStrategy::SingleNode,
23418            PlacementStrategy::Replicated,
23419            PlacementStrategy::Sharded,
23420        ] {
23421            // Route the paired `:shard-key` fixture-builder through the
23422            // typed cross-slot invariant predicate
23423            // [`PlacementStrategy::requires_shard_key`] rather than the
23424            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
23425            // arm-identity predicate — same discipline the sibling
23426            // `placement_strategy_variants_round_trip` fixture builder now
23427            // reads through.
23428            let shard_key = estrategia
23429                .requires_shard_key()
23430                .then(|| "tenantId".to_string());
23431            let p = Placement {
23432                estrategia,
23433                clusters: vec!["rio".into()],
23434                affinity: None,
23435                shard_key,
23436            };
23437            assert_eq!(
23438                p.estrategia(),
23439                estrategia,
23440                "Placement::estrategia must return :placement :estrategia \
23441                 verbatim (got {:?}, expected {estrategia:?})",
23442                p.estrategia(),
23443            );
23444            assert_eq!(
23445                p.estrategia(),
23446                p.estrategia,
23447                "Placement::estrategia accessor and .estrategia field \
23448                 access must byte-equal — the accessor is the substrate-\
23449                 primitive typed dispatch every downstream distribution-\
23450                 strategy consumer must route through",
23451            );
23452        }
23453    }
23454
23455    #[test]
23456    fn validate_placement_reads_through_lifted_estrategia_accessor() {
23457        // Three-consumer coherence pin: the
23458        // [`AplicacaoSpec::validate_placement`]
23459        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
23460        // `estrategia:` field (which reads through
23461        // [`Placement::estrategia`] to name the strategy the empty
23462        // `:clusters` list was declared against), the same method's
23463        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
23464        // reads through [`Placement::estrategia`] to fan across the
23465        // shape-gate cascades), and the non-`Sharded`-arm
23466        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
23467        // `estrategia:` field (which reads through
23468        // [`Placement::estrategia`] to name the strategy the declared-
23469        // but-inert `:shard-key` was authored under) must all key off
23470        // the lifted accessor, so any future rebrand on the typed
23471        // slot's reader shape lands at exactly one place. Pins the
23472        // three-site coherence by exercising each error surface end-
23473        // to-end and asserting the surfaced `estrategia:` field byte-
23474        // equals the accessor's return. Peer of the sibling per-
23475        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
23476        // pin on the M3 mesh-slot `Copy`-return scalar axis.
23477
23478        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
23479        // whose `estrategia:` field must byte-equal the accessor's return
23480        // for every variant in the closed accept-set.
23481        for estrategia in [
23482            PlacementStrategy::SingleNode,
23483            PlacementStrategy::Replicated,
23484            PlacementStrategy::Sharded,
23485        ] {
23486            let mut spec = three_member_spec();
23487            spec.placement.estrategia = estrategia;
23488            spec.placement.clusters = Vec::new();
23489            // Route the paired `:shard-key` spec-mutator through the typed
23490            // cross-slot invariant predicate
23491            // [`PlacementStrategy::requires_shard_key`] rather than the
23492            // [`gen_platform::IsVariant`]-derived
23493            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
23494            // same discipline the sibling
23495            // `placement_strategy_variants_round_trip` and
23496            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
23497            // fixture builders now read through.
23498            spec.placement.shard_key = estrategia
23499                .requires_shard_key()
23500                .then(|| "tenantId".to_string());
23501            let err = spec.validate().unwrap_err();
23502            match err {
23503                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
23504                    assert_eq!(
23505                        e,
23506                        spec.placement.estrategia(),
23507                        "PlacementWithoutClusters.estrategia must byte-equal \
23508                         Placement::estrategia() — the error carrier reads \
23509                         through the lifted accessor",
23510                    );
23511                }
23512                other => panic!(
23513                    "expected PlacementWithoutClusters, got {other:?} for \
23514                     estrategia={estrategia:?}"
23515                ),
23516            }
23517        }
23518
23519        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
23520        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
23521        // must byte-equal the accessor's return for both non-`Sharded`
23522        // strategies.
23523        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
23524            let mut spec = three_member_spec();
23525            spec.placement.estrategia = estrategia;
23526            spec.placement.shard_key = Some("tenantId".into());
23527            let err = spec.validate().unwrap_err();
23528            match err {
23529                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
23530                    assert_eq!(
23531                        e,
23532                        spec.placement.estrategia(),
23533                        "ShardKeyOnNonSharded.estrategia must byte-equal \
23534                         Placement::estrategia() — the non-Sharded-arm \
23535                         refusal reads through the lifted accessor",
23536                    );
23537                }
23538                other => panic!(
23539                    "expected ShardKeyOnNonSharded, got {other:?} for \
23540                     estrategia={estrategia:?}"
23541                ),
23542            }
23543        }
23544    }
23545
23546    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
23547    //
23548    // The [`Placement::clusters`] accessor lift is the second slice-return
23549    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
23550    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
23551    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
23552    // below cover (1) the accessor's byte-equal projection against the raw
23553    // field access across the empty / singleton / cohort fixtures the
23554    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
23555    // and the per-cluster validate loop fan between, and (2) the two-
23556    // consumer coherence of the paired pre-flight refusal probe and the
23557    // per-cluster validate loop routing through the accessor on both arms.
23558
23559    #[test]
23560    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
23561        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
23562        // [`Placement::clusters`] must return the `:placement :clusters`
23563        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
23564        // the same backing buffer the raw `self.clusters.as_slice()`
23565        // field access borrows from, byte-equal across every
23566        // representative fixture in the accept-set — the empty slice
23567        // (the pre-validation sentinel every
23568        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
23569        // the singleton slice (the minimal `SingleNode`-shape cohort),
23570        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
23571        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
23572        //
23573        // Pins against a future silent detour that returned
23574        // `&Vec<String>` (which would type-check but leak the storage-
23575        // side `Vec`'s grow/push/reserve surface no consumer of the
23576        // typed view reaches for), a fresh-allocated `Vec<String>` copy
23577        // (which would type-check via a coercion but silently break
23578        // every downstream caller that relied on the slice sharing the
23579        // backing buffer's identity), or an out-of-order or length-
23580        // drifted projection (which would silently split the paired
23581        // pre-flight `.is_empty()` refusal probe's input from the per-
23582        // cluster validate loop's traversal input).
23583        //
23584        // Peer of the sibling M2
23585        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23586        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23587        // `:supervisor` static-child-list axis, extended onto the M3
23588        // per-`:placement` distribution-target-list `Vec`-carry axis.
23589        let fixtures: Vec<Vec<String>> = vec![
23590            Vec::new(),
23591            vec!["rio".into()],
23592            vec!["rio".into(), "mar".into()],
23593            vec!["rio".into(), "mar".into(), "plo".into()],
23594        ];
23595        for clusters in fixtures {
23596            let p = Placement {
23597                clusters: clusters.clone(),
23598                ..Placement::default()
23599            };
23600            assert_eq!(
23601                p.clusters(),
23602                clusters.as_slice(),
23603                "Placement::clusters must return :placement :clusters \
23604                 verbatim (got {:?}, expected {:?})",
23605                p.clusters(),
23606                clusters.as_slice(),
23607            );
23608            assert_eq!(
23609                p.clusters(),
23610                p.clusters.as_slice(),
23611                "Placement::clusters accessor and .clusters.as_slice() \
23612                 field access must byte-equal — the accessor is the \
23613                 substrate-primitive typed dispatch every downstream \
23614                 cluster-pool consumer must route through",
23615            );
23616            assert_eq!(
23617                p.clusters().len(),
23618                p.clusters.len(),
23619                "Placement::clusters().len() must byte-equal \
23620                 self.clusters.len() — a length-drift would silently \
23621                 split the paired pre-flight `.is_empty()` refusal \
23622                 probe input from the per-cluster validate loop's \
23623                 traversal input",
23624            );
23625        }
23626    }
23627
23628    #[test]
23629    fn validate_placement_reads_through_lifted_clusters_accessor() {
23630        // Two-consumer coherence pin: the
23631        // [`AplicacaoSpec::validate_placement`] pre-flight
23632        // `self.placement.clusters().is_empty()` refusal probe (which
23633        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
23634        // the accessor projects the empty slice) and the per-cluster
23635        // validate loop's `for c in self.placement.clusters()`
23636        // traversal (which must reach every entry in the same order
23637        // the accessor projects, so both the per-entry value-shape
23638        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
23639        // and the duplicate-detection HashSet insert that trips
23640        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
23641        // accessor's projection) must both key off the lifted
23642        // accessor, so any future rebrand on the typed slot's reader
23643        // shape lands at exactly one place. Pins the two-site
23644        // coherence by exercising each production consumer end-to-end:
23645        // (1) the `PlacementWithoutClusters` refusal under the empty
23646        // slice, (2) the `PlacementClusterInvalid` refusal fires on
23647        // the second entry of a two-cluster cohort whose head is
23648        // valid but tail is not (which requires the loop to reach the
23649        // second entry through the accessor), and (3) the
23650        // `PlacementClusterDuplicate` refusal fires on the second
23651        // entry of a two-cluster cohort that shares a name (which
23652        // requires the loop to reach both entries — a first-entry-only
23653        // projection would silently pass since the dedup HashSet has
23654        // room for the first insert).
23655        //
23656        // Peer of the sibling M2
23657        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23658        // (bc92bce) coherence pin on the per-`:supervisor` static-
23659        // child-list axis, extended onto the M3 per-`:placement`
23660        // distribution-target-list `Vec`-carry axis.
23661
23662        // (1) Pre-flight `.is_empty()` probe: the empty slice must
23663        // trip `PlacementWithoutClusters`.
23664        let mut spec = three_member_spec();
23665        spec.placement.clusters = Vec::new();
23666        match spec.validate().unwrap_err() {
23667            AplicacaoError::PlacementWithoutClusters { .. } => {}
23668            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
23669        }
23670        assert!(
23671            spec.placement.clusters().is_empty(),
23672            "the pre-flight refusal input must be the empty slice per \
23673             the accessor's projection",
23674        );
23675
23676        // (2) Per-cluster validate loop: a two-cluster cohort with an
23677        // invalid tail entry must trip `PlacementClusterInvalid` on
23678        // the tail — the loop must reach the second entry through
23679        // the accessor.
23680        let mut spec = three_member_spec();
23681        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
23682        match spec.validate().unwrap_err() {
23683            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
23684                assert_eq!(
23685                    cluster, "BAD_CLUSTER",
23686                    "PlacementClusterInvalid.cluster must carry the \
23687                     tail entry the loop reached through the accessor",
23688                );
23689            }
23690            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
23691        }
23692        assert_eq!(
23693            spec.placement.clusters().len(),
23694            2,
23695            "the per-cluster validate loop's traversal input must be \
23696             a two-element slice per the accessor's projection",
23697        );
23698
23699        // (3) Per-cluster validate loop: a two-cluster cohort that
23700        // shares a name must trip `PlacementClusterDuplicate` on the
23701        // second entry — the loop must reach both entries through the
23702        // accessor for the dedup HashSet's second insert to collide.
23703        let mut spec = three_member_spec();
23704        spec.placement.clusters = vec!["rio".into(), "rio".into()];
23705        match spec.validate().unwrap_err() {
23706            AplicacaoError::PlacementClusterDuplicate { cluster } => {
23707                assert_eq!(
23708                    cluster, "rio",
23709                    "PlacementClusterDuplicate.cluster must carry the \
23710                     shared cluster name verbatim",
23711                );
23712            }
23713            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
23714        }
23715        assert_eq!(
23716            spec.placement.clusters().len(),
23717            2,
23718            "the per-cluster validate loop's traversal input must be \
23719             a two-element slice per the accessor's projection",
23720        );
23721    }
23722
23723    #[test]
23724    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
23725        // The canonical per-`:membros` member-list-slice-shape pin:
23726        // [`AplicacaoSpec::membros`] must return the `:membros` typed
23727        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
23728        // same backing buffer the raw `self.membros.as_slice()` field
23729        // access borrows from, byte-equal across every representative
23730        // fixture in the accept-set — the empty slice (the pre-
23731        // validation sentinel every [`AplicacaoError::NoMembros`]
23732        // refusal keys off), the singleton slice (the minimal one-
23733        // Servico Aplicacao shape), and multi-entry cohorts (the peer
23734        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
23735        // load-bearing identity of the application graph).
23736        //
23737        // Pins against a future silent detour that returned
23738        // `&Vec<Membro>` (which would type-check but leak the storage-
23739        // side `Vec`'s grow/push/reserve surface no consumer of the
23740        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
23741        // (which would type-check via a coercion but silently break
23742        // every downstream caller that relied on the slice sharing the
23743        // backing buffer's identity), or an out-of-order or length-
23744        // drifted projection (which would silently split the paired
23745        // `HashSet<&str>` name-set seed's collect input from the
23746        // pre-flight `.is_empty()` refusal probe's input from the per-
23747        // member validate loop's traversal input from the
23748        // programs.yaml emitter's per-entry fan-out loop's input from
23749        // the `feira app graph` per-member print traversal's input).
23750        //
23751        // Peer of the sibling M2
23752        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23753        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23754        // `:supervisor` static-child-list axis and the sibling M3
23755        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
23756        // (a6e18d7) `&[String]` byte-equal pin on the per-
23757        // `:placement` distribution-target-list axis — extends the
23758        // slice-return-accessor byte-equal-projection discipline onto
23759        // the outermost M3 mesh-slot type's per-Aplicacao member-list
23760        // `Vec`-carry axis.
23761        let fixtures: Vec<Vec<Membro>> = vec![
23762            Vec::new(),
23763            vec![membro("catalog", "^0.1")],
23764            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23765            vec![
23766                membro("catalog", "^0.1"),
23767                membro("cart", "^0.1"),
23768                membro("payment", "^0.2"),
23769            ],
23770        ];
23771        for membros in fixtures {
23772            let s = AplicacaoSpec {
23773                membros: membros.clone(),
23774                contratos: Vec::new(),
23775                politicas: MeshPolicy::default(),
23776                placement: Placement::default(),
23777                entrada: None,
23778            };
23779            assert_eq!(
23780                s.membros(),
23781                membros.as_slice(),
23782                "AplicacaoSpec::membros must return :membros verbatim \
23783                 (got {:?}, expected {:?})",
23784                s.membros(),
23785                membros.as_slice(),
23786            );
23787            assert_eq!(
23788                s.membros(),
23789                s.membros.as_slice(),
23790                "AplicacaoSpec::membros accessor and .membros.as_slice() \
23791                 field access must byte-equal — the accessor is the \
23792                 substrate-primitive typed dispatch every downstream \
23793                 member-list consumer must route through",
23794            );
23795            assert_eq!(
23796                s.membros().len(),
23797                s.membros.len(),
23798                "AplicacaoSpec::membros().len() must byte-equal \
23799                 self.membros.len() — a length-drift would silently \
23800                 split the paired `HashSet<&str>` name-set seed's \
23801                 collect input from the pre-flight `.is_empty()` \
23802                 refusal probe input from the per-member validate \
23803                 loop's traversal input",
23804            );
23805        }
23806    }
23807
23808    #[test]
23809    fn validate_reads_through_lifted_membros_accessor() {
23810        // Three-consumer coherence pin: the
23811        // [`AplicacaoSpec::validate_membros`] pre-flight
23812        // `self.membros().is_empty()` refusal probe (which must trip
23813        // [`AplicacaoError::NoMembros`] when the accessor projects the
23814        // empty slice), the same method's per-member validate loop's
23815        // `for m in self.membros()` traversal (which must reach every
23816        // entry in the same order the accessor projects, so both the
23817        // per-entry empty-`:caixa` gate that trips
23818        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
23819        // detection `insert_first_seen` that trips
23820        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
23821        // projection), and the peer [`AplicacaoSpec::validate`]'s
23822        // `HashSet<&str>` name-set seed's
23823        // `self.membros().iter().map(Membro::nome).collect()` collect
23824        // input (which every `:contratos` `:de` / `:para` membership
23825        // lookup rejects an unknown name against) must all three key
23826        // off the lifted accessor, so any future rebrand on the typed
23827        // slot's reader shape lands at exactly one place. Pins the
23828        // three-site coherence by exercising each production consumer
23829        // end-to-end: (1) the `NoMembros` refusal under the empty
23830        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
23831        // second entry of a two-member cohort whose head is valid but
23832        // tail has an empty `:caixa` (which requires the loop to
23833        // reach the second entry through the accessor), and (3) the
23834        // `MembroDuplicate` refusal fires on the second entry of a
23835        // two-member cohort that shares a `:caixa` name (which
23836        // requires the loop to reach both entries through the
23837        // accessor for the dedup HashSet's second insert to collide).
23838        //
23839        // Peer of the sibling M2
23840        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23841        // (bc92bce) coherence pin on the per-`:supervisor` static-
23842        // child-list axis and the sibling M3
23843        // `validate_placement_reads_through_lifted_clusters_accessor`
23844        // (a6e18d7) coherence pin on the per-`:placement` distribution-
23845        // target-list axis — extends the slice-return-accessor
23846        // multi-consumer coherence discipline onto the outermost M3
23847        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
23848
23849        // (1) Pre-flight `.is_empty()` probe: the empty slice must
23850        // trip `NoMembros`.
23851        let mut spec = three_member_spec();
23852        spec.membros = Vec::new();
23853        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
23854        assert!(
23855            spec.membros().is_empty(),
23856            "the pre-flight refusal input must be the empty slice per \
23857             the accessor's projection",
23858        );
23859
23860        // (2) Per-member validate loop: a two-member cohort with an
23861        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
23862        // the tail — the loop must reach the second entry through
23863        // the accessor.
23864        let mut spec = three_member_spec();
23865        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
23866        assert_eq!(
23867            spec.validate().unwrap_err(),
23868            AplicacaoError::MembroCaixaEmpty,
23869        );
23870        assert_eq!(
23871            spec.membros().len(),
23872            2,
23873            "the per-member validate loop's traversal input must be \
23874             a two-element slice per the accessor's projection",
23875        );
23876
23877        // (3) Per-member validate loop: a two-member cohort that
23878        // shares a `:caixa` name must trip `MembroDuplicate` on the
23879        // second entry — the loop must reach both entries through the
23880        // accessor for the dedup HashSet's second insert to collide.
23881        let mut spec = three_member_spec();
23882        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
23883        match spec.validate().unwrap_err() {
23884            AplicacaoError::MembroDuplicate { caixa } => {
23885                assert_eq!(
23886                    caixa, "catalog",
23887                    "MembroDuplicate.caixa must carry the shared \
23888                     member name verbatim",
23889                );
23890            }
23891            other => panic!("expected MembroDuplicate, got {other:?}"),
23892        }
23893        assert_eq!(
23894            spec.membros().len(),
23895            2,
23896            "the per-member validate loop's traversal input must be \
23897             a two-element slice per the accessor's projection",
23898        );
23899    }
23900
23901    #[test]
23902    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
23903        // The canonical per-`:contratos` contract-list-slice-shape pin:
23904        // [`AplicacaoSpec::contratos`] must return the `:contratos`
23905        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
23906        // slice-view over the same backing buffer the raw
23907        // `self.contratos.as_slice()` field access borrows from, byte-
23908        // equal across every representative fixture in the accept-set —
23909        // the empty slice (the pre-validation "internal-only mesh" shape
23910        // an Aplicacao whose members exchange no typed edges renders
23911        // through), the singleton slice (the minimal one-edge Aplicacao
23912        // shape), and multi-entry cohorts (the peer multi-edge shapes
23913        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
23914        // of the application graph).
23915        //
23916        // Pins against a future silent detour that returned
23917        // `&Vec<WitContract>` (which would type-check but leak the
23918        // storage-side `Vec`'s grow/push/reserve surface no consumer of
23919        // the typed view reaches for), a fresh-allocated
23920        // `Vec<WitContract>` copy (which would type-check via a coercion
23921        // but silently break every downstream caller that relied on the
23922        // slice sharing the backing buffer's identity), or an out-of-
23923        // order or length-drifted projection (which would silently split
23924        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
23925        // seed's traversal input from the `detect_sync_cycles` per-edge
23926        // adjacency-list seed's traversal input from the
23927        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
23928        // BTreeMap grouping loop's traversal input from the
23929        // `feira app graph` per-contract print traversal's input).
23930        //
23931        // Peer of the immediately-adjacent sibling M3
23932        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
23933        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
23934        // node-list axis, the sibling M3
23935        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
23936        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
23937        // distribution-target-list axis, and the sibling M2
23938        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23939        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23940        // `:supervisor` static-child-list axis — extends the slice-
23941        // return-accessor byte-equal-projection discipline onto the
23942        // outermost M3 mesh-slot type's per-Aplicacao contract-list
23943        // `Vec`-carry axis, closing the last unlifted per-
23944        // `AplicacaoSpec` `Vec`-carry axis.
23945        let fixtures: Vec<Vec<WitContract>> = vec![
23946            Vec::new(),
23947            vec![contract_http("cart", "catalog", "/products/:id")],
23948            vec![
23949                contract_http("cart", "catalog", "/products/:id"),
23950                contract_http("cart", "payment", "/charge"),
23951            ],
23952            vec![
23953                contract_http("cart", "catalog", "/products/:id"),
23954                contract_http("cart", "payment", "/charge"),
23955                contract_http("payment", "catalog", "/audit"),
23956            ],
23957        ];
23958        for contratos in fixtures {
23959            let s = AplicacaoSpec {
23960                membros: vec![
23961                    membro("catalog", "^0.1"),
23962                    membro("cart", "^0.1"),
23963                    membro("payment", "^0.2"),
23964                ],
23965                contratos: contratos.clone(),
23966                politicas: MeshPolicy::default(),
23967                placement: Placement::default(),
23968                entrada: None,
23969            };
23970            assert_eq!(
23971                s.contratos(),
23972                contratos.as_slice(),
23973                "AplicacaoSpec::contratos must return :contratos verbatim \
23974                 (got {:?}, expected {:?})",
23975                s.contratos(),
23976                contratos.as_slice(),
23977            );
23978            assert_eq!(
23979                s.contratos(),
23980                s.contratos.as_slice(),
23981                "AplicacaoSpec::contratos accessor and \
23982                 .contratos.as_slice() field access must byte-equal — \
23983                 the accessor is the substrate-primitive typed dispatch \
23984                 every downstream contract-list consumer must route \
23985                 through",
23986            );
23987            assert_eq!(
23988                s.contratos().len(),
23989                s.contratos.len(),
23990                "AplicacaoSpec::contratos().len() must byte-equal \
23991                 self.contratos.len() — a length-drift would silently \
23992                 split the paired per-edge validate-loop's traversal \
23993                 input from the sync-cycle adjacency-list seed's \
23994                 traversal input from the cilium_network_policies \
23995                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
23996                 input from the `feira app graph` per-contract print \
23997                 traversal's input",
23998            );
23999        }
24000    }
24001
24002    #[test]
24003    fn validate_reads_through_lifted_contratos_accessor() {
24004        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
24005        // per-`:contratos` validate-loop's `for c in self.contratos()`
24006        // traversal (which must reach every entry in the same order the
24007        // accessor projects, so both the per-entry
24008        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
24009        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
24010        // dedup `HashSet` insert key off the accessor's projection),
24011        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
24012        // `for c in self.contratos()` adjacency-list seed (which drives
24013        // the sync-subgraph deadlock-detection gate via
24014        // [`AplicacaoError::SyncCycle`]), and the peer
24015        // [`caixa_mesh::cilium_network_policies`]'s
24016        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
24017        // grouping loop (which drives the per-CNP fan-out) must all
24018        // three key off the lifted accessor, so any future rebrand on
24019        // the typed slot's reader shape lands at exactly one place. Pins
24020        // the three-site coherence by exercising the two caixa-core
24021        // production consumers end-to-end: (1) the empty-`:contratos`
24022        // slice must validate without a per-edge diagnostic (the
24023        // per-edge loop is a no-op under the empty projection), (2) the
24024        // `ContratoMemberMissing` refusal fires on the second entry of a
24025        // two-edge cohort whose head references a valid member but tail
24026        // references a phantom name (which requires the loop to reach
24027        // the second entry through the accessor), and (3) the
24028        // `SyncCycle` refusal fires on a self-referential two-edge
24029        // cohort through the sync-cycle detector's peer projection
24030        // (which requires the detector to iterate the accessor's
24031        // projection to add the back-edge to its adjacency list).
24032        //
24033        // Peer of the sibling M3
24034        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24035        // three-consumer coherence pin on the per-`:membros` node-list
24036        // axis and the sibling M3
24037        // `validate_placement_reads_through_lifted_clusters_accessor`
24038        // (a6e18d7) coherence pin on the per-`:placement` distribution-
24039        // target-list axis — extends the slice-return-accessor multi-
24040        // consumer coherence discipline onto the outermost M3 mesh-slot
24041        // type's per-Aplicacao contract-list `Vec`-carry axis.
24042
24043        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
24044        // and no per-edge diagnostic surfaces. Validate succeeds on
24045        // the well-formed `:membros` head.
24046        let mut spec = three_member_spec();
24047        spec.contratos = Vec::new();
24048        assert!(
24049            spec.validate().is_ok(),
24050            "empty :contratos must validate — the per-edge loop is a \
24051             no-op under the accessor's empty projection",
24052        );
24053        assert!(
24054            spec.contratos().is_empty(),
24055            "the per-edge validate loop's traversal input must be the \
24056             empty slice per the accessor's projection",
24057        );
24058
24059        // (2) Per-edge validate loop: a two-edge cohort whose tail
24060        // references a phantom `:para` member must trip
24061        // `ContratoMemberMissing` on the tail — the loop must reach
24062        // the second entry through the accessor for the membership
24063        // lookup to fail on the phantom name.
24064        let mut spec = three_member_spec();
24065        spec.contratos = vec![
24066            contract_http("cart", "catalog", "/products/:id"),
24067            contract_http("cart", "phantom", "/x"),
24068        ];
24069        let err = spec.validate().unwrap_err();
24070        assert!(
24071            matches!(
24072                err,
24073                AplicacaoError::ContratoMemberMissing { ref caixa }
24074                    if caixa == "phantom"
24075            ),
24076            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
24077        );
24078        assert_eq!(
24079            spec.contratos().len(),
24080            2,
24081            "the per-edge validate loop's traversal input must be \
24082             a two-element slice per the accessor's projection",
24083        );
24084
24085        // (3) Sync-cycle detector: a two-edge synchronous cohort
24086        // whose second edge closes the sync-subgraph back onto the
24087        // first must trip [`AplicacaoError::ContratoCycle`] — the
24088        // detector must iterate the accessor's projection to add
24089        // both edges to its adjacency list, so a length-drift on
24090        // the accessor's projection would silently disagree with
24091        // the sync-cycle detector on which edge closes the loop.
24092        // Peer projection to the `validate` per-edge loop above:
24093        // the sync-cycle detector routes through the same lifted
24094        // accessor, so a rebrand of the reader shape lands at one
24095        // place. Uses a two-edge cohort (cart → catalog → cart)
24096        // because the per-edge `ContratoSelfLoop` gate fires before
24097        // the sync-cycle detector on a single self-referential edge
24098        // (`cart → cart`) — the cycle-detector's input must be a
24099        // multi-edge cohort for its per-edge traversal input to be
24100        // observably wider than the per-edge validate loop's input.
24101        let mut spec = three_member_spec();
24102        spec.contratos = vec![
24103            contract_http("cart", "catalog", "/products/:id"),
24104            contract_http("catalog", "cart", "/callback"),
24105        ];
24106        let err = spec.validate().unwrap_err();
24107        assert!(
24108            matches!(err, AplicacaoError::ContratoCycle { .. }),
24109            "expected ContratoCycle from the sync-cycle detector on a \
24110             two-edge back-edge cohort, got {err:?}",
24111        );
24112        assert_eq!(
24113            spec.contratos().len(),
24114            2,
24115            "the sync-cycle detector's traversal input must be a \
24116             two-element slice per the accessor's projection",
24117        );
24118    }
24119
24120    #[test]
24121    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
24122        // The canonical per-`:politicas` outer-composite-reference-shape
24123        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
24124        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
24125        // the same backing storage the raw `&self.politicas` field
24126        // access borrows from, byte-equal across every representative
24127        // fixture in the accept-set — the default `MeshPolicy` (the
24128        // author-empty "no policy on any axis" shape whose
24129        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
24130        // shapes carrying one axis at a time
24131        // (`{mtls_required, timeout, retries, circuit_breaker,
24132        // rate_limit}` — the minimal five-axis fan-out over the
24133        // per-axis lifted accessor family every downstream mesh-artifact
24134        // emitter dispatches on), and the multi-axis composite (the
24135        // canonical `three_member_spec` fixture's `{timeout, retries,
24136        // mtls_required}` triple — the load-bearing shape every
24137        // Aplicacao-scoped fixture in this suite constructs).
24138        //
24139        // Pins against a future silent detour that returned a fresh-
24140        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
24141        // impl but silently break every downstream caller that relied
24142        // on the reference sharing the composite's backing identity), a
24143        // reference to an operator-resolved overlay (the future
24144        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
24145        // acknowledges — its resolution must land at exactly this
24146        // accessor body, not silently divert the raw slot away from a
24147        // second consumer), or an axis-shuffled projection (a future
24148        // detour that swapped `timeout` and `retries` through the
24149        // accessor would silently split the paired `validate_politicas`
24150        // per-axis bracket-dispatch's traversal input from the peer
24151        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
24152        // emitter's fan-out input from the peer
24153        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
24154        // overlay emitter's fan-out input).
24155        //
24156        // Peer of the sibling M3
24157        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
24158        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
24159        // node-list `Vec`-carry axis and the sibling M3
24160        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
24161        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
24162        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
24163        // accessor byte-equal-projection discipline onto the outermost
24164        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
24165        // reference axis, the first `&Composite`-return accessor on the
24166        // outer [`AplicacaoSpec`] type.
24167        let fixtures: Vec<MeshPolicy> = vec![
24168            MeshPolicy::default(),
24169            MeshPolicy {
24170                mtls_required: Some(true),
24171                ..MeshPolicy::default()
24172            },
24173            MeshPolicy {
24174                mtls_required: Some(false),
24175                ..MeshPolicy::default()
24176            },
24177            MeshPolicy {
24178                timeout: Some(Duration::from_secs(30)),
24179                ..MeshPolicy::default()
24180            },
24181            MeshPolicy {
24182                retries: Some(3),
24183                ..MeshPolicy::default()
24184            },
24185            MeshPolicy {
24186                circuit_breaker: Some(CircuitBreaker {
24187                    max_failures: 5,
24188                    window: Duration::from_secs(30),
24189                }),
24190                ..MeshPolicy::default()
24191            },
24192            MeshPolicy {
24193                rate_limit: Some(RateLimit {
24194                    rate: 100,
24195                    window: Duration::from_secs(1),
24196                }),
24197                ..MeshPolicy::default()
24198            },
24199            MeshPolicy {
24200                timeout: Some(Duration::from_secs(30)),
24201                retries: Some(3),
24202                mtls_required: Some(true),
24203                ..MeshPolicy::default()
24204            },
24205        ];
24206        for politicas in fixtures {
24207            let s = AplicacaoSpec {
24208                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24209                contratos: Vec::new(),
24210                politicas: politicas.clone(),
24211                placement: Placement::default(),
24212                entrada: None,
24213            };
24214            assert_eq!(
24215                *s.politicas(),
24216                politicas,
24217                "AplicacaoSpec::politicas must return :politicas verbatim \
24218                 (got {:?}, expected {:?})",
24219                s.politicas(),
24220                politicas,
24221            );
24222            assert!(
24223                std::ptr::eq(s.politicas(), &s.politicas),
24224                "AplicacaoSpec::politicas accessor and &self.politicas \
24225                 field access must borrow the same backing storage — \
24226                 the accessor is the substrate-primitive typed dispatch \
24227                 every downstream mesh-policy composite consumer must \
24228                 route through, and a reference-identity split would \
24229                 silently break every consumer that relied on the \
24230                 borrow sharing the composite's storage",
24231            );
24232            assert_eq!(
24233                s.politicas().is_empty(),
24234                s.politicas.is_empty(),
24235                "AplicacaoSpec::politicas().is_empty() must byte-equal \
24236                 self.politicas.is_empty() — an emptiness-drift would \
24237                 silently split the paired `validate_politicas` \
24238                 per-axis bracket-dispatch's seed from the peer \
24239                 caixa-mesh CNP mTLS-overlay emitter's key from the \
24240                 peer caixa-mesh HTTPRoute timeout+retry overlay \
24241                 emitter's key",
24242            );
24243        }
24244    }
24245
24246    #[test]
24247    fn validate_politicas_reads_through_lifted_politicas_accessor() {
24248        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
24249        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
24250        // followed by the per-axis fan-out `p.timeout()` /
24251        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
24252        // the lifted axis-level accessor family) must key off the
24253        // lifted outer accessor, so any future rebrand on the typed
24254        // slot's outer-composite reader shape lands at exactly one
24255        // place. Pins the multi-axis coherence by exercising each
24256        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
24257        // a `Some(Duration::ZERO)` timeout under the outer accessor's
24258        // reference projection, (2) `PolicyRetriesZero` fires on a
24259        // `Some(0)` retries under the same projection, and (3) an
24260        // empty [`MeshPolicy::default`] passes `validate_politicas` —
24261        // the outer accessor's reference-projection reaches every
24262        // per-axis branch without silently short-circuiting any.
24263        //
24264        // Peer of the sibling M3
24265        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24266        // three-consumer coherence pin on the per-`:membros` node-list
24267        // axis and the sibling M3
24268        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24269        // three-consumer coherence pin on the per-`:contratos`
24270        // edge-list axis — extends the multi-consumer coherence
24271        // discipline onto the outermost M3 mesh-slot type's per-
24272        // Aplicacao mesh-policy composite-reference axis, the first
24273        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
24274        // type.
24275
24276        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
24277        // reference projection: a `Some(Duration::ZERO)` timeout must
24278        // trip the zero-floor gate. The bracket-dispatch's first arm
24279        // reads `p.timeout()` on the reference returned by the outer
24280        // accessor.
24281        let mut spec = three_member_spec();
24282        spec.politicas.timeout = Some(Duration::ZERO);
24283        spec.politicas.retries = None;
24284        spec.politicas.circuit_breaker = None;
24285        spec.politicas.rate_limit = None;
24286        assert_eq!(
24287            spec.validate().unwrap_err(),
24288            AplicacaoError::PolicyTimeoutZero,
24289        );
24290        assert!(
24291            std::ptr::eq(spec.politicas(), &spec.politicas),
24292            "the `validate_politicas` per-axis bracket-dispatch's \
24293             traversal input must be the same backing composite the \
24294             accessor's reference projection borrows from",
24295        );
24296
24297        // (2) `PolicyRetriesZero` refusal under the outer accessor's
24298        // reference projection: a `Some(0)` retries must trip the
24299        // zero-floor gate. The bracket-dispatch's second arm reads
24300        // `p.retries()` on the reference returned by the outer accessor.
24301        let mut spec = three_member_spec();
24302        spec.politicas.timeout = None;
24303        spec.politicas.retries = Some(0);
24304        spec.politicas.circuit_breaker = None;
24305        spec.politicas.rate_limit = None;
24306        assert_eq!(
24307            spec.validate().unwrap_err(),
24308            AplicacaoError::PolicyRetriesZero,
24309        );
24310
24311        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
24312        // — every per-axis arm short-circuits on `None`, so the outer
24313        // accessor's reference projection reaches the fall-through
24314        // `Ok(())` without any per-axis refusal firing.
24315        let mut spec = three_member_spec();
24316        spec.politicas = MeshPolicy::default();
24317        assert!(
24318            spec.validate().is_ok(),
24319            "an empty `MeshPolicy` must pass `validate_politicas` — \
24320             every per-axis arm short-circuits on `None` under the \
24321             outer accessor's reference projection",
24322        );
24323        assert!(
24324            spec.politicas().is_empty(),
24325            "the outer accessor's reference projection must be the \
24326             empty composite per the `MeshPolicy::default()` fixture",
24327        );
24328    }
24329
24330    #[test]
24331    #[allow(clippy::too_many_lines)]
24332    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
24333        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
24334        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
24335        // must both key off the lifted axis-level accessors
24336        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
24337        // the peer `:circuit-breaker` / `:rate-limit` arms already
24338        // routing through [`MeshPolicy::circuit_breaker`] /
24339        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
24340        // per axis on the substrate primitive" shape at the fan-out
24341        // (four axes, four accessors, no raw-field-access site
24342        // anywhere on the bracket-dispatch). Pins the per-axis
24343        // coherence at the accept-set boundaries the bracket carves:
24344        //   1. accessor byte-equal to raw field on every representative
24345        //      accept-set value (`None`, sub-cap, at-cap, past-cap
24346        //      sentinel) — a future accessor drift that no longer
24347        //      shipped the raw slot verbatim would surface here,
24348        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
24349        //      routed through the accessor's projection, proving the
24350        //      first arm reads through the accessor rather than a
24351        //      silent-detour peer-axis field access,
24352        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
24353        //      through the accessor's projection, proving the second
24354        //      arm reads through the accessor,
24355        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
24356        //      passes validate under the accessor projection (paired
24357        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
24358        //      sibling axis), pinning the upper-boundary accept-arm
24359        //      also routes through the accessor.
24360        //
24361        // Peer of the sibling M3
24362        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24363        // outer-composite-reference coherence pin (which asserts the
24364        // `let p = self.politicas()` seed); extends the discipline onto
24365        // the per-axis fan-out layer that consumes the seed's
24366        // reference. Same shape as
24367        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24368        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24369        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
24370        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
24371
24372        // (1) Accessor byte-equal to raw field on the `:timeout` axis
24373        // across the accept-set boundaries the bracket dispatch's
24374        // three-arm gate carves out
24375        // ([`crate::render::require_positive_canonical_bounded_duration`]
24376        // — zero-floor + canonical-form + upper-cap).
24377        for timeout in [
24378            None,
24379            Some(Duration::ZERO),
24380            Some(Duration::from_millis(1)),
24381            Some(POLICY_TIMEOUT_MAX),
24382        ] {
24383            let p = MeshPolicy {
24384                timeout,
24385                ..MeshPolicy::default()
24386            };
24387            assert_eq!(
24388                p.timeout(),
24389                p.timeout,
24390                "MeshPolicy::timeout accessor must byte-equal the raw \
24391                 .timeout field across every accept-set boundary the \
24392                 validate_politicas :timeout arm carves out — a drift \
24393                 here would silently split the validate bracket's arm \
24394                 from the peer caixa-mesh HTTPRoute timeout-overlay \
24395                 emitter's read",
24396            );
24397        }
24398
24399        // (2) Accessor byte-equal to raw field on the `:retries` axis
24400        // across the accept-set boundaries the bracket dispatch's
24401        // two-arm gate carves out
24402        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
24403        // + upper-cap).
24404        for retries in [
24405            None,
24406            Some(0u32),
24407            Some(1u32),
24408            Some(POLICY_RETRIES_MAX),
24409            Some(POLICY_RETRIES_MAX + 1),
24410            Some(u32::MAX),
24411        ] {
24412            let p = MeshPolicy {
24413                retries,
24414                ..MeshPolicy::default()
24415            };
24416            assert_eq!(
24417                p.retries(),
24418                p.retries,
24419                "MeshPolicy::retries accessor must byte-equal the raw \
24420                 .retries field across every accept-set boundary the \
24421                 validate_politicas :retries arm carves out — a drift \
24422                 here would silently split the validate bracket's arm \
24423                 from the peer caixa-mesh HTTPRoute retry-overlay \
24424                 emitter's read",
24425            );
24426        }
24427
24428        // (3) `PolicyTimeoutZero` fires on the accessor-projected
24429        // zero-floor boundary. A silent detour that no longer read
24430        // through `p.timeout()` (a peer-axis field read, an accidental
24431        // Option::and-then chain that collapsed the None arm to Some,
24432        // an accessor rebrand that clamped the return through the
24433        // upper cap) would fail to refuse here.
24434        let mut spec = three_member_spec();
24435        spec.politicas.timeout = Some(Duration::ZERO);
24436        spec.politicas.retries = None;
24437        spec.politicas.circuit_breaker = None;
24438        spec.politicas.rate_limit = None;
24439        assert_eq!(
24440            spec.politicas().timeout(),
24441            Some(Duration::ZERO),
24442            "the accessor projection must reflect the fixture's \
24443             `Some(Duration::ZERO)` :timeout verbatim",
24444        );
24445        assert_eq!(
24446            spec.validate().unwrap_err(),
24447            AplicacaoError::PolicyTimeoutZero,
24448            "the validate_politicas :timeout zero-floor arm must fire \
24449             through the lifted accessor's projection — a silent \
24450             detour to a peer-axis field would fail to refuse",
24451        );
24452
24453        // (4) `PolicyRetriesZero` fires on the accessor-projected
24454        // zero-floor boundary on the sibling `:retries` axis.
24455        let mut spec = three_member_spec();
24456        spec.politicas.timeout = None;
24457        spec.politicas.retries = Some(0);
24458        spec.politicas.circuit_breaker = None;
24459        spec.politicas.rate_limit = None;
24460        assert_eq!(
24461            spec.politicas().retries(),
24462            Some(0),
24463            "the accessor projection must reflect the fixture's \
24464             `Some(0)` :retries verbatim",
24465        );
24466        assert_eq!(
24467            spec.validate().unwrap_err(),
24468            AplicacaoError::PolicyRetriesZero,
24469            "the validate_politicas :retries zero-floor arm must fire \
24470             through the lifted accessor's projection — a silent \
24471             detour to a peer-axis field would fail to refuse",
24472        );
24473
24474        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
24475        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
24476        // must pass validate under the accessor projection — pins the
24477        // upper-boundary accept-arm also routes through the lifted
24478        // accessor (a drift that clamped or short-circuited at the
24479        // upper boundary would fail the whole-spec validate here).
24480        let mut spec = three_member_spec();
24481        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
24482        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
24483        spec.politicas.circuit_breaker = None;
24484        spec.politicas.rate_limit = None;
24485        assert_eq!(
24486            spec.politicas().timeout(),
24487            Some(POLICY_TIMEOUT_MAX),
24488            "the accessor projection must reflect the fixture's \
24489             at-cap :timeout verbatim",
24490        );
24491        assert_eq!(
24492            spec.politicas().retries(),
24493            Some(POLICY_RETRIES_MAX),
24494            "the accessor projection must reflect the fixture's \
24495             at-cap :retries verbatim",
24496        );
24497        assert!(
24498            spec.validate().is_ok(),
24499            "at-cap :timeout + :retries must pass validate under the \
24500             accessor projection — the upper-boundary accept-arm on \
24501             both axes routes through the lifted accessor",
24502        );
24503    }
24504
24505    #[test]
24506    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
24507        // The canonical per-`:placement` outer-composite-reference-shape
24508        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
24509        // typed `Placement` verbatim as a `&Placement` reference over the
24510        // same backing storage the raw `&self.placement` field access
24511        // borrows from, byte-equal across every representative fixture in
24512        // the accept-set — the default `Placement` (the substrate seed
24513        // shape whose [`PlacementStrategy::default`] evaluates to
24514        // `SingleNode` with an empty `:clusters` pool and both
24515        // optional-scalar axes `None`), and every canonical strategy /
24516        // cluster-pool / optional-scalar combination the
24517        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
24518        // three [`PlacementStrategy`] variants — `SingleNode`,
24519        // `Replicated`, `Sharded` — cross-projected with a non-empty
24520        // `:clusters` pool and, on the `Sharded` arm, a non-empty
24521        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
24522        // canonical `three_member_spec` `Replicated` fixture's
24523        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
24524        //
24525        // Pins against a future silent detour that returned a fresh-
24526        // cloned `Placement` copy (which would type-check via a `Clone`
24527        // impl but silently break every downstream caller that relied on
24528        // the reference sharing the composite's backing identity), a
24529        // reference to an operator-resolved overlay (the future per-
24530        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
24531        // acknowledges — its resolution must land at exactly this
24532        // accessor body, not silently divert the raw slot away from a
24533        // second consumer), or an axis-shuffled projection (a future
24534        // detour that swapped `clusters` and `affinity` through the
24535        // accessor would silently split the paired `validate_placement`
24536        // per-axis bracket-dispatch's traversal input from the peer
24537        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
24538        // programs.yaml distribution-annotation emitter's fan-out input
24539        // from the peer `feira app graph` per-Aplicacao print line's
24540        // input).
24541        //
24542        // Peer of the sibling M3
24543        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24544        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
24545        // outer mesh-policy composite-reference axis, and of the sibling
24546        // slice-return `aplicacao_spec_membros_returns_membros_slice_
24547        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
24548        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
24549        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
24550        // the outer-accessor byte-equal-projection discipline onto the
24551        // outermost M3 mesh-slot type's per-Aplicacao distribution
24552        // composite-reference axis, the second `&Composite`-return
24553        // accessor on the outer [`AplicacaoSpec`] type.
24554        let fixtures: Vec<Placement> = vec![
24555            Placement::default(),
24556            Placement {
24557                estrategia: PlacementStrategy::SingleNode,
24558                clusters: vec!["rio".into()],
24559                affinity: None,
24560                shard_key: None,
24561            },
24562            Placement {
24563                estrategia: PlacementStrategy::Replicated,
24564                clusters: vec!["rio".into(), "mar".into()],
24565                affinity: None,
24566                shard_key: None,
24567            },
24568            Placement {
24569                estrategia: PlacementStrategy::Replicated,
24570                clusters: vec!["rio".into(), "mar".into()],
24571                affinity: Some("data-locality".into()),
24572                shard_key: None,
24573            },
24574            Placement {
24575                estrategia: PlacementStrategy::Sharded,
24576                clusters: vec!["rio".into(), "mar".into()],
24577                affinity: None,
24578                shard_key: Some("tenantId".into()),
24579            },
24580            Placement {
24581                estrategia: PlacementStrategy::Sharded,
24582                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
24583                affinity: Some("low-latency".into()),
24584                shard_key: Some("metadata.tenantId".into()),
24585            },
24586        ];
24587        for placement in fixtures {
24588            let s = AplicacaoSpec {
24589                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24590                contratos: Vec::new(),
24591                politicas: MeshPolicy::default(),
24592                placement: placement.clone(),
24593                entrada: None,
24594            };
24595            assert_eq!(
24596                *s.placement(),
24597                placement,
24598                "AplicacaoSpec::placement must return :placement verbatim \
24599                 (got {:?}, expected {:?})",
24600                s.placement(),
24601                placement,
24602            );
24603            assert!(
24604                std::ptr::eq(s.placement(), &s.placement),
24605                "AplicacaoSpec::placement accessor and &self.placement \
24606                 field access must borrow the same backing storage — the \
24607                 accessor is the substrate-primitive typed dispatch every \
24608                 downstream distribution-composite consumer must route \
24609                 through, and a reference-identity split would silently \
24610                 break every consumer that relied on the borrow sharing \
24611                 the composite's storage",
24612            );
24613            assert_eq!(
24614                s.placement().estrategia(),
24615                s.placement.estrategia,
24616                "AplicacaoSpec::placement().estrategia() must byte-equal \
24617                 self.placement.estrategia — a strategy-drift would \
24618                 silently split the paired `validate_placement` \
24619                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
24620                 peer caixa-mesh programs.yaml `placement.estrategia` \
24621                 emitter's key from the peer `feira app graph` printer's \
24622                 strategy label",
24623            );
24624            assert_eq!(
24625                s.placement().clusters(),
24626                s.placement.clusters.as_slice(),
24627                "AplicacaoSpec::placement().clusters() must byte-equal \
24628                 self.placement.clusters — a cluster-pool drift would \
24629                 silently split the paired `validate_placement` \
24630                 pre-flight `.is_empty()` refusal probe's traversal from \
24631                 the peer caixa-mesh programs.yaml `placement.clusters` \
24632                 emitter's fan-out from the peer `feira app graph` \
24633                 printer's cluster list",
24634            );
24635        }
24636    }
24637
24638    #[test]
24639    fn validate_placement_reads_through_lifted_placement_accessor() {
24640        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
24641        // per-axis bracket-dispatch seed (`let p = self.placement();`,
24642        // followed by the per-axis fan-out `p.clusters()` /
24643        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
24644        // lifted axis-level accessor family) must key off the lifted
24645        // outer accessor, so any future rebrand on the typed slot's
24646        // outer-composite reader shape lands at exactly one place. Pins
24647        // the multi-axis coherence by exercising each per-axis refusal
24648        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
24649        // `:clusters` pool under the outer accessor's reference
24650        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
24651        // strategy with a `None` `:shard-key` under the same projection,
24652        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
24653        // with a `Some` `:shard-key` under the same projection, and
24654        // (4) the canonical `three_member_spec` `Replicated` fixture
24655        // passes `validate_placement` under the outer accessor's
24656        // reference projection — the accessor's reference-projection
24657        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
24658        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
24659        // without silently short-circuiting any.
24660        //
24661        // Peer of the sibling M3
24662        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24663        // (534dc21) multi-axis coherence pin on the per-`:politicas`
24664        // outer mesh-policy composite-reference axis — extends the
24665        // multi-consumer coherence discipline onto the outermost M3
24666        // mesh-slot type's per-Aplicacao distribution composite-
24667        // reference axis, the second `&Composite`-return accessor on
24668        // the outer [`AplicacaoSpec`] type.
24669
24670        // (1) `PlacementWithoutClusters` refusal under the outer
24671        // accessor's reference projection: an empty `:clusters` pool
24672        // must trip the pre-flight refusal probe. The bracket-dispatch's
24673        // first arm reads `p.clusters()` on the reference returned by
24674        // the outer accessor.
24675        let mut spec = three_member_spec();
24676        spec.placement.clusters = Vec::new();
24677        assert_eq!(
24678            spec.validate().unwrap_err(),
24679            AplicacaoError::PlacementWithoutClusters {
24680                estrategia: PlacementStrategy::Replicated,
24681            },
24682        );
24683        assert!(
24684            std::ptr::eq(spec.placement(), &spec.placement),
24685            "the `validate_placement` per-axis bracket-dispatch's \
24686             traversal input must be the same backing composite the \
24687             accessor's reference projection borrows from",
24688        );
24689
24690        // (2) `ShardedWithoutKey` refusal under the outer accessor's
24691        // reference projection: a `Sharded` strategy with a `None`
24692        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
24693        // The bracket-dispatch's third arm reads `p.estrategia()` for
24694        // the match scrutinee then `p.shard_key()` for the cascade
24695        // scrutinee, both on the reference returned by the outer
24696        // accessor.
24697        let mut spec = three_member_spec();
24698        spec.placement.estrategia = PlacementStrategy::Sharded;
24699        spec.placement.shard_key = None;
24700        assert_eq!(
24701            spec.validate().unwrap_err(),
24702            AplicacaoError::ShardedWithoutKey,
24703        );
24704
24705        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
24706        // reference projection: a non-`Sharded` strategy with a `Some`
24707        // `:shard-key` must trip the declared-but-inert refusal. The
24708        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
24709        // + `p.estrategia()` for the diagnostic on the reference
24710        // returned by the outer accessor.
24711        let mut spec = three_member_spec();
24712        spec.placement.estrategia = PlacementStrategy::Replicated;
24713        spec.placement.shard_key = Some("tenantId".into());
24714        assert_eq!(
24715            spec.validate().unwrap_err(),
24716            AplicacaoError::ShardKeyOnNonSharded {
24717                estrategia: PlacementStrategy::Replicated,
24718                shard_key: "tenantId".into(),
24719            },
24720        );
24721
24722        // (4) Canonical `three_member_spec` `Replicated` fixture passes
24723        // `validate_placement` — every per-axis arm reaches the fall-
24724        // through `Ok(())` without any per-axis refusal firing under the
24725        // outer accessor's reference projection.
24726        let spec = three_member_spec();
24727        assert!(
24728            spec.validate().is_ok(),
24729            "the canonical Replicated placement fixture must pass \
24730             `validate_placement` — every per-axis arm short-circuits on \
24731             valid input under the outer accessor's reference projection",
24732        );
24733        assert_eq!(
24734            spec.placement().estrategia(),
24735            PlacementStrategy::Replicated,
24736            "the outer accessor's reference projection must be the \
24737             canonical Replicated fixture's strategy",
24738        );
24739        assert_eq!(
24740            spec.placement().clusters(),
24741            &["rio", "mar"],
24742            "the outer accessor's reference projection must be the \
24743             canonical Replicated fixture's cluster pool",
24744        );
24745    }
24746
24747    #[test]
24748    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
24749        // The canonical per-`:entrada` outer-composite-optional-
24750        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
24751        // the `:entrada` typed `Option<Entrada>` verbatim as an
24752        // `Option<&Entrada>` reference over the same backing storage
24753        // the raw `self.entrada.as_ref()` field access borrows from,
24754        // byte-equal across every representative fixture in the
24755        // accept-set — the author-omitted `None` shape (the
24756        // "internal-only mesh" partition every downstream external-
24757        // gateway emitter treats as "emit nothing"), the minimal
24758        // singleton `:entrada` composite (host + destination + empty
24759        // paths + default port), the paths-carrying composite (the
24760        // canonical `three_member_spec` fixture's ["/api" "/health"]
24761        // path-list shape every HTTPRoute per-rule fan-out emitter
24762        // reads), and the non-default port composite (the canonical
24763        // custom-port shape the port-fallback resolver reads).
24764        //
24765        // Pins against a future silent detour that returned a fresh-
24766        // cloned `Entrada` copy (which would type-check via a `Clone`
24767        // impl but silently break every downstream caller that
24768        // relied on the reference sharing the composite's backing
24769        // identity), a reference to an operator-resolved overlay
24770        // (the future per-cluster `:entrada-overrides` slot the
24771        // MESH-COMPOSITION §V federation roadmap acknowledges — its
24772        // resolution must land at exactly this accessor body, not
24773        // silently divert the raw slot away from a second consumer),
24774        // a `None` → `Some(Entrada::default)` cluster-default
24775        // projection (which would collapse the load-bearing
24776        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
24777        // the peer `gateway_routes` early-return + `feira app graph`
24778        // internal-only-mesh partition both read), or an axis-
24779        // shuffled projection (a future detour that swapped
24780        // `host` and `para` through the accessor would silently
24781        // split the paired `validate` per-`:entrada` shape-and-
24782        // membership gate's traversal input from the peer
24783        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
24784        // fan-out input from the peer `feira app graph` external-
24785        // gateway summary line).
24786        //
24787        // Peer of the sibling M3
24788        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24789        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
24790        // `:politicas` outer mesh-policy composite-reference axis
24791        // and of the sibling M3
24792        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
24793        // (9abb8f0) `&Placement` byte-equal pin on the per-
24794        // `:placement` outer distribution-composite composite-
24795        // reference axis — extends the outer-accessor byte-equal-
24796        // projection discipline onto the last unlifted outermost M3
24797        // mesh-slot type's per-Aplicacao external-gateway composite-
24798        // reference axis, the third and final `&Composite`-return
24799        // accessor on the outer [`AplicacaoSpec`] type.
24800        let fixtures: Vec<Option<Entrada>> = vec![
24801            None,
24802            Some(Entrada {
24803                host: "checkout.quero.cloud".into(),
24804                para: "cart".into(),
24805                paths: Vec::new(),
24806                port: DEFAULT_SERVICO_PORT,
24807            }),
24808            Some(Entrada {
24809                host: "checkout.quero.cloud".into(),
24810                para: "cart".into(),
24811                paths: vec!["/api".into(), "/health".into()],
24812                port: DEFAULT_SERVICO_PORT,
24813            }),
24814            Some(Entrada {
24815                host: "checkout.quero.cloud".into(),
24816                para: "cart".into(),
24817                paths: vec!["/api".into()],
24818                port: 9443,
24819            }),
24820        ];
24821        for entrada in fixtures {
24822            let s = AplicacaoSpec {
24823                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24824                contratos: Vec::new(),
24825                politicas: MeshPolicy::default(),
24826                placement: Placement::default(),
24827                entrada: entrada.clone(),
24828            };
24829            assert_eq!(
24830                s.entrada(),
24831                entrada.as_ref(),
24832                "AplicacaoSpec::entrada must return :entrada verbatim \
24833                 (got {:?}, expected {:?})",
24834                s.entrada(),
24835                entrada.as_ref(),
24836            );
24837            match (s.entrada(), s.entrada.as_ref()) {
24838                (Some(a), Some(b)) => assert!(
24839                    std::ptr::eq(a, b),
24840                    "AplicacaoSpec::entrada accessor and \
24841                     self.entrada.as_ref() field access must borrow \
24842                     the same backing storage — the accessor is the \
24843                     substrate-primitive typed dispatch every \
24844                     downstream external-gateway composite consumer \
24845                     must route through, and a reference-identity \
24846                     split would silently break every consumer that \
24847                     relied on the borrow sharing the composite's \
24848                     storage",
24849                ),
24850                (None, None) => {}
24851                _ => panic!(
24852                    "AplicacaoSpec::entrada presence bit must byte-\
24853                     equal self.entrada.is_some() — a presence-bit \
24854                     drift would silently split the paired `validate` \
24855                     per-`:entrada` shape-and-membership gate's \
24856                     traversal head from the peer \
24857                     caixa-mesh gateway_routes early-return partition \
24858                     from the peer `feira app graph` internal-only-\
24859                     mesh partition",
24860                ),
24861            }
24862            assert_eq!(
24863                s.entrada().is_some(),
24864                s.entrada.is_some(),
24865                "AplicacaoSpec::entrada().is_some() must byte-equal \
24866                 self.entrada.is_some() — a presence-bit drift would \
24867                 silently split every downstream `Option<&Entrada>` \
24868                 consumer's partition on the internal-only-mesh arm",
24869            );
24870        }
24871    }
24872
24873    #[test]
24874    fn validate_reads_through_lifted_entrada_accessor() {
24875        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
24876        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
24877        // self.entrada() { … }`, followed by the per-axis fan-out
24878        // `validate_entrada_para(&e.para)` /
24879        // `EntradaMemberMissing` membership lookup /
24880        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
24881        // per-`e.paths` `validate_entrada_path` traversal) must key
24882        // off the lifted outer accessor, so any future rebrand on
24883        // the typed slot's outer-composite reader shape lands at
24884        // exactly one place. Pins the multi-axis coherence by
24885        // exercising each per-axis refusal end-to-end: (1) the
24886        // author-omitted `None` shape short-circuits past every
24887        // per-`:entrada` refusal (the internal-only mesh partition
24888        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
24889        // fires on a well-shaped but phantom `:para` under the outer
24890        // accessor's reference projection, and (3) the canonical
24891        // `three_member_spec` `:entrada` fixture passes `validate`
24892        // under the outer accessor's reference projection.
24893        //
24894        // Peer of the sibling M3
24895        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24896        // (534dc21) multi-axis coherence pin on the per-`:politicas`
24897        // outer mesh-policy composite-reference axis and the sibling
24898        // M3
24899        // [`validate_placement_reads_through_lifted_placement_accessor`]
24900        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
24901        // outer distribution-composite composite-reference axis —
24902        // extends the multi-consumer coherence discipline onto the
24903        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
24904        // external-gateway composite-reference axis, the third and
24905        // final `&Composite`-return accessor on the outer
24906        // [`AplicacaoSpec`] type.
24907
24908        // (1) `None` :entrada — the internal-only-mesh partition
24909        // short-circuits past every per-`:entrada` refusal. The outer
24910        // accessor's reference projection reaches the fall-through
24911        // `Ok(())` on the `None` arm without any per-axis refusal
24912        // firing.
24913        let mut spec = three_member_spec();
24914        spec.entrada = None;
24915        assert!(
24916            spec.validate().is_ok(),
24917            "an author-omitted `:entrada` must pass `validate` — the \
24918             internal-only-mesh partition short-circuits past every \
24919             per-`:entrada` refusal under the outer accessor's \
24920             reference projection",
24921        );
24922        assert!(
24923            spec.entrada().is_none(),
24924            "the outer accessor's reference projection must name the \
24925             internal-only-mesh partition per the `None` fixture",
24926        );
24927
24928        // (2) `EntradaMemberMissing` refusal under the outer accessor's
24929        // reference projection: a well-shaped but phantom `:para` must
24930        // trip the membership-lookup refusal. The gate's second arm
24931        // reads `e.para` on the reference returned by the outer
24932        // accessor.
24933        let mut spec = three_member_spec();
24934        if let Some(e) = spec.entrada.as_mut() {
24935            e.para = "phantom".into();
24936        }
24937        assert_eq!(
24938            spec.validate().unwrap_err(),
24939            AplicacaoError::EntradaMemberMissing {
24940                para: "phantom".into(),
24941            },
24942        );
24943        match (spec.entrada(), spec.entrada.as_ref()) {
24944            (Some(a), Some(b)) => assert!(
24945                std::ptr::eq(a, b),
24946                "the `validate` per-`:entrada` gate's traversal head \
24947                 must be the same backing composite the accessor's \
24948                 reference projection borrows from",
24949            ),
24950            _ => panic!("fixture must carry Some(:entrada)"),
24951        }
24952
24953        // (3) Canonical `three_member_spec` `:entrada` fixture passes
24954        // `validate` — every per-axis arm reaches the fall-through
24955        // `Ok(())` without any per-axis refusal firing under the
24956        // outer accessor's reference projection.
24957        let spec = three_member_spec();
24958        assert!(
24959            spec.validate().is_ok(),
24960            "the canonical `:entrada` fixture must pass `validate` — \
24961             every per-axis arm short-circuits on valid input under \
24962             the outer accessor's reference projection",
24963        );
24964        assert!(
24965            spec.entrada().is_some(),
24966            "the outer accessor's reference projection must be the \
24967             canonical `:entrada` fixture's composite",
24968        );
24969    }
24970
24971    #[test]
24972    fn port_for_destination_reads_through_lifted_entrada_accessor() {
24973        // Peer coherence pin: the
24974        // [`AplicacaoSpec::port_for_destination`] per-destination
24975        // L4-port fallback resolver's composite-projection seed
24976        // (`self.entrada().filter(…).map_or(…)`) must key off the
24977        // lifted outer accessor. Pins the coherence by exercising
24978        // the resolver end-to-end: (1) the `None` `:entrada` shape
24979        // falls through to `DEFAULT_SERVICO_PORT` under the outer
24980        // accessor's reference projection, (2) a non-matching
24981        // destination falls through to `DEFAULT_SERVICO_PORT` under
24982        // the outer accessor's reference projection, and (3) the
24983        // matching destination resolves to the `:entrada :port`
24984        // value under the outer accessor's reference projection.
24985        //
24986        // Peer of the sibling
24987        // [`validate_reads_through_lifted_entrada_accessor`] multi-
24988        // consumer coherence pin on the same per-`:entrada` outer-
24989        // composite axis — extends the multi-consumer coherence
24990        // discipline onto the second per-`:entrada` production
24991        // consumer, the L4-port fallback resolver.
24992
24993        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
24994        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
24995        // arm under the outer accessor's reference projection.
24996        let mut spec = three_member_spec();
24997        spec.entrada = None;
24998        assert_eq!(
24999            spec.port_for_destination("cart"),
25000            DEFAULT_SERVICO_PORT,
25001            "the port-fallback resolver must fall through to \
25002             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
25003             under the outer accessor's reference projection",
25004        );
25005
25006        // (2) Non-matching destination — the resolver's `filter(…)`
25007        // arm rejects a mismatched destination and falls through
25008        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
25009        // reference projection.
25010        let mut spec = three_member_spec();
25011        if let Some(e) = spec.entrada.as_mut() {
25012            e.para = "cart".into();
25013            e.port = 9443;
25014        }
25015        assert_eq!(
25016            spec.port_for_destination("catalog"),
25017            DEFAULT_SERVICO_PORT,
25018            "the port-fallback resolver must fall through to \
25019             DEFAULT_SERVICO_PORT on a non-matching destination \
25020             under the outer accessor's reference projection",
25021        );
25022
25023        // (3) Matching destination — the resolver's `map_or(…)` arm
25024        // returns the `:entrada :port` value under the outer
25025        // accessor's reference projection.
25026        let mut spec = three_member_spec();
25027        if let Some(e) = spec.entrada.as_mut() {
25028            e.para = "cart".into();
25029            e.port = 9443;
25030        }
25031        assert_eq!(
25032            spec.port_for_destination("cart"),
25033            9443,
25034            "the port-fallback resolver must return the \
25035             `:entrada :port` value on a matching destination \
25036             under the outer accessor's reference projection",
25037        );
25038    }
25039
25040    #[test]
25041    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
25042        // The canonical per-`:politicas` `:mtls-required` mTLS-
25043        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
25044        // must return the `:politicas :mtls-required` typed bool
25045        // verbatim as an `Option<bool>`, byte-equal to the raw field
25046        // access across every value in the three-way accept-set —
25047        // `None` (cluster default applies), `Some(true)` (mTLS
25048        // handshake enforced — the sandboxing-by-default arm the
25049        // MeshPolicy's docstring names), `Some(false)` (handshake
25050        // skipped — the explicit debug-edge opt-out).
25051        //
25052        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
25053        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
25054        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
25055        // shape — first `Option<Copy-T>`-return accessor on the M3
25056        // mesh-slot family. Pins against a future silent detour that
25057        // re-derived the toggle from a peer axis (an accidental
25058        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
25059        // whenever a breaker is set), a `None` → `Some(false)` cluster-
25060        // default projection (the canonical `Option<bool>` → `bool`
25061        // collapse footgun the surrounding `is_empty()` predicate
25062        // guards on the peer emptiness axis), or a `Some(true)` /
25063        // `Some(false)` variant swap that landed on one consumer
25064        // without the other.
25065        for required in [None, Some(true), Some(false)] {
25066            let p = MeshPolicy {
25067                mtls_required: required,
25068                ..MeshPolicy::default()
25069            };
25070            assert_eq!(
25071                p.mtls_required(),
25072                required,
25073                "MeshPolicy::mtls_required must return :politicas \
25074                 :mtls-required verbatim (got {:?}, expected {required:?})",
25075                p.mtls_required(),
25076            );
25077            assert_eq!(
25078                p.mtls_required(),
25079                p.mtls_required,
25080                "MeshPolicy::mtls_required must byte-equal the raw \
25081                 .mtls_required field access across every value in the \
25082                 three-way accept-set",
25083            );
25084        }
25085    }
25086
25087    #[test]
25088    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
25089        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
25090        // arm must key off [`MeshPolicy::mtls_required`], not the raw
25091        // `.mtls_required` field access. Structurally: toggling ONLY
25092        // the `mtls_required` slot on an otherwise-default MeshPolicy
25093        // must flip `is_empty()` from `true` (all-`None`) to `false`
25094        // (one axis carries a value); the flip must be observed for
25095        // both `Some(true)` and `Some(false)` since the emptiness
25096        // semantic reads "any axis carries a value" — not "any axis
25097        // carries a truthy value" — the same non-collapsing shape the
25098        // sibling M2 [`crate::LimitsSpec::is_empty`] /
25099        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
25100        // peer `Option<T>`-typed slot surfaces.
25101        //
25102        // Pins against a future silent detour that re-derived the
25103        // emptiness predicate off a peer axis (an accidental
25104        // `.rate_limit.is_none()`-only chain that dropped the
25105        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
25106        // collapse to a truthy-only check (which would silently
25107        // classify `Some(false)` as empty), or an accessor-side
25108        // detour that no longer names the substrate-primitive typed
25109        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
25110        // == false` fallback in the accessor that would silently
25111        // classify both `None` and `Some(false)` as the same value).
25112        //
25113        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
25114        // (7cd2a28) accessor-composition pin on the sibling optional-
25115        // scalar axis — same "the emptiness / shape-gate predicate
25116        // must route through the substrate-primitive typed dispatch"
25117        // discipline extended onto the peer per-`:politicas` emptiness
25118        // predicate.
25119        let empty = MeshPolicy::default();
25120        assert!(
25121            empty.is_empty(),
25122            "MeshPolicy::default() must be is_empty() — every axis \
25123             defaults to None",
25124        );
25125        for required in [Some(true), Some(false)] {
25126            let p = MeshPolicy {
25127                mtls_required: required,
25128                ..MeshPolicy::default()
25129            };
25130            assert!(
25131                !p.is_empty(),
25132                "MeshPolicy::is_empty must return false when \
25133                 :mtls-required is {required:?} — the emptiness \
25134                 predicate reads \"any axis carries a value\", not \
25135                 \"any axis carries a truthy value\"",
25136            );
25137            assert_eq!(
25138                p.mtls_required().is_none(),
25139                p.is_empty(),
25140                "when :mtls-required is the only set axis, \
25141                 is_empty() must equal mtls_required().is_none() — \
25142                 the accessor and the emptiness predicate must \
25143                 route through the same substrate-primitive typed \
25144                 dispatch on the :mtls-required arm",
25145            );
25146        }
25147    }
25148
25149    #[test]
25150    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
25151        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
25152        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
25153        // accessor must return by value, not by reference. Peer of the
25154        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
25155        // borrow-invariant pin on the sibling `Option<String>` slot,
25156        // but extended onto the peer `Option<bool>` copy-invariant
25157        // shape — the accessor's returned `Option<bool>` must outlive
25158        // `&self` (multiple calls must return equal values from a
25159        // dropped-`&self` copy, since the returned Option carries no
25160        // borrow), and calling the accessor twice on the same
25161        // MeshPolicy must yield the same `Option<bool>` verbatim
25162        // (idempotent, no side effects on `&self`).
25163        //
25164        // Pins against a future silent detour that returned
25165        // `Option<&bool>` (which would type-check but silently break
25166        // every downstream caller — [`single_field_overlay`]'s first
25167        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
25168        // detached copy at the call site), an accidental
25169        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
25170        // would also type-check but return `Option<&bool>`), or a
25171        // one-arm-only accessor that reads `Some(*b)` in the Some arm
25172        // but reads a fresh Default::default() in the None arm.
25173        for required in [None, Some(true), Some(false)] {
25174            let p = MeshPolicy {
25175                mtls_required: required,
25176                ..MeshPolicy::default()
25177            };
25178            let first = p.mtls_required();
25179            let second = p.mtls_required();
25180            assert_eq!(
25181                first, second,
25182                "MeshPolicy::mtls_required must be idempotent — two \
25183                 successive calls on the same &self must return the \
25184                 same Option<bool>",
25185            );
25186            assert_eq!(
25187                first, required,
25188                "MeshPolicy::mtls_required must return :politicas \
25189                 :mtls-required verbatim by copy — got {first:?}, \
25190                 expected {required:?}",
25191            );
25192        }
25193    }
25194
25195    #[test]
25196    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
25197        // The canonical per-`:politicas` `:retries` transient-failure-
25198        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
25199        // the `:politicas :retries` typed `u32` verbatim as an
25200        // `Option<u32>`, byte-equal to the raw field access across every
25201        // representative value in the accept-set — `None` (cluster
25202        // default applies — typically "no retries beyond a single
25203        // dispatch attempt" the caixa-mesh `retry_overlay` builder
25204        // documents), `Some(1)` (the lower boundary of the
25205        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
25206        // `AplicacaoSpec::validate_politicas` gate carves out on the
25207        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
25208        // (the upper boundary the same gate carves out on the sibling
25209        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
25210        // past-the-guard sentinel that pins the accessor doesn't perform
25211        // a silent bounds-collapse at the return path).
25212        //
25213        // Sibling of the peer per-`:politicas`
25214        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
25215        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
25216        // peer per-`:politicas` `Option<u32>` shape — second
25217        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
25218        // Pins against a future silent detour that re-derived the retry
25219        // cap from a peer axis (an accidental `.circuit_breaker
25220        // .as_ref().map(|b| b.max_failures)` collapse that read the
25221        // breaker's max-failure count as a retry budget), a
25222        // `None → Some(0)` cluster-default projection (which would
25223        // silently re-introduce the `PolicyRetriesZero` refusal case at
25224        // the emit boundary), or a bounds-collapsing accessor that
25225        // clamped the return through `POLICY_RETRIES_MAX` (the
25226        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25227        // must ship the raw slot verbatim so a validate-time gate
25228        // regression surfaces at the emit boundary rather than being
25229        // silently absorbed).
25230        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
25231            let p = MeshPolicy {
25232                retries,
25233                ..MeshPolicy::default()
25234            };
25235            assert_eq!(
25236                p.retries(),
25237                retries,
25238                "MeshPolicy::retries must return :politicas :retries \
25239                 verbatim (got {:?}, expected {retries:?})",
25240                p.retries(),
25241            );
25242            assert_eq!(
25243                p.retries(),
25244                p.retries,
25245                "MeshPolicy::retries must byte-equal the raw .retries \
25246                 field access across every value in the accept-set",
25247            );
25248        }
25249    }
25250
25251    #[test]
25252    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
25253        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
25254        // must key off [`MeshPolicy::retries`], not the raw `.retries`
25255        // field access. Structurally: toggling ONLY the `retries` slot
25256        // on an otherwise-default MeshPolicy must flip `is_empty()`
25257        // from `true` (all-`None`) to `false` (one axis carries a
25258        // value); the flip must be observed for every value in the
25259        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25260        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
25261        // the emptiness semantic reads "any axis carries a value" —
25262        // not "any axis carries a value the validate gate accepts" —
25263        // the same non-collapsing shape the peer M2
25264        // [`crate::LimitsSpec::is_empty`] /
25265        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25266        //
25267        // Pins against a future silent detour that re-derived the
25268        // emptiness predicate off a peer axis (an accidental
25269        // `.rate_limit.is_none()`-only chain that dropped the
25270        // `retries` arm entirely), a `retries == Some(_)` collapse
25271        // that key-off a validate-gate-clamped bounds check (which
25272        // would silently classify a past-the-guard `Some(u32::MAX)`
25273        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
25274        // check), or an accessor-side detour that no longer names the
25275        // substrate-primitive typed dispatch.
25276        //
25277        // Sibling of the peer per-`:politicas`
25278        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
25279        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
25280        // same "the emptiness predicate must route through the
25281        // substrate-primitive typed dispatch" discipline extended onto
25282        // the peer per-`:politicas` `Option<u32>` axis.
25283        let empty = MeshPolicy::default();
25284        assert!(
25285            empty.is_empty(),
25286            "MeshPolicy::default() must be is_empty() — every axis \
25287             defaults to None",
25288        );
25289        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
25290            let p = MeshPolicy {
25291                retries,
25292                ..MeshPolicy::default()
25293            };
25294            assert!(
25295                !p.is_empty(),
25296                "MeshPolicy::is_empty must return false when \
25297                 :retries is {retries:?} — the emptiness \
25298                 predicate reads \"any axis carries a value\", not \
25299                 \"any axis carries a value the validate gate \
25300                 accepts\"",
25301            );
25302            assert_eq!(
25303                p.retries().is_none(),
25304                p.is_empty(),
25305                "when :retries is the only set axis, is_empty() \
25306                 must equal retries().is_none() — the accessor and \
25307                 the emptiness predicate must route through the same \
25308                 substrate-primitive typed dispatch on the :retries \
25309                 arm",
25310            );
25311        }
25312    }
25313
25314    #[test]
25315    fn mesh_policy_retries_projects_option_u32_by_copy() {
25316        // The by-copy pin: [`MeshPolicy::retries`] returns
25317        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
25318        // accessor must return by value, not by reference. Sibling of
25319        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
25320        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
25321        // extended onto the sibling `Option<u32>` copy-invariant
25322        // shape — the accessor's returned `Option<u32>` must outlive
25323        // `&self` (multiple calls must return equal values from a
25324        // dropped-`&self` copy, since the returned Option carries no
25325        // borrow), and calling the accessor twice on the same
25326        // MeshPolicy must yield the same `Option<u32>` verbatim
25327        // (idempotent, no side effects on `&self`).
25328        //
25329        // Pins against a future silent detour that returned
25330        // `Option<&u32>` (which would type-check but silently break
25331        // every downstream caller — [`crate::render::single_field_overlay`]'s
25332        // first parameter is `Option<T: Clone>`, and `&u32` would
25333        // fold to a detached copy at the call site), an accidental
25334        // `Option::as_ref()` projection (`self.retries.as_ref()` would
25335        // also type-check but return `Option<&u32>`), or a one-arm-
25336        // only accessor that reads `Some(*n)` in the Some arm but
25337        // reads a fresh `Default::default()` (`0_u32`) in the None
25338        // arm.
25339        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
25340            let p = MeshPolicy {
25341                retries,
25342                ..MeshPolicy::default()
25343            };
25344            let first = p.retries();
25345            let second = p.retries();
25346            assert_eq!(
25347                first, second,
25348                "MeshPolicy::retries must be idempotent — two \
25349                 successive calls on the same &self must return the \
25350                 same Option<u32>",
25351            );
25352            assert_eq!(
25353                first, retries,
25354                "MeshPolicy::retries must return :politicas :retries \
25355                 verbatim by copy — got {first:?}, expected {retries:?}",
25356            );
25357        }
25358    }
25359
25360    #[test]
25361    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
25362        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
25363        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
25364        // return the `:politicas :timeout` typed [`Duration`] verbatim
25365        // as an `Option<Duration>`, byte-equal to the raw field access
25366        // across every representative value in the accept-set — `None`
25367        // (cluster default applies — typically the gateway class's
25368        // implementation-side per-request wall-clock cap the caixa-mesh
25369        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
25370        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
25371        // set the surrounding `AplicacaoSpec::validate_politicas` gate
25372        // carves out on the sibling `PolicyTimeoutZero` /
25373        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
25374        // (the upper boundary the same gate carves out on the sibling
25375        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
25376        // (a past-the-guard sentinel that pins the accessor doesn't
25377        // perform a silent bounds-collapse into `None` on the zero-
25378        // Duration arm — validate rejects zero but the accessor must
25379        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
25380        // past-the-guard sentinel that pins the accessor doesn't
25381        // perform a silent bounds-collapse at the return path).
25382        //
25383        // Sibling of the peer per-`:politicas`
25384        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
25385        // `Option<u32>` optional-scalar axis and the peer per-
25386        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
25387        // pin on the sibling `Option<bool>` optional-scalar axis,
25388        // extended onto the peer per-`:politicas` `Option<Duration>`
25389        // shape — third `Option<Copy-T>`-return accessor on the M3
25390        // mesh-slot family. Pins against a future silent detour that
25391        // re-derived the per-call cap from a peer axis (an accidental
25392        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
25393        // read the breaker's rolling-window duration as a per-call
25394        // deadline), a `None → Some(Duration::MAX)` cluster-default
25395        // projection (which would silently re-introduce the
25396        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
25397        // blocking" arm at the emit boundary), or a bounds-collapsing
25398        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
25399        // (the `AplicacaoSpec::validate` gate owns the bounds; the
25400        // accessor must ship the raw slot verbatim so a validate-time
25401        // gate regression surfaces at the emit boundary rather than
25402        // being silently absorbed).
25403        for timeout in [
25404            None,
25405            Some(Duration::from_millis(1)),
25406            Some(POLICY_TIMEOUT_MAX),
25407            Some(Duration::ZERO),
25408            Some(Duration::MAX),
25409        ] {
25410            let p = MeshPolicy {
25411                timeout,
25412                ..MeshPolicy::default()
25413            };
25414            assert_eq!(
25415                p.timeout(),
25416                timeout,
25417                "MeshPolicy::timeout must return :politicas :timeout \
25418                 verbatim (got {:?}, expected {timeout:?})",
25419                p.timeout(),
25420            );
25421            assert_eq!(
25422                p.timeout(),
25423                p.timeout,
25424                "MeshPolicy::timeout must byte-equal the raw .timeout \
25425                 field access across every value in the accept-set",
25426            );
25427        }
25428    }
25429
25430    #[test]
25431    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
25432        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
25433        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
25434        // field access. Structurally: toggling ONLY the `timeout` slot
25435        // on an otherwise-default MeshPolicy must flip `is_empty()`
25436        // from `true` (all-`None`) to `false` (one axis carries a
25437        // value); the flip must be observed for every value in the
25438        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25439        // gate accepts (`Some(Duration::from_millis(1))`,
25440        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
25441        // reads "any axis carries a value" — not "any axis carries a
25442        // value the validate gate accepts" — the same non-collapsing
25443        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
25444        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25445        //
25446        // Pins against a future silent detour that re-derived the
25447        // emptiness predicate off a peer axis (an accidental
25448        // `.rate_limit.is_none()`-only chain that dropped the
25449        // `timeout` arm entirely), a `timeout == Some(_)` collapse
25450        // that key-off a validate-gate-clamped bounds check (which
25451        // would silently classify a past-the-guard `Some(Duration::MAX)`
25452        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
25453        // check), or an accessor-side detour that no longer names the
25454        // substrate-primitive typed dispatch.
25455        //
25456        // Sibling of the peer per-`:politicas`
25457        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
25458        // the sibling `Option<u32>` optional-scalar axis and the peer
25459        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25460        // accessor-composition pin on the sibling `Option<bool>`
25461        // optional-scalar axis — same "the emptiness predicate must
25462        // route through the substrate-primitive typed dispatch"
25463        // discipline extended onto the peer per-`:politicas`
25464        // `Option<Duration>` axis.
25465        let empty = MeshPolicy::default();
25466        assert!(
25467            empty.is_empty(),
25468            "MeshPolicy::default() must be is_empty() — every axis \
25469             defaults to None",
25470        );
25471        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
25472            let p = MeshPolicy {
25473                timeout,
25474                ..MeshPolicy::default()
25475            };
25476            assert!(
25477                !p.is_empty(),
25478                "MeshPolicy::is_empty must return false when \
25479                 :timeout is {timeout:?} — the emptiness \
25480                 predicate reads \"any axis carries a value\", not \
25481                 \"any axis carries a value the validate gate \
25482                 accepts\"",
25483            );
25484            assert_eq!(
25485                p.timeout().is_none(),
25486                p.is_empty(),
25487                "when :timeout is the only set axis, is_empty() \
25488                 must equal timeout().is_none() — the accessor and \
25489                 the emptiness predicate must route through the same \
25490                 substrate-primitive typed dispatch on the :timeout \
25491                 arm",
25492            );
25493        }
25494    }
25495
25496    #[test]
25497    fn mesh_policy_timeout_projects_option_duration_by_copy() {
25498        // The by-copy pin: [`MeshPolicy::timeout`] returns
25499        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
25500        // and the accessor must return by value, not by reference.
25501        // Sibling of the peer per-`:politicas`
25502        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
25503        // sibling `Option<u32>` optional-scalar axis and the peer
25504        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25505        // by-copy pin on the sibling `Option<bool>` optional-scalar
25506        // axis, extended onto the peer per-`:politicas`
25507        // `Option<Duration>` copy-invariant shape — the accessor's
25508        // returned `Option<Duration>` must outlive `&self` (multiple
25509        // calls must return equal values from a dropped-`&self`
25510        // copy, since the returned Option carries no borrow), and
25511        // calling the accessor twice on the same MeshPolicy must
25512        // yield the same `Option<Duration>` verbatim (idempotent, no
25513        // side effects on `&self`).
25514        //
25515        // Pins against a future silent detour that returned
25516        // `Option<&Duration>` (which would type-check but silently
25517        // break every downstream caller — [`crate::render::single_field_overlay`]'s
25518        // first parameter is `Option<T: Clone>`, and `&Duration`
25519        // would fold to a detached copy at the call site), an
25520        // accidental `Option::as_ref()` projection
25521        // (`self.timeout.as_ref()` would also type-check but return
25522        // `Option<&Duration>`), or a one-arm-only accessor that
25523        // reads `Some(*d)` in the Some arm but reads a fresh
25524        // `Default::default()` (`Duration::ZERO`) in the None arm
25525        // (which would silently re-classify every unset `:timeout`
25526        // as the `PolicyTimeoutZero`-refused zero-Duration value at
25527        // the accessor boundary).
25528        for timeout in [
25529            None,
25530            Some(Duration::from_millis(1)),
25531            Some(POLICY_TIMEOUT_MAX),
25532            Some(Duration::ZERO),
25533            Some(Duration::MAX),
25534        ] {
25535            let p = MeshPolicy {
25536                timeout,
25537                ..MeshPolicy::default()
25538            };
25539            let first = p.timeout();
25540            let second = p.timeout();
25541            assert_eq!(
25542                first, second,
25543                "MeshPolicy::timeout must be idempotent — two \
25544                 successive calls on the same &self must return the \
25545                 same Option<Duration>",
25546            );
25547            assert_eq!(
25548                first, timeout,
25549                "MeshPolicy::timeout must return :politicas :timeout \
25550                 verbatim by copy — got {first:?}, expected {timeout:?}",
25551            );
25552        }
25553    }
25554
25555    #[test]
25556    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
25557        // The canonical per-`:politicas` `:rate-limit` Envoy-
25558        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
25559        // [`MeshPolicy::rate_limit`] must return the `:politicas
25560        // :rate-limit` typed [`RateLimit`] verbatim as an
25561        // `Option<RateLimit>`, byte-equal to the raw field access
25562        // across every representative value in the accept-set — `None`
25563        // (cluster default applies — no per-Aplicacao rate declaration,
25564        // the gateway-class per-listener default arm the future caixa-
25565        // mesh `local_rate_limit_overlay` emitter documents),
25566        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
25567        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
25568        // accept-set the surrounding
25569        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25570        // sibling `PolicyRateLimitZero` refusal, paired with the
25571        // canonical-window "1 second" arm of the three-unit
25572        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
25573        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
25574        // (the upper boundary the same gate carves out on the sibling
25575        // `PolicyRateLimitExceedsCap` refusal, paired with the
25576        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
25577        // (a past-the-guard sentinel that pins the accessor doesn't
25578        // perform a silent bounds-collapse into `None` on the
25579        // zero-rate/zero-window arm — validate rejects zero but the
25580        // accessor must ship the raw slot verbatim so a validate-time
25581        // gate regression surfaces at the emit boundary rather than
25582        // being silently absorbed), and
25583        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
25584        // (a past-the-guard sentinel that pins the accessor doesn't
25585        // perform a silent bounds-collapse at the return path).
25586        //
25587        // First `Option<Copy-composite-T>`-return accessor pin on the
25588        // M3 mesh-slot family (peer of the sibling per-`:politicas`
25589        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
25590        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
25591        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
25592        // Copy accessor pins, extended onto the peer per-`:politicas`
25593        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
25594        // and the accessor returns by value). Pins against a future
25595        // silent detour that re-derived the rate declaration from a
25596        // peer axis (an accidental
25597        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
25598        // collapse that read the breaker's trip threshold + rolling
25599        // window as a rate declaration), a `None → Some(default())`
25600        // cluster-default projection (which would silently re-
25601        // introduce a "cluster default is 0/s" arm the emit boundary
25602        // would take as "declared but inert" — the canonical
25603        // declared-but-inert footgun the sibling
25604        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
25605        // amplification-shape axis), a bounds-collapsing accessor
25606        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
25607        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
25608        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
25609        // accessor must ship the raw slot verbatim), or a
25610        // by-reference detour (`Option<&RateLimit>`) that broke every
25611        // downstream consumer keying off `Option<RateLimit>` by-copy.
25612        for rl in [
25613            None,
25614            Some(RateLimit {
25615                rate: 1,
25616                window: Duration::from_secs(1),
25617            }),
25618            Some(RateLimit {
25619                rate: POLICY_RATE_LIMIT_MAX,
25620                window: Duration::from_secs(3600),
25621            }),
25622            Some(RateLimit {
25623                rate: 0,
25624                window: Duration::ZERO,
25625            }),
25626            Some(RateLimit {
25627                rate: u32::MAX,
25628                window: Duration::MAX,
25629            }),
25630        ] {
25631            let p = MeshPolicy {
25632                rate_limit: rl,
25633                ..MeshPolicy::default()
25634            };
25635            assert_eq!(
25636                p.rate_limit(),
25637                rl,
25638                "MeshPolicy::rate_limit must return :politicas :rate-limit \
25639                 verbatim (got {:?}, expected {rl:?})",
25640                p.rate_limit(),
25641            );
25642            assert_eq!(
25643                p.rate_limit(),
25644                p.rate_limit,
25645                "MeshPolicy::rate_limit must byte-equal the raw \
25646                 .rate_limit field access across every value in the \
25647                 accept-set",
25648            );
25649        }
25650    }
25651
25652    #[test]
25653    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
25654        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
25655        // must key off [`MeshPolicy::rate_limit`], not the raw
25656        // `.rate_limit` field access. Structurally: toggling ONLY the
25657        // `rate_limit` slot on an otherwise-default MeshPolicy must
25658        // flip `is_empty()` from `true` (all-`None`) to `false` (one
25659        // axis carries a value); the flip must be observed for every
25660        // representative value in the accept-set the surrounding
25661        // [`AplicacaoSpec::validate_politicas`] gate accepts
25662        // (`Some(RateLimit { rate: 1, window: 1s })`,
25663        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
25664        // since the emptiness semantic reads "any axis carries a
25665        // value" — not "any axis carries a value the validate gate
25666        // accepts" — the same non-collapsing shape the peer M2
25667        // [`crate::LimitsSpec::is_empty`] /
25668        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25669        //
25670        // Pins against a future silent detour that re-derived the
25671        // emptiness predicate off a peer axis (an accidental
25672        // `.timeout.is_none()`-only chain that dropped the
25673        // `rate_limit` arm entirely — the last unlifted inline field
25674        // access on `is_empty` before this lift), a `rate_limit ==
25675        // Some(_)` collapse that key-off a validate-gate-clamped
25676        // bounds check (which would silently classify a past-the-
25677        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
25678        // because it fails the value-shape gate), or an accessor-
25679        // side detour that no longer names the substrate-primitive
25680        // typed dispatch.
25681        //
25682        // Fourth "the emptiness predicate must route through the
25683        // substrate-primitive typed dispatch" composition pin on the
25684        // M3 mesh-slot family — closes the last unlifted composition
25685        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
25686        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
25687        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
25688        // 7073d0f is_empty-composition pins on the sibling primitive-
25689        // Copy axes, extended onto the peer per-`:politicas`
25690        // composite-Copy `Option<RateLimit>` axis).
25691        let empty = MeshPolicy::default();
25692        assert!(
25693            empty.is_empty(),
25694            "MeshPolicy::default() must be is_empty() — every axis \
25695             defaults to None",
25696        );
25697        for rl in [
25698            RateLimit {
25699                rate: 1,
25700                window: Duration::from_secs(1),
25701            },
25702            RateLimit {
25703                rate: POLICY_RATE_LIMIT_MAX,
25704                window: Duration::from_secs(3600),
25705            },
25706        ] {
25707            let p = MeshPolicy {
25708                rate_limit: Some(rl),
25709                ..MeshPolicy::default()
25710            };
25711            assert!(
25712                !p.is_empty(),
25713                "MeshPolicy::is_empty must return false when \
25714                 :rate-limit is {rl:?} — the emptiness predicate \
25715                 reads \"any axis carries a value\", not \"any axis \
25716                 carries a value the validate gate accepts\"",
25717            );
25718            assert_eq!(
25719                p.rate_limit().is_none(),
25720                p.is_empty(),
25721                "when :rate-limit is the only set axis, is_empty() \
25722                 must equal rate_limit().is_none() — the accessor \
25723                 and the emptiness predicate must route through the \
25724                 same substrate-primitive typed dispatch on the \
25725                 :rate-limit arm",
25726            );
25727        }
25728    }
25729
25730    #[test]
25731    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
25732        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25733        // `:rate-limit` value-shape gate must key off
25734        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
25735        // field bind. Structurally: a `MeshPolicy` whose only set
25736        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
25737        // the `PolicyRateLimitZero` refusal exactly, and the same
25738        // MeshPolicy with the rate at the canonical lower boundary
25739        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
25740        // The pair jointly pins the accessor + validate-gate
25741        // composition: any future silent detour that had the accessor
25742        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
25743        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
25744        // silently absorb the `PolicyRateLimitZero` refusal at the
25745        // accessor boundary — the composition pin catches that at
25746        // caixa-core build time.
25747        //
25748        // Sibling of the peer [`validate_politicas`]
25749        // `:mtls-required` / `:retries` / `:timeout` composition pins
25750        // on the sibling primitive-Copy optional-scalar axes — same
25751        // "the validate / shape-gate predicate must route through the
25752        // substrate-primitive typed dispatch" discipline extended
25753        // onto the peer per-`:politicas` composite-Copy
25754        // `Option<RateLimit>` axis. Second composition-with-accessor
25755        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
25756        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
25757        let mut spec = three_member_spec();
25758        spec.politicas = MeshPolicy {
25759            rate_limit: Some(RateLimit {
25760                rate: 0,
25761                window: Duration::from_secs(1),
25762            }),
25763            ..MeshPolicy::default()
25764        };
25765        assert!(
25766            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
25767            "validate_politicas must reject rate == 0 with \
25768             PolicyRateLimitZero — the accessor and the validate gate \
25769             must route through the same substrate-primitive typed \
25770             dispatch on the :rate-limit zero-floor arm",
25771        );
25772        spec.politicas = MeshPolicy {
25773            rate_limit: Some(RateLimit {
25774                rate: 1,
25775                window: Duration::from_secs(1),
25776            }),
25777            ..MeshPolicy::default()
25778        };
25779        assert!(
25780            spec.validate().is_ok(),
25781            "validate_politicas must accept rate == 1 (the canonical \
25782             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
25783             set) with a canonical 1s window",
25784        );
25785    }
25786
25787    #[test]
25788    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
25789        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
25790        // `outlier_detection`-mesh consecutive-failure-ejection scalar
25791        // pin: [`MeshPolicy::circuit_breaker`] must return the
25792        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
25793        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
25794        // raw field access across every representative value in the
25795        // accept-set — `None` (cluster default applies — no
25796        // per-Aplicacao breaker declaration, the gateway-class per-
25797        // listener default arm the future caixa-mesh
25798        // `outlier_detection_overlay` emitter documents),
25799        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
25800        // (the lower boundary of the accept-set the surrounding
25801        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25802        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
25803        // refusals),
25804        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
25805        // (the upper boundary the same gate carves out on the sibling
25806        // `PolicyBreakerMaxFailuresExceedsCap` /
25807        // `PolicyBreakerWindowExceedsCap` refusals),
25808        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
25809        // (a past-the-guard sentinel that pins the accessor doesn't
25810        // perform a silent bounds-collapse into `None` on the
25811        // zero-failures/zero-window arm — validate rejects zero but
25812        // the accessor must ship the raw slot verbatim so a validate-
25813        // time gate regression surfaces at the emit boundary rather
25814        // than being silently absorbed), and
25815        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
25816        // (a past-the-guard sentinel that pins the accessor doesn't
25817        // perform a silent bounds-collapse at the return path).
25818        //
25819        // Second `Option<Copy-composite-T>`-return accessor pin on the
25820        // M3 mesh-slot family (peer of the sibling per-`:politicas`
25821        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
25822        // composite-Copy accessor pin, and of the sibling per-
25823        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
25824        // [`MeshPolicy::retries`] bdfb399 /
25825        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
25826        // accessor pins). Pins against a future silent detour that
25827        // re-derived the breaker declaration from a peer axis (an
25828        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
25829        // collapse that read the rate-limit's bucket capacity + refill
25830        // period as a breaker declaration), a `None → Some(default())`
25831        // cluster-default projection (which would silently re-
25832        // introduce the `PolicyBreakerZeroFailures` /
25833        // `PolicyBreakerZeroWindow` refusal cases at the emit
25834        // boundary), a bounds-collapsing accessor that clamped
25835        // `cb.max_failures` through
25836        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
25837        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
25838        // [`AplicacaoSpec::validate`] gate owns the bounds; the
25839        // accessor must ship the raw slot verbatim), or a
25840        // by-reference detour (`Option<&CircuitBreaker>`) that broke
25841        // every downstream consumer keying off `Option<CircuitBreaker>`
25842        // by-copy.
25843        for cb in [
25844            None,
25845            Some(CircuitBreaker {
25846                max_failures: 1,
25847                window: Duration::from_millis(1),
25848            }),
25849            Some(CircuitBreaker {
25850                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25851                window: POLICY_BREAKER_WINDOW_MAX,
25852            }),
25853            Some(CircuitBreaker {
25854                max_failures: 0,
25855                window: Duration::ZERO,
25856            }),
25857            Some(CircuitBreaker {
25858                max_failures: u32::MAX,
25859                window: Duration::MAX,
25860            }),
25861        ] {
25862            let p = MeshPolicy {
25863                circuit_breaker: cb,
25864                ..MeshPolicy::default()
25865            };
25866            assert_eq!(
25867                p.circuit_breaker(),
25868                cb,
25869                "MeshPolicy::circuit_breaker must return :politicas \
25870                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
25871                p.circuit_breaker(),
25872            );
25873            assert_eq!(
25874                p.circuit_breaker(),
25875                p.circuit_breaker,
25876                "MeshPolicy::circuit_breaker must byte-equal the raw \
25877                 .circuit_breaker field access across every value in \
25878                 the accept-set",
25879            );
25880        }
25881    }
25882
25883    #[test]
25884    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
25885        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
25886        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
25887        // `.circuit_breaker` field access. Structurally: toggling ONLY
25888        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
25889        // must flip `is_empty()` from `true` (all-`None`) to `false`
25890        // (one axis carries a value); the flip must be observed for
25891        // every representative value in the accept-set the surrounding
25892        // [`AplicacaoSpec::validate_politicas`] gate accepts
25893        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
25894        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
25895        // since the emptiness semantic reads "any axis carries a
25896        // value" — not "any axis carries a value the validate gate
25897        // accepts" — the same non-collapsing shape the peer M2
25898        // [`crate::LimitsSpec::is_empty`] /
25899        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25900        //
25901        // Pins against a future silent detour that re-derived the
25902        // emptiness predicate off a peer axis (an accidental
25903        // `.rate_limit.is_none()`-only chain that dropped the
25904        // `circuit_breaker` arm entirely — the last unlifted inline
25905        // field access on `is_empty` before this lift), a
25906        // `circuit_breaker == Some(_)` collapse that key-off a
25907        // validate-gate-clamped bounds check (which would silently
25908        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
25909        // 0, window: 0s })` as empty because it fails the value-shape
25910        // gate), or an accessor-side detour that no longer names the
25911        // substrate-primitive typed dispatch.
25912        //
25913        // Fifth "the emptiness predicate must route through the
25914        // substrate-primitive typed dispatch" composition pin on the
25915        // M3 mesh-slot family — closes the last unlifted composition
25916        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
25917        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
25918        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
25919        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
25920        // composition pins on the sibling primitive-Copy + composite-
25921        // Copy axes, extended onto the peer per-`:politicas`
25922        // composite-Copy `Option<CircuitBreaker>` axis).
25923        let empty = MeshPolicy::default();
25924        assert!(
25925            empty.is_empty(),
25926            "MeshPolicy::default() must be is_empty() — every axis \
25927             defaults to None",
25928        );
25929        for cb in [
25930            CircuitBreaker {
25931                max_failures: 1,
25932                window: Duration::from_millis(1),
25933            },
25934            CircuitBreaker {
25935                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25936                window: POLICY_BREAKER_WINDOW_MAX,
25937            },
25938        ] {
25939            let p = MeshPolicy {
25940                circuit_breaker: Some(cb),
25941                ..MeshPolicy::default()
25942            };
25943            assert!(
25944                !p.is_empty(),
25945                "MeshPolicy::is_empty must return false when \
25946                 :circuit-breaker is {cb:?} — the emptiness predicate \
25947                 reads \"any axis carries a value\", not \"any axis \
25948                 carries a value the validate gate accepts\"",
25949            );
25950            assert_eq!(
25951                p.circuit_breaker().is_none(),
25952                p.is_empty(),
25953                "when :circuit-breaker is the only set axis, \
25954                 is_empty() must equal circuit_breaker().is_none() — \
25955                 the accessor and the emptiness predicate must route \
25956                 through the same substrate-primitive typed dispatch \
25957                 on the :circuit-breaker arm",
25958            );
25959        }
25960    }
25961
25962    #[test]
25963    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
25964        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25965        // `:circuit-breaker` value-shape gate must key off
25966        // [`MeshPolicy::circuit_breaker`], not the raw
25967        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
25968        // whose only set axis is a `Some(CircuitBreaker { max_failures:
25969        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
25970        // refusal exactly, and the same MeshPolicy with the breaker at
25971        // the canonical lower boundary
25972        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
25973        // pass validate. The pair jointly pins the accessor +
25974        // validate-gate composition: any future silent detour that had
25975        // the accessor omit the `Some(CircuitBreaker { max_failures:
25976        // 0, .. })` arm (a
25977        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
25978        // collapse) would silently absorb the
25979        // `PolicyBreakerZeroFailures` refusal at the accessor
25980        // boundary — the composition pin catches that at caixa-core
25981        // build time.
25982        //
25983        // Sibling of the peer [`validate_politicas`]
25984        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
25985        // composition pins on the sibling primitive-Copy + composite-
25986        // Copy optional-scalar axes — same "the validate / shape-gate
25987        // predicate must route through the substrate-primitive typed
25988        // dispatch" discipline extended onto the peer per-`:politicas`
25989        // composite-Copy `Option<CircuitBreaker>` axis. Second
25990        // composition-with-accessor pin on the M3 mesh-slot
25991        // `Option<CircuitBreaker>` arm alongside the
25992        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
25993        let mut spec = three_member_spec();
25994        spec.politicas = MeshPolicy {
25995            circuit_breaker: Some(CircuitBreaker {
25996                max_failures: 0,
25997                window: Duration::from_millis(1),
25998            }),
25999            ..MeshPolicy::default()
26000        };
26001        assert!(
26002            matches!(
26003                spec.validate(),
26004                Err(AplicacaoError::PolicyBreakerZeroFailures)
26005            ),
26006            "validate_politicas must reject max_failures == 0 with \
26007             PolicyBreakerZeroFailures — the accessor and the validate \
26008             gate must route through the same substrate-primitive \
26009             typed dispatch on the :circuit-breaker zero-floor arm",
26010        );
26011        spec.politicas = MeshPolicy {
26012            circuit_breaker: Some(CircuitBreaker {
26013                max_failures: 1,
26014                window: Duration::from_millis(1),
26015            }),
26016            ..MeshPolicy::default()
26017        };
26018        assert!(
26019            spec.validate().is_ok(),
26020            "validate_politicas must accept a CircuitBreaker at the \
26021             canonical lower boundary (max_failures = 1, window = \
26022             1ms) — the accessor and the validate gate must route \
26023             through the same substrate-primitive typed dispatch on \
26024             the :circuit-breaker arm",
26025        );
26026    }
26027
26028    #[test]
26029    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
26030        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
26031        // Envoy-outlier-detection trip-threshold scalar pin:
26032        // [`CircuitBreaker::max_failures`] must return the
26033        // `:politicas :circuit-breaker :max-failures` typed `u32`
26034        // verbatim, byte-equal to the raw field access across every
26035        // representative value in the accept-set — `1` (the lower
26036        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
26037        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
26038        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
26039        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
26040        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
26041        // refusal), `0` (a past-the-guard sentinel that pins the accessor
26042        // doesn't perform a silent bounds-collapse into `1` on the zero
26043        // arm — validate rejects zero but the accessor must ship the
26044        // raw slot verbatim so a validate-time gate regression surfaces
26045        // at the emit boundary rather than being silently absorbed),
26046        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
26047        // doesn't perform a silent bounds-collapse through
26048        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
26049        //
26050        // First sub-struct required-scalar accessor pin on the M3
26051        // mesh-slot family — sibling in shape to the peer per-`:membros`
26052        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
26053        // (a40b0e3) required-`String`-carry accessor pins and the peer
26054        // per-`:contratos` [`WitContract::source`] /
26055        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
26056        // accessor pins, extended onto the peer per-`CircuitBreaker`
26057        // required-`u32` scalar-value axis. Pins against a future silent
26058        // detour that re-derived the trip threshold from a peer axis (an
26059        // accidental `self.window.as_secs() as u32` collapse that read
26060        // the breaker's rolling-window duration as a failure count), a
26061        // `0 → 1` cluster-default projection (which would silently absorb
26062        // the `PolicyBreakerZeroFailures` refusal case at the accessor
26063        // boundary), or a bounds-collapsing accessor that clamped the
26064        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
26065        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
26066        // must ship the raw slot verbatim).
26067        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
26068            let cb = CircuitBreaker {
26069                max_failures,
26070                window: Duration::from_secs(60),
26071            };
26072            assert_eq!(
26073                cb.max_failures(),
26074                max_failures,
26075                "CircuitBreaker::max_failures must return :politicas \
26076                 :circuit-breaker :max-failures verbatim (got {}, \
26077                 expected {max_failures})",
26078                cb.max_failures(),
26079            );
26080            assert_eq!(
26081                cb.max_failures(),
26082                cb.max_failures,
26083                "CircuitBreaker::max_failures must byte-equal the raw \
26084                 .max_failures field access across every value in the \
26085                 u32 accept-set",
26086            );
26087        }
26088    }
26089
26090    #[test]
26091    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
26092        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26093        // `:circuit-breaker :max-failures` zero-floor arm must key off
26094        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
26095        // field access. Structurally: a `CircuitBreaker { max_failures:
26096        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
26097        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
26098        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
26099        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
26100        // pass validate. The pair jointly pins the accessor +
26101        // validate-gate composition: any future silent detour that had
26102        // the accessor return a fresh `1` on the zero arm (a
26103        // `.max_failures().max(1)` collapse) would silently absorb the
26104        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
26105        // and the validate gate would accept a struct-literal
26106        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
26107        // catches that at caixa-core build time.
26108        //
26109        // Peer of the sibling per-`:politicas`
26110        // [`MeshPolicy::mtls_required`] (c0110f1) /
26111        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
26112        // (7073d0f) accessor-composition pins on the sibling optional-
26113        // scalar axes — same "the validate / shape-gate predicate must
26114        // route through the substrate-primitive typed dispatch"
26115        // discipline extended onto the peer per-`CircuitBreaker`
26116        // required-scalar composition axis.
26117        let mut spec = three_member_spec();
26118        spec.politicas = MeshPolicy {
26119            circuit_breaker: Some(CircuitBreaker {
26120                max_failures: 0,
26121                window: Duration::from_secs(60),
26122            }),
26123            ..MeshPolicy::default()
26124        };
26125        assert!(
26126            matches!(
26127                spec.validate(),
26128                Err(AplicacaoError::PolicyBreakerZeroFailures)
26129            ),
26130            "validate_politicas must reject max_failures == 0 with \
26131             PolicyBreakerZeroFailures — the accessor and the validate \
26132             gate must route through the same substrate-primitive typed \
26133             dispatch on the :max-failures zero-floor arm",
26134        );
26135        spec.politicas = MeshPolicy {
26136            circuit_breaker: Some(CircuitBreaker {
26137                max_failures: 1,
26138                window: Duration::from_secs(60),
26139            }),
26140            ..MeshPolicy::default()
26141        };
26142        assert!(
26143            spec.validate().is_ok(),
26144            "validate_politicas must accept max_failures == 1 (the \
26145             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
26146             accept-set)",
26147        );
26148    }
26149
26150    #[test]
26151    fn circuit_breaker_max_failures_projects_u32_by_copy() {
26152        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
26153        // `u32` by copy — `u32` is `Copy` and the accessor must return
26154        // by value, not by reference. Peer of the sibling
26155        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
26156        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
26157        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
26158        // optional-scalar axes, extended onto the peer
26159        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
26160        // the accessor's returned `u32` must outlive `&self` (multiple
26161        // calls must return equal values from a dropped-`&self` copy,
26162        // since the returned scalar carries no borrow), and calling
26163        // the accessor twice on the same CircuitBreaker must yield the
26164        // same `u32` verbatim (idempotent, no side effects on `&self`).
26165        //
26166        // Pins against a future silent detour that returned `&u32`
26167        // (which would type-check but silently break every downstream
26168        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
26169        // first parameter is `u32`, and `&u32` would fold to a detached
26170        // copy at the call site with a `*` deref the sibling accessors
26171        // don't need), an accidental `.max_failures.wrapping_add(0)`
26172        // detour that returned a fresh copy through an arithmetic
26173        // no-op (breaking a future `const fn` regression), or a
26174        // one-arm-only accessor that returned a saturating value on
26175        // some sentinel input (breaking the pass-through invariant the
26176        // sibling required-scalar accessors carry).
26177        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
26178            let cb = CircuitBreaker {
26179                max_failures,
26180                window: Duration::from_secs(60),
26181            };
26182            let first = cb.max_failures();
26183            let second = cb.max_failures();
26184            assert_eq!(
26185                first, second,
26186                "CircuitBreaker::max_failures must be idempotent — two \
26187                 successive calls on the same &self must return the \
26188                 same u32",
26189            );
26190            assert_eq!(
26191                first, max_failures,
26192                "CircuitBreaker::max_failures must return :politicas \
26193                 :circuit-breaker :max-failures verbatim by copy — \
26194                 got {first}, expected {max_failures}",
26195            );
26196        }
26197    }
26198
26199    #[test]
26200    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
26201        // The canonical per-`:politicas :circuit-breaker` `:window`
26202        // Envoy-outlier-detection rolling-observation-interval scalar
26203        // pin: [`CircuitBreaker::window`] must return the
26204        // `:politicas :circuit-breaker :window` typed `Duration`
26205        // verbatim, byte-equal to the raw field access across every
26206        // representative value in the accept-set — `Duration::from_millis(1)`
26207        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
26208        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
26209        // gate carves out on the sibling `PolicyBreakerZeroWindow`
26210        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
26211        // same gate carves out on the sibling
26212        // `PolicyBreakerWindowExceedsCap` refusal),
26213        // `Duration::ZERO` (a past-the-guard sentinel that pins the
26214        // accessor doesn't perform a silent bounds-collapse into
26215        // `Duration::from_millis(1)` on the zero arm — validate rejects
26216        // zero but the accessor must ship the raw slot verbatim so a
26217        // validate-time gate regression surfaces at the emit boundary
26218        // rather than being silently absorbed),
26219        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
26220        // far above the 1h cap — that pins the accessor doesn't perform
26221        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
26222        // at the return path).
26223        //
26224        // Second sub-struct required-scalar accessor pin on the M3
26225        // mesh-slot family — sibling in shape to the just-landed
26226        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
26227        // (3a74062) required-`u32` accessor pin on the peer
26228        // per-`CircuitBreaker` required-axis, extended onto the
26229        // per-sub-struct required-`Duration` axis. Pins against a
26230        // future silent detour that re-derived the observation window
26231        // from a peer axis (an accidental
26232        // `Duration::from_secs(self.max_failures as u64)` collapse that
26233        // read the breaker's trip count as an observation-interval
26234        // duration), a `Duration::ZERO → Duration::from_millis(1)`
26235        // cluster-default projection (which would silently absorb the
26236        // `PolicyBreakerZeroWindow` refusal case at the accessor
26237        // boundary), or a bounds-collapsing accessor that clamped the
26238        // return through `POLICY_BREAKER_WINDOW_MAX` (the
26239        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
26240        // must ship the raw slot verbatim).
26241        for window in [
26242            Duration::from_millis(1),
26243            POLICY_BREAKER_WINDOW_MAX,
26244            Duration::ZERO,
26245            Duration::from_secs(86_400),
26246        ] {
26247            let cb = CircuitBreaker {
26248                max_failures: 5,
26249                window,
26250            };
26251            assert_eq!(
26252                cb.window(),
26253                window,
26254                "CircuitBreaker::window must return :politicas \
26255                 :circuit-breaker :window verbatim (got {:?}, \
26256                 expected {window:?})",
26257                cb.window(),
26258            );
26259            assert_eq!(
26260                cb.window(),
26261                cb.window,
26262                "CircuitBreaker::window must byte-equal the raw \
26263                 .window field access across every value in the \
26264                 Duration accept-set",
26265            );
26266        }
26267    }
26268
26269    #[test]
26270    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
26271        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26272        // `:circuit-breaker :window` zero-floor arm must key off
26273        // [`CircuitBreaker::window`], not the raw `.window` field
26274        // access. Structurally: a `CircuitBreaker { window:
26275        // Duration::ZERO, .. }` embedded in a
26276        // `:politicas :circuit-breaker` slot must surface the
26277        // `PolicyBreakerZeroWindow` refusal exactly, and a
26278        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
26279        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
26280        // accept-set) must pass validate. The pair jointly pins the
26281        // accessor + validate-gate composition: any future silent
26282        // detour that had the accessor return a fresh
26283        // `Duration::from_millis(1)` on the zero arm (a
26284        // `.window().max(Duration::from_millis(1))` collapse) would
26285        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
26286        // accessor boundary and the validate gate would accept a
26287        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
26288        // — the composition pin catches that at caixa-core build time.
26289        //
26290        // Peer of the sibling per-`CircuitBreaker`
26291        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
26292        // pin on the peer required-scalar `:max-failures` axis — same
26293        // "the validate / shape-gate predicate must route through the
26294        // substrate-primitive typed dispatch" discipline extended onto
26295        // the peer per-`CircuitBreaker` required-`Duration` composition
26296        // axis.
26297        let mut spec = three_member_spec();
26298        spec.politicas = MeshPolicy {
26299            circuit_breaker: Some(CircuitBreaker {
26300                max_failures: 5,
26301                window: Duration::ZERO,
26302            }),
26303            ..MeshPolicy::default()
26304        };
26305        assert!(
26306            matches!(
26307                spec.validate(),
26308                Err(AplicacaoError::PolicyBreakerZeroWindow)
26309            ),
26310            "validate_politicas must reject window == Duration::ZERO \
26311             with PolicyBreakerZeroWindow — the accessor and the \
26312             validate gate must route through the same substrate-\
26313             primitive typed dispatch on the :window zero-floor arm",
26314        );
26315        spec.politicas = MeshPolicy {
26316            circuit_breaker: Some(CircuitBreaker {
26317                max_failures: 5,
26318                window: Duration::from_millis(1),
26319            }),
26320            ..MeshPolicy::default()
26321        };
26322        assert!(
26323            spec.validate().is_ok(),
26324            "validate_politicas must accept window == \
26325             Duration::from_millis(1) (the lower boundary of the \
26326             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
26327        );
26328    }
26329
26330    #[test]
26331    fn circuit_breaker_window_projects_duration_by_copy() {
26332        // The by-copy pin: [`CircuitBreaker::window`] returns
26333        // `Duration` by copy — `Duration` is `Copy` and the accessor
26334        // must return by value, not by reference. Peer of the sibling
26335        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
26336        // (3a74062) by-copy pin on the peer required-scalar
26337        // `:max-failures` axis, extended onto the peer
26338        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
26339        // — the accessor's returned `Duration` must outlive `&self`
26340        // (multiple calls must return equal values from a
26341        // dropped-`&self` copy, since the returned scalar carries no
26342        // borrow), and calling the accessor twice on the same
26343        // CircuitBreaker must yield the same `Duration` verbatim
26344        // (idempotent, no side effects on `&self`).
26345        //
26346        // Pins against a future silent detour that returned
26347        // `&Duration` (which would type-check but silently break every
26348        // downstream `Duration`-by-value consumer —
26349        // [`crate::render::require_positive_canonical_bounded_duration`]'s
26350        // first parameter is `Duration`, and `&Duration` would fold to
26351        // a detached copy at the call site with a `*` deref the sibling
26352        // accessors don't need), an accidental `.window + Duration::ZERO`
26353        // detour that returned a fresh copy through an arithmetic
26354        // no-op (breaking a future `const fn` regression), or a
26355        // one-arm-only accessor that returned a saturating value on
26356        // some sentinel input (breaking the pass-through invariant the
26357        // sibling required-scalar accessors carry).
26358        for window in [
26359            Duration::from_millis(1),
26360            POLICY_BREAKER_WINDOW_MAX,
26361            Duration::ZERO,
26362            Duration::from_secs(86_400),
26363        ] {
26364            let cb = CircuitBreaker {
26365                max_failures: 5,
26366                window,
26367            };
26368            let first = cb.window();
26369            let second = cb.window();
26370            assert_eq!(
26371                first, second,
26372                "CircuitBreaker::window must be idempotent — two \
26373                 successive calls on the same &self must return the \
26374                 same Duration",
26375            );
26376            assert_eq!(
26377                first, window,
26378                "CircuitBreaker::window must return :politicas \
26379                 :circuit-breaker :window verbatim by copy — \
26380                 got {first:?}, expected {window:?}",
26381            );
26382        }
26383    }
26384
26385    #[test]
26386    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
26387        // Apex-identity pair-invariant pin composing both substrate-
26388        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
26389        // and [`WitContract::destination`] — at the emit-side call shape
26390        // every per-`(:de, :para)` CNP L4 port reader now takes. The
26391        // invariant, evaluated per-edge:
26392        //
26393        //   spec.port_for_destination(c.destination()) == expected_port
26394        //
26395        // where `expected_port` is `entrada.port` when
26396        // `c.destination() == entrada.destination()` and
26397        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
26398        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
26399        // pin on the per-`:entrada` axis — that pin encodes the apex
26400        // ingress L4 identity via `entrada.destination()`; this pin
26401        // encodes the per-edge L4 identity via `c.destination()`, and
26402        // both compose on the same substrate-primitive resolver so a
26403        // future refactor that silently split either accessor's apex
26404        // behavior surfaces at caixa-core build time.
26405        let mut spec = three_member_spec();
26406        if let Some(e) = spec.entrada.as_mut() {
26407            e.para = "cart".into();
26408            e.port = 8443;
26409        }
26410        let apex_contract = WitContract {
26411            de: "checkout".into(),
26412            para: "cart".into(),
26413            wit: "wasi:http/proxy".into(),
26414            endpoint: Some("/hello".into()),
26415            subject: None,
26416            slot: None,
26417        };
26418        assert_eq!(
26419            spec.port_for_destination(apex_contract.destination()),
26420            8443,
26421            "`spec.port_for_destination(c.destination())` must equal \
26422             `entrada.port` when the contract callee names the ingress \
26423             apex — the CNP per-edge L4 port and the HTTPRoute apex \
26424             backendRef port share this substrate-primitive resolver.",
26425        );
26426        let non_apex_contract = WitContract {
26427            de: "cart".into(),
26428            para: "payment".into(),
26429            wit: "wasi:http/proxy".into(),
26430            endpoint: Some("/charge".into()),
26431            subject: None,
26432            slot: None,
26433        };
26434        assert_eq!(
26435            spec.port_for_destination(non_apex_contract.destination()),
26436            DEFAULT_SERVICO_PORT,
26437            "`spec.port_for_destination(c.destination())` must fall back \
26438             to the substrate-canonical port floor when the contract \
26439             callee is not the ingress apex — the resolver's non-apex \
26440             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
26441        );
26442    }
26443
26444    #[test]
26445    fn membro_key_consts_are_lower_camel_case_shape() {
26446        // Shape-pin: every `MEMBRO_KEY_*` const must be a
26447        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26448        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26449        // leading capital, no whitespace / dots) — the canonical shape
26450        // the `#[serde(rename_all = "camelCase")]` derive produces on
26451        // [`Membro`]. A future flip to a non-camelCase attribute at
26452        // the derive surfaces both here (this test fails on the
26453        // stale-constant shape) and at
26454        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
26455        // fails on the mismatch between const and derive). Peer with
26456        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
26457        // on the sibling `SupervisorSpec` top-level axis.
26458        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
26459            assert!(
26460                !key.is_empty(),
26461                "MEMBRO_KEY_* must be non-empty (got {key:?})"
26462            );
26463            let first = key.chars().next().unwrap();
26464            assert!(
26465                first.is_ascii_lowercase(),
26466                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
26467                 (got {key:?}, leads with {first:?})",
26468            );
26469            assert!(
26470                key.chars().all(|c| c.is_ascii_alphanumeric()),
26471                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
26472                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26473            );
26474        }
26475    }
26476
26477    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
26478
26479    #[test]
26480    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
26481        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
26482        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
26483        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
26484        // keys the `#[serde(rename_all = "camelCase")]` attribute on
26485        // [`WitContract`] emits for the required-triad. The three
26486        // sibling payload-arm keys already pin under
26487        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
26488        // `STORE_FIELD_NAME` — pin all six alongside so a future
26489        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26490        // verbatim-field-name flip at the derive attribute (any of which
26491        // would silently break every downstream JSON consumer that
26492        // reaches for one of the six via `Value::get(...)`) surfaces
26493        // here as a build-time test failure at `aplicacao.rs`, not as an
26494        // apply-time `.get(<stale-canonical-const>)` returning `None`
26495        // far from the derive-attr drift's commit. Peer with the sibling
26496        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26497        // pin on the M3 `:membros` per-entry axis — same discipline the
26498        // `Membro` per-entry lift established, extended here to the
26499        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
26500        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
26501        // axis on the Aplicacao surface without a lifted serde-key peer.
26502        let c = WitContract {
26503            de: "cart".into(),
26504            para: "catalog".into(),
26505            wit: "wasi:http/proxy".into(),
26506            endpoint: Some("/lookup".into()),
26507            subject: None,
26508            slot: None,
26509        };
26510        let json = serde_json::to_string(&c).unwrap();
26511        for key in [
26512            crate::CONTRATO_KEY_DE,
26513            crate::CONTRATO_KEY_PARA,
26514            crate::CONTRATO_KEY_WIT,
26515            WitTarget::HTTP_FIELD_NAME,
26516        ] {
26517            let quoted = format!("\"{key}\"");
26518            assert!(
26519                json.contains(&quoted),
26520                "serialized WitContract must carry the lifted \
26521                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
26522                 {quoted} verbatim in the JSON emission (got: {json})",
26523            );
26524        }
26525
26526        // Pin the two remaining payload-arm keys by round-tripping a
26527        // `WitContract` under each payload-shape (pub-sub, store) — the
26528        // required-triad appears on every emission but the payload arms
26529        // only surface when their `Option<String>` field is `Some`.
26530        let pubsub = WitContract {
26531            de: "cart".into(),
26532            para: "events".into(),
26533            wit: "nats:pub-sub".into(),
26534            endpoint: None,
26535            subject: Some("orders.placed".into()),
26536            slot: None,
26537        };
26538        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
26539        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
26540        assert!(
26541            pubsub_json.contains(&pubsub_quoted),
26542            "serialized pub-sub WitContract must carry the lifted \
26543             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
26544             verbatim in the JSON emission (got: {pubsub_json})",
26545        );
26546        let store = WitContract {
26547            de: "cart".into(),
26548            para: "sessions".into(),
26549            wit: "wasi:keyvalue/store".into(),
26550            endpoint: None,
26551            subject: None,
26552            slot: Some("cart/$id".into()),
26553        };
26554        let store_json = serde_json::to_string(&store).unwrap();
26555        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
26556        assert!(
26557            store_json.contains(&store_quoted),
26558            "serialized store WitContract must carry the lifted \
26559             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
26560             verbatim in the JSON emission (got: {store_json})",
26561        );
26562    }
26563
26564    #[test]
26565    fn contrato_key_consts_are_pairwise_distinct() {
26566        // Cross-axis drift-detection pin: a future collapse of the six
26567        // canonical [`WitContract`] per-entry byte-strings onto the same
26568        // value (e.g. an accidental copy-paste flip of
26569        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
26570        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
26571        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
26572        // every downstream probe on one axis onto the sibling axis's
26573        // overlay entry and pass every propagation-probe test that
26574        // expected only the stale axis's value. Peer of the sibling
26575        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
26576        // widened here to the six-way axis the `WitContract`
26577        // required-triad + `WitTarget` payload-triad jointly cover.
26578        let all = [
26579            crate::CONTRATO_KEY_DE,
26580            crate::CONTRATO_KEY_PARA,
26581            crate::CONTRATO_KEY_WIT,
26582            WitTarget::HTTP_FIELD_NAME,
26583            WitTarget::PUBSUB_FIELD_NAME,
26584            WitTarget::STORE_FIELD_NAME,
26585        ];
26586        for (i, a) in all.iter().enumerate() {
26587            for b in all.iter().skip(i + 1) {
26588                assert_ne!(
26589                    a, b,
26590                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
26591                     must be pairwise-distinct canonical byte-sequences \
26592                     — got `{a}` == `{b}`",
26593                );
26594            }
26595        }
26596    }
26597
26598    #[test]
26599    fn contrato_key_consts_are_lower_camel_case_shape() {
26600        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
26601        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
26602        // byte-sequence (no `snake_case` underscores, no `kebab-case`
26603        // hyphens, no leading colon, no `PascalCase` leading capital, no
26604        // whitespace / dots) — the canonical shape the
26605        // `#[serde(rename_all = "camelCase")]` derive produces on
26606        // [`WitContract`]. A future flip to a non-camelCase attribute at
26607        // the derive surfaces both here (this test fails on the
26608        // stale-constant shape) and at
26609        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26610        // (that test fails on the mismatch between const and derive).
26611        // Peer with `membro_key_consts_are_lower_camel_case_shape`
26612        // (ce80ca0) on the sibling `Membro` per-entry axis.
26613        for key in [
26614            crate::CONTRATO_KEY_DE,
26615            crate::CONTRATO_KEY_PARA,
26616            crate::CONTRATO_KEY_WIT,
26617            WitTarget::HTTP_FIELD_NAME,
26618            WitTarget::PUBSUB_FIELD_NAME,
26619            WitTarget::STORE_FIELD_NAME,
26620        ] {
26621            assert!(
26622                !key.is_empty(),
26623                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26624                 non-empty (got {key:?})"
26625            );
26626            let first = key.chars().next().unwrap();
26627            assert!(
26628                first.is_ascii_lowercase(),
26629                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
26630                 with an ASCII-lowercase byte (got {key:?}, leads with \
26631                 {first:?})",
26632            );
26633            assert!(
26634                key.chars().all(|c| c.is_ascii_alphanumeric()),
26635                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26636                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
26637                 whitespace (got {key:?})",
26638            );
26639        }
26640    }
26641
26642    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
26643
26644    #[test]
26645    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
26646        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
26647        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
26648        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
26649        // name the exact camelCase JSON keys the
26650        // `#[serde(rename_all = "camelCase")]` attribute on
26651        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
26652        // pin that each canonical byte-sequence appears verbatim in the
26653        // JSON — a future accidental `rename_all = "snake_case"` /
26654        // `"kebab-case"` / verbatim-field-name flip at the derive
26655        // attribute (any of which would silently break every downstream
26656        // JSON consumer that reaches for one of the four consts via
26657        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
26658        // emitter's per-Aplicacao hostname/paths/port projection, the
26659        // future `app-operator` reconciler's per-Aplicacao ingress
26660        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
26661        // materializer's admission-time cross-check) surfaces here as
26662        // a build-time test failure at `aplicacao.rs`, not as an
26663        // apply-time `.get(<stale-canonical-const>)` returning `None`
26664        // far from the derive-attr drift's commit. Peer with the
26665        // sibling
26666        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26667        // (ca463a4) and
26668        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26669        // pins on the M3 collection-slot atom axes — same discipline
26670        // both collection-slot lifts established, extended here to the
26671        // singleton `:entrada` mesh-slot atom axis, the last M3
26672        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
26673        // axis on the Aplicacao surface without a lifted serde-key
26674        // peer.
26675        let e = Entrada {
26676            host: "checkout.quero.cloud".into(),
26677            para: "cart".into(),
26678            paths: vec!["/cart".into()],
26679            port: 8080,
26680        };
26681        let json = serde_json::to_string(&e).unwrap();
26682        for key in [
26683            crate::ENTRADA_KEY_HOST,
26684            crate::ENTRADA_KEY_PARA,
26685            crate::ENTRADA_KEY_PATHS,
26686            crate::ENTRADA_KEY_PORT,
26687        ] {
26688            let quoted = format!("\"{key}\"");
26689            assert!(
26690                json.contains(&quoted),
26691                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
26692                 byte-sequence {quoted} verbatim in the JSON emission \
26693                 (got: {json})",
26694            );
26695        }
26696    }
26697
26698    #[test]
26699    fn entrada_key_consts_are_pairwise_distinct() {
26700        // Cross-axis drift-detection pin: a future collapse of the four
26701        // canonical [`Entrada`] singleton byte-strings onto the same
26702        // value (e.g. an accidental copy-paste flip of
26703        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
26704        // silently reroute every downstream probe on one axis onto the
26705        // sibling axis's overlay entry and pass every propagation-probe
26706        // test that expected only the stale axis's value — the
26707        // Gateway/HTTPRoute emitter would read the hostname string
26708        // where the destination-Servico name was expected (or vice
26709        // versa), the admission-webhook cross-check would compare the
26710        // wrong pair of values, and the resulting Gateway resource
26711        // would either be admitted with garbage or rejected at the
26712        // controller far from the rebrand commit's source. Peer of the
26713        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
26714        // tetrad (40cc4e5), the two-way distinct pin on the
26715        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
26716        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
26717        // triad (ca463a4).
26718        let all = [
26719            crate::ENTRADA_KEY_HOST,
26720            crate::ENTRADA_KEY_PARA,
26721            crate::ENTRADA_KEY_PATHS,
26722            crate::ENTRADA_KEY_PORT,
26723        ];
26724        for (i, a) in all.iter().enumerate() {
26725            for b in all.iter().skip(i + 1) {
26726                assert_ne!(
26727                    a, b,
26728                    "ENTRADA_KEY_* consts must be pairwise-distinct \
26729                     canonical byte-sequences — got `{a}` == `{b}`",
26730                );
26731            }
26732        }
26733    }
26734
26735    #[test]
26736    fn entrada_key_consts_are_lower_camel_case_shape() {
26737        // Shape-pin: every `ENTRADA_KEY_*` const must be a
26738        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26739        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26740        // leading capital, no whitespace / dots) — the canonical shape
26741        // the `#[serde(rename_all = "camelCase")]` derive produces on
26742        // [`Entrada`]. A future flip to a non-camelCase attribute at
26743        // the derive surfaces both here (this test fails on the
26744        // stale-constant shape) and at
26745        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
26746        // test fails on the mismatch between const and derive). Peer
26747        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
26748        // and `contrato_key_consts_are_lower_camel_case_shape`
26749        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
26750        // entry axes.
26751        for key in [
26752            crate::ENTRADA_KEY_HOST,
26753            crate::ENTRADA_KEY_PARA,
26754            crate::ENTRADA_KEY_PATHS,
26755            crate::ENTRADA_KEY_PORT,
26756        ] {
26757            assert!(
26758                !key.is_empty(),
26759                "ENTRADA_KEY_* must be non-empty (got {key:?})"
26760            );
26761            let first = key.chars().next().unwrap();
26762            assert!(
26763                first.is_ascii_lowercase(),
26764                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
26765                 (got {key:?}, leads with {first:?})",
26766            );
26767            assert!(
26768                key.chars().all(|c| c.is_ascii_alphanumeric()),
26769                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
26770                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26771            );
26772        }
26773    }
26774
26775    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
26776
26777    #[test]
26778    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
26779        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
26780        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
26781        // [`crate::POLITICAS_KEY_RETRIES`] /
26782        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
26783        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
26784        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
26785        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
26786        // on [`MeshPolicy`] emits. Three of the five axes
26787        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
26788        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
26789        // camelCase transforms — the derive-attribute is load-bearing
26790        // on those, unlike the sibling `Entrada` / `Membro` /
26791        // `WitContract` structs whose fields are all lowercase-single-
26792        // word and where the derive is a no-op on every axis.
26793        // Serialize a fully-populated [`MeshPolicy`] (every axis
26794        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
26795        // on none of the five slots) and pin that each canonical
26796        // byte-sequence appears verbatim in the JSON — a future
26797        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26798        // verbatim-field-name flip at the derive attribute (any of
26799        // which would silently break every downstream JSON consumer
26800        // that reaches for one of the five consts via
26801        // `Value::get(...)` — the future M4 per-edge `:politicas`
26802        // overlay projection onto Cilium `L7Rules` and Gateway API
26803        // `HTTPRoute` backend timeouts, the future
26804        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26805        // admission-time mesh-policy cross-check, the future
26806        // `feira lint` per-`:politicas` bound-check gate) surfaces here
26807        // as a build-time test failure at `aplicacao.rs`, not as an
26808        // apply-time `.get(<stale-canonical-const>)` returning `None`
26809        // far from the derive-attr drift's commit. Peer with the
26810        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
26811        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26812        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
26813        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
26814        // atom axes — same discipline every M3 sibling lift
26815        // established, extended here to the singleton `:politicas`
26816        // mesh-slot atom axis, closing the last M3 typed-struct
26817        // top-level `#[serde(rename_all = "camelCase")]` axis on the
26818        // Aplicacao surface without a lifted serde-key peer.
26819        let p = MeshPolicy {
26820            timeout: Some(Duration::from_secs(30)),
26821            retries: Some(3),
26822            circuit_breaker: Some(CircuitBreaker {
26823                max_failures: 5,
26824                window: Duration::from_secs(60),
26825            }),
26826            mtls_required: Some(true),
26827            rate_limit: Some(RateLimit {
26828                rate: 100,
26829                window: Duration::from_secs(1),
26830            }),
26831        };
26832        let json = serde_json::to_string(&p).unwrap();
26833        for key in [
26834            crate::POLITICAS_KEY_TIMEOUT,
26835            crate::POLITICAS_KEY_RETRIES,
26836            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26837            crate::POLITICAS_KEY_MTLS_REQUIRED,
26838            crate::POLITICAS_KEY_RATE_LIMIT,
26839        ] {
26840            let quoted = format!("\"{key}\"");
26841            assert!(
26842                json.contains(&quoted),
26843                "serialized MeshPolicy must carry the lifted \
26844                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
26845                 JSON emission (got: {json})",
26846            );
26847        }
26848    }
26849
26850    #[test]
26851    fn politicas_key_consts_are_pairwise_distinct() {
26852        // Cross-axis drift-detection pin: a future collapse of the five
26853        // canonical [`MeshPolicy`] singleton byte-strings onto the same
26854        // value (e.g. an accidental copy-paste flip of
26855        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
26856        // would silently reroute every downstream probe on one axis
26857        // onto the sibling axis's overlay entry and pass every
26858        // propagation-probe test that expected only the stale axis's
26859        // value — the M4 per-edge `:politicas` overlay projection would
26860        // read the retry-count string where the timeout duration was
26861        // expected (or vice versa), the CR materializer's admission
26862        // cross-check would compare the wrong pair of values, and the
26863        // resulting mesh reconciler would either bind the wrong axis
26864        // or reject the resource at reconcile far from the rebrand
26865        // commit's source. Peer of the sibling four-way distinct pin
26866        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
26867        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
26868        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
26869        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
26870        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26871        let all = [
26872            crate::POLITICAS_KEY_TIMEOUT,
26873            crate::POLITICAS_KEY_RETRIES,
26874            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26875            crate::POLITICAS_KEY_MTLS_REQUIRED,
26876            crate::POLITICAS_KEY_RATE_LIMIT,
26877        ];
26878        for (i, a) in all.iter().enumerate() {
26879            for b in all.iter().skip(i + 1) {
26880                assert_ne!(
26881                    a, b,
26882                    "POLITICAS_KEY_* consts must be pairwise-distinct \
26883                     canonical byte-sequences — got `{a}` == `{b}`",
26884                );
26885            }
26886        }
26887    }
26888
26889    #[test]
26890    fn politicas_key_consts_are_lower_camel_case_shape() {
26891        // Shape-pin: every `POLITICAS_KEY_*` const must be a
26892        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26893        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26894        // leading capital, no whitespace / dots) — the canonical shape
26895        // the `#[serde(rename_all = "camelCase")]` derive produces on
26896        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
26897        // at the derive surfaces both here (this test fails on the
26898        // stale-constant shape) and at
26899        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26900        // (that test fails on the mismatch between const and derive).
26901        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
26902        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26903        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26904        // (ca463a4) on the sibling M3 typed-struct axes.
26905        for key in [
26906            crate::POLITICAS_KEY_TIMEOUT,
26907            crate::POLITICAS_KEY_RETRIES,
26908            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26909            crate::POLITICAS_KEY_MTLS_REQUIRED,
26910            crate::POLITICAS_KEY_RATE_LIMIT,
26911        ] {
26912            assert!(
26913                !key.is_empty(),
26914                "POLITICAS_KEY_* must be non-empty (got {key:?})"
26915            );
26916            let first = key.chars().next().unwrap();
26917            assert!(
26918                first.is_ascii_lowercase(),
26919                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
26920                 byte (got {key:?}, leads with {first:?})",
26921            );
26922            assert!(
26923                key.chars().all(|c| c.is_ascii_alphanumeric()),
26924                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
26925                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26926            );
26927        }
26928    }
26929
26930    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
26931
26932    #[test]
26933    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
26934        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
26935        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
26936        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
26937        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
26938        // [`CircuitBreaker`] emits inside the
26939        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
26940        // two axes (`max_failures` → `maxFailures`) is a non-trivial
26941        // camelCase transform — the derive-attribute is load-bearing on
26942        // that axis, unlike the sibling `window` field where the derive
26943        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
26944        // pin that each canonical byte-sequence appears verbatim in the
26945        // JSON — a future accidental `rename_all = "snake_case"` /
26946        // `"kebab-case"` / verbatim-field-name flip at the derive
26947        // attribute (any of which would silently break every downstream
26948        // JSON consumer that reaches for one of the two consts via
26949        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
26950        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
26951        // per-edge `:politicas` overlay projection onto the mesh's
26952        // per-backend consecutive-failure-counter tripping threshold, the
26953        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26954        // admission-time breaker cross-check, the future `feira lint`
26955        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
26956        // here as a build-time test failure at `aplicacao.rs`, not as an
26957        // apply-time `.get(<stale-canonical-const>)` returning `None`
26958        // far from the derive-attr drift's commit. Peer with the sibling
26959        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26960        // (b55cca7) parent-axis pin — that test pins the outer
26961        // sub-block key the derive on [`MeshPolicy`] emits, this test
26962        // pins the inner keys the derive on the payload type emits, so
26963        // the two together lock the whole [`MeshPolicy`] breaker-tuning
26964        // shape end-to-end at build time.
26965        let cb = CircuitBreaker {
26966            max_failures: 5,
26967            window: Duration::from_secs(60),
26968        };
26969        let json = serde_json::to_string(&cb).unwrap();
26970        for key in [
26971            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26972            crate::CIRCUIT_BREAKER_KEY_WINDOW,
26973        ] {
26974            let quoted = format!("\"{key}\"");
26975            assert!(
26976                json.contains(&quoted),
26977                "serialized CircuitBreaker must carry the lifted \
26978                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
26979                 in the JSON emission (got: {json})",
26980            );
26981        }
26982    }
26983
26984    #[test]
26985    fn circuit_breaker_key_consts_are_pairwise_distinct() {
26986        // Cross-axis drift-detection pin: a future collapse of the two
26987        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
26988        // same value (e.g. an accidental copy-paste flip of
26989        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
26990        // `"maxFailures"`) would silently reroute every downstream
26991        // probe on one axis onto the sibling axis's overlay entry and
26992        // pass every propagation-probe test that expected only the
26993        // stale axis's value — the M4 per-edge `:politicas` overlay
26994        // projection would read the failure-count where the window
26995        // duration was expected (or vice versa), the CR materializer's
26996        // admission cross-check would compare the wrong pair of values,
26997        // and the resulting mesh reconciler would either bind the wrong
26998        // axis or reject the resource at reconcile far from the rebrand
26999        // commit's source. Peer of the sibling five-way distinct pin on
27000        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
27001        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
27002        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
27003        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
27004        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
27005        let all = [
27006            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27007            crate::CIRCUIT_BREAKER_KEY_WINDOW,
27008        ];
27009        for (i, a) in all.iter().enumerate() {
27010            for b in all.iter().skip(i + 1) {
27011                assert_ne!(
27012                    a, b,
27013                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
27014                     canonical byte-sequences — got `{a}` == `{b}`",
27015                );
27016            }
27017        }
27018    }
27019
27020    #[test]
27021    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
27022        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
27023        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27024        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27025        // leading capital, no whitespace / dots) — the canonical shape
27026        // the `#[serde(rename_all = "camelCase")]` derive produces on
27027        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
27028        // at the derive surfaces both here (this test fails on the
27029        // stale-constant shape) and at
27030        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
27031        // (that test fails on the mismatch between const and derive).
27032        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
27033        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
27034        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27035        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27036        // (ca463a4) on the sibling M3 typed-struct axes.
27037        for key in [
27038            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27039            crate::CIRCUIT_BREAKER_KEY_WINDOW,
27040        ] {
27041            assert!(
27042                !key.is_empty(),
27043                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
27044            );
27045            let first = key.chars().next().unwrap();
27046            assert!(
27047                first.is_ascii_lowercase(),
27048                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
27049                 byte (got {key:?}, leads with {first:?})",
27050            );
27051            assert!(
27052                key.chars().all(|c| c.is_ascii_alphanumeric()),
27053                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
27054                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27055            );
27056        }
27057    }
27058
27059    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
27060
27061    #[test]
27062    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
27063        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
27064        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
27065        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
27066        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
27067        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
27068        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
27069        // [`Placement`] emits. One of the four axes (`shard_key` →
27070        // `shardKey`) is a non-trivial camelCase transform — the
27071        // derive-attribute is load-bearing on that axis, unlike the
27072        // sibling `estrategia` / `clusters` / `affinity` axes whose
27073        // source-side field names carry no `_` and where the derive is a
27074        // no-op. Serialize a fully-populated [`Placement`] (both
27075        // `Option`-carrying axes `Some(_)` so
27076        // `skip_serializing_if = "Option::is_none"` fires on neither of
27077        // the two optional slots) and pin that each canonical
27078        // byte-sequence appears verbatim in the JSON — a future
27079        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
27080        // verbatim-field-name flip at the derive attribute (any of which
27081        // would silently break every downstream consumer that reaches
27082        // for one of the four consts via
27083        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
27084        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
27085        // aggregator's per-cluster fanout filter keying off
27086        // `placement.clusters`, the M3 shard-pool dispatch materializer
27087        // keying off `placement.shardKey`, the M3 Adaptive compression
27088        // pass weighting off `placement.affinity`, every downstream
27089        // dispatcher branching on `placement.estrategia`, the future
27090        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
27091        // admission-time placement cross-check, the future `feira lint`
27092        // per-`:placement` bound-check gate) surfaces here as a
27093        // build-time test failure at `aplicacao.rs`, not as an
27094        // apply-time `.get(<stale-canonical-const>)` returning `None`
27095        // far from the derive-attr drift's commit. Peer with the sibling
27096        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
27097        // (b55cca7),
27098        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
27099        // (468e959),
27100        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
27101        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
27102        // (ca463a4), and
27103        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
27104        // pins on the M3 collection-slot / singleton-slot atom axes —
27105        // closes the last M3 typed-struct top-level
27106        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
27107        // surface without a drift-detection pin.
27108        let p = Placement {
27109            estrategia: PlacementStrategy::Sharded,
27110            clusters: vec!["rio".into(), "mar".into()],
27111            affinity: Some("data-locality".into()),
27112            shard_key: Some("$tenantId".into()),
27113        };
27114        let json = serde_json::to_string(&p).unwrap();
27115        for key in [
27116            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27117            crate::M3_PLACEMENT_KEY_CLUSTERS,
27118            crate::M3_PLACEMENT_KEY_AFFINITY,
27119            crate::M3_PLACEMENT_KEY_SHARD_KEY,
27120        ] {
27121            let quoted = format!("\"{key}\"");
27122            assert!(
27123                json.contains(&quoted),
27124                "serialized Placement must carry the lifted \
27125                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
27126                 the JSON emission (got: {json})",
27127            );
27128        }
27129    }
27130
27131    #[test]
27132    fn m3_placement_key_consts_are_pairwise_distinct() {
27133        // Cross-axis drift-detection pin: a future collapse of the four
27134        // canonical [`Placement`] sub-block byte-strings onto the same
27135        // value (e.g. an accidental copy-paste flip of
27136        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
27137        // `"affinity"`) would silently reroute every downstream probe on
27138        // one axis onto the sibling axis's overlay entry and pass every
27139        // propagation-probe test that expected only the stale axis's
27140        // value — the M3 shard-pool dispatch materializer would read the
27141        // affinity placement-hint where the shard-selection template was
27142        // expected (or vice versa), the M3 Adaptive compression pass's
27143        // cross-check would compare the wrong pair of values, and the
27144        // resulting placement engine would either bind the wrong axis or
27145        // reject the resource at reconcile far from the rebrand commit's
27146        // source. Peer of the sibling two-way distinct pin on the
27147        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
27148        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
27149        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
27150        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
27151        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
27152        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
27153        let all = [
27154            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27155            crate::M3_PLACEMENT_KEY_CLUSTERS,
27156            crate::M3_PLACEMENT_KEY_AFFINITY,
27157            crate::M3_PLACEMENT_KEY_SHARD_KEY,
27158        ];
27159        for (i, a) in all.iter().enumerate() {
27160            for b in all.iter().skip(i + 1) {
27161                assert_ne!(
27162                    a, b,
27163                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
27164                     canonical byte-sequences — got `{a}` == `{b}`",
27165                );
27166            }
27167        }
27168    }
27169
27170    #[test]
27171    fn m3_placement_key_consts_are_lower_camel_case_shape() {
27172        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
27173        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27174        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27175        // leading capital, no whitespace / dots) — the canonical shape
27176        // the `#[serde(rename_all = "camelCase")]` derive produces on
27177        // [`Placement`]. A future flip to a non-camelCase attribute at
27178        // the derive surfaces both here (this test fails on the stale-
27179        // constant shape) and at
27180        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
27181        // (that test fails on the mismatch between const and derive).
27182        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
27183        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
27184        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
27185        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27186        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27187        // (ca463a4) on the sibling M3 typed-struct axes.
27188        for key in [
27189            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27190            crate::M3_PLACEMENT_KEY_CLUSTERS,
27191            crate::M3_PLACEMENT_KEY_AFFINITY,
27192            crate::M3_PLACEMENT_KEY_SHARD_KEY,
27193        ] {
27194            assert!(
27195                !key.is_empty(),
27196                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
27197            );
27198            let first = key.chars().next().unwrap();
27199            assert!(
27200                first.is_ascii_lowercase(),
27201                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
27202                 byte (got {key:?}, leads with {first:?})",
27203            );
27204            assert!(
27205                key.chars().all(|c| c.is_ascii_alphanumeric()),
27206                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
27207                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27208            );
27209        }
27210    }
27211
27212    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
27213    //    destination-facing L4 port resolver every per-Aplicacao renderer
27214    //    reaching for a per-destination Servico TCP port axis routes
27215    //    through. The four pin tests below fix the four-way accept-set
27216    //    the resolver must always honor: (:entrada-para-matches,
27217    //    :entrada-para-mismatches, :entrada-none-so-fallback,
27218    //    :entrada-port-non-default-honored) — drift on any arm surfaces
27219    //    at caixa-core build time rather than at cluster-apply time.
27220
27221    #[test]
27222    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
27223        // The typed `:entrada` block's `:para "cart"` matches the
27224        // queried destination, so the resolver returns the author-
27225        // declared `:port` scalar verbatim — the canonical "the
27226        // destination Servico IS the ingress apex, honor the typed
27227        // listener port" arm of the port-resolution dispatch.
27228        let mut spec = three_member_spec();
27229        if let Some(e) = spec.entrada.as_mut() {
27230            e.para = "cart".into();
27231            e.port = 9090;
27232        }
27233        assert_eq!(
27234            spec.port_for_destination("cart"),
27235            9090,
27236            "port_for_destination(entrada.para) must return entrada.port \
27237             verbatim, not the DEFAULT_SERVICO_PORT fallback"
27238        );
27239    }
27240
27241    #[test]
27242    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
27243        // The typed `:entrada` block names `:para "cart"`, but the
27244        // queried destination is `"payment"` — a Servico that
27245        // participates in the mesh graph but is not the ingress apex.
27246        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
27247        // canonical port floor, closing the "non-apex destination reads
27248        // the substrate default" arm. Same fixture the peer
27249        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
27250        // pin at caixa-mesh exercises through the CNP emit-side path;
27251        // this pin exercises the shared underlying resolver directly.
27252        let spec = three_member_spec();
27253        assert_eq!(
27254            spec.port_for_destination("payment"),
27255            DEFAULT_SERVICO_PORT,
27256            "port_for_destination(non-apex-destination) must route \
27257             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
27258        );
27259    }
27260
27261    #[test]
27262    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
27263        // Internal-only Aplicacao — no `:entrada` block declared. Every
27264        // per-destination port query falls back to the lifted
27265        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
27266        // the Aplicacao surface admits `:entrada None` (internal mesh
27267        // with no external gateway); every downstream renderer's per-
27268        // destination port axis must still resolve to a well-defined
27269        // scalar even without an ingress apex.
27270        let mut spec = three_member_spec();
27271        spec.entrada = None;
27272        assert_eq!(
27273            spec.port_for_destination("cart"),
27274            DEFAULT_SERVICO_PORT,
27275            "port_for_destination on an internal-only Aplicacao must \
27276             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
27277             every destination"
27278        );
27279        assert_eq!(
27280            spec.port_for_destination("payment"),
27281            DEFAULT_SERVICO_PORT,
27282            "port_for_destination on an internal-only Aplicacao must \
27283             fall back uniformly across every destination — the fallback \
27284             is not entrada-shape-conditional"
27285        );
27286    }
27287
27288    #[test]
27289    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
27290        // Structural pin against a hypothetical future refactor that
27291        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
27292        // the resolver (a "normalize to the default when the author's
27293        // port matches the substrate default" collapse) — that would
27294        // break renderer sites that carry meaning on the emitted port
27295        // value beyond bare equality (a future per-cluster listener-
27296        // audit that keys off the author-declared port, not the
27297        // resolved-with-fallback port). Pin that a non-default
27298        // entrada.port is returned verbatim so drift here surfaces at
27299        // caixa-core build time.
27300        let mut spec = three_member_spec();
27301        if let Some(e) = spec.entrada.as_mut() {
27302            e.para = "cart".into();
27303            e.port = 8443;
27304        }
27305        assert_ne!(
27306            8443, DEFAULT_SERVICO_PORT,
27307            "test fixture must probe a port distinct from \
27308             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
27309        );
27310        assert_eq!(
27311            spec.port_for_destination("cart"),
27312            8443,
27313            "port_for_destination(entrada.para) must return entrada.port \
27314             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
27315        );
27316    }
27317
27318    #[test]
27319    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
27320        // Apex-identity pair-invariant pin composing both substrate-
27321        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
27322        // and [`Entrada::destination`] — at the emit-side call shape
27323        // every per-Aplicacao renderer's ingress-apex L4 port reader
27324        // now takes. The invariant:
27325        //
27326        //   spec.port_for_destination(entrada.destination()) == entrada.port
27327        //
27328        // holds by construction under today's single-destination
27329        // `:entrada` slot (`destination()` returns `entrada.para`, and
27330        // the resolver's apex arm matches `para == destination` and
27331        // returns `entrada.port`), and every downstream consumer that
27332        // composes the two accessors at the ingress apex — the
27333        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
27334        // `backendRefs[0].port` emit-site path, the peer future M4 CR
27335        // materializer's admission-webhook that promotes the scalar to
27336        // a per-CR override overlay, every future per-Aplicacao snapshot
27337        // renderer's apex-facing L4 port reader — reaches through the
27338        // same composition. Pin the identity across four permutations
27339        // (`:para` × `:port` including a non-default port to exercise
27340        // the honor-verbatim arm and a non-cart `:para` to exercise
27341        // destination-agnostic identity) so a future refactor that
27342        // silently split either accessor's apex behavior surfaces at
27343        // caixa-core build time — a subtle `destination()` renaming
27344        // that returned `entrada.host.as_str()` instead of
27345        // `entrada.para.as_str()` would blow this pin loudly, closing
27346        // the last quiet failure mode the two lifts admit in composition.
27347        //
27348        // Peer discipline with the sibling caixa-mesh cross-crate pin
27349        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
27350        // on the two-renderer pair-invariant axis; this pin encodes the
27351        // same two-consumer coherence rule at the substrate-primitive
27352        // level so the invariant survives even if every renderer is
27353        // deleted.
27354        for (para, port) in [
27355            ("cart", DEFAULT_SERVICO_PORT),
27356            ("cart", 8443u16),
27357            ("payment", 9090u16),
27358            ("catalog", 443u16),
27359        ] {
27360            let mut spec = three_member_spec();
27361            if let Some(e) = spec.entrada.as_mut() {
27362                e.para = para.into();
27363                e.port = port;
27364            }
27365            let expected_port = spec
27366                .entrada()
27367                .expect("three_member_spec carries a typed `:entrada` block")
27368                .port();
27369            let composed_port = {
27370                let entrada = spec.entrada().expect("entrada present");
27371                spec.port_for_destination(entrada.destination())
27372            };
27373            assert_eq!(
27374                composed_port, expected_port,
27375                "`spec.port_for_destination(entrada.destination())` must \
27376                 equal `entrada.port` under today's single-destination \
27377                 `:entrada` slot — this is the apex-identity contract \
27378                 every downstream ingress-apex L4 port reader relies on. \
27379                 Input :entrada :para: {para:?}, :entrada :port: {port}"
27380            );
27381        }
27382    }
27383
27384    #[test]
27385    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
27386        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
27387        // per-`:entrada` apex-arm membership probe must key off
27388        // [`Entrada::destination`], not the raw `.para` field access.
27389        // Structurally: setting ONLY the `:entrada :para` field to a
27390        // fresh non-cart destination on an otherwise-well-formed
27391        // Aplicacao must (1) leave `e.destination()` byte-equal to
27392        // `e.para.as_str()` (the accessor is byte-projective by
27393        // definition), and (2) cause the resolver's apex arm to fire
27394        // and return `entrada.port` at exactly that new destination
27395        // while every other destination string falls through to
27396        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
27397        // membership check. Pins against a future silent detour that
27398        // (a) re-derived the apex-arm membership probe off
27399        // `e.para == destination` in `port_for_destination` instead of
27400        // `e.destination() == destination`, silently disagreeing with
27401        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
27402        // consumers (`entrada.destination()` at
27403        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
27404        // caixa-mesh/src/lib.rs:2739) that already reach through the
27405        // accessor, (b) accessor-side introduced a per-tenant alias
27406        // arm the caller was unaware of, silently rewriting an
27407        // author-declared `:para "cart"` value to a canary-aliased
27408        // form — the raw-field-access resolver would fall through to
27409        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
27410        // while the peer emit-site consumers landed on the aliased
27411        // destination, splitting the ingress-apex L4 port at
27412        // cluster-apply time.
27413        //
27414        // Peer of the sibling
27415        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
27416        // (d0de220) composition pin on the per-`:membros` refusal-arm
27417        // axis — same "the shape-gate predicate must route through the
27418        // substrate-primitive typed dispatch" discipline extended onto
27419        // the per-`:entrada` apex-arm membership-probe axis. Closes
27420        // the last unlifted `.para` production-code read site on
27421        // `Entrada` in `caixa-core` — after this converge every
27422        // `caixa-core` `.para` field access outside the accessor's own
27423        // body and outside the `WitContract` per-`:contratos` sibling
27424        // axis is either a test-side field-setter or a doc-comment
27425        // reference.
27426        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
27427            let mut spec = three_member_spec();
27428            if let Some(e) = spec.entrada.as_mut() {
27429                e.para = para.into();
27430                e.port = port;
27431            }
27432            let e = spec
27433                .entrada
27434                .as_ref()
27435                .expect("three_member_spec carries a typed `:entrada` block");
27436            assert_eq!(
27437                e.destination(),
27438                e.para.as_str(),
27439                "Entrada::destination must byte-equal the .para field \
27440                 access — an accessor-side detour that no longer \
27441                 projects the raw field would silently split this \
27442                 drift-detection test from the port_for_destination \
27443                 apex-arm membership probe",
27444            );
27445            assert_eq!(
27446                spec.port_for_destination(para),
27447                port,
27448                "port_for_destination must key off the accessor-projected \
27449                 destination and return `entrada.port` on the apex arm — \
27450                 input :entrada :para: {para:?}, :entrada :port: {port}",
27451            );
27452            assert_eq!(
27453                spec.port_for_destination("ghost-destination-never-a-member"),
27454                DEFAULT_SERVICO_PORT,
27455                "port_for_destination must fall through to \
27456                 DEFAULT_SERVICO_PORT on a non-matching destination \
27457                 under the accessor-projected membership check — input \
27458                 :entrada :para: {para:?}, :entrada :port: {port}",
27459            );
27460        }
27461    }
27462
27463    #[test]
27464    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
27465        // The canonical per-`:politicas :rate-limit` `:rate`
27466        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
27467        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
27468        // typed `u32` verbatim, byte-equal to the raw field access
27469        // across every representative value in the accept-set — `1` (the
27470        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
27471        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
27472        // carves out on the sibling `PolicyRateLimitZero` refusal),
27473        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
27474        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
27475        // `0` (a past-the-guard sentinel that pins the accessor doesn't
27476        // perform a silent bounds-collapse into `1` on the zero arm —
27477        // validate rejects zero but the accessor must ship the raw slot
27478        // verbatim so a validate-time gate regression surfaces at the
27479        // emit boundary rather than being silently absorbed), `u32::MAX`
27480        // (a past-the-guard sentinel that pins the accessor doesn't
27481        // perform a silent bounds-collapse through
27482        // `POLICY_RATE_LIMIT_MAX` at the return path).
27483        //
27484        // First sub-struct required-scalar accessor pin on the
27485        // `RateLimit` axis — sibling in shape to the peer
27486        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
27487        // required-`u32` accessor pin on the peer per-sub-struct
27488        // required-axis. Pins against a future silent detour that
27489        // re-derived the token capacity from a peer axis (an accidental
27490        // `self.window.as_secs() as u32` collapse that read the
27491        // rate-limit window duration as a token count), a `0 → 1`
27492        // cluster-default projection (which would silently absorb the
27493        // `PolicyRateLimitZero` refusal case at the accessor boundary),
27494        // or a bounds-collapsing accessor that clamped the return
27495        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
27496        // gate owns the bounds; the accessor must ship the raw slot
27497        // verbatim).
27498        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27499            let rl = RateLimit {
27500                rate,
27501                window: Duration::from_secs(1),
27502            };
27503            assert_eq!(
27504                rl.rate(),
27505                rate,
27506                "RateLimit::rate must return :politicas :rate-limit :rate \
27507                 verbatim (got {}, expected {rate})",
27508                rl.rate(),
27509            );
27510            assert_eq!(
27511                rl.rate(),
27512                rl.rate,
27513                "RateLimit::rate must byte-equal the raw .rate field \
27514                 access across every value in the u32 accept-set",
27515            );
27516        }
27517    }
27518
27519    #[test]
27520    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
27521        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27522        // `:rate-limit :rate` zero-floor arm must key off
27523        // [`RateLimit::rate`], not the raw `.rate` field access.
27524        // Structurally: a `RateLimit { rate: 0, window:
27525        // Duration::from_secs(1) }` embedded in a `:politicas
27526        // :rate-limit` slot must surface the `PolicyRateLimitZero`
27527        // refusal exactly, and a `RateLimit { rate: 1, window:
27528        // Duration::from_secs(1) }` (the lower boundary of the
27529        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
27530        // The pair jointly pins the accessor + validate-gate composition:
27531        // any future silent detour that had the accessor return a fresh
27532        // `1` on the zero arm (a `.rate().max(1)` collapse) would
27533        // silently absorb the `PolicyRateLimitZero` refusal at the
27534        // accessor boundary and the validate gate would accept a
27535        // struct-literal `RateLimit { rate: 0, .. }` — the composition
27536        // pin catches that at caixa-core build time.
27537        //
27538        // Peer of the sibling per-`CircuitBreaker`
27539        // [`CircuitBreaker::max_failures`] (3a74062) /
27540        // [`CircuitBreaker::window`] (373957f) accessor-composition
27541        // pins on the peer required-scalar axes — same "the validate /
27542        // shape-gate predicate must route through the substrate-primitive
27543        // typed dispatch" discipline extended onto the peer
27544        // per-`RateLimit` required-`u32` composition axis.
27545        let mut spec = three_member_spec();
27546        spec.politicas = MeshPolicy {
27547            rate_limit: Some(RateLimit {
27548                rate: 0,
27549                window: Duration::from_secs(1),
27550            }),
27551            ..MeshPolicy::default()
27552        };
27553        assert!(
27554            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
27555            "validate_politicas must reject rate == 0 with \
27556             PolicyRateLimitZero — the accessor and the validate gate \
27557             must route through the same substrate-primitive typed \
27558             dispatch on the :rate zero-floor arm",
27559        );
27560        spec.politicas = MeshPolicy {
27561            rate_limit: Some(RateLimit {
27562                rate: 1,
27563                window: Duration::from_secs(1),
27564            }),
27565            ..MeshPolicy::default()
27566        };
27567        assert!(
27568            spec.validate().is_ok(),
27569            "validate_politicas must accept rate == 1 (the lower \
27570             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
27571        );
27572    }
27573
27574    #[test]
27575    fn rate_limit_rate_projects_u32_by_copy() {
27576        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
27577        // `u32` is `Copy` and the accessor must return by value, not by
27578        // reference. Peer of the sibling per-`CircuitBreaker`
27579        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
27580        // peer required-scalar `:max-failures` axis, extended onto the
27581        // peer per-`RateLimit` required-`u32` copy-invariant shape —
27582        // the accessor's returned `u32` must outlive `&self` (multiple
27583        // calls must return equal values from a dropped-`&self` copy,
27584        // since the returned scalar carries no borrow), and calling the
27585        // accessor twice on the same RateLimit must yield the same
27586        // `u32` verbatim (idempotent, no side effects on `&self`).
27587        //
27588        // Pins against a future silent detour that returned `&u32`
27589        // (which would type-check but silently break every downstream
27590        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
27591        // first parameter is `u32`, and `&u32` would fold to a detached
27592        // copy at the call site with a `*` deref the sibling accessors
27593        // don't need), an accidental `.rate.wrapping_add(0)` detour that
27594        // returned a fresh copy through an arithmetic no-op (breaking a
27595        // future `const fn` regression), or a one-arm-only accessor
27596        // that returned a saturating value on some sentinel input
27597        // (breaking the pass-through invariant the sibling required-
27598        // scalar accessors carry).
27599        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27600            let rl = RateLimit {
27601                rate,
27602                window: Duration::from_secs(1),
27603            };
27604            let first = rl.rate();
27605            let second = rl.rate();
27606            assert_eq!(
27607                first, second,
27608                "RateLimit::rate must be idempotent — two successive \
27609                 calls on the same &self must return the same u32",
27610            );
27611            assert_eq!(
27612                first, rate,
27613                "RateLimit::rate must return :politicas :rate-limit :rate \
27614                 verbatim by copy — got {first}, expected {rate}",
27615            );
27616        }
27617    }
27618
27619    #[test]
27620    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
27621        // The canonical per-`:politicas :rate-limit` `:window`
27622        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
27623        // pin: [`RateLimit::window`] must return the
27624        // `:politicas :rate-limit :window` typed `Duration` verbatim,
27625        // byte-equal to the raw field access across every
27626        // representative value in the accept-set — `Duration::from_secs(1)`
27627        // (the `"s"` canonical window, the lower row of
27628        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
27629        // [`AplicacaoSpec::validate_politicas`] gate accepts via
27630        // [`is_canonical_rate_limit_window`]),
27631        // `Duration::from_secs(60)` (the `"m"` canonical window, the
27632        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
27633        // window, the upper row), `Duration::ZERO` (a past-the-guard
27634        // sentinel that pins the accessor doesn't perform a silent
27635        // bounds-collapse into `Duration::from_secs(1)` on the zero
27636        // arm — validate rejects an off-set window through
27637        // `PolicyRateLimitWindowNotCanonical` but the accessor must
27638        // ship the raw slot verbatim so a validate-time gate
27639        // regression surfaces at the emit boundary rather than being
27640        // silently absorbed), `Duration::from_millis(500)` (a
27641        // sub-canonical past-the-guard sentinel that pins the accessor
27642        // doesn't silently normalize a non-canonical fractional
27643        // magnitude onto the nearest canonical row).
27644        //
27645        // Second sub-struct required-scalar accessor pin on the
27646        // `RateLimit` axis — sibling in shape to the just-landed
27647        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
27648        // accessor pin on the peer per-sub-struct required-axis,
27649        // extended onto the per-`RateLimit` required-`Duration` axis.
27650        // Pins against a future silent detour that re-derived the
27651        // refill period from a peer axis (an accidental
27652        // `Duration::from_secs(self.rate as u64)` collapse that read
27653        // the rate-limit token capacity as a refill-interval
27654        // duration), a `Duration::ZERO → Duration::from_secs(1)`
27655        // canonical-default projection (which would silently absorb
27656        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
27657        // accessor boundary), or a canonical-set-collapsing accessor
27658        // that clamped the return through [`rate_limit_window_unit`]
27659        // (the `AplicacaoSpec::validate` gate owns the canonical-set
27660        // membership; the accessor must ship the raw slot verbatim).
27661        for window in [
27662            Duration::from_secs(1),
27663            Duration::from_secs(60),
27664            Duration::from_secs(3600),
27665            Duration::ZERO,
27666            Duration::from_millis(500),
27667        ] {
27668            let rl = RateLimit { rate: 100, window };
27669            assert_eq!(
27670                rl.window(),
27671                window,
27672                "RateLimit::window must return :politicas :rate-limit :window \
27673                 verbatim (got {:?}, expected {window:?})",
27674                rl.window(),
27675            );
27676            assert_eq!(
27677                rl.window(),
27678                rl.window,
27679                "RateLimit::window must byte-equal the raw .window field \
27680                 access across every value in the Duration accept-set",
27681            );
27682        }
27683    }
27684
27685    #[test]
27686    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
27687        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27688        // `:rate-limit :window` canonical-set arm must key off
27689        // [`RateLimit::window`], not the raw `.window` field access.
27690        // Structurally: a `RateLimit { window: Duration::from_millis(500),
27691        // .. }` embedded in a `:politicas :rate-limit` slot must
27692        // surface the `PolicyRateLimitWindowNotCanonical` refusal
27693        // exactly (with the sub-canonical `Duration::from_millis(500)`
27694        // magnitude carried through verbatim), and a `RateLimit
27695        // { window: Duration::from_secs(1), .. }` (the lower row of
27696        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
27697        // The pair jointly pins the accessor + validate-gate
27698        // composition: any future silent detour that had the accessor
27699        // normalize the off-set window to the nearest canonical row
27700        // (a `.window().max(Duration::from_secs(1))` collapse, or a
27701        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
27702        // collapse) would silently absorb the
27703        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
27704        // boundary — including a drift in the error's `window` payload
27705        // (the emit-side diagnostic reader keys off the offending
27706        // magnitude verbatim, so a normalization at the accessor
27707        // boundary would silently pin the wrong magnitude in the
27708        // refusal). The composition pin catches that at caixa-core
27709        // build time.
27710        //
27711        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
27712        // (7f81a60) accessor-composition pin on the peer required-
27713        // scalar `:rate` axis — same "the validate / shape-gate
27714        // predicate must route through the substrate-primitive typed
27715        // dispatch, and the error payload must project through the
27716        // same accessor" discipline extended onto the peer
27717        // per-`RateLimit` required-`Duration` composition axis.
27718        let mut spec = three_member_spec();
27719        spec.politicas = MeshPolicy {
27720            rate_limit: Some(RateLimit {
27721                rate: 100,
27722                window: Duration::from_millis(500),
27723            }),
27724            ..MeshPolicy::default()
27725        };
27726        match spec.validate() {
27727            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
27728                assert_eq!(
27729                    window,
27730                    Duration::from_millis(500),
27731                    "PolicyRateLimitWindowNotCanonical must carry the \
27732                     offending :window magnitude verbatim through the \
27733                     accessor — got {window:?}, expected 500ms",
27734                );
27735            }
27736            other => panic!(
27737                "validate_politicas must reject non-canonical :window \
27738                 with PolicyRateLimitWindowNotCanonical — the accessor \
27739                 and the validate gate must route through the same \
27740                 substrate-primitive typed dispatch on the :window \
27741                 canonical-set arm; got {other:?}",
27742            ),
27743        }
27744        spec.politicas = MeshPolicy {
27745            rate_limit: Some(RateLimit {
27746                rate: 100,
27747                window: Duration::from_secs(1),
27748            }),
27749            ..MeshPolicy::default()
27750        };
27751        assert!(
27752            spec.validate().is_ok(),
27753            "validate_politicas must accept window == Duration::from_secs(1) \
27754             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
27755        );
27756    }
27757
27758    #[test]
27759    fn rate_limit_window_projects_duration_by_copy() {
27760        // The by-copy pin: [`RateLimit::window`] returns `Duration`
27761        // by copy — `Duration` is `Copy` and the accessor must return
27762        // by value, not by reference. Peer of the sibling per-`RateLimit`
27763        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
27764        // required-scalar `:rate` axis, extended onto the peer
27765        // per-`RateLimit` required-`Duration` copy-invariant shape —
27766        // the accessor's returned `Duration` must outlive `&self`
27767        // (multiple calls must return equal values from a
27768        // dropped-`&self` copy, since the returned scalar carries no
27769        // borrow), and calling the accessor twice on the same
27770        // RateLimit must yield the same `Duration` verbatim
27771        // (idempotent, no side effects on `&self`).
27772        //
27773        // Pins against a future silent detour that returned
27774        // `&Duration` (which would type-check but silently break every
27775        // downstream `Duration`-by-value consumer —
27776        // [`is_canonical_rate_limit_window`]'s first parameter is
27777        // `Duration`, and `&Duration` would fold to a detached copy at
27778        // the call site with a `*` deref the sibling accessors don't
27779        // need), an accidental `.window + Duration::ZERO` detour that
27780        // returned a fresh copy through an arithmetic no-op (breaking
27781        // a future `const fn` regression), or a one-arm-only accessor
27782        // that returned a canonical fallback on some sentinel input
27783        // (breaking the pass-through invariant the sibling required-
27784        // scalar accessors carry).
27785        for window in [
27786            Duration::from_secs(1),
27787            Duration::from_secs(60),
27788            Duration::from_secs(3600),
27789            Duration::ZERO,
27790            Duration::from_millis(500),
27791        ] {
27792            let rl = RateLimit { rate: 100, window };
27793            let first = rl.window();
27794            let second = rl.window();
27795            assert_eq!(
27796                first, second,
27797                "RateLimit::window must be idempotent — two successive \
27798                 calls on the same &self must return the same Duration",
27799            );
27800            assert_eq!(
27801                first, window,
27802                "RateLimit::window must return :politicas :rate-limit :window \
27803                 verbatim by copy — got {first:?}, expected {window:?}",
27804            );
27805        }
27806    }
27807
27808    #[test]
27809    fn placement_estrategia_default_pins_m3_canonical_value() {
27810        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
27811        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
27812        // active-active-across-every-named-cluster arm, the closest
27813        // canonical M3 production reference the substrate carries and
27814        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
27815        // for every un-`:placement`-declared Aplicacao. Pinning the arm
27816        // here surfaces a future rebrand of the M3-canonical
27817        // distribution default (a widening to `Sharded` once the
27818        // substrate discovers hash-keyed distribution as the more
27819        // common production shape, a tightening to `SingleNode` for
27820        // stateful Erlang/OTP distributed-app-takeover semantics
27821        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
27822        // operator pins through a future `:placement-overrides` slot)
27823        // as a deliberate test edit, not a silent contract migration.
27824        // Peer of the sibling M2 per-supervisor value pins
27825        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
27826        // /
27827        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
27828        // extended onto the M3 mesh-primitive-defining `:placement
27829        // :estrategia` axis.
27830        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
27831    }
27832
27833    #[test]
27834    fn placement_strategy_default_routes_through_lifted_default() {
27835        // Composition pin: the [`Default for PlacementStrategy`] impl's
27836        // return arm must route through the substrate-canonical
27837        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
27838        // a raw `Self::Replicated` arm. Prior to the lift the impl
27839        // carried an inline `Self::Replicated` arm with no compile-time
27840        // link back to the shared M3-canonical `Replicated` arm the
27841        // paired [`Default for Placement`] impl's struct-literal
27842        // `estrategia` field, the serde-side `#[serde(default)]` on
27843        // [`Placement::estrategia`] that resolves an author-omitted
27844        // wire-form `:placement :estrategia` scalar through the impl,
27845        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
27846        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
27847        // routes through [`Placement::default`] which routes through the
27848        // strategy default) all key off — so a future rebrand of the
27849        // M3-canonical distribution default would have had to be threaded
27850        // through the `Default` impl and the three peer routes in
27851        // lockstep or the four consumers would silently split. Byte-
27852        // parity against the lifted constant closes the split. Peer of
27853        // the sibling
27854        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
27855        // /
27856        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
27857        // composition pins on the M2 per-supervisor axes.
27858        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
27859    }
27860
27861    #[test]
27862    fn placement_default_estrategia_routes_through_lifted_default() {
27863        // Composition pin: the [`Default for Placement`] impl's
27864        // struct-literal `estrategia` field must route through the
27865        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
27866        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
27867        // impl that the sibling
27868        // `placement_strategy_default_routes_through_lifted_default` pin
27869        // already routes onto the constant). Structurally: every
27870        // `Placement::default()` call must yield an `estrategia` field
27871        // byte-equal to the lifted constant so the two paired defaults —
27872        // the [`Default for PlacementStrategy`] impl arm and the
27873        // struct-literal default arm here — cannot silently split on any
27874        // future M3-canonical distribution-default rebrand. Peer of the
27875        // sibling M2
27876        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
27877        // byte-parity pin on the [`Default for SupervisorSpec`]
27878        // struct-literal `estrategia` field extended onto the M3
27879        // mesh-primitive-defining slot family.
27880        assert_eq!(
27881            Placement::default().estrategia,
27882            PLACEMENT_ESTRATEGIA_DEFAULT,
27883        );
27884    }
27885
27886    #[test]
27887    fn placement_serde_default_estrategia_routes_through_lifted_default() {
27888        // Composition pin: the serde-side `#[serde(default)]` on
27889        // [`Placement::estrategia`] — the wire-format author-omitted
27890        // `:placement :estrategia` arm — must resolve onto the substrate-
27891        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
27892        // (via the [`Default for PlacementStrategy`] impl the sibling
27893        // `placement_strategy_default_routes_through_lifted_default` pin
27894        // already routes onto the constant). Structurally: a `Placement`
27895        // deserialized from a payload that omits the `estrategia` key
27896        // must yield an `estrategia` field byte-equal to the lifted
27897        // constant, so the wire-format author-omitted arm and the
27898        // [`PlacementStrategy::default`] impl arm cannot silently split
27899        // on any future M3-canonical distribution-default rebrand. Peer
27900        // of the sibling M2
27901        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
27902        // byte-parity pin on the wire-format author-omitted `:children
27903        // :restart` scalar extended onto the M3 mesh-primitive-defining
27904        // slot family.
27905        let omitted: Placement = serde_json::from_str("{}")
27906            .expect("Placement must deserialize with the estrategia key omitted");
27907        assert_eq!(
27908            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
27909            "an author-omitted :placement :estrategia slot must degrade onto \
27910             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
27911             {:?}, expected {:?})",
27912            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
27913        );
27914    }
27915}