Skip to main content

caixa_core/
aplicacao.rs

1//! Typed Aplicacao — the fourth caixa kind that turns a graph of
2//! Servicos into a single declarative application (mesh).
3//!
4//! See `theory/MESH-COMPOSITION.md` for the design frame: an
5//! Aplicacao composes [`crate::CaixaKind::Servico`] caixas via WIT-typed
6//! `:contratos` (inter-Servico edges), declares mesh-level
7//! `:politicas` (timeouts, retries, breakers, mTLS), pins
8//! `:placement` strategy (single-node / replicated / sharded), and
9//! exposes `:entrada` (gateway).
10//!
11//! ```lisp
12//! (defcaixa
13//!   :nome      "checkout"
14//!   :versao    "0.1.0"
15//!   :kind      Aplicacao
16//!   :membros   ((:caixa "catalog"     :versao "^0.1")
17//!               (:caixa "cart"        :versao "^0.1")
18//!               (:caixa "payment"     :versao "^0.2"))
19//!   :contratos ((:de "cart" :para "catalog"
20//!                :wit "wasi:http/proxy" :endpoint "/products/:id")
21//!               (:de "cart" :para "payment"
22//!                :wit "wasi:http/proxy" :endpoint "/charge"))
23//!   :politicas ((:timeout "30s")
24//!               (:retries 3)
25//!               (:circuit-breaker (:max-failures 5 :window "60s"))
26//!               (:mtls-required t))
27//!   :placement (:estrategia replicated
28//!               :clusters   ("rio" "mar" "plo"))
29//!   :entrada   (:host  "checkout.quero.cloud"
30//!               :para  "cart"
31//!               :paths ("/api/cart" "/api/products")))
32//! ```
33//!
34//! All the typed slots compose with the M2 primitives the Servicos
35//! they reference already declare (`:limits`, `:behavior`,
36//! `:upgrade-from`). The Aplicacao adds the *graph-level*
37//! standardization on top.
38
39use std::time::Duration;
40
41use serde::{Deserialize, Serialize};
42use thiserror::Error;
43
44use crate::supervisor; // we reuse the duration-string codec at module scope
45
46// ── inter-Servico contracts ──────────────────────────────────────────
47
48/// One typed edge in the Aplicacao graph. The build refuses any
49/// contract whose `:de` or `:para` doesn't appear in `:membros`, and
50/// (M3+) cross-checks the `:wit` shape against both Servicos'
51/// declared imports/exports.
52#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
53#[serde(rename_all = "camelCase")]
54pub struct WitContract {
55    /// Caller Servico — must reference an entry in the Aplicacao's
56    /// `:membros`. The Servico's caixa.lisp must declare a matching
57    /// `:capabilities` import for the `:wit` world.
58    pub de: String,
59
60    /// Callee Servico — must reference an entry in `:membros`. The
61    /// Servico must declare a matching `:capabilities` export.
62    pub para: String,
63
64    /// WIT world reference — e.g. `"wasi:http/proxy"`,
65    /// `"wasi:keyvalue/store"`, `"nats:pub-sub"`. Strings for V0;
66    /// M4 promotes these to a typed enum once the WIT registry
67    /// stabilizes in tatara-lisp.
68    pub wit: String,
69
70    /// HTTP endpoint path, present when `:wit` is HTTP-shaped.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub endpoint: Option<String>,
73
74    /// NATS / event-stream subject, present when `:wit` is pub-sub-shaped.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub subject: Option<String>,
77
78    /// Key/value or queue slot, present when `:wit` is store-shaped.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub slot: Option<String>,
81}
82
83/// Canonical lowercase byte-prefix set the substrate's WIT-shape
84/// dispatch routes `wasi:http/*` / `http:*` values through as the
85/// HTTP-shaped arm. The single source of truth every consumer that
86/// classifies a `:wit` value as HTTP-shaped consults —
87/// [`WitContract::is_http`] on the typed contract, the
88/// `AplicacaoSpec::validate` positive-sweep test's payload-dispatch
89/// helper, and every future renderer that routes an L7 emission off a
90/// bare `&str` (the M4 per-edge WIT registry resolver, the future
91/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer). Spelled
92/// exactly as the [`is_wit_world_ref`][iwr] predicate documents the
93/// canonical lowercase prefixes ("`wasi:http/`, `nats:`,
94/// `wasi:keyvalue/`, `kafka:`, `kv:`, `http:`") so drift between the
95/// substrate's accept-set and this crate's dispatch-set is a
96/// build-time compile error (unused-import), not a per-renderer
97/// silent L7-→-L4 demotion at apply time.
98///
99/// [iwr]: crate::render::is_wit_world_ref
100pub const WIT_HTTP_SHAPE_PREFIXES: &[&str] = &["wasi:http/", "http:"];
101
102/// Canonical lowercase byte-prefix set the substrate's WIT-shape
103/// dispatch routes `nats:*` / `kafka:*` values through as the
104/// pub-sub-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
105/// [`WIT_STORE_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
106/// HTTP constant's docstring for the full lift rationale.
107pub const WIT_PUBSUB_SHAPE_PREFIXES: &[&str] = &["nats:", "kafka:"];
108
109/// Canonical lowercase byte-prefix set the substrate's WIT-shape
110/// dispatch routes `wasi:keyvalue/*` / `kv:*` values through as the
111/// key/value-store-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
112/// [`WIT_PUBSUB_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
113/// HTTP constant's docstring for the full lift rationale.
114pub const WIT_STORE_SHAPE_PREFIXES: &[&str] = &["wasi:keyvalue/", "kv:"];
115
116/// True when `wit` — a raw `:contratos :wit` value — starts with any
117/// entry in the `prefixes` accept-set. The single canonical
118/// prefix-driven WIT-shape classification combinator every peer
119/// per-shape predicate ([`wit_shape_is_http`], [`wit_shape_is_pubsub`],
120/// [`wit_shape_is_store`]) routes through, closing the 3-site
121/// duplication of the `PREFIXES.iter().any(|p| wit.starts_with(p))`
122/// combinator the prior open-coded implementations each carried.
123///
124/// A future 4th WIT-shape dispatch arm (a hypothetical `wasi:sockets/*`
125/// / `tcp:*` transport-layer shape, an `oci:*` capability-import
126/// carrier) becomes exactly one new [`WIT_*_SHAPE_PREFIXES`] const +
127/// one new `wit_shape_is_<name>` one-liner routing through this
128/// combinator, not a fourth copy of the `iter().any(starts_with)`
129/// combinator paired to its own prefix-set. Same "one canonical
130/// combinator, thin per-arm projections" discipline the peer
131/// [`WitTarget::payload_pair`] (6788ed6) already established for the
132/// downstream per-arm `(field, payload)` dispatch, extended to the
133/// upstream per-arm `PREFIXES → bool` dispatch.
134///
135/// Declared `pub const fn` — the four peer classifiers
136/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
137/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) route through
138/// this combinator in `const`-eval context, so the raw `&str → bool`
139/// WIT-shape dispatch reaches every substrate-side `const`-context
140/// consumer (the module-scope `const _: () = assert!(…)` canonical-
141/// accept-set + partition-witness pins immediately below the four
142/// peer classifiers, any future M4
143/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
144/// webhook `const fn` per-`:contratos :wit` shape-arm resolver over a
145/// raw &str, any future `const fn` per-`:contratos`-edge WIT-registry
146/// prefix-set overlay resolver over the substrate primitive that fans
147/// on the shape arm at compile time) through the same typed dispatch
148/// on the substrate primitive at const-eval time as at runtime. The
149/// prior `prefixes.iter().any(|p| wit.starts_with(p))` body carried
150/// non-`const` bounds on stable Rust 1.94 (`.iter()` / `.any()` /
151/// `str::starts_with(&str)` via the non-`const` `Pattern` trait); the
152/// new body routes the per-prefix probe through a manual byte-level
153/// `starts_with` loop over the paired `str::as_bytes` (`pub const fn`)
154/// slice projections, dispatching through primitive-`u8` `!=` and
155/// `usize` comparison + `pub const fn` `<[u8]>::len` and const-stable
156/// slice indexing (since Rust 1.79) — every operation `const`-eval-
157/// callable on stable, no iterator methods, no `Pattern` trait.
158#[must_use]
159pub const fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
160    let bytes = wit.as_bytes();
161    let mut i = 0;
162    while i < prefixes.len() {
163        let prefix = prefixes[i].as_bytes();
164        if prefix.len() <= bytes.len() {
165            let mut j = 0;
166            let mut matches = true;
167            while j < prefix.len() {
168                if bytes[j] != prefix[j] {
169                    matches = false;
170                    break;
171                }
172                j += 1;
173            }
174            if matches {
175                return true;
176            }
177        }
178        i += 1;
179    }
180    false
181}
182
183/// True when `wit` — a raw `:contratos :wit` value — targets an
184/// HTTP-shaped WIT world (starts with any prefix in
185/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
186/// consumer routes L7-HTTP emission through, whether they carry a
187/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
188/// here) or only the raw `wit` string (the positive-sweep test's
189/// payload-dispatch helper, future renderers that classify off a
190/// bare `&str`). Lifting to a free function makes the shape-dispatch
191/// arm reachable without materializing a scratch [`WitContract`] at
192/// every classification point, and pins the six-prefix accept-set at
193/// one place so future additions (e.g. an `"https:"` peer of
194/// `"http:"`) reach every consumer by construction. Routes through
195/// the lifted [`wit_shape_matches`] combinator so the
196/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
197/// canonical primitive, not one open-coded copy per peer arm.
198///
199/// Declared `pub const fn` — routes through the peer `pub const fn`
200/// [`wit_shape_matches`] combinator so every substrate-side
201/// `const`-context WIT-shape-arm-classifier consumer (the module-scope
202/// `const _: () = assert!(…)` canonical-accept-set + partition-witness
203/// pins immediately below, any future M4 admission-webhook
204/// `const fn` per-`:contratos :wit` HTTP-arm resolver over a raw &str)
205/// reaches through the same typed dispatch on the substrate primitive
206/// at const-eval time as at runtime.
207#[must_use]
208pub const fn wit_shape_is_http(wit: &str) -> bool {
209    wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES)
210}
211
212/// True when `wit` — a raw `:contratos :wit` value — targets a
213/// pub-sub-shaped WIT world (starts with any prefix in
214/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
215/// [`wit_shape_is_store`] on the shape-dispatch axis; see
216/// [`wit_shape_is_http`] for the lift rationale. Routes through the
217/// lifted [`wit_shape_matches`] combinator.
218///
219/// Declared `pub const fn` — sibling in `const`-eval posture to the
220/// peer [`wit_shape_is_http`] classifier; see that function's `const`
221/// posture-block for the full rationale.
222#[must_use]
223pub const fn wit_shape_is_pubsub(wit: &str) -> bool {
224    wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES)
225}
226
227/// True when `wit` — a raw `:contratos :wit` value — targets a
228/// key/value-store-shaped WIT world (starts with any prefix in
229/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
230/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
231/// [`wit_shape_is_http`] for the lift rationale. Routes through the
232/// lifted [`wit_shape_matches`] combinator.
233///
234/// Declared `pub const fn` — sibling in `const`-eval posture to the
235/// peer [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] classifiers;
236/// see [`wit_shape_is_http`]'s `const` posture-block for the full
237/// rationale.
238#[must_use]
239pub const fn wit_shape_is_store(wit: &str) -> bool {
240    wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES)
241}
242
243/// True when `wit` — a raw `:contratos :wit` value — targets *none* of
244/// the three known payload-shape WIT worlds; the payload-less
245/// capability arm of the 4-way WIT-shape partition on the raw
246/// `:contratos :wit` axis. Peer of [`wit_shape_is_http`] /
247/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] on the shape-
248/// dispatch axis — closes the free-function classifier family the
249/// three payload-arm predicates opened onto the exact-inverse
250/// disjunction of the trio, so any downstream consumer that must
251/// classify a raw `:wit` `&str` onto the payload-less capability arm
252/// (a future substrate-side capability-shape-only emitter — the M4
253/// per-Aplicacao WIT-registry capability-import materializer, the
254/// future `feira app graph --capability` filter, the future per-
255/// cluster capability-scope reconciler that skips L4/L7 emission for
256/// payload-less edges, the future `mesh.pleme.io/v1alpha1/Aplicacao`
257/// CR admission webhook's per-shape histogram) reaches for exactly
258/// one typed dispatch at the substrate primitive rather than an
259/// open-coded per-consumer `!wit_shape_is_http(wit) &&
260/// !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)` triplet
261/// negation — each of which would silently misclassify a future 4th
262/// payload-arm addition (a hypothetical `wasi:sockets/*` transport-
263/// layer shape, an `oci:*` capability-import carrier per the sibling
264/// [`wit_shape_matches`] docstring's trajectory bullet) as
265/// capability without a compile-time signal at the consumer site.
266///
267/// Fourth arm on the free-function WIT-shape-predicate family — closes
268/// the {[`wit_shape_is_http`], [`wit_shape_is_pubsub`],
269/// [`wit_shape_is_store`]} trio into a 4-way partition witness on the
270/// raw `:contratos :wit` `&str` axis, mirroring the paired sibling
271/// [`WitContract`]-surface [`WitContract::is_capability`] predicate and
272/// the post-projection [`WitTarget`]-side
273/// `gen_platform::IsVariant`-derived [`WitTarget::is_capability`]
274/// (7f6aa98 `IsVariant` derive lift on the peer arm-set). Every
275/// [`WitTarget`] variant now carries a matched peer predicate on both
276/// the raw `&str` axis (this function + [`wit_shape_is_http`] /
277/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`]) and the
278/// [`WitContract`] surface (the sibling 4-arm predicate family
279/// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
280/// [`WitContract::is_store`] / [`WitContract::is_capability`]),
281/// pinned in load-bearing by the sibling
282/// [`tests::wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis`]
283/// partition-witness pin and the peer
284/// [`tests::wit_contract_shape_methods_delegate_to_free_functions`]
285/// delegation pin.
286///
287/// Prior to this lift the "not one of the three known payload shapes"
288/// classification only reached the raw `&str` axis by materializing a
289/// scratch [`WitContract`] and delegating through
290/// [`WitContract::is_capability`] — a five-field constructor at every
291/// classification point for a pure `&str → bool` question, and a
292/// dependency on the payload-carrier scalar layout the classifier
293/// does not read. Same "one canonical combinator, thin per-arm
294/// projections" discipline the peer [`wit_shape_is_http`] /
295/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] trio already
296/// established, extended to close the 4-arm partition on the raw
297/// `&str` axis.
298///
299/// Note: purely syntactic classification on the negated `:wit` prefix-
300/// set — unlike [`WitContract::target`], which additionally rejects
301/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
302/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
303/// payload-shape mismatches. An empty or structurally malformed `wit`
304/// string returns `true` here (the prefix set matches nothing), and
305/// the surrounding validate-side gate cascade is where the
306/// [`AplicacaoError::EmptyWit`] / [`AplicacaoError::ContratoWitInvalid`]
307/// diagnostic surfaces — this function is the classifier, not the
308/// validator.
309///
310/// Declared `pub const fn` — closes the 4-arm classifier family's
311/// `const`-eval-surface pass on the payload-less capability arm,
312/// peer of the sibling `pub const fn` [`wit_shape_is_http`] /
313/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] classifiers, so
314/// the raw `&str → bool` WIT-shape partition on the capability arm
315/// reaches every substrate-side `const`-context consumer through one
316/// typed dispatch. See [`wit_shape_is_http`]'s `const` posture-block
317/// for the full rationale.
318#[must_use]
319pub const fn wit_shape_is_capability(wit: &str) -> bool {
320    !wit_shape_is_http(wit) && !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)
321}
322
323// Compile-time pins on the 4-arm WIT-shape classifier family — the
324// module-scope const-eval assertions below trip at caixa-core build
325// time (not test time) if a future edit rewires any of the four
326// classifier's arm-set away from the accept-set MESH-COMPOSITION §II.3
327// pins. Anchor the `const`-eval-surface posture of the four peer
328// classifiers on canonical accept-set samples (one per WIT_*_SHAPE_PREFIXES
329// prefix) plus pairwise-exclusion samples asserting the trio partitions
330// the payload-carrying arm-set and the capability arm carries the
331// complementary payload-less remainder. Any future accidental downgrade
332// of one classifier to non-`const` fails these items at caixa-core build
333// time; any future prefix-set edit that overlaps two arms (e.g. a `kv:`
334// prefix accidentally re-emitted under `WIT_HTTP_SHAPE_PREFIXES`) trips
335// the corresponding partition-witness item. Peer of the sibling M3
336// [`PlacementStrategy::requires_shard_key`] partition pins at
337// aplicacao.rs:5121-5123 on the sibling closed-set typed-enum
338// discriminator axis.
339const _: () = assert!(wit_shape_is_http("wasi:http/proxy"));
340const _: () = assert!(wit_shape_is_http("http:incoming"));
341const _: () = assert!(wit_shape_is_pubsub("nats:events"));
342const _: () = assert!(wit_shape_is_pubsub("kafka:topic"));
343const _: () = assert!(wit_shape_is_store("wasi:keyvalue/store"));
344const _: () = assert!(wit_shape_is_store("kv:cache"));
345const _: () = assert!(wit_shape_is_capability("wasi:filesystem/preopens"));
346const _: () = assert!(wit_shape_is_capability(""));
347// Pairwise-exclusion pins — the three payload-carrying arms are
348// pairwise disjoint on the canonical accept-set samples, and the
349// capability arm is the exact-inverse disjunction of the trio
350// (the free-function classifier family's 4-way partition witness).
351const _: () = assert!(!wit_shape_is_http("nats:events"));
352const _: () = assert!(!wit_shape_is_http("kv:cache"));
353const _: () = assert!(!wit_shape_is_pubsub("wasi:http/proxy"));
354const _: () = assert!(!wit_shape_is_pubsub("wasi:keyvalue/store"));
355const _: () = assert!(!wit_shape_is_store("wasi:http/proxy"));
356const _: () = assert!(!wit_shape_is_store("nats:events"));
357const _: () = assert!(!wit_shape_is_capability("wasi:http/proxy"));
358const _: () = assert!(!wit_shape_is_capability("nats:events"));
359const _: () = assert!(!wit_shape_is_capability("wasi:keyvalue/store"));
360
361impl WitContract {
362    /// Substrate-canonical per-`:contratos` caller-Servico scalar
363    /// accessor every consumer that reads the edge's source endpoint
364    /// keys off — returns the author-declared `:contratos :de`
365    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
366    /// own [`String`] storage.
367    ///
368    /// The `:contratos :de` slot names the caller-side member Servico
369    /// on a typed inter-Servico edge (validated by
370    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
371    /// Aplicacao declares — a stray `:de` that doesn't name a member is
372    /// [`AplicacaoError::ContratoMemberMissing`], not a silent
373    /// caller-attachment miss at cluster-apply time). Peer of the
374    /// sibling [`WitContract::destination`] accessor on the same
375    /// per-`:contratos` entry — the pair `( source(), destination() )`
376    /// jointly names the typed edge every renderer that fans on the
377    /// caller-callee identity keys off (the
378    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
379    /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
380    /// map, the per-edge dedup key, the per-edge membership-lookup
381    /// diagnostic).
382    ///
383    /// Prior to this lift the `.de` byte-string was accessed inline at
384    /// four caixa-core sites (the two validate-side membership lookups
385    /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
386    /// tuple's caller-arm at
387    /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
388    /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
389    /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
390    /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
391    /// — five open-coded `.de.as_str()` field-accesses that expressed
392    /// no compile-time link back to the typed slot. A future extension
393    /// of the `:contratos :de` axis to a richer author surface (a
394    /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
395    /// canary flow, a per-cluster caller-alias table the operator pins
396    /// through a future `:placement`-scoped slot, the M4
397    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
398    /// admission-webhook that promotes the scalar to a caller-set
399    /// projection) would have had to be threaded through every
400    /// open-coded copy in lockstep or one consumer would silently
401    /// disagree with the peers on which caller Servico a given edge
402    /// resolves to. Lifting the resolution rule to a typed method on
403    /// the substrate primitive means every downstream caller-facing
404    /// consumer reaches for one typed dispatch — the resolver's
405    /// accept-set migrates as a unit on any future axis addition.
406    ///
407    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
408    /// (6db982c) accessor on the analogous per-ingress-Servico scalar
409    /// axis — same "one typed dispatch on the substrate primitive,
410    /// thin projections at each consumer" discipline extended onto the
411    /// per-`:contratos` caller-Servico byte-string axis.
412    ///
413    /// Declared `pub const fn` — the body composes exclusively through
414    /// the `pub const fn` [`String::as_str`] projection (const-stable
415    /// since Rust 1.87, well within the workspace MSRV), so every
416    /// downstream `const`-context consumer of the per-`:contratos`
417    /// caller-Servico byte-string reaches through the same substrate-
418    /// primitive dispatch at const-eval time as at runtime. Peer of
419    /// the sibling `pub const fn` [`Self::destination`] /
420    /// [`Self::world_ref`] scalar accessors on the same
421    /// per-`:contratos` byte-string trio (the family closure the
422    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
423    /// locks load-bearing), and mirror on the method-surface of the
424    /// sibling free-function [`wit_shape_matches`] +
425    /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
426    /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] `const`-
427    /// eval-surface pass (d46420c) on the raw `&str → bool` WIT-shape
428    /// dispatch family.
429    #[must_use]
430    pub const fn source(&self) -> &str {
431        self.de.as_str()
432    }
433
434    /// Substrate-canonical per-`:contratos` callee-Servico scalar
435    /// accessor every consumer that reads the edge's destination
436    /// endpoint keys off — returns the author-declared
437    /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
438    /// from the typed slot's own [`String`] storage.
439    ///
440    /// The `:contratos :para` slot names the callee-side member Servico
441    /// on a typed inter-Servico edge (validated by
442    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
443    /// Aplicacao declares — a stray `:para` that doesn't name a member
444    /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
445    /// callee-attachment miss at cluster-apply time). Callee-side twin
446    /// of the sibling [`WitContract::source`] accessor — the pair
447    /// jointly names the typed edge every renderer that fans on the
448    /// caller-callee identity keys off, and this accessor is also the
449    /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
450    /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
451    /// composes with `destination()` at every emit site that projects a
452    /// per-edge destination Servico's L4 listener port.
453    ///
454    /// Prior to this lift the `.para` byte-string was accessed inline
455    /// at five sites — four caixa-core (the validate-side membership
456    /// lookup at `!names.contains(c.para.as_str())`, the per-edge
457    /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
458    /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
459    /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
460    /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
461    /// — with no compile-time link back to the typed slot. A future
462    /// extension of the `:contratos :para` axis to a richer author
463    /// surface (a multi-callee weighted-fan-out overlay for canary /
464    /// blue-green routing on typed edges, a per-cluster callee-alias
465    /// table the operator pins through a future `:placement`-scoped
466    /// slot, the M4 CR materializer's per-CR admission-webhook that
467    /// promotes the scalar to a callee-set projection) would have had
468    /// to be threaded through every open-coded copy in lockstep or one
469    /// consumer would silently disagree on which callee Servico a given
470    /// edge resolves to (a per-CNP `endpointSelector` that names a
471    /// different destination than its L4 port resolver reads for, a
472    /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
473    /// as distinct while the adjacency map collapses them, or vice
474    /// versa). Lifting to a typed method on the substrate primitive
475    /// means every downstream callee-facing consumer reaches for one
476    /// typed dispatch.
477    ///
478    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
479    /// (6db982c) accessor — both name the "destination-Servico
480    /// byte-string" concept on their respective mesh-slot atoms (per-
481    /// ingress apex vs. per-typed-edge callee), and both extend the
482    /// substrate-primitive-owns-the-resolver discipline onto the
483    /// per-slot destination-Servico scalar axis. Composes with
484    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
485    /// emit-side per-edge L4 port reader — the composition
486    /// `spec.port_for_destination(c.destination())` pins the CNP per-
487    /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
488    /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
489    /// `spec.port_for_destination(entrada.destination())`.
490    ///
491    /// Declared `pub const fn` — sibling in `const`-eval posture to the
492    /// peer `pub const fn` [`Self::source`] / [`Self::world_ref`]
493    /// per-`:contratos` byte-string scalar accessors, all three
494    /// projecting through the `pub const fn` [`String::as_str`]
495    /// (const-stable since Rust 1.87). See [`Self::source`] for the
496    /// family-closure rationale.
497    #[must_use]
498    pub const fn destination(&self) -> &str {
499        self.para.as_str()
500    }
501
502    /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
503    /// accessor every consumer that reads the edge's WIT world
504    /// discriminator keys off — returns the author-declared
505    /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
506    /// the typed slot's own [`String`] storage.
507    ///
508    /// The `:contratos :wit` slot names the WIT world the typed edge
509    /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
510    /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
511    /// be a well-shaped WIT world reference via
512    /// [`crate::render::is_wit_world_ref`] and by
513    /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
514    /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
515    /// [`WitContract::source`] / [`WitContract::destination`] accessors
516    /// on the same per-`:contratos` entry — the triple
517    /// `( source(), destination(), world_ref() )` jointly names the
518    /// typed edge every renderer that fans on the caller-callee-shape
519    /// identity keys off (the per-edge dedup key at
520    /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
521    /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
522    /// [`caixa_mesh::cilium_network_policies`], the
523    /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
524    /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
525    /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
526    ///
527    /// Prior to this lift the `.wit` byte-string was accessed inline at
528    /// five sites — three caixa-core (the `WitContract::is_*` shape-
529    /// dispatch predicates' `&self.wit` arg, the validate-side empty
530    /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
531    /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
532    /// printer's `{}` format-slot at `c.wit`) — five open-coded
533    /// `.wit` field-accesses that expressed no compile-time link back to
534    /// the typed slot. A future extension of the `:contratos :wit` axis
535    /// to a richer author surface (an M4 promotion from `String` to a
536    /// typed WIT-world enum once the WIT registry stabilizes in tatara-
537    /// lisp per this struct's own `:wit` field docstring, a per-cluster
538    /// WIT-alias table the operator pins through a future
539    /// `:placement`-scoped slot, a canonicalization pass that lowercases
540    /// `wasi:*` prefixes) would have had to be threaded through every
541    /// open-coded copy in lockstep or one consumer would silently
542    /// disagree with the peers on which WIT shape a given edge resolves
543    /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
544    /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
545    /// empty-check that missed a whitespace-only string a peer accessor
546    /// stripped, or vice versa). Lifting to a typed method on the
547    /// substrate primitive means every downstream WIT-shape-facing
548    /// consumer reaches for one typed dispatch — the resolver's
549    /// accept-set migrates as a unit on any future axis addition.
550    ///
551    /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
552    /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
553    /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
554    /// 6db982c), per-`:membros` [`Membro::nome`] /
555    /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
556    /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
557    /// on the substrate primitive, thin projections at each consumer"
558    /// discipline extended onto the last unlifted per-`:contratos`
559    /// scalar (the WIT-world-reference arm).
560    ///
561    /// [fag]: caixa-feira/src/cmd/app.rs
562    ///
563    /// Declared `pub const fn` — sibling in `const`-eval posture to the
564    /// peer `pub const fn` [`Self::source`] / [`Self::destination`]
565    /// per-`:contratos` byte-string scalar accessors on the trio, and
566    /// the load-bearing enabler for the paired `pub const fn`
567    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
568    /// [`Self::is_capability`] WIT-shape-predicate family (each
569    /// composes as `wit_shape_is_<arm>(self.world_ref())` and inherits
570    /// the `const`-eval posture by construction once this accessor
571    /// carries it). See [`Self::source`] for the family-closure
572    /// rationale and the paired
573    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
574    /// for the load-bearing witness.
575    #[must_use]
576    pub const fn world_ref(&self) -> &str {
577        self.wit.as_str()
578    }
579
580    /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
581    /// payload-target scalar accessor every consumer that reads the
582    /// edge's L7 HTTP request path payload keys off — returns the
583    /// author-declared `:contratos :endpoint` byte-string verbatim as
584    /// an `Option<&str>`, borrowed from the typed slot's own
585    /// `Option<String>` storage; `None` when the slot is absent (the
586    /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
587    /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
588    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
589    /// [`WitTarget::Capability`] edge carries none of the three).
590    ///
591    /// The `:contratos :endpoint` slot carries the HTTP request path
592    /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
593    /// — same shape required of `:entrada :paths`, gated by the shared
594    /// [`crate::render::is_gateway_api_http_path`] predicate) that
595    /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
596    /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
597    /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
598    /// downstream consumer that reads the payload keys off this scalar
599    /// (the [`WitContract::target`] Http-arm payload extraction that
600    /// materializes [`WitTarget::Http { endpoint }`] under the paired
601    /// [`WitTarget::HTTP_FIELD_NAME`] label, the
602    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
603    /// key's endpoint arm that pins the payload as part of the six-tuple
604    /// dedup key alongside the sibling `:subject`/`:slot` arms, the
605    /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
606    /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
607    /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
608    /// emission path that lands the payload verbatim as a Cilium L7
609    /// `path:` rule).
610    ///
611    /// Prior to this lift the `.endpoint` field was accessed inline at
612    /// two production sites in `caixa-core/src/aplicacao.rs` — the
613    /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
614    /// self.endpoint.as_deref();` binding at the top of the method, and
615    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
616    /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
617    /// field-accesses that expressed no compile-time link back to the
618    /// typed slot. A future extension of the `:contratos :endpoint`
619    /// axis to a richer author surface (an M4 promotion from
620    /// `Option<String>` to a typed HTTP path-template enum once the
621    /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
622    /// this struct's own `:wit` field docstring, a per-cluster endpoint-
623    /// alias table the operator pins through a future `:placement`-
624    /// scoped slot, a canonicalization pass that percent-encodes non-
625    /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
626    /// materializer applies per-tenant) would have had to be threaded
627    /// through both open-coded copies in lockstep or the two consumers
628    /// would silently disagree on which HTTP path a given edge resolves
629    /// to — the [`WitContract::target`] payload-extraction reading
630    /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
631    /// the operator-resolved `"/tenant-a/lookup"` would silently split
632    /// the [`WitTarget::Http`]-arm rendered payload from the actual
633    /// dedup-key uniqueness axis, a two-consumer split at the validator
634    /// far from the source `caixa.lisp` with no field naming the
635    /// payload-drift root cause. Lifting the resolution rule to a typed
636    /// method on the substrate primitive means every downstream
637    /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
638    /// L7-payload surface reaches for exactly one typed dispatch — the
639    /// resolver's accept-set migrates as a unit on any future axis
640    /// addition.
641    ///
642    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
643    /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
644    /// accessors on the M3 mesh-slot family — same "one typed dispatch
645    /// on the substrate primitive, thin projections at each consumer"
646    /// discipline extended onto the per-`:contratos` HTTP-shaped
647    /// payload-carrier `Option<String>` optional-scalar axis. First
648    /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
649    /// atom — opens the "optional per-slot payload-carrier scalar"
650    /// projection pattern the sibling per-`:contratos` `:subject` /
651    /// `:slot` future lifts fold on, matching the closed
652    /// per-`:contratos` scalar-value accessor family
653    /// ([`WitContract::source`] / [`WitContract::destination`] /
654    /// [`WitContract::world_ref`]) already lifted onto the mandatory-
655    /// scalar `String` axes. Named `endpoint()` to match the storage
656    /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
657    /// author-facing label const; the accessor's identity name maps
658    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
659    /// docstring already carries.
660    #[must_use]
661    pub const fn endpoint(&self) -> Option<&str> {
662        match &self.endpoint {
663            Some(s) => Some(s.as_str()),
664            None => None,
665        }
666    }
667
668    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
669    /// payload-target scalar accessor every consumer that reads the
670    /// edge's NATS / Kafka publish subject payload keys off — returns
671    /// the author-declared `:contratos :subject` byte-string verbatim
672    /// as an `Option<&str>`, borrowed from the typed slot's own
673    /// `Option<String>` storage; `None` when the slot is absent (the
674    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
675    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
676    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
677    /// [`WitTarget::Capability`] edge carries none of the three).
678    ///
679    /// The `:contratos :subject` slot carries the NATS / Kafka publish
680    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
681    /// per-edge target selector — `orders.paid`, `events.>`, whatever
682    /// subject namespace the author names on the pub-sub edge) that
683    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
684    /// arm's `subject: &'a str` payload when the edge's `:wit` world
685    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
686    /// downstream consumer that reads the payload keys off this scalar
687    /// (the [`WitContract::target`] PubSub-arm payload extraction that
688    /// materializes [`WitTarget::PubSub { subject }`] under the paired
689    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
690    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
691    /// key's subject arm that pins the payload as part of the six-tuple
692    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
693    /// future M4 per-edge WIT registry resolver's pub-sub-arm
694    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
695    /// materializer's per-edge NATS admission webhook, the future
696    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
697    /// as a NATS subject the operator pins per-CR).
698    ///
699    /// Prior to this lift the `.subject` field was accessed inline at
700    /// two production sites in `caixa-core/src/aplicacao.rs` — the
701    /// [`WitContract::target`] payload-shape dispatch's `let subject =
702    /// self.subject.as_deref();` binding at the top of the method, and
703    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
704    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
705    /// field-accesses that expressed no compile-time link back to the
706    /// typed slot. A future extension of the `:contratos :subject` axis
707    /// to a richer author surface (an M4 promotion from `Option<String>`
708    /// to a typed NATS-subject-template enum once the WIT registry
709    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
710    /// struct's own `:wit` field docstring, a per-cluster subject-alias
711    /// table the operator pins through a future `:placement`-scoped
712    /// slot, a canonicalization pass that lowercases / dedupes wildcard
713    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
714    /// applies per-tenant) would have had to be threaded through both
715    /// open-coded copies in lockstep or the two consumers would silently
716    /// disagree on which NATS subject a given edge resolves to — the
717    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
718    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
719    /// resolved `"tenant-a.orders.paid"` would silently split the
720    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
721    /// key uniqueness axis, a two-consumer split at the validator far
722    /// from the source `caixa.lisp` with no field naming the payload-
723    /// drift root cause. Lifting the resolution rule to a typed method
724    /// on the substrate primitive means every downstream pub-sub-payload-
725    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
726    /// surface reaches for exactly one typed dispatch — the resolver's
727    /// accept-set migrates as a unit on any future axis addition.
728    ///
729    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
730    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
731    /// carrier axis — second `Option<&str>`-return accessor on the
732    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
733    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
734    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
735    /// key/value-store arm as the last unlifted per-`:contratos`
736    /// `Option<String>` axis. Named `subject()` to match the storage
737    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
738    /// author-facing label const; the accessor's identity name maps
739    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
740    /// docstring already carries.
741    #[must_use]
742    pub const fn subject(&self) -> Option<&str> {
743        match &self.subject {
744            Some(s) => Some(s.as_str()),
745            None => None,
746        }
747    }
748
749    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
750    /// shaped payload-target scalar accessor every consumer that reads
751    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
752    /// off — returns the author-declared `:contratos :slot` byte-string
753    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
754    /// own `Option<String>` storage; `None` when the slot is absent
755    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
756    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
757    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
758    /// [`WitTarget::Capability`] edge carries none of the three).
759    ///
760    /// The `:contratos :slot` slot carries the key/value store
761    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
762    /// arm's per-edge target selector — `carts/{cart_id}`,
763    /// `sessions/{tenant}/{sid}`, whatever key-template the author
764    /// names on the store edge) that [`WitContract::target`] projects
765    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
766    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
767    /// accept-set. Every downstream consumer that reads the payload
768    /// keys off this scalar (the [`WitContract::target`] Store-arm
769    /// payload extraction that materializes [`WitTarget::Store { slot }`]
770    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
771    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
772    /// key's store arm that pins the payload as part of the six-tuple
773    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
774    /// the future M4 per-edge WIT registry resolver's store-arm
775    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
776    /// materializer's per-edge key/value admission webhook, the future
777    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
778    /// as a key-template the operator pins per-CR).
779    ///
780    /// Prior to this lift the `.slot` field was accessed inline at two
781    /// production sites in `caixa-core/src/aplicacao.rs` — the
782    /// [`WitContract::target`] payload-shape dispatch's `let slot =
783    /// self.slot.as_deref();` binding at the top of the method, and
784    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
785    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
786    /// field-accesses that expressed no compile-time link back to the
787    /// typed slot. A future extension of the `:contratos :slot` axis
788    /// to a richer author surface (an M4 promotion from `Option<String>`
789    /// to a typed key-template enum once the WIT registry stabilizes
790    /// key-template parameter shapes in tatara-lisp per this struct's
791    /// own `:wit` field docstring, a per-cluster slot-alias table the
792    /// operator pins through a future `:placement`-scoped slot, a
793    /// canonicalization pass that lowercases the bucket prefix, a
794    /// per-CR fully-qualified rewrite the M4 CR materializer applies
795    /// per-tenant) would have had to be threaded through both
796    /// open-coded copies in lockstep or the two consumers would
797    /// silently disagree on which key-template a given edge resolves
798    /// to — the [`WitContract::target`] payload-extraction reading
799    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
800    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
801    /// would silently split the [`WitTarget::Store`]-arm rendered
802    /// payload from the actual dedup-key uniqueness axis, a
803    /// two-consumer split at the validator far from the source
804    /// `caixa.lisp` with no field naming the payload-drift root cause.
805    /// Lifting the resolution rule to a typed method on the substrate
806    /// primitive means every downstream store-payload-facing consumer
807    /// of the Aplicacao's per-`:contratos` payload surface reaches for
808    /// exactly one typed dispatch — the resolver's accept-set migrates
809    /// as a unit on any future axis addition.
810    ///
811    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
812    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
813    /// accessors on the M3 mesh-slot payload-carrier axis — third and
814    /// final `Option<&str>`-return accessor on the per-`:contratos`
815    /// mesh-slot atom, closes the last unlifted per-`:contratos`
816    /// `Option<String>` axis and completes the "optional per-slot
817    /// payload-carrier scalar" projection pattern the peer HTTP /
818    /// pub-sub arms established across the three payload-shape
819    /// dispatch arms. Named `slot()` to match the storage field's
820    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
821    /// author-facing label const; the accessor's identity name maps
822    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
823    /// docstring already carries.
824    #[must_use]
825    pub const fn slot(&self) -> Option<&str> {
826        match &self.slot {
827            Some(s) => Some(s.as_str()),
828            None => None,
829        }
830    }
831
832    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
833    /// caller-callee-pair accessor every consumer that constructs an
834    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
835    /// caller-callee pair keys off — returns the author-declared
836    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
837    /// owned `(String, String)` tuple, projected through the lifted
838    /// [`WitContract::source`] / [`WitContract::destination`] scalar
839    /// accessors so any future rebrand on the caller-arm / callee-arm
840    /// projection axis (an M4 per-cluster caller-alias table the
841    /// operator pins through a future `:placement`-scoped slot, a
842    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
843    /// a per-`:membros` alias overlay from the future `:membros
844    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
845    /// acknowledges) reaches every diagnostic-construction site by
846    /// construction.
847    ///
848    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
849    /// owned form" primitive every per-`:contratos` diagnostic variant on
850    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
851    /// nine variants [`AplicacaoError::EmptyWit`],
852    /// [`AplicacaoError::ContratoEndpointEmpty`],
853    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
854    /// [`AplicacaoError::ContratoEndpointInvalid`],
855    /// [`AplicacaoError::ContratoSubjectEmpty`],
856    /// [`AplicacaoError::ContratoSubjectInvalid`],
857    /// [`AplicacaoError::ContratoSlotEmpty`],
858    /// [`AplicacaoError::ContratoSlotInvalid`], and
859    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
860    /// para: String` field pair the constructor site reads verbatim off
861    /// the [`WitContract`] the diagnostic points at, so a diagnostic
862    /// whose `de:` and `para:` labels silently drift off the source
863    /// caller/callee — a per-cluster caller-alias rewrite that landed on
864    /// one variant's inline `de: c.de.clone()` field access but not on
865    /// its sibling variant's, an accidental swap of the `de:` and `para:`
866    /// arms in a copy-paste of the constructor block — would emit a
867    /// build-time error whose "which caixa is at fault" question the
868    /// operator answers wrongly, far from the source `caixa.lisp`.
869    ///
870    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
871    /// pair was inlined at seven [`WitContract::target`] error-
872    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
873    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
874    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
875    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
876    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
877    /// the [`AplicacaoError::ContratoSlotEmpty`] /
878    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
879    /// two [`AplicacaoSpec::validate`] error-construction sites (the
880    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
881    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
882    /// insert-first-seen closure) — nine open-coded `.de.clone() +
883    /// .para.clone()` pairs that expressed no compile-time contract that
884    /// the caller-arm and callee-arm arms of the same diagnostic
885    /// construction reach for the same [`WitContract`] instance or that
886    /// the `de:` and `para:` label pair binds to the fields the author
887    /// declared. Any future rebrand on the axis — an M4 per-cluster
888    /// caller/callee-alias rewrite the operator pins through a future
889    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
890    /// per-CR fully-qualified namespace prefix the M4
891    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
892    /// per-tenant, a canonicalization pass that lowercases the caller +
893    /// callee identifiers post-parse — would have had to be threaded
894    /// through every open-coded copy in lockstep or one variant's
895    /// diagnostic would silently name a different caller/callee pair
896    /// than its peer, silently degrading the "which caixa is at fault"
897    /// self-locating signal every operator-facing typed diagnostic
898    /// exists to carry. Lifting the pair to a typed method on the
899    /// substrate primitive means every downstream diagnostic-construction
900    /// site reaches for exactly one typed dispatch — the resolver's
901    /// projection migrates as a unit on any future axis addition.
902    ///
903    /// Peer of the sibling per-`:contratos` scalar accessor family
904    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
905    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
906    /// scalar-value axes — first composite-projection accessor on the
907    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
908    /// form `.clone()` field-accesses that pair the sibling
909    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
910    /// one typed dispatch. Named `edge_pair()` to reflect the identity
911    /// name of the projected tuple (the typed-edge caller-callee pair,
912    /// distinct from the sibling triple-projection
913    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
914    /// closure in [`WitContract::target`] + the paired
915    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
916    /// site's `(de, para, wit)` triple onto one typed dispatch).
917    #[must_use]
918    pub fn edge_pair(&self) -> (String, String) {
919        (self.source().to_string(), self.destination().to_string())
920    }
921
922    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
923    /// :wit)` triple every per-edge diagnostic constructor that names
924    /// all three axes threads verbatim into its `de:` / `para:` /
925    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
926    /// / missing-target / invalid-wit / capability-with-payload arms
927    /// (eight sites all shape `let (de, para, wit) = edge();
928    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
929    /// accessor landed) and the sibling
930    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
931    /// constructor (which paired `edge_pair()` for the `(de, para)`
932    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
933    /// typed-dispatch + raw-field-access shape the sibling accessor
934    /// family already flagged as a drift risk). Nine total call sites
935    /// collapse onto this helper.
936    ///
937    /// Lifted with the same one-source-of-truth discipline
938    /// [`WitContract::edge_pair`] carries on the paired
939    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
940    /// arms compose through the lifted [`WitContract::source`] /
941    /// [`WitContract::destination`] / [`WitContract::world_ref`]
942    /// scalar accessors byte-for-byte (pinned by the paired
943    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
944    /// composition-pin), so any future rebrand on the per-`:contratos`
945    /// caller / callee / world-ref axis (an M4 per-cluster
946    /// caller/callee-alias rewrite the operator pins through a future
947    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
948    /// per-CR fully-qualified namespace prefix the M4
949    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
950    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
951    /// on `source()` / `destination()`, a per-CR canonicalization pass
952    /// that lowercases the WIT world ref post-parse) migrates as a
953    /// single caixa-core edit rather than a coordinated rewrite of
954    /// nine open-coded triple-constructors.
955    ///
956    /// Peer of the sibling per-`:contratos` composite-projection
957    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
958    /// composite-value axes — closes the last unlifted owned-form
959    /// composite-tuple axis on the per-`:contratos` diagnostic-
960    /// construction surface. Named `edge_triple()` to reflect the
961    /// identity name of the projected tuple (the typed-edge
962    /// caller-callee-wit triple, sibling to the caller-callee-only
963    /// pair `edge_pair()` returns).
964    #[must_use]
965    pub fn edge_triple(&self) -> (String, String, String) {
966        (
967            self.source().to_string(),
968            self.destination().to_string(),
969            self.world_ref().to_string(),
970        )
971    }
972
973    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
974    /// dedups typed edges keys off — routes through the lifted
975    /// [`WitContract::source`] / [`WitContract::destination`] /
976    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
977    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
978    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
979    /// type alias's six axes migrate as a unit on any future axis
980    /// addition (adding a seventh field to [`WitContract`] is one
981    /// [`ContratoIdentity`] alias edit + one accessor addition + one
982    /// arm here, not a coordinated rewrite of every open-coded
983    /// six-tuple builder that dedups on the identity axis).
984    ///
985    /// Sibling of [`WitContract::edge_pair`] /
986    /// [`WitContract::edge_triple`] on the composite-projection axis:
987    /// the pair projects the caller-callee axes, the triple extends it
988    /// with the world-ref, this method extends it with the three
989    /// payload-carrier axes. Every projection returns the same six
990    /// scalar accessors' outputs; the three methods differ only in
991    /// which arms they surface.
992    ///
993    /// Declared `pub const fn` — every callee is itself `pub const fn`
994    /// ([`Self::source`] / [`Self::destination`] / [`Self::world_ref`]
995    /// project through `pub const fn` [`String::as_str`], const-stable
996    /// since Rust 1.87; [`Self::endpoint`] / [`Self::subject`] /
997    /// [`Self::slot`] project through the same `String::as_str` under a
998    /// `match &self.<field> { Some(s) => Some(s.as_str()), None => None }`
999    /// arm — the sibling `Option<String> → Option<&str>` shape 0650f64
1000    /// closed the const-eval surface on) and tuple construction from
1001    /// borrowed-reference / `Option`-of-borrowed-reference arms is
1002    /// itself trivially const. The `ContratoIdentity<'_>` alias
1003    /// resolves to a `(&str, &str, &str, Option<&str>, Option<&str>,
1004    /// Option<&str>)` tuple whose every arm is `Copy` — no destructor,
1005    /// no heap allocation, no non-const call folded through the tuple's
1006    /// construction. Sibling in `const`-eval posture to the peer
1007    /// `pub const fn` [`WitContract::is_http`] / [`Self::is_pubsub`] /
1008    /// [`Self::is_store`] / [`Self::is_capability`] WIT-shape-predicate
1009    /// composite-projection family the sibling
1010    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1011    /// already anchors — this extends the same `const`-eval-surface
1012    /// posture onto the peer six-arm composite-projection axis where
1013    /// the projection surfaces the full identity tuple rather than a
1014    /// per-`(:de, :para, :wit)`-triple boolean shape probe. Pinned load-
1015    /// bearing by
1016    /// [`wit_contract_identity_projection_accessor_is_const_fn`] below
1017    /// (a future accidental downgrade fires E0015 at the wrapper at
1018    /// caixa-core build time).
1019    #[must_use]
1020    pub const fn identity(&self) -> ContratoIdentity<'_> {
1021        (
1022            self.source(),
1023            self.destination(),
1024            self.world_ref(),
1025            self.endpoint(),
1026            self.subject(),
1027            self.slot(),
1028        )
1029    }
1030
1031    /// True when this contract targets an HTTP-shaped WIT world.
1032    ///
1033    /// Declared `pub const fn` — routes through the paired `pub const
1034    /// fn` [`Self::world_ref`] scalar accessor and the substrate's
1035    /// `pub const fn` free-function classifier [`wit_shape_is_http`]
1036    /// (d46420c). Sibling in `const`-eval posture to the peer
1037    /// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
1038    /// [`Self::is_capability`] WIT-shape-predicate family; the closed
1039    /// 4-arm partition on the raw `:contratos :wit` axis now carries
1040    /// the same `const`-eval-surface posture as the free-function
1041    /// classifier family it composes through. Pinned load-bearing by
1042    /// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
1043    /// test (a future accidental downgrade to non-`const` fires E0015
1044    /// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
1045    /// build time).
1046    #[must_use]
1047    pub const fn is_http(&self) -> bool {
1048        wit_shape_is_http(self.world_ref())
1049    }
1050
1051    /// True when this contract targets a pub-sub-shaped WIT world.
1052    ///
1053    /// Declared `pub const fn` — sibling in `const`-eval posture to
1054    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
1055    /// [`Self::is_capability`] WIT-shape-predicate family. See
1056    /// [`Self::is_http`] for the family-closure rationale.
1057    #[must_use]
1058    pub const fn is_pubsub(&self) -> bool {
1059        wit_shape_is_pubsub(self.world_ref())
1060    }
1061
1062    /// True when this contract targets a key/value-shaped WIT world.
1063    ///
1064    /// Declared `pub const fn` — sibling in `const`-eval posture to
1065    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
1066    /// [`Self::is_capability`] WIT-shape-predicate family. See
1067    /// [`Self::is_http`] for the family-closure rationale.
1068    #[must_use]
1069    pub const fn is_store(&self) -> bool {
1070        wit_shape_is_store(self.world_ref())
1071    }
1072
1073    /// True when this contract targets *none* of the three known payload-
1074    /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
1075    /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1076    /// open on the [`WitContract`] surface. Returns the exact-inverse
1077    /// disjunction of the peer trio — `true` when none of the three
1078    /// prefix-set predicates matches the raw `:contratos :wit` value; the
1079    /// author-declared WIT world is a pure typed capability edge with no
1080    /// payload selector (the shape [`WitContract::target`] projects onto
1081    /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
1082    /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
1083    ///
1084    /// The `:contratos :wit` shape-space is closed at four arms
1085    /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
1086    /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
1087    /// everything else on the payload-less capability arm), and every
1088    /// downstream consumer that must filter contratos by shape-class
1089    /// keys off the four sibling predicates (the [`WitContract::target`]
1090    /// dispatch's implicit `else` after the three payload-shape arm
1091    /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
1092    /// every future substrate-side capability-shape-only emitter — the
1093    /// M4 per-Aplicacao WIT-registry capability-import materializer, the
1094    /// future `feira app graph --capability` per-Aplicacao capability-
1095    /// column filter, the future per-cluster capability-scope reconciler
1096    /// that skips L4/L7 emission for payload-less edges since Cilium
1097    /// can't introspect WASI capability calls, the future
1098    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
1099    /// shape shape-count histogram). Every such consumer reaches for one
1100    /// typed dispatch on the substrate primitive so the "which arm
1101    /// carries the capability-only shape?" answer lives at one caixa-core
1102    /// edit rather than open-coded across per-consumer
1103    /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
1104    /// negations, each of which would silently drop a future fourth
1105    /// payload-arm addition without a compile-time signal at the
1106    /// consumer site.
1107    ///
1108    /// Prior to this lift the "not one of the three known payload
1109    /// shapes" classification sat inline at [`WitContract::target`]'s
1110    /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
1111    /// [`WitTarget::Capability`] admission arm after the three `if
1112    /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
1113    /// { … }` guards) with no named accessor for downstream consumers
1114    /// to reach through. A future substrate-side capability-only
1115    /// filter or a future capability-scope reconciler would have had to
1116    /// re-inline the same triplet negation at every emit site with no
1117    /// compile-time link back to the sibling trio, and a future arm
1118    /// addition (a hypothetical fourth payload-shape prefix set — a
1119    /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
1120    /// import carrier per the sibling [`wit_shape_matches`] docstring's
1121    /// trajectory bullet) would land the new predicate on the payload-
1122    /// carrying trio and silently misclassify the new shape as
1123    /// capability at every triplet-negation consumer site, propagating
1124    /// the drift far from the caixa-core prefix-set commit.
1125    ///
1126    /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
1127    /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
1128    /// trio into a 4-way partition witness on the raw `:contratos :wit`
1129    /// axis, mirroring the paired post-projection [`WitTarget`]
1130    /// `gen_platform::IsVariant`-derived 4-way predicate set
1131    /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
1132    /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
1133    /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
1134    /// arm-set). The two typed axes — pre-projection on the raw
1135    /// `:contratos :wit` string, post-projection on the validated typed
1136    /// view — now carry a matched 4-arm predicate discipline: every
1137    /// arm on the closed [`WitTarget`] set has a peer pre-projection
1138    /// predicate on the [`WitContract`] surface, and any future
1139    /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
1140    /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
1141    /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
1142    /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
1143    /// pre-projection axis through a matching peer prefix-set + peer
1144    /// predicate lift by construction — the compile-time exhaustiveness
1145    /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
1146    /// the post-projection accessor family stays in sync, and the sibling
1147    /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
1148    /// partition-witness pin locks the pre-projection classification in
1149    /// load-bearing so a peer prefix-set addition that widened one arm's
1150    /// accept-set without shrinking the [`Self::is_capability`] accept-set
1151    /// surfaces as a test failure at caixa-core build time rather than a
1152    /// silent per-consumer split at renderer emit time.
1153    ///
1154    /// Composes byte-for-byte through the lifted peer trio
1155    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
1156    /// any future rebrand of any prefix-set const flows through this
1157    /// method by construction without a coordinated per-consumer rewrite
1158    /// (pinned by the sibling
1159    /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
1160    /// composition-witness).
1161    ///
1162    /// Note: purely syntactic classification on the `:wit` prefix-set —
1163    /// unlike [`Self::target`], which additionally rejects value-shape-
1164    /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
1165    /// package) via [`crate::render::is_wit_world_ref`] and payload-
1166    /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
1167    /// structurally malformed returns `true` from `is_capability()` (the
1168    /// prefix set matches nothing), and the surrounding
1169    /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
1170    /// is where the [`AplicacaoError::EmptyWit`] /
1171    /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
1172    /// predicate is the classifier, not the validator.
1173    ///
1174    /// Declared `pub const fn` — closes the WIT-shape-predicate
1175    /// family's `const`-eval-surface pass at the fourth (payload-less)
1176    /// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
1177    /// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
1178    /// See [`Self::is_http`] for the family-closure rationale.
1179    #[must_use]
1180    pub const fn is_capability(&self) -> bool {
1181        wit_shape_is_capability(self.world_ref())
1182    }
1183
1184    /// True when this contract's caller equals its callee — a
1185    /// structurally degenerate typed edge that no `:contratos` entry can
1186    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
1187    /// Servico B" is an *inter*-Servico contract between two distinct
1188    /// graph nodes). A Servico contracting with itself resolves to an
1189    /// in-process call the wasm-engine never routes through the mesh at
1190    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
1191    /// per-edge policy can express the intended shape — the pub-sub
1192    /// path silently rendered a self-allow rule that is a no-op (intra-
1193    /// pod traffic bypasses the mesh entirely), and the synchronous
1194    /// paths surfaced as a misleading `ContratoCycle` whose path was
1195    /// `["cart", "cart"]` — framing a self-edge as a multi-node
1196    /// deadlock. Every downstream consumer that must reject the shape
1197    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
1198    /// gate at caixa-core/src/aplicacao.rs:5559, every future
1199    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
1200    /// axis, every future adjacency-graph builder that must skip self-
1201    /// edges rather than fold them into an incidental cycle) now keys
1202    /// off exactly one typed dispatch on the substrate primitive, so
1203    /// any future rebrand on the axis (an M4-typed-caller enum whose
1204    /// identity comparison rule the accessor could route through, an
1205    /// operator-side per-cluster caller/callee-alias table the
1206    /// materializer resolves per-CR before the equality probe, a
1207    /// promotion of the pointwise `==` to a set-membership check once
1208    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
1209    /// so a per-replica self-edge is rejected under the same predicate)
1210    /// migrates as a single caixa-core edit rather than a coordinated
1211    /// rewrite of every downstream self-edge consumer. Composes
1212    /// byte-for-byte through the lifted [`Self::source`] /
1213    /// [`Self::destination`] scalar accessors — the accessor pair every
1214    /// per-`:contratos` scalar-value axis already routes through — so
1215    /// any future rebrand of the underlying `:de` / `:para` storage
1216    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1217    /// a per-Aplicacao interning arena the M4 CR materializer authors,
1218    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1219    /// same one body without a coordinated per-consumer rewrite.
1220    ///
1221    /// Sibling in shape to the peer per-`:contratos` shape-predicate
1222    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1223    /// on the `:wit` world-ref axis — extended onto the per-edge
1224    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1225    /// partition the WIT-shape-space; `is_self_loop` partitions the
1226    /// caller-callee identity-space. Named `is_self_loop()` to reflect
1227    /// the graph-theoretic identity of the shape (a loop from a graph
1228    /// node to itself, distinct from the sibling multi-node
1229    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1230    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1231    /// variant already carrying the term.
1232    #[must_use]
1233    pub fn is_self_loop(&self) -> bool {
1234        self.source() == self.destination()
1235    }
1236
1237    /// Typed view of the contract's payload target. Enforces that the
1238    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1239    /// fields agree, and that each carried value is itself
1240    /// value-shape valid:
1241    ///
1242    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1243    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1244    ///     `PathPrefix` invariant — same shape required of `:entrada
1245    ///     :paths`)
1246    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1247    ///     non-empty (NATS / Kafka publish without a subject is a
1248    ///     no-op subscribe, never the author's intent)
1249    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1250    ///     non-empty (an empty slot template addresses the bucket
1251    ///     root, defeating the per-key isolation the slot exists for)
1252    ///   - Anything else ⇒ none of the three; the contract is a pure
1253    ///     typed capability edge with no payload selector.
1254    ///
1255    /// Translates the Apollo Federation discipline ("conflicts are
1256    /// errors at compile time, not warnings at runtime";
1257    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1258    /// a contract whose WIT shape disagrees with its target field, or
1259    /// whose target field carries a value-shape-invalid string, is a
1260    /// build error — not a silent renderer drop. The returned
1261    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1262    /// non-empty (and absolute, for `Http`); every downstream consumer
1263    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1264    /// the M4 per-edge policy resolver) can rely on that without
1265    /// re-checking.
1266    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1267        // Route the HTTP-shaped payload-target extraction through the
1268        // lifted [`WitContract::endpoint`] accessor rather than the raw
1269        // `self.endpoint.as_deref()` field access — the two production
1270        // consumers of the per-`:contratos :endpoint` HTTP-shaped
1271        // payload-carrier scalar (this method's Http-arm payload
1272        // extraction, the [`AplicacaoSpec::validate`] duplicate-
1273        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1274        // off exactly one typed dispatch on the substrate primitive, so
1275        // any future rebrand on the axis (an M4 per-cluster endpoint-
1276        // alias rewrite, a per-CR fully-qualified path prefix the M4
1277        // materializer applies per-tenant, an M4 promotion from
1278        // `Option<String>` to a typed HTTP path-template enum) migrates
1279        // as a single caixa-core edit rather than a coordinated rewrite
1280        // of the two call sites — peer of the sibling M3 per-`:placement`
1281        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1282        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1283        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1284        let endpoint = self.endpoint();
1285        let subject = self.subject();
1286        // Route the store-arm payload-carrier scalar through the
1287        // lifted [`WitContract::slot`] accessor rather than the raw
1288        // `self.slot.as_deref()` field access — the two production
1289        // consumers of the per-`:contratos :slot` key/value-store-
1290        // shaped payload-carrier scalar (this method's Store-arm
1291        // payload extraction, the [`AplicacaoSpec::validate`]
1292        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1293        // arm) now key off exactly one typed dispatch on the substrate
1294        // primitive. Closes the last unlifted per-`:contratos`
1295        // `Option<String>` axis, completing the payload-carrier
1296        // accessor family peer of the sibling per-`:contratos`
1297        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1298        // (90de675) lifts across the HTTP / pub-sub arms.
1299        let slot = self.slot();
1300        // Route the local `(de, para, wit)` triple-projection closure
1301        // through the lifted [`WitContract::edge_triple`] typed accessor
1302        // rather than re-inlining `(self.de.clone(), self.para.clone(),
1303        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1304        // triple-carrying diagnostic constructors below (wrong-target /
1305        // missing-target on all three payload arms + capability-with-
1306        // payload + invalid-wit) now key off exactly one typed dispatch
1307        // on the substrate-primitive composite projection, sibling to
1308        // the peer [`WitContract::edge_pair`]-routed
1309        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1310        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1311        // diagnostic constructors on the same per-`:contratos`
1312        // diagnostic-construction surface.
1313        let edge = || self.edge_triple();
1314
1315        // The `:wit` value drives every downstream dispatch — the
1316        // is_http/is_pubsub/is_store prefix matchers below, the
1317        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1318        // exclusion. Until this gate landed `target()` accepted any
1319        // non-empty string and silently demoted unrecognized shapes to
1320        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1321        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1322        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1323        // package, the paste-from-binary footgun a multi-line blob
1324        // accidentally landing in the slot, the un-percent-encoded
1325        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1326        // routing, got L4-only" footgun. Empty is still pre-checked at
1327        // the [`AplicacaoSpec::validate`] call site via the narrower
1328        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1329        // validate layer); the value-shape gate here picks up the
1330        // structurally-invalid non-empty cases the empty check misses,
1331        // and remains correct under direct `target()` calls outside
1332        // validate (the predicate's defensive empty arm returns a
1333        // parser-shaped reason rather than silently falling through to
1334        // the Capability arm). Same trajectory as c4213a4 (WitContract
1335        // endpoint/subject/slot value-shape gates lifted into
1336        // `target()`) on the peer payload axes.
1337        if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
1338            let (de, para, wit) = edge();
1339            return Err(AplicacaoError::ContratoWitInvalid {
1340                de,
1341                para,
1342                wit,
1343                reason,
1344            });
1345        }
1346
1347        if self.is_http() {
1348            if subject.is_some() || slot.is_some() {
1349                let (de, para, wit) = edge();
1350                return Err(AplicacaoError::ContratoWrongTarget {
1351                    de,
1352                    para,
1353                    wit,
1354                    expected: WitTarget::HTTP_FIELD_NAME,
1355                });
1356            }
1357            let ep = endpoint.ok_or_else(|| {
1358                let (de, para, wit) = edge();
1359                AplicacaoError::ContratoMissingTarget {
1360                    de,
1361                    para,
1362                    wit,
1363                    expected: WitTarget::HTTP_FIELD_NAME,
1364                }
1365            })?;
1366            if ep.is_empty() {
1367                let (de, para) = self.edge_pair();
1368                return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
1369            }
1370            if !ep.starts_with('/') {
1371                let (de, para) = self.edge_pair();
1372                return Err(AplicacaoError::ContratoEndpointNotAbsolute {
1373                    de,
1374                    para,
1375                    endpoint: ep.to_string(),
1376                });
1377            }
1378            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1379            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1380            // API v1 HTTPPathMatch.value admission grammar with the
1381            // sibling `:entrada :paths` axis. Until this gate landed
1382            // `target()` only refused the empty string + the missing-
1383            // leading-`/` form; a structurally invalid endpoint
1384            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1385            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1386            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1387            // path-traversal segment, the >1024-byte slug) silently
1388            // passed validate and the failure surfaced at apply time
1389            // as a Cilium policy rejection / silent traffic drop, far
1390            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1391            // grammar `:entrada :paths` already gates (55410e4), now
1392            // shared with `:contratos :endpoint` through the lifted
1393            // `crate::render::is_gateway_api_http_path` predicate.
1394            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1395                let (de, para) = self.edge_pair();
1396                return Err(AplicacaoError::ContratoEndpointInvalid {
1397                    de,
1398                    para,
1399                    endpoint: ep.to_string(),
1400                    reason,
1401                });
1402            }
1403            return Ok(WitTarget::Http { endpoint: ep });
1404        }
1405        if self.is_pubsub() {
1406            if endpoint.is_some() || slot.is_some() {
1407                let (de, para, wit) = edge();
1408                return Err(AplicacaoError::ContratoWrongTarget {
1409                    de,
1410                    para,
1411                    wit,
1412                    expected: WitTarget::PUBSUB_FIELD_NAME,
1413                });
1414            }
1415            let s = subject.ok_or_else(|| {
1416                let (de, para, wit) = edge();
1417                AplicacaoError::ContratoMissingTarget {
1418                    de,
1419                    para,
1420                    wit,
1421                    expected: WitTarget::PUBSUB_FIELD_NAME,
1422                }
1423            })?;
1424            if s.is_empty() {
1425                let (de, para) = self.edge_pair();
1426                return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1427            }
1428            // The `:subject` lands at runtime as the NATS subject the
1429            // producer publishes to and the consumer subscribes from.
1430            // Until this gate landed `target()` only refused the
1431            // empty string; a structurally invalid subject
1432            // (`"foo..bar"` — empty token between separators,
1433            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1434            // server's subject parser rejects, `"foo bar"` —
1435            // un-percent-encoded whitespace, `"foo.café"` —
1436            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1437            // empty leading/trailing tokens, the >256-byte
1438            // paste-from-binary slug) silently passed validate and
1439            // the failure surfaced at runtime as a NATS server-side
1440            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1441            // a silent message drop, far from the source caixa.lisp.
1442            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1443            // trajectory `:contratos :endpoint` (4f0390b) and
1444            // `:contratos :wit` (6226bf4) already gate, now shared
1445            // with `:contratos :subject` through the lifted
1446            // `crate::render::is_nats_subject` predicate.
1447            if let Err(reason) = crate::render::is_nats_subject(s) {
1448                let (de, para) = self.edge_pair();
1449                return Err(AplicacaoError::ContratoSubjectInvalid {
1450                    de,
1451                    para,
1452                    subject: s.to_string(),
1453                    reason,
1454                });
1455            }
1456            return Ok(WitTarget::PubSub { subject: s });
1457        }
1458        if self.is_store() {
1459            if endpoint.is_some() || subject.is_some() {
1460                let (de, para, wit) = edge();
1461                return Err(AplicacaoError::ContratoWrongTarget {
1462                    de,
1463                    para,
1464                    wit,
1465                    expected: WitTarget::STORE_FIELD_NAME,
1466                });
1467            }
1468            let sl = slot.ok_or_else(|| {
1469                let (de, para, wit) = edge();
1470                AplicacaoError::ContratoMissingTarget {
1471                    de,
1472                    para,
1473                    wit,
1474                    expected: WitTarget::STORE_FIELD_NAME,
1475                }
1476            })?;
1477            if sl.is_empty() {
1478                let (de, para) = self.edge_pair();
1479                return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1480            }
1481            // Value-shape gate on the third (and last) typed payload
1482            // axis the `WitContract::target` dispatch carries — the
1483            // peer of [`crate::render::is_gateway_api_http_path`] for
1484            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1485            // for `:subject` (63e18a0). Until this gate landed
1486            // `target()` only refused the empty string; a structurally
1487            // invalid slot (`"check out/$order"` — un-percent-encoded
1488            // whitespace whose runtime behavior varies unpredictably
1489            // across kv backends, `"checkout/\x01order"` — control
1490            // character that Redis admits but corrupts on next read
1491            // and DynamoDB rejects outright, `"chéckout/$order"` —
1492            // un-percent-encoded non-ASCII byte each backend re-encodes
1493            // differently, `"checkout\n/$order"` — embedded newline,
1494            // the 513-byte paste-from-binary slug) silently passed
1495            // validate and surfaced at runtime as a per-backend kv
1496            // write rejection (DynamoDB / etcd) or as a silent
1497            // next-read corruption (Redis-via-RESP3), far from the
1498            // source caixa.lisp with no field naming which `:contratos`
1499            // edge carried the typo. The lifted predicate makes the
1500            // kv-backend intersection-floor a substrate-level
1501            // invariant at validate time, not a runtime "this passed
1502            // validate but the kv backend rejected on first write"
1503            // surprise — closes the typed payload-axis value-shape
1504            // trajectory across all three legs of the four
1505            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1506            // that caixa-mesh + the future kv emitters land in.
1507            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1508                let (de, para) = self.edge_pair();
1509                return Err(AplicacaoError::ContratoSlotInvalid {
1510                    de,
1511                    para,
1512                    slot: sl.to_string(),
1513                    reason,
1514                });
1515            }
1516            return Ok(WitTarget::Store { slot: sl });
1517        }
1518
1519        // Unrecognized WIT world — must not carry any payload target.
1520        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1521            let (de, para, wit) = edge();
1522            return Err(AplicacaoError::ContratoWrongTarget {
1523                de,
1524                para,
1525                wit,
1526                expected: WitTarget::CAPABILITY_EXPECTED,
1527            });
1528        }
1529        Ok(WitTarget::Capability)
1530    }
1531
1532    /// Substrate-canonical post-validation projection of the typed
1533    /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
1534    /// downstream of an [`AplicacaoSpec`] that has already crossed the
1535    /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
1536    /// [`typed_view`]-shaped entry point that composes `validate` into
1537    /// the projection) reaches through when it needs the typed
1538    /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
1539    /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
1540    /// coherence for every `:contratos` entry. The peer accessor to the
1541    /// [`Self::target`] `Result`-returning validator on the same
1542    /// per-`:contratos` typed-projection axis — [`Self::target`] is the
1543    /// pre-validation validator that computes the projection *and* raises
1544    /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
1545    /// (`:wit`, payload) mismatch; this method is the post-validation
1546    /// projection every downstream consumer reaches through once the
1547    /// pre-validation gate has succeeded.
1548    ///
1549    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1550    ///
1551    /// Prior to this lift the "call `.target()` then `.expect(…)` with
1552    /// the same message" pattern sat inline at two production sites with
1553    /// no compile-time link between them: the
1554    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
1555    /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
1556    /// (`c.target().expect("validated by typed_view").http_endpoint()`)
1557    /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
1558    /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
1559    /// (`c.target().expect("validated by typed_view").graph_label()`),
1560    /// each open-coding the same `.target().expect("validated by
1561    /// typed_view")` pair with the message spelled twice. A future
1562    /// vocabulary shift on the panic-message axis (a tightening from
1563    /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
1564    /// validate"` as the substrate's validator entry-point vocabulary
1565    /// sharpens, a per-consumer disambiguation, an M4 promotion of the
1566    /// panic to a `debug_assert` under a `--release` build profile) would
1567    /// have had to be threaded through both open-coded call sites in
1568    /// lockstep or one consumer would silently disagree with the peer on
1569    /// which invariant the panic message names. Same "same shape written
1570    /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
1571    /// discipline the sibling [`Self::edge_pair`] /
1572    /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
1573    /// lifts already establish on the paired composite-projection axis;
1574    /// this lift extends it onto the post-validation typed-view axis.
1575    ///
1576    /// Every future downstream consumer of the projected typed view
1577    /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
1578    /// CR materializer's per-edge admission webhook, the future
1579    /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
1580    /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
1581    /// resolver, the future `feira app graph --l7` / `--pubsub` /
1582    /// `--kv` per-shape column emitters) reaches through this one typed
1583    /// dispatch on the substrate primitive rather than an open-coded
1584    /// per-consumer `.target().expect(…)` pair with the message
1585    /// re-inlined. The invariant the accessor's panic path pins — "this
1586    /// call is only reachable after [`AplicacaoSpec::validate`] has
1587    /// succeeded on the containing spec" — is the substrate's answer to
1588    /// give exactly once, at the primitive, not once per consumer.
1589    ///
1590    /// # Panics
1591    ///
1592    /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
1593    /// would return an `Err` — i.e. if this contract's
1594    /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
1595    /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
1596    /// this accessor only from a code path that has already reached the
1597    /// containing [`AplicacaoSpec`] through a validating entry-point
1598    /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
1599    /// [`typed_view`] compose, the future M4 CR admission webhook's
1600    /// per-CR validate). Use [`Self::target`] instead on any pre-
1601    /// validation code path.
1602    ///
1603    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1604    #[must_use]
1605    pub fn target_projected(&self) -> WitTarget<'_> {
1606        self.target().expect(Self::PROJECTED_INVARIANT_MSG)
1607    }
1608
1609    /// Canonical panic message the [`Self::target_projected`]
1610    /// post-validation projection accessor threads through when the
1611    /// caller has violated the "call only after [`AplicacaoSpec::validate`]
1612    /// has succeeded" precondition. Lifted as a `pub const` on the
1613    /// [`WitContract`] surface so the byte-string lives in one place
1614    /// across the substrate — the [`Self::target_projected`] method
1615    /// body, the two prior production call sites' comments now naming
1616    /// the const, and every future consumer that must format-match the
1617    /// panic-message shape (a future test suite that asserts the panic-
1618    /// message byte-string across a fuzzed invalid-contract corpus,
1619    /// a future custom-panic hook in `caixa-operator` that surfaces the
1620    /// message with per-`:contratos` telemetry, the future admission
1621    /// webhook's per-CR validate-error report) reaches through the same
1622    /// canonical `&'static str`. A future rebrand on the panic-message
1623    /// axis (a tightening from `"validated by typed_view"` to `"validated
1624    /// by AplicacaoSpec::validate"` as the substrate's validator
1625    /// entry-point vocabulary sharpens once caixa-core grows a
1626    /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
1627    /// [`typed_view`]) lands at one caixa-core edit rather than a
1628    /// coordinated per-consumer sweep — same "one canonical declaration
1629    /// per axis, next to the accessor that reads it" discipline the peer
1630    /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
1631    /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
1632    /// const family already establishes on the paired per-consumer-axis
1633    /// diagnostic-scalar surface.
1634    pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
1635}
1636
1637/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1638/// gate (see [`AplicacaoSpec::validate`]): every field that
1639/// distinguishes one contract from another, in declaration order
1640/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1641/// with equal [`ContratoIdentity`]s are the same typed edge declared
1642/// twice — the graph-edge analogue of duplicate `:membros` /
1643/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1644/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1645/// clippy's `type_complexity` lint (and so a future axis added to
1646/// `WitContract` is one alias edit, not a coordinated rewrite of
1647/// every set instantiation).
1648pub type ContratoIdentity<'a> = (
1649    &'a str,
1650    &'a str,
1651    &'a str,
1652    Option<&'a str>,
1653    Option<&'a str>,
1654    Option<&'a str>,
1655);
1656
1657/// Typed view of a [`WitContract`]'s payload target. Each variant
1658/// carries the field its WIT shape requires; constructing a `Http`
1659/// view without an endpoint is impossible by the type system.
1660///
1661/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1662/// instead of probing `Option<String>` fields one by one — the
1663/// "which payload field is set?" question is answered once, at
1664/// validation time.
1665#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1666pub enum WitTarget<'a> {
1667    /// HTTP-shaped WIT world. Carries the configured request path.
1668    Http { endpoint: &'a str },
1669    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1670    ///
1671    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1672    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1673    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1674    /// method name byte-identical to the sibling
1675    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1676    /// arm-discriminator that routes through
1677    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1678    /// through `matches!` on the variant), so the two arm-discriminator
1679    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1680    /// every downstream consumer through the same `is_pubsub()` name.
1681    #[is_variant(name = "pubsub")]
1682    PubSub { subject: &'a str },
1683    /// Key-value-shaped WIT world. Carries the slot template.
1684    Store { slot: &'a str },
1685    /// A typed capability edge with no payload selector — the WIT
1686    /// world stands on its own (rare; reserved for plain capability
1687    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1688    Capability,
1689}
1690
1691impl<'a> WitTarget<'a> {
1692    /// Canonical author-facing `:contratos` payload field name for the
1693    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1694    /// [`AplicacaoError::ContratoMissingTarget`] /
1695    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1696    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1697    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1698    /// the `feira app graph` verb prints. Peer of
1699    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1700    /// on the payload-field-name axis; declared as a peer const next
1701    /// to the [`WitTarget::Http`] variant so a future rename on the
1702    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1703    /// :endpoint …)))` field lands in exactly one place, not scattered
1704    /// across the [`WitContract::target`] gate's six `expected:`
1705    /// literals, the label template, and every downstream consumer
1706    /// that prints a per-arm prefix. Same trajectory as the peer
1707    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1708    /// for the arm's shape, next to the variant declaration.
1709    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1710    /// Canonical author-facing `:contratos` payload field name for the
1711    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1712    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1713    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1714    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1715    /// Canonical author-facing `:contratos` payload field name for the
1716    /// key/value-store-shaped arm. Peer of
1717    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1718    /// on the payload-field-name axis; see
1719    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1720    pub const STORE_FIELD_NAME: &'static str = "slot";
1721
1722    /// Canonical stable human-readable label the payload-less
1723    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1724    /// the byte-string every consumer that formats a payload-less
1725    /// typed capability edge as text lands on (the
1726    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1727    /// naming which identical edge was declared twice, the future
1728    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1729    /// policy resolver's audit view, the operator's mesh-graph audit).
1730    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1731    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1732    /// author-facing label-scalar consts — the same
1733    /// "one canonical declaration per arm, next to the variant, so a
1734    /// future rename lands in one place" discipline extended to the
1735    /// payload-less arm. Until this lift landed the byte-string sat
1736    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1737    /// match arm, once in the pin test asserting the label's
1738    /// [`WitTarget::Capability`] output — with no compile-time link
1739    /// between the two: a rebrand on either side (an operator-facing
1740    /// vocabulary shift, a per-consumer disambiguation like
1741    /// `"(capability — no payload; typed edge only)"`) would silently
1742    /// desynchronize until a downstream consumer surfaced the drift at
1743    /// runtime.
1744    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1745
1746    /// Canonical `expected:` scalar the
1747    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1748    /// through for the payload-less [`WitTarget::Capability`] arm — the
1749    /// byte-string authors read as "this WIT world's shape is not one
1750    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1751    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1752    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1753    /// [`Self::STORE_FIELD_NAME`] consts on the
1754    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1755    /// same "which payload field name goes in the diagnostic" dispatch
1756    /// the three payload-arm consts cover, extended to the payload-less
1757    /// arm. Until this lift landed the byte-string sat twice — once
1758    /// inline in the [`Self::target`] Capability-arm rejection at the
1759    /// production dispatch, once in the pin test asserting the
1760    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1761    /// no compile-time link between the two: a rebrand on either side
1762    /// (an author-facing vocabulary shift to `"capability"` /
1763    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1764    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1765    /// [`WitTarget::Capability`] into per-shape peers) would silently
1766    /// desynchronize until a downstream consumer surfaced the drift at
1767    /// runtime. Same "one canonical declaration per arm, next to the
1768    /// variant, so a future rename lands in one place" discipline the
1769    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1770    /// established for the payload-less arm's human-readable label
1771    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1772    /// so both halves of the "how does the Capability arm surface at
1773    /// its two consumer axes (human-readable label, wrong-target
1774    /// diagnostic)" pipeline route through peer consts declared next
1775    /// to the variant.
1776    ///
1777    /// Pairwise-distinctness against the three payload-arm scalars
1778    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1779    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1780    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1781    /// test — the 4-way closure of the 3-way
1782    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1783    /// the `ContratoWrongTarget::expected` axis, matching the peer
1784    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1785    /// scalar-value distinctness discipline the sibling M3 typed-enum
1786    /// discriminator axis already carries.
1787    pub const CAPABILITY_EXPECTED: &'static str = "none";
1788
1789    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1790    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1791    /// as under [`Self::graph_label`] — the sibling
1792    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1793    /// payload-column axis (the graph verb spells payload-less as
1794    /// `(capability-only)`, distinct from the duplicate-`:contratos`
1795    /// diagnostic's `(capability — no payload)` on the human-readable
1796    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1797    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1798    /// family — extends the "one canonical declaration per arm, next to
1799    /// the variant, so a future rename lands in one place" discipline
1800    /// onto the third payload-less-arm consumer axis (`feira app graph`
1801    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1802    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1803    /// axis).
1804    ///
1805    /// Until this lift landed the byte-string sat inline in
1806    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1807    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1808    /// `"(capability-only)".to_string()` literal, with no compile-time link
1809    /// back to the [`WitTarget::Capability`] variant declaration nor to
1810    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1811    /// peer consts already carrying the "one canonical declaration per
1812    /// payload-less-arm consumer axis" discipline. A rebrand on either
1813    /// side (the graph verb's operator-facing vocabulary tightening from
1814    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1815    /// the WIT registry vocabulary sharpens, an M4 split of
1816    /// [`Self::Capability`] into per-shape peers) would silently
1817    /// desynchronize the graph-verb byte-string from the paired
1818    /// per-arm-adjacent const and land two spellings of the same axis in
1819    /// two spots.
1820    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1821
1822    /// The `(author-facing field name, payload)` pair this typed target
1823    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1824    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1825    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1826    /// [`Self::Store`], `None` for the payload-less
1827    /// [`Self::Capability`] arm.
1828    ///
1829    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1830    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1831    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1832    /// (returns the first component) route through, so a future
1833    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1834    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1835    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1836    /// exactly one new match-arm here (a compile-time exhaustiveness
1837    /// error otherwise), not a coordinated three-way rewrite of the
1838    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1839    /// + every downstream consumer that reaches for the pair.
1840    ///
1841    /// Until this lift landed the three payload arms sat in
1842    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1843    /// invocations (one per variant, each hand-quoting the paired
1844    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1845    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1846    /// "same shape, written N times" duplication THEORY.md §I.3.5
1847    /// ("Generation first, composition second, hand-authoring last;
1848    /// the duplication budget is zero") promotes to a build-time
1849    /// concern, with each per-arm site paired to its own const with no
1850    /// compile-time link between the format template and the arm's
1851    /// payload extraction.
1852    #[must_use]
1853    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1854        match *self {
1855            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1856            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1857            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1858            WitTarget::Capability => None,
1859        }
1860    }
1861
1862    /// The canonical author-facing `:contratos` payload field name
1863    /// this typed target arm carries (`Http` → `Some("endpoint")`,
1864    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1865    /// `None` for the payload-less `Capability` arm.
1866    ///
1867    /// Routes through [`Self::payload_pair`] — the single 4-arm
1868    /// dispatch [`Self::label`] also reads — so a future variant
1869    /// addition is one match-arm edit at [`Self::payload_pair`], not a
1870    /// per-consumer rewrite. Same "exhaustive-match at one canonical
1871    /// dispatch, thin projections at each consumer" trajectory the
1872    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1873    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1874    #[must_use]
1875    pub const fn field_name(&self) -> Option<&'static str> {
1876        match self.payload_pair() {
1877            Some((f, _)) => Some(f),
1878            None => None,
1879        }
1880    }
1881
1882    /// The underlying scalar the payload-carrying arm carries — the
1883    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
1884    /// subject ([`Self::PubSub`] `:subject`), or slot template
1885    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
1886    /// `&'a str` storage — or `None` on the payload-less
1887    /// [`Self::Capability`] arm.
1888    ///
1889    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
1890    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
1891    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
1892    /// the paired sub-selector axis. Both per-half accessors read from
1893    /// one authoritative match, so a future [`WitTarget`] variant
1894    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
1895    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
1896    /// on [`Self::payload_pair`] and both per-half projections + every
1897    /// downstream consumer picks the new arm up by construction — no
1898    /// coordinated N-way rewrite across the paired accessor dispatches,
1899    /// the [`Self::label`] / [`Self::graph_label`] format templates,
1900    /// and every future WIT-registry-shaped consumer.
1901    ///
1902    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
1903    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
1904    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
1905    /// both per-half projections as thin readers, every downstream
1906    /// consumer through the same match" discipline extended onto the
1907    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
1908    /// gap between the two paired-dispatch surfaces: the peer
1909    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
1910    /// the first-component projection until this lift; the second-
1911    /// component sibling now sits alongside so both halves reach every
1912    /// future consumer through the same substrate-primitive dispatch.
1913    ///
1914    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
1915    #[must_use]
1916    pub const fn payload(&self) -> Option<&'a str> {
1917        match self.payload_pair() {
1918            Some((_, p)) => Some(p),
1919            None => None,
1920        }
1921    }
1922
1923    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
1924    /// consumer that fans on the L7-HTTP-shaped payload keys off —
1925    /// returns the [`Self::Http`]-arm's author-declared request path
1926    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
1927    /// projected target is [`Self::Http { endpoint }`], `None` on the
1928    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
1929    /// [`Self::Capability`], each of which carries no HTTP endpoint by
1930    /// definition).
1931    ///
1932    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
1933    /// `path:` rule payload every substrate-side L7-introspecting
1934    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
1935    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
1936    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
1937    /// on the L7 introspection branch; every peer WIT shape stays
1938    /// L4-only because Cilium can't introspect NATS / key-value / plain
1939    /// capability edges), and every future L7-introspecting consumer
1940    /// of the projected target's HTTP endpoint (the future M4
1941    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
1942    /// materializer's per-edge L7 admission-webhook overlay, the
1943    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
1944    /// path bucket-key resolver, the future per-`:contratos`-edge
1945    /// mTLS-required overlay's HTTP-shape scope filter, the future
1946    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
1947    /// through the same typed dispatch.
1948    ///
1949    /// Prior to this lift the sole production consumer of the projected-
1950    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
1951    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
1952    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
1953    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
1954    /// }`) — reached the payload through a raw per-arm `if let` pattern-
1955    /// match that expressed no compile-time link back to the substrate
1956    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
1957    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
1958    /// scalar accessor on the peer per-`:contratos` raw-field axis but
1959    /// with no post-projection peer on the typed-view surface. A future
1960    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
1961    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
1962    /// gRPC-shaped worlds per this enum's own docstring at
1963    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
1964    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
1965    /// would have had to be threaded through the caixa-mesh L7 emit
1966    /// branch's raw `if let` in lockstep — either coalescing the two
1967    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
1968    /// emit path per-arm — with no substrate-primitive dispatch making
1969    /// the "which arms count as L7-HTTP-shaped for path-emission
1970    /// purposes" question the substrate's answer to give. Lifting the
1971    /// resolution to a typed method on the substrate primitive means
1972    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
1973    /// projected-target HTTP endpoint reaches for exactly one typed
1974    /// dispatch — the resolver's accept-set migrates as a unit on any
1975    /// future arm-family widening, and the caixa-mesh L7 emit branch
1976    /// reads through the same substrate primitive.
1977    ///
1978    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
1979    /// (7020470) `Option<&str>` scalar accessor on the raw
1980    /// `:contratos :endpoint` field-access axis — same "one typed
1981    /// dispatch on the substrate primitive, thin projections at each
1982    /// consumer" discipline extended onto the peer post-projection typed-
1983    /// view surface (the [`WitContract::endpoint`] pre-projection
1984    /// accessor returns `Some` for any author-declared `:endpoint`
1985    /// value regardless of the paired `:wit` world's HTTP-shape
1986    /// classification — the raw slot before validation crosses it —
1987    /// while this post-projection [`Self::http_endpoint`] accessor
1988    /// returns `Some` iff the target has been projected onto the
1989    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
1990    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
1991    /// coherence; the two accessors close the pre-projection /
1992    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
1993    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
1994    /// the three payload-carrying arms) — extends the per-arm
1995    /// projection family onto the [`Self::Http`] specialization axis
1996    /// that the pan-arm accessor's shape blends into a single arm-
1997    /// agnostic view; paired with [`Self::pubsub_subject`] /
1998    /// [`Self::store_slot`] on the sibling per-arm axes so every
1999    /// per-payload-arm shape carries a named post-projection accessor
2000    /// on the same shape as `http_endpoint`, closing the per-arm-shape
2001    /// accept-set the substrate primitive owns.
2002    #[must_use]
2003    pub const fn http_endpoint(&self) -> Option<&'a str> {
2004        match *self {
2005            WitTarget::Http { endpoint } => Some(endpoint),
2006            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2007        }
2008    }
2009
2010    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
2011    /// consumer that fans on the pub-sub-shaped payload keys off —
2012    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
2013    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
2014    /// the projected target is [`Self::PubSub { subject }`], `None` on
2015    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
2016    /// [`Self::Capability`], each of which carries no NATS-shaped
2017    /// subject by definition).
2018    ///
2019    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
2020    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
2021    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
2022    /// CR materializer's `spec.subjects[]` projection, the future
2023    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
2024    /// bucket-key resolver, the future `feira app graph --pubsub`
2025    /// per-Aplicacao subject column, any future substrate-lifted
2026    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
2027    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
2028    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
2029    /// future pub-sub-shape consumer reaches for the same typed
2030    /// dispatch this accessor exposes so the "which arm carries the
2031    /// subject scalar?" answer lives at one caixa-core edit rather
2032    /// than open-coded across per-consumer `if let WitTarget::PubSub
2033    /// { subject } = c.target()…` pattern-matches.
2034    ///
2035    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2036    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2037    /// the pre-projection [`WitContract::subject`] scalar accessor on
2038    /// the raw `:contratos :subject` field-access axis — same "one
2039    /// typed dispatch on the substrate primitive, thin projections at
2040    /// each consumer" discipline extended onto the per-arm pub-sub
2041    /// post-projection axis. The pre-projection accessor returns
2042    /// `Some` for any author-declared `:subject` value regardless of
2043    /// the paired `:wit` world's pub-sub-shape classification (the raw
2044    /// slot before validation crosses it); this post-projection
2045    /// accessor returns `Some` iff the target has been projected onto
2046    /// the [`Self::PubSub`] arm, i.e. only after the
2047    /// [`WitContract::target`] gate has admitted the
2048    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2049    /// the pre-/post-projection pair on the pub-sub-subject axis to
2050    /// match the pair the [`WitContract::endpoint`] +
2051    /// [`Self::http_endpoint`] surfaces already close on the peer
2052    /// HTTP-endpoint axis.
2053    ///
2054    /// Sibling of the unified pan-arm [`Self::payload`]
2055    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2056    /// extends the per-arm projection family onto the [`Self::PubSub`]
2057    /// specialization axis that the pan-arm accessor's shape blends
2058    /// into a single arm-agnostic view; the pair
2059    /// (`pubsub_subject`, `store_slot`) closes the trio
2060    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2061    /// payload arm now carries its own per-arm-shape post-projection
2062    /// accessor.
2063    #[must_use]
2064    pub const fn pubsub_subject(&self) -> Option<&'a str> {
2065        match *self {
2066            WitTarget::PubSub { subject } => Some(subject),
2067            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2068        }
2069    }
2070
2071    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2072    /// every consumer that fans on the store-shaped payload keys off —
2073    /// returns the [`Self::Store`]-arm's author-declared slot template
2074    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2075    /// projected target is [`Self::Store { slot }`], `None` on the
2076    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2077    /// [`Self::Capability`], each of which carries no
2078    /// key/value-store slot by definition).
2079    ///
2080    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2081    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2082    /// every future substrate-side store-introspecting per-`(:de,
2083    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2084    /// namespace / prefix reconciler's per-slot projection, the future
2085    /// per-store-backend routing overlay's slot-shape gate, the future
2086    /// `feira app graph --store` per-Aplicacao slot column, any future
2087    /// substrate-lifted store-shape emitter that reads a projected
2088    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2089    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2090    /// Every future store-shape consumer reaches for the same typed
2091    /// dispatch this accessor exposes so the "which arm carries the
2092    /// slot scalar?" answer lives at one caixa-core edit rather than
2093    /// open-coded across per-consumer
2094    /// `if let WitTarget::Store { slot } = c.target()…`
2095    /// pattern-matches.
2096    ///
2097    /// Peer of the sibling [`Self::http_endpoint`] +
2098    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2099    /// axes and of the pre-projection [`WitContract::slot`] scalar
2100    /// accessor on the raw `:contratos :slot` field-access axis — same
2101    /// "one typed dispatch on the substrate primitive, thin projections
2102    /// at each consumer" discipline extended onto the per-arm store
2103    /// post-projection axis. Closes the pre-/post-projection pair on
2104    /// the store-slot axis to match the pairs the
2105    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2106    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2107    /// already close on the peer HTTP-endpoint and pub-sub-subject
2108    /// axes; the substrate-side pre-/post-projection accessor family
2109    /// now spans all three payload arms as a matched trio, so any
2110    /// future arm-shape widening (a `Rest`/`Grpc` split of
2111    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2112    /// lands one accessor without threading through the sibling
2113    /// pre-projection or the peer per-arm post-projection surfaces a
2114    /// compile-time exhaustiveness error at the substrate primitive,
2115    /// not a silent per-consumer split at renderer emit time.
2116    ///
2117    /// Sibling of the unified pan-arm [`Self::payload`]
2118    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2119    /// closes the per-arm projection family onto the [`Self::Store`]
2120    /// specialization axis that the pan-arm accessor's shape blends
2121    /// into a single arm-agnostic view. The trio
2122    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2123    /// pan-arm accept-set on every payload-carrying arm: exactly one
2124    /// per-arm accessor returns `Some(payload)` and the two peers
2125    /// return `None`, and every payload-less [`Self::Capability`]
2126    /// input returns `None` on all three — the partition the sibling
2127    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2128    /// pin locks in load-bearing.
2129    #[must_use]
2130    pub const fn store_slot(&self) -> Option<&'a str> {
2131        match *self {
2132            WitTarget::Store { slot } => Some(slot),
2133            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2134        }
2135    }
2136
2137    /// Render this typed target as a stable human-readable label
2138    /// (`:endpoint "/charge"`, `:subject "events.x"`,
2139    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2140    /// the WIT world is a pure capability edge).
2141    ///
2142    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2143    /// gate so the diagnostic names *which* identical edge was
2144    /// declared twice (not just which `(de, para, wit)` triple).
2145    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2146    /// on the payload-carrying arms (`Some((field, payload)) →
2147    /// format!(":{field} {payload:?}")`) and through the lifted
2148    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2149    /// [`Self::Capability`] arm — so a future variant addition (the
2150    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2151    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2152    /// `Queue`-shaped peer) becomes a single new match-arm on
2153    /// [`Self::payload_pair`] rather than a rewrite of this template
2154    /// (and every downstream consumer that reaches for the label
2155    /// shape: the per-edge policy resolver in M4, the `feira app
2156    /// graph` view, the operator's mesh-graph audit). Until this
2157    /// lift landed the three payload arms carried three near-identical
2158    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2159    /// [`Self::Capability`] arm carried the payload-less byte-string
2160    /// twice (once inline here, once in the pin test) — closing the
2161    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2162    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2163    /// / 4a1e490) peer-const lifts already established for the
2164    /// payload-carrying arms.
2165    #[must_use]
2166    pub fn label(&self) -> String {
2167        match self.payload_pair() {
2168            Some((field, payload)) => format!(":{field} {payload:?}"),
2169            None => Self::CAPABILITY_LABEL.to_string(),
2170        }
2171    }
2172
2173    /// Render this typed target as the `feira app graph` per-`:contratos`
2174    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2175    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2176    /// payload-less arm).
2177    ///
2178    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2179    /// on the payload-carrying arms (`Some((field, payload)) →
2180    /// format!("{field}={payload}")`) and through the lifted
2181    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2182    /// [`Self::Capability`] arm — so a future variant addition
2183    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2184    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2185    /// `Queue`-shaped peer) becomes one match-arm edit at
2186    /// [`Self::payload_pair`], propagating through this graph-verb
2187    /// projection at zero call-site cost, sibling to the peer
2188    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2189    /// same 4-arm dispatch.
2190    ///
2191    /// Until this lift landed the [`caixa-feira`]
2192    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2193    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2194    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2195    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2196    /// `format!("{}={endpoint}", ...)` template and hard-coding
2197    /// `"(capability-only)"` as a fifth payload-less scalar with no link
2198    /// back to the paired [`WitTarget::Capability`] variant declaration.
2199    /// A future variant addition would have had to be threaded through
2200    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2201    /// verb's inline match in lockstep or the two projections would
2202    /// silently disagree on the arm-set the graph verb prints — the
2203    /// duplicate-`:contratos` diagnostic reading one shape while the
2204    /// graph verb's payload column silently dropped the new arm to
2205    /// `(capability-only)`. Lifting the graph-verb projection onto the
2206    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2207    /// the axis: both projections migrate as a unit.
2208    ///
2209    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2210    /// quoting) shape is graph-verb-canonical — distinct from the
2211    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2212    /// duplicate-`:contratos` diagnostic seeds (see
2213    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2214    /// on the payload-less axis for the paired distinction).
2215    #[must_use]
2216    pub fn graph_label(&self) -> String {
2217        match self.payload_pair() {
2218            Some((field, payload)) => format!("{field}={payload}"),
2219            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2220        }
2221    }
2222}
2223
2224/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2225/// pretty-printed byte-string every consumer that formats a typed
2226/// payload target as user-facing text lands on (the
2227/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2228/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2229/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2230/// graph` per-`:contratos`-edge payload column that reaches the graph
2231/// verb through `format!("{target}")`, the future M4 per-edge policy
2232/// resolver's per-edge audit-log line, the operator's mesh-graph
2233/// per-edge inspection view) reaches for the same lifted
2234/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2235/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2236/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2237/// routes through — extending the three-path-convergence
2238/// (`Debug` for structural inspection, `Display` for user-facing text,
2239/// per-arm typed accessor for the canonical byte-string) discipline the
2240/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2241/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2242/// onto the fourth (and only remaining) typed-shape-discriminator axis
2243/// on the caixa surface.
2244///
2245/// Pre-lift the two paths were structurally independent — every consumer
2246/// reaching for a payload byte-string past the [`WitTarget::label`]
2247/// helper had to pick between three paths ([`WitTarget::label`],
2248/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2249/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2250/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2251/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2252/// that reached for `format!("{target}")` — the canonical shape every
2253/// user-facing pretty-print site on the sibling typed-enum axes already
2254/// uses — would silently land on the `Debug` derive's structural output
2255/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2256/// than the `label()` helper's stable byte-string (`:endpoint
2257/// "/charge"` — the author-facing `:contratos` keyword form) the
2258/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2259/// already threads through. The two spellings would diverge silently in
2260/// every downstream diagnostic / graph / audit line reached through
2261/// `format!` rather than through the `label()` helper. Routing
2262/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2263/// path: every `format!("{v}")` call reaches the same
2264/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2265/// and the duplicate-`:contratos` gate already route through, so a
2266/// future variant addition (the M4-and-later per-edge WIT registry may
2267/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2268/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2269/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2270/// match — rather than fanning out through hand-rolled per-arm
2271/// [`std::fmt::Display`] arms.
2272///
2273/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2274/// is the typed view returned by [`WitContract::target`], not a
2275/// closed-set discriminator enum with a gen-platform Discriminant
2276/// registration, so the `Debug` derive's structural output (which every
2277/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2278/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2279/// shape for structural inspection; `Display` (via `label`) reveals the
2280/// stable author-facing payload projection.
2281///
2282/// Pin tests
2283/// [`tests::wit_target_display_routes_through_label_helper`] and
2284/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2285/// assert the two paths agree byte-for-byte on every variant, so a
2286/// future variant addition or `label()` reimplementation that hand-rolls
2287/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2288/// build error visible at caixa-core test time, not a silent
2289/// per-consumer dispatch miss at diagnostic / audit / graph time.
2290impl std::fmt::Display for WitTarget<'_> {
2291    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2292        f.write_str(&self.label())
2293    }
2294}
2295
2296// ── one Aplicacao member ─────────────────────────────────────────────
2297
2298/// A Servico participating in the Aplicacao. Same shape as
2299/// `crate::supervisor::ChildSpec` but without a restart policy —
2300/// supervision is per-Servico (each member has its own
2301/// `:supervisor`), the Aplicacao orchestrates *placement*.
2302#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2303#[serde(rename_all = "camelCase")]
2304pub struct Membro {
2305    /// Member caixa's `:nome`. Resolves through the same dep
2306    /// resolution path as `crate::dep::Dep`.
2307    pub caixa: String,
2308
2309    /// Semver constraint.
2310    pub versao: String,
2311}
2312
2313impl Membro {
2314    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2315    /// accessor every consumer that reads the member's Servico identity
2316    /// keys off — returns the author-declared `:membros :caixa`
2317    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2318    /// own [`String`] storage.
2319    ///
2320    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2321    /// participating in the Aplicacao — validated by
2322    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2323    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2324    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2325    /// [`validate_no_self_membership`]) — and every downstream consumer
2326    /// that fans on the member's identity keys off this scalar (the
2327    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2328    /// lookup, the per-`:membros` duplicate gate's dedup key, the
2329    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2330    /// identity, the self-membership gate, the
2331    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2332    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2333    /// CR materializer's per-member resolver).
2334    ///
2335    /// Prior to this lift the `.caixa` byte-string was read inline at
2336    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2337    /// set collector at
2338    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2339    /// [`validate_membros`] validation-side member-caixa gate at
2340    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2341    /// per-member duplicate-gate dedup key at
2342    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2343    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2344    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2345    /// [`validate_no_self_membership`] self-loop gate at
2346    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2347    /// expressed no compile-time link back to the typed slot. Every
2348    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2349    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2350    /// `name:` axis, so a future extension of the `:membros :caixa`
2351    /// axis to a richer author surface — a per-cluster alias table the
2352    /// operator pins through a future `:placement`-scoped slot, a
2353    /// namespace-qualified rewrite the M4 CR materializer applies
2354    /// per-CR, a per-member overlay from the future `:membros
2355    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2356    /// acknowledges — would have had to be threaded through every
2357    /// open-coded copy in lockstep or one consumer would silently
2358    /// disagree with the peers on which caixa a given member resolves
2359    /// to. A member-set lookup that treated the name as `"cart"` while
2360    /// the peer adjacency map treated it as `"tenant-a/cart"` would
2361    /// silently split the `:contratos` membership-lookup diagnostic from
2362    /// the cycle-detector's node identity — a two-consumer split at the
2363    /// validator far from the source `caixa.lisp` with no field naming
2364    /// the identity-drift root cause. Lifting the resolution rule to a
2365    /// typed method on the substrate primitive means every downstream
2366    /// consumer of the Aplicacao's per-`:membros` identity surface
2367    /// reaches for exactly one typed dispatch — the resolver's
2368    /// accept-set migrates as a unit on any future axis addition.
2369    ///
2370    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2371    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2372    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2373    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2374    /// destination-Servico scalar accessors — same "one typed dispatch
2375    /// on the substrate primitive, thin projections at each consumer"
2376    /// discipline extended onto the per-`:membros` member-caixa `:nome`
2377    /// byte-string axis. Named `nome()` to match the tatara-lisp
2378    /// author-surface term the field's docstring already reaches for
2379    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2380    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2381    /// already carries — the accessor's name maps directly onto the
2382    /// canonical caixa-identity vocabulary rather than shadowing the
2383    /// field's storage-side `caixa` label.
2384    #[must_use]
2385    pub const fn nome(&self) -> &str {
2386        self.caixa.as_str()
2387    }
2388
2389    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2390    /// requirement scalar accessor every consumer that reads the
2391    /// member's version pin keys off — returns the author-declared
2392    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2393    /// from the typed slot's own [`String`] storage.
2394    ///
2395    /// The `:membros :versao` slot carries the Cargo-shaped semver
2396    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2397    /// pins which release of the member-caixa the Aplicacao composes
2398    /// against — the same requirement grammar the peer `:deps :versao`
2399    /// / `:children :versao` axes carry, resolved through the shared
2400    /// [`crate::render::require_valid_versao_requirement`] cascade and
2401    /// the shared [`crate::version::parse_requirement`] parser. Every
2402    /// downstream consumer that fans on the member's version pin keys
2403    /// off this scalar (the [`validate_membros`] per-member requirement
2404    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2405    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
2406    /// m.nome(), m.versao_requirement())` line, every future per-cluster
2407    /// version-lock overlay the operator pins through a future
2408    /// `:placement`-scoped slot, the future
2409    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2410    /// version resolver, the future `feira app deploy` pipeline's
2411    /// per-member lacre BLAKE3-closure lookup).
2412    ///
2413    /// Prior to this lift the `.versao` byte-string was accessed inline
2414    /// at two `&str`-shaped sites — the [`validate_membros`]
2415    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2416    /// …)` and the `feira app graph` per-member printer's `println!(
2417    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2418    /// prior to this lift) — two open-coded field-accesses that expressed
2419    /// no compile-time link back to the typed slot. A future extension of
2420    /// the `:membros :versao` axis to a richer author surface (a
2421    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2422    /// flow, a lacre-projected concrete-version rewrite the operator
2423    /// materializes at CR-admission time, a future `:membros :versao-lock`
2424    /// per-cluster override slot) would have had to be threaded through
2425    /// every open-coded copy in lockstep or one consumer would silently
2426    /// disagree with the peers on which release constraint a given
2427    /// member resolves to. Lifting the resolution rule to a typed method
2428    /// on the substrate primitive means every downstream requirement-
2429    /// facing consumer reaches for exactly one typed dispatch — the
2430    /// resolver's accept-set migrates as a unit on any future axis
2431    /// addition.
2432    ///
2433    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2434    /// member-caixa `:nome` scalar accessor — the pair
2435    /// `(nome(), versao_requirement())` jointly projects the
2436    /// `(caixa, versao)` field pair every renderer that fans on
2437    /// per-member identity + version pin keys off, closing the last
2438    /// unlifted per-`:membros` scalar axis so every downstream
2439    /// per-`:membros` reader now routes through a typed dispatch on the
2440    /// substrate primitive. Named `versao_requirement()` rather than
2441    /// `versao()` because the field's storage-side `.versao` label is
2442    /// already the author-surface term (`:versao`); the accessor's name
2443    /// carries the semantic role — the semver *requirement* string the
2444    /// shared [`crate::version::parse_requirement`] entry-point consumes
2445    /// — so a raw field access and a typed dispatch read differently at
2446    /// every consumer site.
2447    ///
2448    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2449    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2450    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2451    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2452    /// destination-Servico scalar accessors — same "one typed dispatch
2453    /// on the substrate primitive, thin projections at each consumer"
2454    /// discipline extended onto the per-`:membros` member-`:versao`
2455    /// semver-requirement byte-string axis.
2456    #[must_use]
2457    pub const fn versao_requirement(&self) -> &str {
2458        self.versao.as_str()
2459    }
2460}
2461
2462// ── mesh-level policies ──────────────────────────────────────────────
2463
2464/// Mesh policies that apply to every `:contratos` edge unless
2465/// overridden per-edge in M4. V0 is a single global policy block.
2466#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2467#[serde(rename_all = "camelCase")]
2468pub struct MeshPolicy {
2469    /// Per-call timeout. Authored as a duration string (`"30s"`).
2470    #[serde(
2471        default,
2472        skip_serializing_if = "Option::is_none",
2473        with = "supervisor::duration_codec"
2474    )]
2475    pub timeout: Option<Duration>,
2476
2477    /// Number of retries on transient failure. None = no retries.
2478    #[serde(default, skip_serializing_if = "Option::is_none")]
2479    pub retries: Option<u32>,
2480
2481    /// Circuit breaker config. Trips after N failures within W
2482    /// duration; closes after a cooldown.
2483    #[serde(default, skip_serializing_if = "Option::is_none")]
2484    pub circuit_breaker: Option<CircuitBreaker>,
2485
2486    /// Whether mTLS is required for every contrato. Default: true
2487    /// (sandboxing-by-default; explicit opt-out only).
2488    #[serde(default, skip_serializing_if = "Option::is_none")]
2489    pub mtls_required: Option<bool>,
2490
2491    /// Token-bucket rate limit. Authored as `"100/s"` or
2492    /// `"5000/m"`; stored as `(rate, window)`.
2493    #[serde(
2494        default,
2495        skip_serializing_if = "Option::is_none",
2496        with = "rate_limit_codec"
2497    )]
2498    pub rate_limit: Option<RateLimit>,
2499}
2500
2501impl MeshPolicy {
2502    /// True when no `:politicas` axis carries a value — every field is
2503    /// `None`. The same emptiness contract every other M2/M3 typed
2504    /// surface carries ([`crate::LimitsSpec::is_empty`],
2505    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2506    /// typed slot onto a cluster artifact key off this predicate to
2507    /// decide "emit the slot" vs "skip the slot entirely", so an
2508    /// authored-but-unset `:politicas (())` round-trips to a rendered
2509    /// artifact that's structurally identical to one that omits the
2510    /// slot. Lifted as a typed predicate (rather than per-renderer
2511    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2512    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2513    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2514    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2515    /// not a coordinated rewrite of every consumer that's reaching
2516    /// for the emptiness semantic.
2517    #[must_use]
2518    pub const fn is_empty(&self) -> bool {
2519        self.timeout().is_none()
2520            && self.retries().is_none()
2521            && self.circuit_breaker().is_none()
2522            && self.mtls_required().is_none()
2523            && self.rate_limit().is_none()
2524    }
2525
2526    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
2527    /// per-call-deadline scalar accessor every consumer of the
2528    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
2529    /// returns the author-declared `:politicas :timeout` typed
2530    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
2531    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
2532    /// is `Copy`, so the accessor returns by value; no borrow of
2533    /// `&self` past the call). `None` when the slot is absent (the
2534    /// "cluster default applies — typically the gateway class's
2535    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
2536    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
2537    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
2538    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
2539    /// round-trips to a rendered `HTTPRoute` structurally identical to
2540    /// one that omits the slot).
2541    ///
2542    /// The `:politicas :timeout` slot carries the "no infinite blocking"
2543    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
2544    /// the typed slot's `Option<Duration>` accept-set (zero-floor
2545    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
2546    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
2547    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
2548    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
2549    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
2550    /// Every downstream consumer that reads the per-call cap keys off
2551    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2552    /// renderers key off to decide "emit :politicas overlay" vs "skip
2553    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2554    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
2555    /// fans the deadline into every rule via
2556    /// [`crate::render::single_field_overlay`], the future M4 per-
2557    /// Aplicacao Gateway API reconciler materialization pass, the
2558    /// future per-`:contratos`-edge timeout-override overlay the
2559    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
2560    ///
2561    /// Prior to this lift the `.timeout` field was accessed inline at
2562    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
2563    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
2564    /// …)` call — two open-coded field-accesses that expressed no
2565    /// compile-time link back to the typed slot. A future extension of
2566    /// the `:politicas :timeout` axis to a richer author surface — a
2567    /// per-`:contratos`-edge timeout override the operator pins through
2568    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
2569    /// roadmap acknowledges, a per-cluster timeout-default overlay the
2570    /// M4 CR materializer resolves per-CR, a split of the single
2571    /// per-call `Duration` into a richer `{request, backendRequest}`
2572    /// pair once the Gateway API's per-rule `timeouts` block grows the
2573    /// upstream-facing backendRequest arm alongside the client-facing
2574    /// request arm — would have had to be threaded through both open-
2575    /// coded copies in lockstep or the emptiness predicate and the
2576    /// caixa-mesh emit path would silently disagree on which per-call
2577    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
2578    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
2579    /// == false` while the renderer's overlay-emit path silently read
2580    /// a drifted other value, or vice versa: an author's `:timeout
2581    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
2582    /// the emptiness predicate still classified the policy as non-
2583    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
2584    /// | grep -A2 timeouts` audit would land on a route whose author's
2585    /// typed slot value silently vanished at the renderer layer).
2586    /// Lifting the resolution to a typed method on the substrate
2587    /// primitive means every downstream consumer of the Aplicacao's
2588    /// per-`:politicas` deadline surface reaches for exactly one typed
2589    /// dispatch — the resolver's accept-set migrates as a unit on any
2590    /// future axis addition.
2591    ///
2592    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
2593    /// family (sibling of the peer per-`:politicas`
2594    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
2595    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
2596    /// `Option<bool>` accessor — same "one typed dispatch on the
2597    /// substrate primitive, thin projections at each consumer"
2598    /// discipline extended onto the peer per-`:politicas` typed-
2599    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
2600    /// numeric-Copy-T scalar" projection pattern the sibling
2601    /// `Option<u32>` / `Option<bool>` lifts opened, since every
2602    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
2603    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
2604    /// than a scalar). Named `timeout()` to match the storage field's
2605    /// name; the accessor's identity maps onto the canonical MESH-
2606    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
2607    #[must_use]
2608    pub const fn timeout(&self) -> Option<Duration> {
2609        self.timeout
2610    }
2611
2612    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
2613    /// retry-budget scalar accessor every consumer of the Aplicacao's
2614    /// Gateway API v1.x per-rule retry-cap keys off — returns the
2615    /// author-declared `:politicas :retries` typed `u32` verbatim as an
2616    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
2617    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
2618    /// value; no borrow of `&self` past the call). `None` when the slot
2619    /// is absent (the "cluster default applies — typically 'no retries
2620    /// beyond a single dispatch attempt'" arm the caixa-mesh
2621    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
2622    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
2623    /// this predicate too, so an authored-but-unset `:politicas
2624    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
2625    /// identical to one that omits the slot).
2626    ///
2627    /// The `:politicas :retries` slot carries the "transient failure
2628    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
2629    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
2630    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2631    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
2632    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
2633    /// count scalar the caixa-mesh `retry_overlay` builder writes.
2634    /// Every downstream consumer that reads the retry cap keys off this
2635    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2636    /// renderers key off to decide "emit :politicas overlay" vs "skip
2637    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2638    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
2639    /// the value into every rule via [`crate::render::single_field_overlay`],
2640    /// the future M4 per-Aplicacao Gateway API reconciler
2641    /// materialization pass, the future per-`:contratos`-edge retry-
2642    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
2643    /// acknowledges).
2644    ///
2645    /// Prior to this lift the `.retries` field was accessed inline at
2646    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
2647    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
2648    /// …)` call — two open-coded field-accesses that expressed no
2649    /// compile-time link back to the typed slot. A future extension of
2650    /// the `:politicas :retries` axis to a richer author surface — a
2651    /// per-`:contratos`-edge retry override the operator pins through a
2652    /// future `:contratos :retries` slot, a per-cluster retry-default
2653    /// overlay the M4 CR materializer resolves per-CR, a promotion of
2654    /// the plain `u32` attempt-count to a richer `{attempts, codes,
2655    /// backoff}` sub-block once the Gateway API grows the peer
2656    /// `retry.codes` / `retry.backoff` axes — would have had to be
2657    /// threaded through both open-coded copies in lockstep or the
2658    /// emptiness predicate and the caixa-mesh emit path would silently
2659    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
2660    /// (a `:politicas` block whose only axis is a `Some :retries` would
2661    /// satisfy `is_empty() == false` while the renderer's overlay-emit
2662    /// path silently read a drifted other value, or vice versa: an
2663    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
2664    /// block while the emptiness predicate still classified the policy
2665    /// as non-empty). Lifting the resolution to a typed method on the
2666    /// substrate primitive means every downstream consumer of the
2667    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
2668    /// one typed dispatch — the resolver's accept-set migrates as a
2669    /// unit on any future axis addition.
2670    ///
2671    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
2672    /// family (sibling of the peer per-`:politicas`
2673    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
2674    /// same "one typed dispatch on the substrate primitive, thin
2675    /// projections at each consumer" discipline extended onto the
2676    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
2677    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
2678    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
2679    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
2680    /// fold on). Named `retries()` to match the storage field's name;
2681    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
2682    /// §III.2 vocabulary the slot's docstring already carries.
2683    #[must_use]
2684    pub const fn retries(&self) -> Option<u32> {
2685        self.retries
2686    }
2687
2688    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
2689    /// enforcement-toggle scalar accessor every consumer of the
2690    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
2691    /// — returns the author-declared `:politicas :mtls-required` typed
2692    /// bool verbatim as an `Option<bool>`, copied out of the typed
2693    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
2694    /// the accessor returns by value; no borrow of `&self` past the
2695    /// call). `None` when the slot is absent (the "cluster default
2696    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
2697    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
2698    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
2699    /// this predicate too, so an authored-but-unset `:politicas
2700    /// (:mtls-required ())` round-trips to a rendered
2701    /// `CiliumNetworkPolicy` structurally identical to one that omits
2702    /// the slot).
2703    ///
2704    /// The `:politicas :mtls-required` slot carries the "explicit opt-
2705    /// out only, sandboxing-by-default" mTLS-enforcement toggle
2706    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
2707    /// `{None, Some(true), Some(false)}` accept-set maps onto the
2708    /// Cilium `authentication.mode` bijection through
2709    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
2710    /// handshake enforced), `Some(false) → "disabled"` (handshake
2711    /// skipped — the debug-edge opt-out), `None` → omit the block
2712    /// (cluster default applies). Every downstream consumer that
2713    /// reads the toggle keys off this scalar (the
2714    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2715    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2716    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
2717    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
2718    /// ingress rule via [`crate::render::single_field_overlay`], the
2719    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
2720    /// materialization pass, the future per-`:contratos`-edge mTLS
2721    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2722    ///
2723    /// Prior to this lift the `.mtls_required` field was accessed
2724    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2725    /// `self.mtls_required.is_none()` arm and caixa-mesh's
2726    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
2727    /// two open-coded field-accesses that expressed no compile-time
2728    /// link back to the typed slot. A future extension of the
2729    /// `:politicas :mtls-required` axis to a richer author surface —
2730    /// a per-`:contratos`-edge mTLS override the operator pins through
2731    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
2732    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
2733    /// M4 CR materializer resolves per-CR, a three-valued
2734    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
2735    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
2736    /// would have had to be threaded through both open-coded copies in
2737    /// lockstep or the emptiness predicate and the caixa-mesh emit
2738    /// path would silently disagree on which toggle a given
2739    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
2740    /// axis is a `Some`
2741    /// `:mtls-required` would satisfy `is_empty() == false` while the
2742    /// renderer's overlay-emit path silently read a drifted other
2743    /// value, or vice versa). Lifting the resolution to a typed method
2744    /// on the substrate primitive means every downstream consumer of
2745    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
2746    /// for exactly one typed dispatch — the resolver's accept-set
2747    /// migrates as a unit on any future axis addition.
2748    ///
2749    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2750    /// family (peer of the sibling per-`:placement`
2751    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2752    /// same "one typed dispatch on the substrate primitive, thin
2753    /// projections at each consumer" discipline extended onto the
2754    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2755    /// the "optional per-slot Copy-T scalar" projection pattern the
2756    /// sibling per-`:politicas` `:retries` (Option<u32>) /
2757    /// `:timeout` (Option<Duration>) future lifts fold on). Named
2758    /// `mtls_required()` to match the storage field's name; the
2759    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2760    /// §III.2 vocabulary the slot's docstring already carries.
2761    #[must_use]
2762    pub const fn mtls_required(&self) -> Option<bool> {
2763        self.mtls_required
2764    }
2765
2766    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2767    /// `local_rate_limit`-mesh token-bucket-declaration scalar
2768    /// accessor every consumer of the Aplicacao's per-`:politicas`
2769    /// per-`(rate, window)` rate-limit surface keys off — returns the
2770    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2771    /// verbatim as an `Option<RateLimit>`, copied out of the typed
2772    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2773    /// `Copy`, so the accessor returns by value; no borrow of `&self`
2774    /// past the call). `None` when the slot is absent (the "cluster
2775    /// default applies — typically 'no per-Aplicacao rate declaration,
2776    /// gateway-class per-listener default applies'" arm the future
2777    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2778    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2779    /// `rate_limit().is_none()` arm reads this predicate too, so an
2780    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2781    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2782    /// identical to one that omits the slot).
2783    ///
2784    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2785    /// token-bucket rate declaration" contract (MESH-COMPOSITION
2786    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2787    /// (rate lower-bounded by 1 through
2788    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2789    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2790    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2791    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2792    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2793    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2794    /// `:politicas` overlay emits. Every downstream consumer that
2795    /// reads the rate declaration keys off this scalar (the
2796    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2797    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2798    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2799    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2800    /// `rl.window` against [`is_canonical_rate_limit_window`], the
2801    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2802    /// the future per-`:contratos`-edge rate-limit override the
2803    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2804    ///
2805    /// Prior to this lift the `.rate_limit` field was accessed inline
2806    /// at two sites — [`MeshPolicy::is_empty`]'s
2807    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2808    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2809    /// field-accesses that expressed no compile-time link back to the
2810    /// typed slot. A future extension of the `:politicas :rate-limit`
2811    /// axis to a richer author surface — a per-`:contratos`-edge
2812    /// rate-limit override the operator pins through a future
2813    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2814    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2815    /// the M4 CR materializer resolves per-CR, a promotion of the
2816    /// plain `(rate, window)` scalar pair to a richer
2817    /// `{rate, window, burst, key}` sub-block once Envoy's
2818    /// `local_rate_limit` grows the peer `burst_size` /
2819    /// `descriptor_key` axes — would have had to be threaded through
2820    /// both open-coded copies in lockstep or the emptiness predicate
2821    /// and the validate gate would silently disagree on which rate
2822    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2823    /// block whose only axis is a `Some :rate-limit` would satisfy
2824    /// `is_empty() == false` while the validate path silently read a
2825    /// drifted other value, or vice versa: an author's
2826    /// `:rate-limit "100/s"` would omit the value-shape gate while the
2827    /// emptiness predicate still classified the policy as non-empty).
2828    /// Lifting the resolution to a typed method on the substrate
2829    /// primitive means every downstream consumer of the Aplicacao's
2830    /// per-`:politicas` rate-limit surface reaches for exactly one
2831    /// typed dispatch — the resolver's accept-set migrates as a unit
2832    /// on any future axis addition.
2833    ///
2834    /// First `Option<Copy-composite-T>`-return accessor on the M3
2835    /// mesh-slot family — closes the last un-lifted per-`:politicas`
2836    /// scalar-value axis. Peer of the sibling per-`:politicas`
2837    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2838    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2839    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2840    /// "one typed dispatch on the substrate primitive, thin
2841    /// projections at each consumer" discipline extended onto the
2842    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2843    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2844    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2845    /// sub-accessors rather than a top-level accessor because
2846    /// consumers reach for the axes not the aggregate). Named
2847    /// `rate_limit()` to match the storage field's name; the
2848    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2849    /// §III.2 vocabulary the slot's docstring already carries.
2850    #[must_use]
2851    pub const fn rate_limit(&self) -> Option<RateLimit> {
2852        self.rate_limit
2853    }
2854
2855    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2856    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2857    /// declaration scalar accessor every consumer of the Aplicacao's
2858    /// per-`:politicas` breaker declaration keys off — returns the
2859    /// author-declared `:politicas :circuit-breaker` typed
2860    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2861    /// copied out of the typed slot's own `Option<CircuitBreaker>`
2862    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2863    /// by value; no borrow of `&self` past the call). `None` when the
2864    /// slot is absent (the "cluster default applies — typically 'no
2865    /// per-Aplicacao breaker declaration, gateway-class per-listener
2866    /// default applies'" arm the future caixa-mesh
2867    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2868    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2869    /// arm reads this predicate too, so an authored-but-unset
2870    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2871    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2872    /// that omits the slot).
2873    ///
2874    /// The `:politicas :circuit-breaker` slot carries the
2875    /// "per-Aplicacao consecutive-transient-failure trip declaration"
2876    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2877    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2878    /// zero-floor rejected through
2879    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2880    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2881    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2882    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2883    /// canonical-form pinned through
2884    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2885    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2886    /// bijection the future `CiliumClusterwideEnvoyConfig`
2887    /// per-`:politicas` overlay emits. Every downstream consumer that
2888    /// reads the breaker declaration keys off this scalar (the
2889    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2890    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2891    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2892    /// that brackets `cb.max_failures()` against
2893    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2894    /// [`POLICY_BREAKER_WINDOW_MAX`] via
2895    /// [`crate::render::require_positive_canonical_bounded_duration`],
2896    /// the future M4 per-Aplicacao Envoy reconciler materialization
2897    /// pass, the future per-`:contratos`-edge breaker override the
2898    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2899    ///
2900    /// Prior to this lift the `.circuit_breaker` field was accessed
2901    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2902    /// `self.circuit_breaker.is_none()` arm and the
2903    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2904    /// bind — two open-coded field-accesses that expressed no
2905    /// compile-time link back to the typed slot. A future extension of
2906    /// the `:politicas :circuit-breaker` axis to a richer author
2907    /// surface — a per-`:contratos`-edge breaker override the operator
2908    /// pins through a future `:contratos :circuit-breaker` slot the
2909    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2910    /// breaker-default overlay the M4 CR materializer resolves per-CR,
2911    /// a promotion of the plain `(max_failures, window)` scalar pair to
2912    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2913    /// sub-block once Envoy's `outlier_detection` grows the peer
2914    /// ejection-percentage / ejection-time axes — would have had to be
2915    /// threaded through both open-coded copies in lockstep or the
2916    /// emptiness predicate and the validate gate would silently
2917    /// disagree on which breaker declaration a given [`MeshPolicy`]
2918    /// resolves to (a `:politicas` block whose only axis is a
2919    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2920    /// the validate path silently read a drifted other value, or vice
2921    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2922    /// "60s"))` would omit the value-shape gate while the emptiness
2923    /// predicate still classified the policy as non-empty). Lifting
2924    /// the resolution to a typed method on the substrate primitive
2925    /// means every downstream consumer of the Aplicacao's
2926    /// per-`:politicas` breaker surface reaches for exactly one typed
2927    /// dispatch — the resolver's accept-set migrates as a unit on any
2928    /// future axis addition.
2929    ///
2930    /// Second `Option<Copy-composite-T>`-return accessor on the M3
2931    /// mesh-slot family (sibling of the peer per-`:politicas`
2932    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2933    /// on the same composite-Copy shape, and of the sibling per-
2934    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2935    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2936    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2937    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2938    /// same "one typed dispatch on the substrate primitive, thin
2939    /// projections at each consumer" discipline extended onto the last
2940    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2941    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2942    /// match the storage field's name; the accessor's identity maps
2943    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2944    /// docstring already carries. Closes the last unlifted
2945    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2946    /// reader now routes through a typed dispatch on the substrate
2947    /// primitive.
2948    #[must_use]
2949    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2950        self.circuit_breaker
2951    }
2952}
2953
2954#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2955#[serde(rename_all = "camelCase")]
2956pub struct CircuitBreaker {
2957    pub max_failures: u32,
2958    #[serde(with = "supervisor::duration_codec_required")]
2959    pub window: Duration,
2960}
2961
2962impl CircuitBreaker {
2963    /// Substrate-canonical per-`:politicas :circuit-breaker`
2964    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2965    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2966    /// breaker trip-count keys off — returns the author-declared
2967    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2968    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2969    /// so the accessor returns by value; no borrow of `&self` past the
2970    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2971    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2972    /// axis; a `CircuitBreaker` past pattern-match is definitionally
2973    /// present, and its `:max-failures` field carries the trip count as a
2974    /// required-axis scalar).
2975    ///
2976    /// The `:politicas :circuit-breaker :max-failures` axis carries the
2977    /// "consecutive-transient-failure trip threshold" contract
2978    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2979    /// (zero-floor rejected through
2980    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2981    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2982    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2983    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2984    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2985    /// Every downstream consumer that reads the trip threshold keys off
2986    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2987    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2988    /// canonical `require_positive_bounded_u32` helper, the future M4
2989    /// per-Aplicacao Envoy config reconciler materialization pass, the
2990    /// future per-`:contratos`-edge breaker-override overlay the
2991    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2992    ///
2993    /// Prior to this lift the `.max_failures` field was accessed inline
2994    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2995    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2996    /// open-coded field-access that expressed no compile-time link back
2997    /// to the typed sub-struct axis. A future extension of the
2998    /// `:max-failures` axis to a richer author surface — a
2999    /// per-`:contratos`-edge breaker override the operator pins through a
3000    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
3001    /// #3 roadmap acknowledges, a per-cluster max-failures-default
3002    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
3003    /// plain `u32` trip count to a richer
3004    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
3005    /// tuple once Envoy's `outlier_detection` block's peer axes come into
3006    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
3007    /// count arms — would have had to be threaded through every open-
3008    /// coded copy in lockstep or the validate gate and the future M4
3009    /// emit path would silently disagree on which trip threshold a given
3010    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
3011    /// would satisfy validate while the emit path silently read a drifted
3012    /// other value, or vice versa: a validated typed slot would land at
3013    /// the emit boundary as a no-op breaker whose trip threshold is
3014    /// structurally never reached). Lifting the resolution to a typed
3015    /// method on the substrate primitive means every downstream consumer
3016    /// of the Aplicacao's per-`:politicas :circuit-breaker`
3017    /// trip-threshold surface reaches for exactly one typed dispatch —
3018    /// the resolver's accept-set migrates as a unit on any future axis
3019    /// addition.
3020    ///
3021    /// First sub-struct scalar accessor on the M3 mesh-slot family
3022    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
3023    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
3024    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
3025    /// closes the last unlifted per-`:politicas` scalar-value axis after
3026    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
3027    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
3028    /// Same "one typed dispatch on the substrate primitive, thin
3029    /// projections at each consumer" discipline the peer
3030    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3031    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3032    /// [`Membro::versao_requirement`] (a40b0e3),
3033    /// [`Entrada::destination`] (6db982c) accessors carry on their
3034    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
3035    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
3036    /// match the storage field's name; the accessor's identity maps onto
3037    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3038    /// docstring already carries.
3039    #[must_use]
3040    pub const fn max_failures(&self) -> u32 {
3041        self.max_failures
3042    }
3043
3044    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
3045    /// Envoy-outlier-detection rolling-observation-interval scalar
3046    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3047    /// breaker rolling-window duration keys off — returns the
3048    /// author-declared `:politicas :circuit-breaker :window` typed
3049    /// `Duration` verbatim, copied out of the typed slot's own
3050    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
3051    /// by value; no borrow of `&self` past the call). Non-optional (the
3052    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
3053    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
3054    /// `CircuitBreaker` past pattern-match is definitionally present,
3055    /// and its `:window` field carries the rolling-observation interval
3056    /// as a required-axis scalar).
3057    ///
3058    /// The `:politicas :circuit-breaker :window` axis carries the
3059    /// "consecutive-transient-failure rolling-observation interval"
3060    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3061    /// `Duration` accept-set (zero-floor rejected through
3062    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
3063    /// residue rejected through
3064    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
3065    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
3066    /// Envoy `outlier_detection.interval` per-cluster
3067    /// ejection-observation-interval scalar (equivalently the future
3068    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3069    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3070    /// consumer that reads the rolling-observation interval keys off
3071    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3072    /// integer-millisecond canonical-form + cap bracket at
3073    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
3074    /// [`crate::render::require_positive_canonical_bounded_duration`]
3075    /// helper, the future M4 per-Aplicacao Envoy config reconciler
3076    /// materialization pass, the future per-`:contratos`-edge
3077    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3078    /// acknowledges).
3079    ///
3080    /// Prior to this lift the `.window` field was accessed inline at
3081    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
3082    /// `require_positive_canonical_bounded_duration(cb.window, …)`
3083    /// call — one open-coded field-access that expressed no compile-
3084    /// time link back to the typed sub-struct axis. A future extension
3085    /// of the `:window` axis to a richer author surface — a
3086    /// per-`:contratos`-edge window override the operator pins through
3087    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
3088    /// #3 roadmap acknowledges, a per-cluster window-default overlay
3089    /// the M4 CR materializer resolves per-CR, a promotion of the plain
3090    /// `Duration` observation interval to a richer
3091    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
3092    /// once Envoy's `outlier_detection` block's peer axes come into
3093    /// scope, a per-Envoy-cluster minimum-request-volume gate before
3094    /// the window arms — would have had to be threaded through every
3095    /// open-coded copy in lockstep or the validate gate and the future
3096    /// M4 emit path would silently disagree on which observation
3097    /// interval a given [`CircuitBreaker`] resolves to (an author's
3098    /// `:window "60s"` would satisfy validate while the emit path
3099    /// silently read a drifted other value, or vice versa: a validated
3100    /// typed slot would land at the emit boundary as a breaker whose
3101    /// observation window is structurally so wide that no realistic
3102    /// failure-rate shape can trip it). Lifting the resolution to a
3103    /// typed method on the substrate primitive means every downstream
3104    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
3105    /// observation-window surface reaches for exactly one typed
3106    /// dispatch — the resolver's accept-set migrates as a unit on any
3107    /// future axis addition.
3108    ///
3109    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
3110    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
3111    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
3112    /// required-axis, extended onto the per-sub-struct required-`Duration`
3113    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
3114    /// axis. Same "one typed dispatch on the substrate primitive, thin
3115    /// projections at each consumer" discipline the peer
3116    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3117    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3118    /// [`Membro::versao_requirement`] (a40b0e3),
3119    /// [`Entrada::destination`] (6db982c) accessors carry on their
3120    /// respective per-mesh-slot-atom scalar-value axes, extended onto
3121    /// the per-sub-struct required-`Duration` axis. Named `window()` to
3122    /// match the storage field's name; the accessor's identity maps onto
3123    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3124    /// docstring already carries.
3125    #[must_use]
3126    pub const fn window(&self) -> Duration {
3127        self.window
3128    }
3129}
3130
3131#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3132pub struct RateLimit {
3133    /// Requests per window.
3134    pub rate: u32,
3135    /// Window duration.
3136    pub window: Duration,
3137}
3138
3139impl RateLimit {
3140    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
3141    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
3142    /// every consumer of the Aplicacao's per-`:contratos`-edge
3143    /// rate-limit-bucket capacity keys off — returns the author-declared
3144    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
3145    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
3146    /// returns by value; no borrow of `&self` past the call). Non-optional
3147    /// (the surrounding `Option<RateLimit>` is the "slot present?"
3148    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
3149    /// `RateLimit` past pattern-match is definitionally present, and its
3150    /// `:rate` field carries the token-bucket capacity as a required-axis
3151    /// scalar).
3152    ///
3153    /// The `:politicas :rate-limit` `:rate` axis carries the
3154    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
3155    /// the typed slot's `u32` accept-set (zero-floor rejected through
3156    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
3157    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
3158    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
3159    /// token-bucket-capacity scalar (equivalently the future
3160    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3161    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3162    /// consumer that reads the token-bucket capacity keys off this
3163    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3164    /// cap bracket that gates on the canonical
3165    /// [`crate::render::require_positive_bounded_u32`] helper, the
3166    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3167    /// emits the `<n>/<s|m|h>` author surface, the future M4
3168    /// per-Aplicacao Envoy config reconciler materialization pass, the
3169    /// future per-`:contratos`-edge rate-limit-override overlay the
3170    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3171    ///
3172    /// Prior to this lift the `.rate` field was accessed inline at three
3173    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
3174    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
3175    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
3176    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
3177    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
3178    /// field-accesses that expressed no compile-time link back to the
3179    /// typed sub-struct axis. A future extension of the `:rate` axis
3180    /// to a richer author surface — a per-`:contratos`-edge rate
3181    /// override the operator pins through a future `:contratos :rate`
3182    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
3183    /// per-cluster rate-default overlay the M4 CR materializer resolves
3184    /// per-CR, a promotion of the plain `u32` token capacity to a
3185    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
3186    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3187    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
3188    /// before the token arms — would have had to be threaded through
3189    /// every open-coded copy in lockstep or the validate gate, the
3190    /// codec's render path, and the future M4 emit path would silently
3191    /// disagree on which token capacity a given [`RateLimit`] resolves
3192    /// to (an author's `:rate-limit "100/s"` would satisfy validate
3193    /// while the render / emit paths silently read a drifted other
3194    /// value, or vice versa: a validated typed slot would land at the
3195    /// emit boundary as a no-op limiter whose token capacity is
3196    /// structurally so high that no realistic per-edge traffic shape
3197    /// can drain it). Lifting the resolution to a typed method on the
3198    /// substrate primitive means every downstream consumer of the
3199    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
3200    /// reaches for exactly one typed dispatch — the resolver's
3201    /// accept-set migrates as a unit on any future axis addition.
3202    ///
3203    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
3204    /// in shape to the peer per-`CircuitBreaker`
3205    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
3206    /// on the peer per-sub-struct required-axis, extended onto the
3207    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
3208    /// required-axis scalar" projection pattern the sibling
3209    /// [`RateLimit::window`] future lift folds on. Same "one typed
3210    /// dispatch on the substrate primitive, thin projections at each
3211    /// consumer" discipline the peer [`WitContract::source`] /
3212    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
3213    /// (0804823), [`Membro::nome`] (4a32abf),
3214    /// [`Membro::versao_requirement`] (a40b0e3),
3215    /// [`Entrada::destination`] (6db982c),
3216    /// [`CircuitBreaker::max_failures`] (3a74062),
3217    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
3218    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
3219    /// to match the storage field's name; the accessor's identity maps
3220    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3221    /// docstring already carries.
3222    #[must_use]
3223    pub const fn rate(&self) -> u32 {
3224        self.rate
3225    }
3226
3227    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
3228    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
3229    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3230    /// rate-limit-bucket refill period keys off — returns the
3231    /// author-declared `:politicas :rate-limit` typed `Duration`
3232    /// verbatim, copied out of the typed slot's own `Duration` storage
3233    /// (`Duration` is `Copy`, so the accessor returns by value; no
3234    /// borrow of `&self` past the call). Non-optional (the surrounding
3235    /// `Option<RateLimit>` is the "slot present?" projection at the
3236    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
3237    /// pattern-match is definitionally present, and its `:window`
3238    /// field carries the token-bucket refill period as a required-axis
3239    /// scalar).
3240    ///
3241    /// The `:politicas :rate-limit` `:window` axis carries the
3242    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
3243    /// — the typed slot's `Duration` accept-set (constrained to the
3244    /// three canonical windows `{1s, 60s, 3600s}` the
3245    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
3246    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
3247    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
3248    /// per-cluster token-bucket-refill-period scalar (equivalently the
3249    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3250    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3251    /// consumer that reads the token-bucket refill period keys off
3252    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
3253    /// canonical-window gate that keys off
3254    /// [`is_canonical_rate_limit_window`], the
3255    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3256    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
3257    /// [`rate_limit_window_unit`] and non-canonical fallback via
3258    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
3259    /// reconciler materialization pass, the future per-`:contratos`-
3260    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
3261    /// roadmap acknowledges).
3262    ///
3263    /// Prior to this lift the `.window` field was accessed inline at
3264    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
3265    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
3266    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
3267    /// error-payload construction on refusal, and the two
3268    /// [`rate_limit_codec::render`] arms
3269    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
3270    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
3271    /// open-coded field-accesses that expressed no compile-time link
3272    /// back to the typed sub-struct axis. A future extension of the
3273    /// `:window` axis to a richer author surface — a per-`:contratos`-
3274    /// edge window override the operator pins through a future
3275    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
3276    /// acknowledges, a per-cluster window-default overlay the M4 CR
3277    /// materializer resolves per-CR, a promotion of the plain
3278    /// `Duration` refill period to a richer
3279    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
3280    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3281    /// axis comes into scope, an addition of a `"d"` day suffix once
3282    /// Envoy's `rate_limit_action` grows daily-bucket support — would
3283    /// have had to be threaded through every open-coded copy in
3284    /// lockstep or the validate gate, the codec's render path, and
3285    /// the future M4 emit path would silently disagree on which
3286    /// refill period a given [`RateLimit`] resolves to (an author's
3287    /// `:rate-limit "100/s"` would satisfy validate while the render
3288    /// / emit paths silently read a drifted other value, or vice
3289    /// versa: a validated typed slot would land at the emit boundary
3290    /// as a limiter whose refill period is structurally so long that
3291    /// no realistic per-edge traffic shape stays inside the token
3292    /// budget). Lifting the resolution to a typed method on the
3293    /// substrate primitive means every downstream consumer of the
3294    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
3295    /// reaches for exactly one typed dispatch — the resolver's
3296    /// accept-set migrates as a unit on any future axis addition.
3297    ///
3298    /// Second sub-struct scalar accessor on the `RateLimit` axis —
3299    /// sibling in shape to the just-landed [`RateLimit::rate`]
3300    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
3301    /// required-axis, extended onto the per-sub-struct
3302    /// required-`Duration` axis; closes the last unlifted
3303    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
3304    /// per-sub-struct accessor coverage is now complete across both
3305    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
3306    /// the substrate primitive, thin projections at each consumer"
3307    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
3308    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
3309    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
3310    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
3311    /// [`Membro::nome`] (4a32abf),
3312    /// [`Membro::versao_requirement`] (a40b0e3),
3313    /// [`Entrada::destination`] (6db982c) accessors carry on their
3314    /// respective per-mesh-slot-atom scalar-value axes. Named
3315    /// `window()` to match the storage field's name; the accessor's
3316    /// identity maps onto the canonical MESH-COMPOSITION §III.2
3317    /// vocabulary the slot's docstring already carries.
3318    #[must_use]
3319    pub const fn window(&self) -> Duration {
3320        self.window
3321    }
3322
3323    /// Recognize this rate-limit's `:window` as a canonical
3324    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
3325    /// exactly matches one of the three closed-set arm-Durations
3326    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
3327    /// non-canonical magnitude the codec's round-trip would break on
3328    /// (sub-second residue, or a second-magnitude outside the set
3329    /// [`RateLimitUnit::ALL`] enumerates).
3330    ///
3331    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
3332    /// returns `Some` here — the validate gate's
3333    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
3334    /// rejects every window this accessor returns `None` on. Downstream
3335    /// consumers past validate (the codec's [`rate_limit_codec::render`]
3336    /// path, the future M4 per-Aplicacao Envoy config reconciler's
3337    /// materialization pass, the future per-`:contratos`-edge rate-limit-
3338    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3339    /// acknowledges) that read the typed unit off a validated slot can
3340    /// pattern-match on the returned `Some` without re-checking
3341    /// canonicality at the consumer layer — the typed enum surface is
3342    /// the load-bearing carrier of the canonicality invariant.
3343    ///
3344    /// Preferred over the free [`is_canonical_rate_limit_window`]
3345    /// module-private helper at any call site that has the typed
3346    /// [`RateLimit`] in hand (the codec's `render` arm at
3347    /// [`rate_limit_codec::render`], the validate gate's canonical-form
3348    /// arm in [`AplicacaoSpec::validate_politicas`], any future
3349    /// per-`:contratos` edge-override overlay resolver): those consumers
3350    /// reach for the typed enum without going through the
3351    /// `.window()` scalar-projection layer, and get the enum value
3352    /// directly (which the codec's render arm can then format via
3353    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
3354    /// "typed sub-struct scalar accessor, one dispatch on the substrate
3355    /// primitive" discipline the sibling [`RateLimit::rate`] and
3356    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
3357    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
3358    /// projection axis (the third scalar accessor on the [`RateLimit`]
3359    /// axis, first typed-enum-return projection).
3360    ///
3361    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
3362    /// the canonical [`RateLimitUnit`] arm now carries the same
3363    /// `const`-eval-surface posture the sibling `pub const fn`
3364    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
3365    /// this typed sub-struct already carry, composing through the
3366    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
3367    /// reverse-resolver in `const` context. Any downstream substrate-
3368    /// side `const`-context consumer of the typed unit (a module-scope
3369    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
3370    /// invariant pin on a typed fixture, a future M4 admission-webhook
3371    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
3372    /// resolver over a typed [`RateLimit`], any future `const fn`
3373    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3374    /// the substrate primitive) now reaches the same typed dispatch on
3375    /// the substrate primitive at const-eval time as at runtime.
3376    ///
3377    /// Pinned load-bearing at the substrate-primitive level by
3378    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
3379    /// eval-surface pin via `const fn` wrapper).
3380    #[must_use]
3381    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
3382        RateLimitUnit::from_window(self.window)
3383    }
3384}
3385
3386/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
3387/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
3388/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
3389///
3390/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
3391/// the `:politicas :rate-limit` unit surface reads from
3392/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
3393/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
3394/// [`is_canonical_rate_limit_window`] predicate the
3395/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
3396/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
3397/// projection) now lives inside this typed enum's `match self` arms — a
3398/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
3399/// `rate_limit_action` grows daily-bucket support) is one new variant
3400/// plus the exhaustiveness arms on the four methods, so every consumer
3401/// picks it up by compile-time construction rather than a runtime
3402/// table-scan miss.
3403///
3404/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
3405/// scanned via `find_map` at every projection call — an untyped runtime
3406/// walk that carried no compile-time link between the parse arm's
3407/// accepted suffixes, the render arm's emitted suffixes, and the
3408/// validate gate's accepted windows. A future rate-limit-unit addition
3409/// that landed one row without threading through the other consumers
3410/// (or a copy-paste flip that collapsed two rows onto one suffix) would
3411/// silently split the accepted-set across the three consumers — the
3412/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
3413/// for a 24h window that parse can't round-trip, the validate gate
3414/// misses one canonical window. Lifting the pairs onto a typed
3415/// closed-set enum with exhaustive `match` arms makes any such
3416/// half-landed extension a caixa-core build error (the compiler enforces
3417/// arm coverage on every method), not a silent per-consumer drift
3418/// surfacing at apply time. Same "closed-set typed-enum discriminator"
3419/// discipline the sibling [`PlacementStrategy`] (cc8f749),
3420/// [`crate::supervisor::RestartStrategy`],
3421/// [`crate::supervisor::RestartPolicy`],
3422/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
3423/// closed-set typed enums carry on their respective closed-set axes —
3424/// extended onto the seventh closed-set typed-enum discriminator axis
3425/// on the caixa typed surface (the `:politicas :rate-limit :window`
3426/// canonical-unit axis).
3427#[derive(
3428    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3429)]
3430pub enum RateLimitUnit {
3431    /// 1-second window — canonical author-surface suffix `"s"`
3432    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3433    /// with a 1s magnitude.
3434    Second,
3435    /// 1-minute window — canonical author-surface suffix `"m"`
3436    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3437    /// with a 60s magnitude.
3438    Minute,
3439    /// 1-hour window — canonical author-surface suffix `"h"`
3440    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3441    /// with a 3600s magnitude.
3442    Hour,
3443}
3444
3445impl RateLimitUnit {
3446    /// Exhaustive iteration surface for every consumer that reads the
3447    /// full canonical-unit set (the byte-parity witness against the
3448    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
3449    /// webhook's accepted-suffix listing in its rejection body, any
3450    /// future round-trip fuzz harness). A future variant addition to
3451    /// [`RateLimitUnit`] extends this slice as a single edit and every
3452    /// consumer picks up the new entry by construction — the compiler-
3453    /// checked exhaustiveness on the sibling method `match` arms is the
3454    /// build-time guarantee that no arm forgets to grow.
3455    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
3456
3457    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
3458    /// string every `<n>/<unit>` rate-limit shape carries after its
3459    /// `/` separator. The single source of truth the codec's parse and
3460    /// render arms both dispatch on: the parse arm matches an incoming
3461    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
3462    /// output; the render arm emits the entry's `as_suffix` verbatim
3463    /// after the rate magnitude.
3464    #[must_use]
3465    pub const fn as_suffix(self) -> &'static str {
3466        match self {
3467            Self::Second => "s",
3468            Self::Minute => "m",
3469            Self::Hour => "h",
3470        }
3471    }
3472
3473    /// Canonical `Duration` for this unit — the token-bucket refill
3474    /// period the [`RateLimit::window`] axis carries when the surrounding
3475    /// slot's `:rate-limit` author surface named this unit.
3476    #[must_use]
3477    pub const fn window(self) -> Duration {
3478        Duration::from_secs(match self {
3479            Self::Second => 1,
3480            Self::Minute => 60,
3481            Self::Hour => 3_600,
3482        })
3483    }
3484
3485    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
3486    /// `None` when `suffix` is outside the closed-set arm-string set
3487    /// [`Self::as_suffix`] emits. The single `str → Self` projection
3488    /// [`rate_limit_codec::parse`] consumes.
3489    #[must_use]
3490    pub fn from_suffix(suffix: &str) -> Option<Self> {
3491        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
3492    }
3493
3494    /// Recognize a canonical rate-limit `Duration` as one of the three
3495    /// arms, or `None` when `window` carries sub-second residue or a
3496    /// second-magnitude outside the closed-set arm-window set
3497    /// [`Self::window`] emits. The single `Duration → Self` projection
3498    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
3499    /// both consume.
3500    ///
3501    /// `pub const fn` — the reverse `Duration → Self` projection now
3502    /// carries the same `const`-eval-surface posture the sibling
3503    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
3504    /// projection accessors on this closed-set typed enum already
3505    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
3506    /// typed-`RateLimit`-projection sibling composes through in `const`
3507    /// context. Routes byte-for-byte through the peer `pub const fn`
3508    /// [`Self::window`] canonical-`Duration` projection so any future
3509    /// arm-magnitude edit on the sibling accessor reaches this reverse
3510    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
3511    /// per-arm probes each dispatch through one `pub const fn` on the
3512    /// substrate primitive rather than a hand-authored per-arm second-
3513    /// magnitude literal that would silently drift on any future
3514    /// [`Self::window`] arm-magnitude edit.
3515    ///
3516    /// Prior to the `const` lift the body dispatched through
3517    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
3518    /// iterator-driven linear scan whose iterator methods
3519    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
3520    /// `PartialEq` dispatch each carry non-`const` bounds on stable
3521    /// Rust 1.94, so any downstream substrate-side `const`-context
3522    /// consumer of the reverse resolver (a module-scope
3523    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
3524    /// invariant pin on a typed fixture, a future M4
3525    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
3526    /// webhook `const fn` per-`:politicas` canonical-window floor over a
3527    /// typed [`RateLimit`] scalar, any future `const fn`
3528    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3529    /// the substrate primitive that wants to fan on the canonical unit
3530    /// at compile time) surfaced as a downstream E0015 far from the
3531    /// resolver's own declaration. The `pub const fn` posture closes
3532    /// the drift structurally at caixa-core build time.
3533    ///
3534    /// Pinned load-bearing at the substrate-primitive level by
3535    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
3536    /// eval-surface pin via `const fn` wrapper) and
3537    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
3538    /// (composition-witness pin against the peer `Self::window` scalar
3539    /// dispatch).
3540    #[must_use]
3541    pub const fn from_window(window: Duration) -> Option<Self> {
3542        if window.subsec_nanos() != 0 {
3543            return None;
3544        }
3545        // Route through the peer `pub const fn` [`Self::window`]
3546        // canonical-`Duration` projection so any future arm-magnitude
3547        // edit on the sibling accessor reaches this reverse resolver by
3548        // construction — the per-arm `secs` comparison keys off
3549        // `Duration::as_secs` (`pub const fn`), not a hand-authored
3550        // per-arm second-magnitude literal that would silently drift.
3551        let secs = window.as_secs();
3552        if secs == Self::Second.window().as_secs() {
3553            Some(Self::Second)
3554        } else if secs == Self::Minute.window().as_secs() {
3555            Some(Self::Minute)
3556        } else if secs == Self::Hour.window().as_secs() {
3557            Some(Self::Hour)
3558        } else {
3559            None
3560        }
3561    }
3562
3563    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
3564    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
3565    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
3566    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
3567    /// consumes.
3568    ///
3569    /// The peer `Duration → &'static str` axis folded onto the substrate
3570    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
3571    /// production consumers ([`rate_limit_codec::render`] and
3572    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
3573    /// migrated (61421a6): the free helper's `Duration → &str` projection
3574    /// is now the two-step composition
3575    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
3576    /// reads through the typed accessor. This lift closes the peer
3577    /// `&str → Duration` axis by folding the vestigial module-private
3578    /// `rate_limit_window_from_unit` delegate onto this associated method
3579    /// — the codec's parse arm and every future wire-side consumer of the
3580    /// `&str → Duration` projection (a future admission-webhook that
3581    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
3582    /// before it's promoted to a validated typed slot, a future
3583    /// `feira lint` shape-probe that reads the author-surface bytes
3584    /// verbatim) now reach for exactly one typed dispatch on the
3585    /// substrate primitive.
3586    ///
3587    /// Same "closed-set typed-enum discriminator with canonical
3588    /// projections per axis" discipline the sibling [`Self::as_suffix`]
3589    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
3590    /// methods carry — this associated method closes the fifth (and last
3591    /// unlifted) projection axis on the arm-table, so the closed-set enum
3592    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
3593    /// consumer of the `:politicas :rate-limit :window` axis reaches
3594    /// through. A future rate-limit-unit addition (a `"d"` day suffix
3595    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
3596    /// `"ms"` sub-second window once high-throughput per-edge policies
3597    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
3598    /// variant plus one arm per method — the compiler enforces
3599    /// exhaustiveness on every consumer's `match self` arms and picks
3600    /// the new unit up by construction across all five projections.
3601    #[must_use]
3602    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
3603        Self::from_suffix(suffix).map(Self::window)
3604    }
3605}
3606
3607/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
3608/// every consumer that formats a canonical rate-limit unit as user-
3609/// facing text (future M4 admission-webhook rejection bodies naming
3610/// the accepted-suffix set, future `feira app graph` per-`:politicas`
3611/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
3612/// codec's parse arm accepts and the render arm emits. Same
3613/// as_str-through-Display convergence discipline the sibling
3614/// [`PlacementStrategy`], [`crate::CaixaKind`],
3615/// [`crate::supervisor::RestartStrategy`], and
3616/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
3617impl std::fmt::Display for RateLimitUnit {
3618    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3619        f.write_str(self.as_suffix())
3620    }
3621}
3622
3623/// Upper-bound ceiling on the `:politicas :timeout` axis — every
3624/// validated [`MeshPolicy::timeout`] past
3625/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
3626/// (inclusive on both ends, integer-millisecond magnitudes by the
3627/// canonical-form gate immediately preceding).
3628///
3629/// The typed field is `Option<Duration>` (the zero-floor arm
3630/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
3631/// `Duration::ZERO`, and the canonical-form arm
3632/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
3633/// sub-millisecond residue), so a programmatic struct literal
3634/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
3635/// 24h) and the equivalent author-surface form
3636/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
3637/// integer-hour magnitude) both round-trip cleanly through serde — a
3638/// structurally unbounded `Duration` ceiling. A `:timeout` value far
3639/// above the documented production-playbook band (Envoy default `15s`,
3640/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
3641/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
3642/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
3643/// at `~3600s`) silently degenerates the mesh-policy contract: the
3644/// per-call deadline is structurally so long that no realistic
3645/// synchronous-`:contratos` traversal can reach it, so the typed slot
3646/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
3647/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
3648/// blocking" degenerates to a nominal-only contract on the
3649/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
3650/// the sibling `:politicas :retries` axis and the
3651/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
3652/// `:politicas :circuit-breaker :max-failures` axis — all three close
3653/// the "structurally unbounded ceiling on a typed `:politicas` axis"
3654/// footgun the prior zero-floor-and-canonical-form-only checks left
3655/// open.
3656///
3657/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3658/// shared duration codec emits (`"<n>h"` for any integer-hour
3659/// magnitude) — every value in the canonical authoring form's
3660/// `<integer><unit>` grammar at or below this cap renders to a clean
3661/// canonical string. The cap sits an order of magnitude above every
3662/// documented production-playbook recommendation band (Envoy default
3663/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
3664/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
3665/// configured maximum (`proxy_read_timeout` typical max `3600s`),
3666/// below the clearly-pathological "effectively no timeout" floor
3667/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
3668/// want for a long-running synchronous workflow, but a hard wall above
3669/// which the mesh-level deadline is structurally a non-deadline.
3670/// Lifted as a typed `pub const` so the bound has exactly one source
3671/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3672/// materializer's admission webhook and the caixa-mesh-side
3673/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3674/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3675/// other typed upper bound in this crate carries
3676/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3677/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3678/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3679/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3680pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
3681
3682/// Upper-bound ceiling on the `:politicas :retries` axis — every
3683/// validated [`MeshPolicy::retries`] past
3684/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
3685///
3686/// The typed slot is `Option<u32>` (`None` = no retries on transient
3687/// failure; `Some(0)` already rejected by the
3688/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
3689/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
3690/// .. }`) and the equivalent author-surface form
3691/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
3692/// serde / the codec — a structurally unbounded `u32` ceiling. The
3693/// runtime substrate that consumes the value (Envoy's
3694/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3695/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3696/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3697/// admission cap is 10) translates a four-billion-retry policy into a
3698/// thundering-herd amplification vector on transient failure — the
3699/// caller's one request fans out to `retries` server-side calls per
3700/// edge per traversal, multiplying load by `(retries+1)^depth` across
3701/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3702/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3703/// invariant on the retry axis; both belong at the typed-slot layer.
3704///
3705/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3706/// upstream mesh-policy schema that documents one) and sits above the
3707/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3708/// every documented production playbook): a value the author can
3709/// plausibly want, but a hard wall above which the policy is
3710/// structurally a footgun. Lifted as a typed `pub const` so the bound
3711/// has exactly one source of truth — a future axis reaching for the
3712/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3713/// materializer's admission webhook, the caixa-mesh-side
3714/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3715/// one place. Same shape every other typed upper bound in this crate
3716/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3717/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3718/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3719/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3720pub const POLICY_RETRIES_MAX: u32 = 10;
3721
3722/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3723/// axis — every validated [`CircuitBreaker::max_failures`] past
3724/// [`AplicacaoSpec::validate_politicas`] lies in
3725/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3726///
3727/// The typed field is `u32` (the zero-floor arm
3728/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3729/// `0` — a breaker that trips on the first call), so a programmatic
3730/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3731/// and the equivalent author-surface form
3732/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3733/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3734/// `max_failures` value far above the documented production-playbook
3735/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3736/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3737/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3738/// typical 5–50) silently disables the breaker's protection role:
3739/// the threshold is structurally so high that no realistic
3740/// failures-per-`:window` traffic shape can reach it, so the breaker
3741/// never trips and the typed slot becomes a no-op carried on every
3742/// emitted Envoy / Cilium L7 overlay. Pairs with the
3743/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3744/// axis — both close the "structurally unbounded `u32` ceiling on a
3745/// typed policy axis" footgun the prior zero-floor-only checks left
3746/// open.
3747///
3748/// The `1000` ceiling sits an order of magnitude above every
3749/// documented upstream production-playbook recommendation band (the
3750/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3751/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3752/// the clearly-pathological "effectively no protection"
3753/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3754/// plausibly want at hyperscale, but a hard wall above which the
3755/// policy is structurally a no-op. Lifted as a typed `pub const` so
3756/// the bound has exactly one source of truth — the future M4
3757/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3758/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3759/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3760/// one place. Same shape every other typed upper bound in this crate
3761/// carries ([`POLICY_RETRIES_MAX`],
3762/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3763/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3764/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3765pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3766
3767/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3768/// every validated [`CircuitBreaker::window`] past
3769/// [`AplicacaoSpec::validate_politicas`] lies in
3770/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3771/// integer-millisecond magnitudes by the canonical-form gate
3772/// immediately preceding).
3773///
3774/// The typed field is `Duration` (the zero-floor arm
3775/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3776/// `Duration::ZERO`, and the canonical-form arm
3777/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3778/// sub-millisecond residue), so a programmatic struct literal
3779/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3780/// and the equivalent author-surface form
3781/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3782/// integer-hour magnitude) both round-trip cleanly through serde — a
3783/// structurally unbounded `Duration` ceiling. A `:window` value far
3784/// above the documented production-playbook band (Hystrix
3785/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3786/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3787/// Istio `outlierDetection.interval` default `10s`, Envoy
3788/// `outlier_detection.interval` default `10s`, AWS App Mesh
3789/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3790/// breaker's role: a rolling-window failure counter whose window is
3791/// hours long is operationally a lifetime counter, the breaker's
3792/// "recent failures" memory is structurally so long that transient
3793/// failures are never forgotten, and the typed slot becomes a no-op
3794/// trigger that trips once and stays tripped for the lifetime of the
3795/// component carried on every emitted Envoy / Cilium L7 overlay.
3796///
3797/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3798/// shared duration codec emits (`"<n>h"` for any integer-hour
3799/// magnitude) — every value in the canonical authoring form's
3800/// `<integer><unit>` grammar at or below this cap renders to a clean
3801/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3802/// cap on the first typed-`Duration` `:politicas` axis: the two
3803/// duration-typed `:politicas` axes now share a single uniform top
3804/// edge so the next typed-slot wiring (the future caixa-mesh
3805/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3806/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3807/// admission webhook) reaches for either field knowing the value is
3808/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3809/// sits two orders of magnitude above every documented upstream
3810/// production-playbook recommendation band (Hystrix / resilience4j /
3811/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3812/// and below the clearly-pathological "rolling window degenerates to
3813/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3814/// author can plausibly want for a very-low-traffic long-tail
3815/// failure-detection window, but a hard wall above which the breaker's
3816/// rolling-window contract is structurally a lifetime-counter contract.
3817/// Lifted as a typed `pub const` so the bound has exactly one source
3818/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3819/// materializer's admission webhook and the caixa-mesh-side
3820/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3821/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3822/// other typed upper bound in this crate carries
3823/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3824/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3825/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3826/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3827/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3828pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3829
3830/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3831/// every validated [`RateLimit::rate`] past
3832/// [`AplicacaoSpec::validate_politicas`] lies in
3833/// `1..=POLICY_RATE_LIMIT_MAX`.
3834///
3835/// The typed field is `u32` (the zero-floor arm
3836/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3837/// zero-rate limit denies every request, the canonical "I forgot
3838/// that 0 means deny-everything" footgun), so a programmatic struct
3839/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3840/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3841/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3842/// round-trip cleanly through serde — a structurally unbounded `u32`
3843/// ceiling. The runtime substrate consuming the value (Envoy's
3844/// `local_rate_limit.token_bucket.max_tokens`, the future
3845/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3846/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3847/// rate-limit into a no-op rate-limiter: the bucket capacity is
3848/// structurally so high no realistic per-edge traffic shape can
3849/// drain it, the limiter never trips, and the typed slot becomes a
3850/// "rate-limit declared, no enforcement" footgun — the canonical
3851/// declared-but-inert shape every other `:politicas` cap arm
3852/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3853/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3854///
3855/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3856/// above every documented upstream production-playbook recommendation
3857/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3858/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3859/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3860/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3861/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3862/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3863/// `u32::MAX`): a value the author can plausibly want at hyperscale
3864/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3865/// /h-window arm), but a hard wall above which the policy is
3866/// structurally a no-op carried verbatim on every emitted Envoy /
3867/// Cilium L7 overlay. The cap brackets all three canonical windows
3868/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3869/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3870/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3871/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3872/// has exactly one source of truth — the future M4
3873/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3874/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3875/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3876/// one place. Same shape every other typed upper bound in this crate
3877/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3878/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3879/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3880/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3881/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3882/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3883pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3884
3885// `:entrada :host` total-length and per-label cap axes route through
3886// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3887// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3888// pair of aplicacao-private aliases the previous `validate_entrada_host`
3889// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3890// = 63`) were structurally the same K8s Gateway API v1 Hostname
3891// admission-schema bounds — the total-length cap on the OpenAPI
3892// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3893// same regex — that the peer axes at the caixa-core::render level pin,
3894// so hoisting both readers onto the shared lifted constants closes the
3895// third-occurrence duplication threshold structurally: the M4
3896// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3897// label validator, the future per-`Certificate` SAN emitter, and every
3898// other per-Gateway-API-Hostname landing site reach the same one place
3899// as the `:entrada :host` gate does — no per-axis alias drift surface
3900// between them, by construction.
3901
3902/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
3903/// extractor expression — the upper bound `validate_placement_shard_key`
3904/// enforces on every well-shaped shard-key past validate. The realistic
3905/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3906/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3907/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3908/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3909/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3910/// in `:shard-key`" footgun at validate time rather than at the future
3911/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3912const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3913
3914/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3915/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3916/// that maps the shared parser-shaped reason into the
3917/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3918/// is self-locating (the offending `caixa:` is named verbatim) and
3919/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3920/// fix it in one edit. Same diagnostic shape as
3921/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3922/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3923fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3924    // Empty is already gated by `MembroCaixaEmpty` at the call site;
3925    // re-checking here keeps the predicate usable from any future
3926    // call site (the M4 CR materializer) without an empty-check
3927    // footgun. The shared
3928    // [`crate::render::require_valid_dns_1123_label`] helper brackets
3929    // the empty-first + shape cascade every peer name axis
3930    // (`:placement :clusters`, `:placement :affinity`, `:contratos
3931    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3932    // `:upgrade-from :module`) routes through, so drift between the
3933    // eight axes' accepted DNS-1123-label sets is structurally
3934    // impossible.
3935    crate::render::require_valid_dns_1123_label(
3936        caixa,
3937        || AplicacaoError::MembroCaixaEmpty,
3938        |reason| AplicacaoError::MembroCaixaInvalid {
3939            caixa: caixa.to_string(),
3940            reason,
3941        },
3942    )
3943}
3944
3945/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3946/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3947/// that maps the shared parser-shaped reason into the
3948/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3949///
3950/// Cluster names land in DNS-1123-label territory across every consumer:
3951/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3952/// the `lareira-fleet-programs` aggregator applies to scope programs to
3953/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3954/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3955/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3956/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3957/// side schema enforces the DNS-1123 label rule on admission; a
3958/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3959/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3960/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3961/// only gate and the failure surfaces as a no-match at filter time —
3962/// the workload doesn't land in the named cluster, with no diagnostic
3963/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3964/// build time mirrors the `:membros :caixa` value-shape trajectory
3965/// (3f9d7a0) on the peer name axis.
3966///
3967/// The diagnostic carries the offending `cluster:` verbatim plus a
3968/// parser-shaped `reason:` naming the specific violation, so the
3969/// author can grep their caixa.lisp for `:clusters` and fix it in
3970/// one edit. Same diagnostic shape as
3971/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3972fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3973    // Empty is already gated by `PlacementClusterEmpty` at the call
3974    // site; re-checking here keeps the predicate usable from any
3975    // future call site (the M4 CR materializer's per-cluster validator)
3976    // without an empty-check footgun. Routes through the shared
3977    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3978    // name axes each land on.
3979    crate::render::require_valid_dns_1123_label(
3980        cluster,
3981        || AplicacaoError::PlacementClusterEmpty,
3982        |reason| AplicacaoError::PlacementClusterInvalid {
3983            cluster: cluster.to_string(),
3984            reason,
3985        },
3986    )
3987}
3988
3989/// Reject `:placement :affinity` hints whose shape can never legitimately
3990/// land in any downstream selector or label-keyed routing axis. Thin
3991/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3992/// shared parser-shaped reason into the
3993/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3994/// diagnostic is self-locating (the offending `:affinity` is named
3995/// verbatim) and the author can grep their caixa.lisp for
3996/// `:affinity "<hint>"` and fix it in one edit.
3997///
3998/// The `:affinity` slot carries a placement-engine hint — canonical
3999/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
4000/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
4001/// compression overlay and the future M4 placement-engine's per-hint
4002/// routing axis. Each downstream consumer (caixa-mesh's
4003/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
4004/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4005/// `spec.placement.affinity` admission rule, the future M4 per-hint
4006/// node-affinity / pod-affinity rule generator keying off the same
4007/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
4008/// selector) requires the value to be a DNS-1123 label — K8s label
4009/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
4010/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
4011/// admission rule the apiserver enforces.
4012///
4013/// Until this gate landed an `:affinity "DataLocality"` (the canonical
4014/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
4015/// Python-module-name leak), `:affinity "data.locality"` (the
4016/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
4017/// `:affinity "data-locality-"` (boundary-hyphen violation),
4018/// `:affinity "data locality"` (paste-from-doc whitespace),
4019/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
4020/// 64-byte over-cap slug silently passed the empty-only check and the
4021/// failure surfaced as a no-match at the M3 Adaptive compression
4022/// overlay's filter time (`placement.affinity` carried a malformed
4023/// value, no node matched, the workload landed on the default
4024/// heuristic) — the canonical "declared-but-inert" footgun mirroring
4025/// the empty-:affinity / empty-shard-key / zero-:politicas /
4026/// empty-:contratos-target gates already close on every other
4027/// declare-but-no-opinion axis. Lifting the rejection to a build-time
4028/// gate closes the fifth typed slot on the Aplicacao surface to land
4029/// on the canonical DNS-1123 label floor (after the four Servico-name
4030/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
4031/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
4032/// b0e8748).
4033///
4034/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
4035/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
4036/// validated values are guaranteed-accepted by the apiserver without
4037/// re-validation at any downstream renderer or admission layer.
4038fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
4039    // Empty is gated separately at the call site for a self-locating
4040    // diagnostic; re-checking here keeps the predicate usable from any
4041    // future call site (the M4 CR materializer's per-affinity
4042    // validator) without an empty-check footgun. Routes through the
4043    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4044    // peer name axes each land on.
4045    crate::render::require_valid_dns_1123_label(
4046        affinity,
4047        || AplicacaoError::PlacementAffinityEmpty,
4048        |reason| AplicacaoError::PlacementAffinityInvalid {
4049            affinity: affinity.to_string(),
4050            reason,
4051        },
4052    )
4053}
4054
4055/// Reject `:placement :shard-key` extractor expressions whose shape can
4056/// never legitimately drive the future M4 Akka-style cluster-sharding
4057/// reconciler's hash-extractor pass. Maps the per-byte / length checks
4058/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
4059/// diagnostic is self-locating (the offending `:shard-key` value is
4060/// named verbatim alongside the parser-shaped reason) and the author can
4061/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
4062/// edit.
4063///
4064/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
4065/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
4066/// expression naming the message property to hash on. The realistic
4067/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
4068/// property name; `$tenantId` — Akka entity-id placeholder;
4069/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
4070/// `${tenant}` — interpolation-style template) all sit in the printable
4071/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
4072/// multi-line blob landing in `:shard-key`, an embedded space from a
4073/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
4074/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
4075/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
4076/// check and the failure surfaces at the future M4 reconciler's hash
4077/// pass as a runtime extractor-evaluation error far from the source
4078/// `caixa.lisp`, with no field naming which member's `:shard-key`
4079/// carried the offending value.
4080///
4081/// The contract — the printable ASCII single-token intersection-floor
4082/// every Akka-style entity-id extractor implementation admits:
4083///
4084///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
4085///     peer DNS-1123-label-shaped `:placement :affinity` /
4086///     `:placement :clusters` identifier axes; realistic shard-keys sit
4087///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
4088///     blob footguns at validate time;
4089///   - every byte in the printable ASCII range `0x21..=0x7E` —
4090///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
4091///     `"$tenantId\n"` from paste-from-aligned-doc /
4092///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
4093///     `\x7F` — the canonical "embedded null from a copy-paste-binary
4094///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
4095///     un-Punycode-encoded IDN that round-trips inconsistently across
4096///     NFC/NFD normalization).
4097///
4098/// The accepted set is broader than the DNS-1123 label floor the peer
4099/// `:placement :clusters` / `:placement :affinity` axes use because the
4100/// `:shard-key` value is not a K8s `metadata.name` / label-selector
4101/// landing site; it's an extractor expression the future Akka-style
4102/// reconciler reads as a property reference. The realistic forms
4103/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
4104/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
4105/// but every Akka-style entity-id extractor parses. The
4106/// printable-ASCII-token floor accepts every shape any such extractor
4107/// would accept while rejecting the cross-implementation footguns
4108/// (whitespace breaks token boundaries; non-ASCII round-trips
4109/// inconsistently across YAML emitters and NFC/NFD normalization;
4110/// control characters silently corrupt the next read).
4111///
4112/// Until this gate landed `validate_placement` only refused the
4113/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
4114/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
4115/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
4116/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
4117/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
4118/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
4119/// control character from paste-from-binary, the 64-byte over-cap
4120/// paste-from-doc multi-line slug) silently passed validate. The future
4121/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
4122/// would then surface the malformed value either as a runtime
4123/// extractor-evaluation error (whitespace breaks the extractor's token
4124/// boundary, no match) or as a silently-different shard assignment
4125/// across YAML emitters (non-ASCII normalizes differently between the
4126/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
4127/// parser, the same entity ID maps to two distinct shards on a
4128/// re-render). Lifting the shape gate to caixa-build time makes the
4129/// extractor-floor invariant a structural property of every validated
4130/// `Placement`: every `Sharded` placement past `validate_placement` has
4131/// a `:shard-key` the future M4 reconciler can hash without
4132/// re-validating at the runtime layer.
4133///
4134/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
4135/// [`AplicacaoError::ContratoSubjectInvalid`] /
4136/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
4137/// on the peer `:contratos` payload axes — each lifts the
4138/// runtime-side parser's intersection-floor to a caixa-build-time gate,
4139/// closing the canonical "this passed validate but the runtime parser
4140/// rejected it" surprise.
4141fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
4142    // Empty is gated separately at the call site via the more
4143    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
4144    // re-checking here keeps the predicate usable from any future call
4145    // site (the M4 CR materializer's per-shard-key validator) without
4146    // an empty-check footgun.
4147    if key.is_empty() {
4148        return Err(AplicacaoError::ShardedKeyEmpty);
4149    }
4150    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
4151        return Err(AplicacaoError::ShardKeyInvalid {
4152            shard_key: key.to_string(),
4153            reason: format!(
4154                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
4155                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
4156                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
4157                 well under 32 bytes, this length suggests a paste-from-doc \
4158                 multi-line blob landed in `:shard-key` instead of a single-token \
4159                 extractor expression)",
4160                key.len()
4161            ),
4162        });
4163    }
4164    for &b in key.as_bytes() {
4165        if (0x21..=0x7E).contains(&b) {
4166            continue;
4167        }
4168        let reason = if b == b' ' {
4169            "contains a space (Akka-style entity-id extractor expressions are \
4170             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
4171             whitespace breaks the extractor's token boundary at the runtime layer, \
4172             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
4173             a multi-token blob in one `:shard-key` slot)"
4174                .to_string()
4175        } else if b == b'\t' {
4176            "contains a tab character (paste-from-aligned-doc footgun; the \
4177             Akka-style entity-id extractor reads `:shard-key` as a single-token \
4178             reference, embedded whitespace breaks the token boundary at the \
4179             runtime hash-extractor pass)"
4180                .to_string()
4181        } else if b == b'\n' || b == b'\r' {
4182            format!(
4183                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
4184                 paste-from-multiline-doc footgun; the Akka-style entity-id \
4185                 extractor reads `:shard-key` as a single-token reference, embedded \
4186                 newlines either truncate the value at the YAML emitter layer or \
4187                 break the token boundary at the runtime hash-extractor pass)"
4188            )
4189        } else if b < 0x20 || b == 0x7F {
4190            format!(
4191                "contains control character 0x{b:02x} (the canonical \
4192                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
4193                 control characters silently corrupt round-trip serialization \
4194                 across YAML emitters and break the runtime hash-extractor's \
4195                 single-token parser)"
4196            )
4197        } else {
4198            format!(
4199                "contains non-ASCII byte 0x{b:02x} (the canonical \
4200                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
4201                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
4202                 across YAML emitter implementations — the same entity ID can \
4203                 silently map to two distinct shards on a re-render. Use a \
4204                 printable-ASCII extractor expression like `tenantId`, \
4205                 `$tenantId`, or `metadata.tenantId`)"
4206            )
4207        };
4208        return Err(AplicacaoError::ShardKeyInvalid {
4209            shard_key: key.to_string(),
4210            reason,
4211        });
4212    }
4213    Ok(())
4214}
4215
4216/// Reject `:contratos :de` / `:contratos :para` values whose shape
4217/// can never legitimately match a validated `:membros :caixa`. Thin
4218/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4219/// shared parser-shaped reason into the
4220/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
4221/// diagnostic is self-locating (which slot — `:de` or `:para` — and
4222/// the offending value verbatim) and the author can grep their
4223/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
4224/// one edit.
4225///
4226/// Until this gate landed an empty or DNS-1123-malformed `:de` /
4227/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
4228/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
4229/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
4230/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
4231/// un-Punycode-encoded IDN) silently passed the per-axis check and
4232/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
4233/// membership lookup — diagnostic-framed as "this caixa is not in
4234/// `:membros`" when the root cause is "this `:de` value is not a
4235/// well-shaped Servico-name identifier and could never legitimately
4236/// match any validated member". Because every `:membros :caixa` is
4237/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
4238/// `names` HashSet structurally never contains an empty / malformed
4239/// string, so the membership lookup arm misframes every empty /
4240/// malformed input. Lifting the shape arm ahead of the lookup
4241/// preserves the legitimate `ContratoMemberMissing` arm (a
4242/// well-shaped `:de` that simply isn't in `:membros` — a phantom
4243/// reference) while routing every structurally-impossible-to-match
4244/// input through the narrower self-locating shape diagnostic.
4245///
4246/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4247/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
4248/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
4249/// to land on the canonical [`crate::render::is_dns_1123_label`]
4250/// floor. The `slot: &'static str` field carries the kebab-case
4251/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
4252/// per-callback-slot diagnostic shape and the
4253/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
4254/// (85f102c) cross-list-tag pattern.
4255fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
4256    // Routes through the shared
4257    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4258    // name axes each land on. The `slot: &'static str` field flows
4259    // through both error variants so the diagnostic names which
4260    // per-edge axis (`:de` vs `:para`) the offending value came from.
4261    crate::render::require_valid_dns_1123_label(
4262        caixa,
4263        || AplicacaoError::ContratoCaixaEmpty { slot },
4264        |reason| AplicacaoError::ContratoCaixaInvalid {
4265            slot,
4266            caixa: caixa.to_string(),
4267            reason,
4268        },
4269    )
4270}
4271
4272/// Reject `:entrada :para` values whose shape can never legitimately
4273/// match a validated `:membros :caixa`. Thin wrapper around
4274/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
4275/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
4276/// variant, so the diagnostic is self-locating (the offending
4277/// `:entrada :para` value is named verbatim) and the author can grep
4278/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
4279///
4280/// Until this gate landed an empty or DNS-1123-malformed `:entrada
4281/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
4282/// ADR typo, `:para "my_cart"` the Python-module-name leak,
4283/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
4284/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
4285/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
4286/// silently passed the per-axis check and surfaced as
4287/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
4288/// — diagnostic-framed as "this caixa is not in `:membros`" when the
4289/// root cause is "this `:entrada :para` value is not a well-shaped
4290/// Servico-name identifier and could never legitimately match any
4291/// validated member". Because every `:membros :caixa` is shape-
4292/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
4293/// `HashSet` structurally never contains an empty / malformed string,
4294/// so the membership lookup arm misframes every empty / malformed
4295/// input. Lifting the shape arm ahead of the lookup preserves the
4296/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
4297/// simply isn't in `:membros` — a phantom reference) while routing
4298/// every structurally-impossible-to-match input through the narrower
4299/// self-locating shape diagnostic.
4300///
4301/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4302/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
4303/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
4304/// fourth and last Aplicacao-level Servico-name reference axis to
4305/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
4306/// No `slot: &'static str` field because there is only one axis
4307/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
4308/// the simpler shape mirrors [`validate_membro_caixa`] and
4309/// [`validate_placement_cluster`].
4310fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
4311    // Empty is gated separately at the call site for a self-locating
4312    // diagnostic; re-checking here keeps the predicate usable from any
4313    // future call site (the M4 CR materializer's per-`:entrada`
4314    // validator) without an empty-check footgun. Routes through the
4315    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4316    // peer name axes each land on.
4317    crate::render::require_valid_dns_1123_label(
4318        para,
4319        || AplicacaoError::EntradaParaEmpty,
4320        |reason| AplicacaoError::EntradaParaInvalid {
4321            para: para.to_string(),
4322            reason,
4323        },
4324    )
4325}
4326
4327/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
4328/// would refuse at admission time. The contract — exactly the regex
4329/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
4330/// and `HTTPRoute.spec.hostnames[]`,
4331/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
4332/// (max length 253; per-label max length 63):
4333///
4334///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
4335///     uppercase, no underscore, no Unicode/IDN — IDN must be
4336///     pre-encoded as Punycode `xn--…` by the author);
4337///   - exactly one optional leading wildcard label (`*.`); a wildcard
4338///     in any non-leading label position is rejected;
4339///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
4340///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
4341///   - total length 1..=253 bytes;
4342///   - no IPv4 literal (Gateway API forbids IP literals);
4343///   - no scheme (`https://`, `http://`), no port (`:8080`), no
4344///     whitespace, no path (`/`).
4345///
4346/// Lifted as a typed gate (rather than an inline cascade in
4347/// `validate()`) so the contract lives in one place — every future
4348/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4349/// materializer's host validator, the future per-`:entrada` SAN
4350/// emission for cert-manager Certificates, the multi-`:entrada`
4351/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
4352/// for the same predicate, not its own. Same compounding shape as
4353/// `is_canonical_rate_limit_window` (808017c) and
4354/// [`WitTarget::label`] (previously the free `contrato_target_label`
4355/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
4356/// per-variant label match is compiler-checked-exhaustive).
4357///
4358/// The diagnostic carries the offending `host:` verbatim plus a
4359/// parser-shaped `reason:` naming the specific violation, so the
4360/// author can grep their caixa.lisp for `:host "<host>"` and fix it
4361/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
4362/// (9888b13).
4363fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
4364    // Empty is already gated by `EmptyEntradaHost` at the call site;
4365    // re-checking here keeps the predicate usable from any future
4366    // call site (M4 CR materializer) without an empty-check footgun.
4367    if host.is_empty() {
4368        return Err(AplicacaoError::EmptyEntradaHost);
4369    }
4370    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
4371        return Err(AplicacaoError::EntradaHostInvalid {
4372            host: host.to_string(),
4373            reason: format!(
4374                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
4375                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
4376                host.len(),
4377                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
4378            ),
4379        });
4380    }
4381    if host.contains("://") {
4382        return Err(AplicacaoError::EntradaHostInvalid {
4383            host: host.to_string(),
4384            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
4385                     Gateway API takes the bare hostname)"
4386                .to_string(),
4387        });
4388    }
4389    if host.contains('/') {
4390        return Err(AplicacaoError::EntradaHostInvalid {
4391            host: host.to_string(),
4392            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
4393                     matching is in `:entrada :paths`)"
4394                .to_string(),
4395        });
4396    }
4397    // After the `://` scheme-prefix and `/` path arms have ruled out the
4398    // two `:`-bearing shapes the Gateway API actively rejects with
4399    // location-shaped diagnostics, any remaining `:` in the host body is
4400    // either the canonical "I put the port in the `:host` slot"
4401    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
4402    // slot lives one axis away on the same `:entrada` block) or an
4403    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
4404    // Hostname forbids identically to the IPv4-literal arm below. Both
4405    // shapes silently fell through the `://` and `/` arms before this
4406    // lift and surfaced as a deep `label "<rest>:<port>" contains
4407    // invalid character ':'` diagnostic from the per-byte loop near the
4408    // bottom of this predicate, which named the offending byte but not
4409    // the canonical authoring fix — for the port case the author has to
4410    // know the `:entrada` block carries a separate `:port u16` slot
4411    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
4412    // move the value over; for the IPv6 case the author has to know
4413    // Gateway API v1 forbids IP literals across the board. The contract
4414    // doc-comment above already promises "no port (`:8080`)" verbatim
4415    // in the rejected-shape enumeration but the predicate's
4416    // implementation refused the `:` only as a side-effect of the
4417    // per-label `[a-z0-9-]` character-class loop; this arm brings the
4418    // implementation in line with the documented contract by surfacing
4419    // the canonical fix at the top-level shape gate, peer with how the
4420    // `://` arm names the scheme prefix and the `/` arm names the
4421    // `:entrada :paths` axis. Same compounding trajectory the recent
4422    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
4423    // — the typed slot's rejected set matches the apiserver's rejected
4424    // set, structurally, with a self-locating diagnostic at the
4425    // offending axis instead of a deep parser-shape leak.
4426    if host.contains(':') {
4427        return Err(AplicacaoError::EntradaHostInvalid {
4428            host: host.to_string(),
4429            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
4430                     slot — a separate `u16` axis on the same `:entrada` block, \
4431                     defaulting to 8080 — not in the host body; drop the `:<port>` \
4432                     suffix and author the bare hostname. If you intended an IPv6 \
4433                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
4434                     Hostname forbids IP literals identically to the IPv4-literal \
4435                     arm — use a DNS name)"
4436                .to_string(),
4437        });
4438    }
4439    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
4440    // predicate — the same single source of truth every peer
4441    // ASCII-whitespace scan in caixa-core flows through: the four
4442    // typed-magnitude codec sites (`limits::parse_byte_size` backing
4443    // `:limits :memory`, `limits::parse_duration` backing `:limits
4444    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
4445    // `aplicacao::rate_limit_codec::parse` backing `:politicas
4446    // :rate-limit`) and the shared duration codec
4447    // (`supervisor::duration_codec::parse`) backing `:supervisor
4448    // :restart-window` / `:politicas :timeout` / `:politicas
4449    // :circuit-breaker :window`. This landing closes the last string-typed
4450    // slot in caixa-core still calling `.bytes().any(|b|
4451    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
4452    // across every typed slot now shares one predicate, so a future
4453    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
4454    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
4455    // deliberately excluded from the peer non-ASCII predicate) can
4456    // extend at this shared site in one edit rather than seven
4457    // independent scans diverging over time. Naming the offending byte
4458    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
4459    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
4460    // the offending byte verbatim" discipline every peer codec site
4461    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
4462    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
4463    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
4464        return Err(AplicacaoError::EntradaHostInvalid {
4465            host: host.to_string(),
4466            reason: format!(
4467                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
4468                 Hostname is a single-token DNS name — leading, trailing, \
4469                 or embedded whitespace breaks the K8s apiserver's Hostname \
4470                 regex at admission time; the paste-from-aligned-doc / \
4471                 paste-from-shell-history / paste-from-CSV footgun silently \
4472                 lands a multi-token blob in `:entrada :host`. Strip every \
4473                 whitespace byte and author the bare hostname — space \
4474                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
4475                 refuse identically)"
4476            ),
4477        });
4478    }
4479    // Peer of the ASCII-whitespace scan above: route the non-ASCII
4480    // subset of Unicode `White_Space` through the shared
4481    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
4482    // single source of truth every peer non-ASCII-whitespace scan in
4483    // caixa-core flows through: `limits::parse_byte_size` (`:limits
4484    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
4485    // `limits::parse_millicores` (`:limits :cpu`),
4486    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
4487    // and `supervisor::duration_codec::parse` (`:supervisor
4488    // :restart-window` / `:politicas :timeout` / `:politicas
4489    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
4490    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
4491    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
4492    // paste-from-web-doc), or an EM-SPACE-split host
4493    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
4494    // survived this predicate's ASCII byte-scan (none of the UTF-8
4495    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
4496    // `u8::is_ascii_whitespace`), then landed on the per-label
4497    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
4498    // predicate with the generic `label "…" must start and end with an
4499    // alphanumeric` diagnostic — a "far from source at build-time"
4500    // leak that names the label-shape violation but not the
4501    // paste-from-typography origin the author actually needs to fix.
4502    // Peer with the four codec sites the 1b75b38 landing pinned: the
4503    // typed slot's diagnostic axis names the offending codepoint
4504    // (`U+XXXX`) verbatim rather than laundering the value through a
4505    // downstream label-shape arm, so the author can grep their
4506    // caixa.lisp for the invisible codepoint at the surfaced position
4507    // rather than eyeball a multi-byte host for embedded NBSP / LINE
4508    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
4509    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
4510    // drift between any two typed-slot sites' non-ASCII-whitespace
4511    // rejection set becomes a single-edit fix at the shared predicate
4512    // rather than N independent inline scans diverging over time, and
4513    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
4514    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
4515    // `char::is_whitespace`" class the peer non-ASCII predicate's
4516    // doc-comment names as the follow-up trajectory) extends at the
4517    // shared predicate in one edit rather than seven.
4518    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
4519        return Err(AplicacaoError::EntradaHostInvalid {
4520            host: host.to_string(),
4521            reason: format!(
4522                "contains non-ASCII Unicode whitespace character {ch:?} \
4523                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
4524                 single-token DNS name limited to `[a-z0-9-]` labels; \
4525                 the paste-from-typography footgun silently lands an \
4526                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
4527                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
4528                 `U+3000`, and every other member of the Unicode \
4529                 `White_Space` property outside the ASCII byte range) \
4530                 in `:entrada :host`, which the K8s apiserver's \
4531                 Hostname regex refuses at admission time far from the \
4532                 caixa.lisp source line. Strip every non-ASCII \
4533                 whitespace character and author the bare hostname \
4534                 with only ASCII bytes (write \"checkout.quero.cloud\" \
4535                 verbatim)",
4536                codepoint = ch as u32,
4537            ),
4538        });
4539    }
4540
4541    // Strip the optional single leading wildcard label *before* the
4542    // trailing-dot check so the bare `"*."` form surfaces the more
4543    // self-locating "wildcard without domain" diagnostic instead of
4544    // the generic "trailing dot" one.
4545    let (had_wildcard, rest) = match host.strip_prefix("*.") {
4546        Some(r) => (true, r),
4547        None => (false, host),
4548    };
4549    if had_wildcard && rest.is_empty() {
4550        return Err(AplicacaoError::EntradaHostInvalid {
4551            host: host.to_string(),
4552            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
4553        });
4554    }
4555    if rest.contains('*') {
4556        return Err(AplicacaoError::EntradaHostInvalid {
4557            host: host.to_string(),
4558            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
4559                     no inner or trailing `*` labels"
4560                .to_string(),
4561        });
4562    }
4563    if rest.ends_with('.') {
4564        return Err(AplicacaoError::EntradaHostInvalid {
4565            host: host.to_string(),
4566            reason: "must not have a trailing `.` (Gateway API hostnames are not \
4567                     fully-qualified with a root dot; the apiserver regex rejects \
4568                     trailing dots)"
4569                .to_string(),
4570        });
4571    }
4572
4573    // Reject pure IPv4 literals: four dot-separated labels, every
4574    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
4575    // literals as Hostnames.
4576    let labels: Vec<&str> = rest.split('.').collect();
4577    if labels.len() == 4
4578        && labels
4579            .iter()
4580            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
4581    {
4582        return Err(AplicacaoError::EntradaHostInvalid {
4583            host: host.to_string(),
4584            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
4585                     literals; use a DNS name)"
4586                .to_string(),
4587        });
4588    }
4589
4590    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
4591    // hyphen, with non-hyphen at both boundaries.
4592    for label in &labels {
4593        if label.is_empty() {
4594            return Err(AplicacaoError::EntradaHostInvalid {
4595                host: host.to_string(),
4596                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
4597            });
4598        }
4599        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
4600            return Err(AplicacaoError::EntradaHostInvalid {
4601                host: host.to_string(),
4602                reason: format!(
4603                    "label {label:?} exceeds DNS-1123 label max length of \
4604                     {cap} bytes (got {} bytes)",
4605                    label.len(),
4606                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
4607                ),
4608            });
4609        }
4610        let bytes = label.as_bytes();
4611        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
4612            return Err(AplicacaoError::EntradaHostInvalid {
4613                host: host.to_string(),
4614                reason: format!(
4615                    "label {label:?} must start and end with an alphanumeric \
4616                     (no leading or trailing `-`)"
4617                ),
4618            });
4619        }
4620        for &b in bytes {
4621            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
4622            if !valid {
4623                let msg = if b.is_ascii_uppercase() {
4624                    format!(
4625                        "label {label:?} contains uppercase character {ch:?} \
4626                         (Gateway API hostnames are lowercase-only; use {lower:?})",
4627                        ch = b as char,
4628                        lower = label.to_ascii_lowercase()
4629                    )
4630                } else if b == b'_' {
4631                    format!(
4632                        "label {label:?} contains `_` (Gateway API hostnames \
4633                         allow only `[a-z0-9-]`; use `-` instead)"
4634                    )
4635                } else {
4636                    format!(
4637                        "label {label:?} contains invalid character {ch:?} \
4638                         (Gateway API hostnames allow only `[a-z0-9-]`)",
4639                        ch = b as char
4640                    )
4641                };
4642                return Err(AplicacaoError::EntradaHostInvalid {
4643                    host: host.to_string(),
4644                    reason: msg,
4645                });
4646            }
4647        }
4648    }
4649    Ok(())
4650}
4651
4652/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
4653/// would refuse at admission time. Thin wrapper around
4654/// [`crate::render::is_gateway_api_http_path`] that maps the shared
4655/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
4656/// variant, preserving the more self-locating
4657/// [`AplicacaoError::EntradaPathEmpty`] /
4658/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
4659/// path fails those narrower invariants first.
4660///
4661/// The contract is the canonical HTTP-path grammar — `1..=
4662/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
4663/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
4664/// whitespace/control/non-ASCII bytes — shared with the
4665/// `:contratos :endpoint` axis through the lifted predicate so drift
4666/// between either landing site and the K8s apiserver-side
4667/// HTTPPathMatch.value OpenAPI schema is a build error visible at
4668/// the predicate, not a per-renderer "this passed validate but failed
4669/// admission" surprise. The diagnostic carries the offending `path:`
4670/// verbatim plus a parser-shaped `reason:` naming the specific
4671/// violation, so the author can grep their caixa.lisp for `:paths`
4672/// and fix it in one edit. Same diagnostic shape as
4673/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
4674/// axis.
4675fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
4676    // Empty and missing-leading-`/` are already gated at the call
4677    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
4678    // checking here keeps the per-axis narrower diagnostics in force
4679    // when the predicate is reached directly (and `is_gateway_api_http_path`
4680    // itself defends against `bytes[0]`-style indexing on empty
4681    // input).
4682    if path.is_empty() {
4683        return Err(AplicacaoError::EntradaPathEmpty);
4684    }
4685    if !path.starts_with('/') {
4686        return Err(AplicacaoError::EntradaPathNotAbsolute {
4687            path: path.to_string(),
4688        });
4689    }
4690    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
4691        AplicacaoError::EntradaPathInvalid {
4692            path: path.to_string(),
4693            reason,
4694        }
4695    })
4696}
4697
4698mod rate_limit_codec {
4699    // `Duration` is no longer named here — the codec routes through
4700    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4701    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4702    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4703    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4704    // closed-set enum's arm-table rather than through vestigial free-helper
4705    // delegates.
4706    use super::{RateLimit, RateLimitUnit};
4707    use serde::{Deserialize, Deserializer, Serializer};
4708
4709    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4710        match v {
4711            Some(rl) => s.serialize_str(&render(*rl)),
4712            None => s.serialize_none(),
4713        }
4714    }
4715
4716    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4717        let opt: Option<String> = Option::deserialize(d)?;
4718        match opt {
4719            None => Ok(None),
4720            Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
4721        }
4722    }
4723
4724    fn parse(s: &str) -> Result<RateLimit, String> {
4725        // Whitespace-rejection arm — peer with the leading-`+`
4726        // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
4727        // same canonical-form render-determinism axis. Until this gate
4728        // landed the parser silently tolerated leading / trailing /
4729        // internal whitespace via the top-level `s.trim()` and the
4730        // per-part `rate_str.trim()` / `unit.trim()` calls, so every
4731        // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
4732        // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
4733        // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
4734        // serde silently round-tripped to `"100/s"` on the next emit
4735        // (a *different* canonical string) — breaking the THEORY.md
4736        // Part V render-determinism contract on the same
4737        // canonical-form-drift axis the leading-`+` arm below (the
4738        // 4eeae98 predecessor) and the leading-zero arm below (the
4739        // 4f46830 predecessor) already close.
4740        //
4741        // The canonical author shape is `<integer>/<s|m|h>` with no
4742        // whitespace bytes anywhere — every string [`render`] emits
4743        // carries none, so the parser's accepted set must match for
4744        // serialize / deserialize to round-trip losslessly. This gate
4745        // makes the pre-existing `s.trim()` / `rate_str.trim()` /
4746        // `unit.trim()` calls below strict no-ops on the accepted set
4747        // (every byte-position match they would perform is now already
4748        // trimmed away by the accepted set itself), while the arm
4749        // surfaces every rejected whitespace-carrying shape with a
4750        // self-locating diagnostic naming the offending byte and the
4751        // canonical form the author intended, peer with every prior
4752        // canonical-form-drift arm on this codec.
4753        //
4754        // Routed through the lifted
4755        // [`crate::render::find_ascii_whitespace_byte`] predicate — the
4756        // same source of truth the four peer typed-magnitude codec
4757        // sites (`limits::parse_byte_size`, `limits::parse_duration`,
4758        // `limits::parse_millicores`, `supervisor::duration_codec`)
4759        // share. `u8::is_ascii_whitespace()` at the predicate covers
4760        // the five WhatWG-conformant ASCII whitespace bytes (space,
4761        // tab, LF, FF, CR); the "single lifted predicate" discipline
4762        // the peer non-ASCII arm below carries on the strictly-
4763        // complementary Unicode `White_Space` class extends here to
4764        // the ASCII byte set as well.
4765        if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
4766            return Err(format!(
4767                "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4768                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4769                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4770                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4771                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4772                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4773                 on first serialize — breaking the THEORY.md Part V render-determinism \
4774                 contract every typed slot carries. Strip every whitespace byte (write \
4775                 `\"100/s\"` verbatim)"
4776            ));
4777        }
4778        // Non-ASCII Unicode `White_Space` arm — the strictly-
4779        // complementary class the ASCII arm above cannot see.
4780        // `str::trim` at the top of every peer codec uses
4781        // `char::is_whitespace` (Unicode `White_Space`, strictly
4782        // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
4783        // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4784        // survives the byte-scan (its UTF-8 bytes are not in
4785        // `is_ascii_whitespace`), gets silently stripped by the
4786        // top-level `s.trim()` below, and the value round-trips
4787        // through `render` to a *different* canonical form
4788        // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
4789        // render-determinism contract every typed slot carries.
4790        // Closed here (`:politicas :rate-limit`) and at the three
4791        // peer codec sites (`limits::parse_byte_size`,
4792        // `limits::parse_duration`, `supervisor::duration_codec`)
4793        // through the shared
4794        // [`crate::render::find_non_ascii_whitespace_char`] predicate
4795        // — the "single lifted predicate across all four codec sites
4796        // in one follow-up run" the 24a8ad4 commit body's `Forward
4797        // compounding` bullet named as the next compounding step.
4798        if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
4799            return Err(format!(
4800                "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4801                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4802                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4803                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4804                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4805                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4806                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4807                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4808                 silently strips it at parse entry, and the value round-trips through \
4809                 `render` to a *different* canonical form (`\"100/s\"`) on first \
4810                 serialize — breaking the THEORY.md Part V render-determinism contract \
4811                 every typed slot carries. Strip every non-ASCII whitespace character \
4812                 (write `\"100/s\"` verbatim with only ASCII bytes)",
4813                cp = ch as u32
4814            ));
4815        }
4816        let s = s.trim();
4817        let (rate_str, unit) = s
4818            .split_once('/')
4819            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4820        let rate_trim = rate_str.trim();
4821        // The canonical authoring form for `:politicas :rate-limit` is
4822        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4823        // non-negative integer with no decimal point and no leading
4824        // sign, so the parser's accepted set must match for
4825        // serialize/deserialize to round-trip without canonical-form
4826        // drift. Until this gate landed the parser accepted any
4827        // `u32::from_str`-shaped magnitude — and current Rust
4828        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4829        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4830        // serde silently round-tripped to `"100/s"` on the next emit
4831        // (a *different* canonical string) — breaking the THEORY.md
4832        // Part V render-determinism contract on the fifth typed-codec
4833        // surface in caixa-core (peer with the four duration codecs the
4834        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4835        // already covered: `supervisor::duration_codec` backing three
4836        // typed-duration slots, `limits::parse_duration` backing
4837        // `:limits :wall-clock`, `limits::parse_byte_size` backing
4838        // `:limits :memory`). The fractional / decimal-shaped sibling
4839        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4840        // existing rejection arm, but the diagnostic is value-laundered
4841        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4842        // doesn't name the canonical-form remediation or the round-trip
4843        // drift the next emit would produce); this gate lifts the
4844        // fractional arm onto the same canonical-form diagnostic the
4845        // peer codecs carry.
4846        //
4847        // Strict canonical form: every byte of the magnitude is an
4848        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4849        // inputs the gate distinguishes "non-canonical-but-numeric"
4850        // (parses as f64 or i64 — surfaced with a self-locating
4851        // diagnostic naming the canonical authoring form and the
4852        // round-trip drift the rejected shape would produce on first
4853        // serialize) from "garbage" (parses as neither — surfaced with
4854        // the existing narrower `"not a u32"` wording so its
4855        // diagnostic shape remains stable for the parser-shape footgun
4856        // case).
4857        //
4858        // Routed through the lifted
4859        // [`crate::render::is_digit_only_magnitude`] predicate — the
4860        // same source of truth the four peer typed-magnitude codec
4861        // sites share.
4862        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4863        if !digit_only {
4864            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4865            if numeric {
4866                return Err(format!(
4867                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4868                     canonical authoring form for `:politicas :rate-limit` is \
4869                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4870                     with no decimal point and no leading `+` / `-` sign. A fractional / \
4871                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4872                     through `render` to a *different* canonical form (`\"1/s\"`, \
4873                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
4874                     THEORY.md Part V render-determinism contract every typed slot \
4875                     carries. Pick an integer rate that fits the desired window \
4876                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4877                ));
4878            }
4879            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4880        }
4881        // Leading-zero arm — peer with the prior `"+100/s"` arm above
4882        // (4eeae98's predecessor) on the same canonical-form
4883        // render-determinism axis. The digit-only gate accepts
4884        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4885        // them losslessly (= 100, 0, 7), but `render` emits the
4886        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4887        // a *different* canonical string on the next emit, breaking
4888        // the THEORY.md Part V render-determinism contract the same
4889        // way `"+100/s"` did before the leading-`+` arm landed. The
4890        // single-byte magnitude `"0"` itself round-trips losslessly
4891        // through `render` (`render(0)` emits `"0/s"`) — the
4892        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4893        // what refuses rate-zero authoring, so `"0/s"` stays in the
4894        // accepted set at this codec layer and the diagnostic
4895        // partitioning between canonical-form drift (this arm) and
4896        // semantic-zero (the downstream gate) remains stable.
4897        // Peer with the future leading-zero arms on the three peer
4898        // typed-magnitude codecs the trajectory acknowledges:
4899        // `supervisor::duration_codec`, `limits::parse_duration`,
4900        // `limits::parse_byte_size` — each carries the same
4901        // canonical-form-drift class today; this gate lands the
4902        // discipline on the fourth typed-magnitude codec in
4903        // caixa-core first because the peer `"+100/s"` arm above is
4904        // the closest predecessor on the trajectory.
4905        //
4906        // Routed through the lifted
4907        // [`crate::render::is_leading_zero_padded_magnitude`]
4908        // predicate — the same source of truth the four peer
4909        // typed-magnitude codec sites share.
4910        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4911            return Err(format!(
4912                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4913                 canonical authoring form for `:politicas :rate-limit` is \
4914                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4915                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4916                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4917                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4918                 first serialize — breaking the THEORY.md Part V render-determinism \
4919                 contract every typed slot carries. Strip the leading zeros (write \
4920                 `\"100/s\"` instead of `\"0100/s\"`)"
4921            ));
4922        }
4923        // The digit-only gate guarantees every byte is `[0-9]`, and
4924        // the leading-zero arm above guarantees the magnitude is
4925        // either the single byte `"0"` or starts with `[1-9]`, so
4926        // the only way `u32::from_str` can fail here is overflow
4927        // (the magnitude exceeds `u32::MAX`). Surface that with an
4928        // overflow-shaped wording so the diagnostic names the
4929        // offending magnitude verbatim rather than collapsing onto
4930        // the non-canonical arm. Same shape
4931        // `supervisor::duration_codec` (1c55a2a) carries on the peer
4932        // duration-codec axis.
4933        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4934            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4935        })?;
4936        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
4937        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
4938        // arm reads the `&str → Duration` projection through the
4939        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4940        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
4941        // with [`super::RateLimitUnit::window`]) rather than the vestigial
4942        // module-private `rate_limit_window_from_unit` free helper the
4943        // predecessor 61421a6 left as the last unlifted delegate on this
4944        // axis. One typed dispatch on the substrate primitive instead of
4945        // one runtime call through the free-helper delegate; the sole
4946        // production consumer of the `&str → Duration` axis (this parse
4947        // arm) now reaches for exactly one typed method on the closed-set
4948        // enum, sibling to the codec's render arm's
4949        // [`super::RateLimit::canonical_unit`] dispatch on the paired
4950        // `Duration → RateLimitUnit` axis and to the validate gate's
4951        // [`super::RateLimit::canonical_unit`] shape-probe on the
4952        // canonical-window axis. A future rate-limit-unit addition (a
4953        // `"d"` day suffix once Envoy's `rate_limit_action` grows
4954        // daily-bucket support, a `"ms"` sub-second window once
4955        // high-throughput per-edge policies come into scope per
4956        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
4957        // on the closed-set enum, and the compiler enforces exhaustiveness
4958        // on every consumer's `match self` arms — this parse arm's
4959        // accepted-suffix set, the render arm's emitted-suffix set, the
4960        // validate gate's canonical-window set, and every future
4961        // per-`:contratos`-edge rate-limit-override overlay all pick it up
4962        // by construction.
4963        let unit = unit.trim();
4964        let window = RateLimitUnit::window_from_suffix(unit)
4965            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4966        Ok(RateLimit { rate, window })
4967    }
4968
4969    fn render(rl: RateLimit) -> String {
4970        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4971        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4972        // this render arm reads the `Duration → RateLimitUnit` projection
4973        // through the substrate primitive [`super::RateLimit::canonical_unit`]
4974        // (returns `None` on every non-canonical window — the sub-second /
4975        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4976        // formats the returned typed enum through its
4977        // [`std::fmt::Display`] impl (which routes through
4978        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4979        // the substrate primitive instead of one runtime `find_map`
4980        // walk through the free-helper delegate chain
4981        // [`super::rate_limit_window_unit`] (the vestigial free helper's
4982        // sole production consumer was this arm; every other consumer of
4983        // the `Duration → unit` axis — the validate gate below and the
4984        // future M4 per-Aplicacao Envoy config reconciler — now reads
4985        // the same typed method).
4986        //
4987        // A future rate-limit-unit addition (a `"d"` day suffix once
4988        // Envoy's `rate_limit_action` grows daily-bucket support) is
4989        // one variant + one arm per method on the closed-set enum, and
4990        // the compiler enforces exhaustiveness on every consumer's
4991        // `match self` arms — the codec's `parse` accepted-suffix set,
4992        // this render arm's emitted-suffix set, the validate gate's
4993        // canonical-window set, and every future per-`:contratos`-edge
4994        // rate-limit-override overlay all pick it up by construction.
4995        if let Some(unit) = rl.canonical_unit() {
4996            format!("{}/{unit}", rl.rate())
4997        } else {
4998            // Defensive fallback for non-canonical windows. Note:
4999            // [`AplicacaoSpec::validate_politicas`] rejects any
5000            // non-canonical `:rate-limit :window` via
5001            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
5002            // a validated `RateLimit` never reaches this branch. The
5003            // emitted `<n>/<k>s` form is *not* round-trippable through
5004            // [`parse`] (which accepts only the closed-set
5005            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
5006            // explicit count) — the validate gate is what makes the
5007            // round-trip a structural property; this branch exists only
5008            // so a programmatic non-validated serialize doesn't panic.
5009            format!("{}/{}s", rl.rate(), rl.window().as_secs())
5010        }
5011    }
5012}
5013
5014// ── placement strategy ───────────────────────────────────────────────
5015
5016/// How the Aplicacao distributes across clusters. Three options:
5017///
5018/// - `SingleNode` — one cluster runs the app at a time; takeover on
5019///   death (Erlang/OTP distributed-app semantics).
5020/// - `Replicated` — every named cluster runs an instance (active-active).
5021/// - `Sharded` — entities distribute by hash key across clusters
5022///   (Akka cluster sharding).
5023#[derive(
5024    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
5025)]
5026pub enum PlacementStrategy {
5027    SingleNode,
5028    Replicated,
5029    Sharded,
5030}
5031
5032/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
5033/// distribution-strategy default for the `:placement :estrategia` axis —
5034/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
5035/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
5036/// so every substrate-side consumer that resolves "what
5037/// [`PlacementStrategy`] variant does an author-omitted `:placement
5038/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
5039/// primitive [`PlacementStrategy`].
5040///
5041/// The `:placement :estrategia` default axis has three production
5042/// consumers on the substrate side today: the [`Default for
5043/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
5044/// impl's struct-literal `estrategia` field, and the serde-side
5045/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
5046/// author-omitted `:placement :estrategia` scalar through the [`Default
5047/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
5048/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
5049/// impl and implicit `PlacementStrategy::default()` routes at the sibling
5050/// consumers, with no compile-time link back to the paired
5051/// [`crate::manifest::Caixa::aplicacao_view`] fold's
5052/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
5053/// production consumer that resolves an author-omitted `:placement` slot
5054/// (entirely omitted, not just the `:estrategia` scalar within a declared
5055/// `:placement` block) through [`Placement::default`] which then routes
5056/// through this same discriminator. A future coherent rebrand of the
5057/// `:placement :estrategia` default (a widening to `Sharded` once the
5058/// substrate discovers hash-keyed distribution as the more common
5059/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
5060/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
5061/// names, a per-cluster overlay the operator pins through a future
5062/// `:placement-overrides` slot) would have had to migrate a lifted
5063/// discriminator on one path and open-coded discriminators on the peers
5064/// in lockstep or the four consumers would silently drift out of
5065/// pairing. Lifting the resolution rule to a typed `pub const` on the
5066/// substrate primitive means the M3-mesh-canonical `:placement
5067/// :estrategia` default migrates as one unit on any future axis change.
5068///
5069/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
5070/// §II.2's active-active-across-every-named-cluster arm — the closest
5071/// canonical M3 production reference the substrate carries, matching the
5072/// caixa-mesh default axis every M3 renderer already keys off (a
5073/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
5074/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
5075/// under the substrate's fleet-programs aggregator without an explicit
5076/// `:placement :estrategia` override). The two alternatives the closed
5077/// [`PlacementStrategy::ALL`] accept-set carries
5078/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
5079/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
5080/// Akka-style hash-keyed distribution across clusters,
5081/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
5082/// postures an author declares explicitly, never a posture an omitted
5083/// slot should silently assume.
5084///
5085/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
5086/// exactly one source of truth on the `:placement :estrategia` axis, on
5087/// the same substrate-primitive lift discipline the sibling M2
5088/// per-supervisor default set carries
5089/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
5090/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
5091/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
5092/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
5093/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
5094/// ([`crate::render::DEFAULT_NAMESPACE`],
5095/// [`crate::render::DEFAULT_LIBRARY_NAME`],
5096/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
5097/// the M3 mesh-primitive-defining slot family to converge onto the
5098/// substrate-primitive-lift discipline the M2 supervisor-slot family
5099/// already carries end-to-end.
5100pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
5101
5102impl Default for PlacementStrategy {
5103    fn default() -> Self {
5104        // Route the [`Default for PlacementStrategy`] impl through the
5105        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
5106        // `pub const` rather than a raw `Self::Replicated` arm — one
5107        // source of truth for the M3-mesh-canonical active-active-
5108        // across-every-named-cluster `:placement :estrategia` default
5109        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
5110        // lift discipline the sibling M2 per-supervisor default set
5111        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
5112        // paired halves) carries end-to-end. Pinned by
5113        // `placement_strategy_default_routes_through_lifted_default`.
5114        PLACEMENT_ESTRATEGIA_DEFAULT
5115    }
5116}
5117
5118impl PlacementStrategy {
5119    /// Exhaustive iteration surface for every consumer that reads the
5120    /// full closed-set (the future M4 admission-webhook's accepted-
5121    /// strategy listing in its rejection body, a future `feira app
5122    /// placement --list` CLI-side surfacing of the accepted arm-set,
5123    /// any future round-trip fuzz harness). A future variant addition
5124    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
5125    /// names as a trajectory item) extends this slice as a single edit
5126    /// and every consumer picks up the new entry by construction — the
5127    /// compiler-checked exhaustiveness on the sibling method `match`
5128    /// arms is the build-time guarantee that no arm forgets to grow.
5129    /// Same shape as the sibling closed-set typed enums'
5130    /// [`RateLimitUnit::ALL`] (6bce03d) and
5131    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5132    /// surfaces — the third closed-set typed enum on the caixa surface
5133    /// to converge onto the same discipline.
5134    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
5135
5136    /// Canonical camelCase-schema discriminator scalar this variant
5137    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
5138    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
5139    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5140    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
5141    /// every substrate consumer that dispatches on the strategy (the
5142    /// `lareira-fleet-programs` aggregator, the future `app-operator`
5143    /// reconciler, the M3 Adaptive compression pass) reads the same
5144    /// byte-string the `Serialize` derive emits — the pin test in
5145    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
5146    /// asserts the two paths agree.
5147    #[must_use]
5148    pub const fn as_str(self) -> &'static str {
5149        match self {
5150            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
5151            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
5152            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
5153        }
5154    }
5155
5156    /// Substrate-canonical reverse projection on the `:placement
5157    /// :estrategia` closed-set axis — parses the camelCase-schema
5158    /// discriminator scalar back to the typed variant, or `None` when
5159    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
5160    /// emits. Dispatches on the same lifted
5161    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5162    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5163    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
5164    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
5165    /// the round-trip migrate through one caixa-core edit on any future
5166    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
5167    /// §II.5 hint names as a trajectory item lands one variant + one
5168    /// arm per method and the compiler enforces exhaustiveness on every
5169    /// consumer's `match self` arms).
5170    ///
5171    /// Prior to this lift the substrate carried only the forward
5172    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
5173    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
5174    /// derive that emits the same byte-string under
5175    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
5176    /// consumer that wanted to parse a wire-form strategy scalar had to
5177    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
5178    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
5179    /// compile-time link back to the typed variant's canonical lifted
5180    /// constant. A future variant rename or a per-arm serde-attribute
5181    /// drift would silently split the wire byte-string one non-serde
5182    /// consumer parsed from the one the emitter wrote, with the
5183    /// failure surfacing at parse time far from the rebrand commit.
5184    ///
5185    /// Same closed-set-reverse-projection discipline the sibling
5186    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
5187    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
5188    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
5189    /// defining `:placement :estrategia` closed-set axis, the third
5190    /// substrate-side closed-set typed enum to converge on the two-way
5191    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
5192    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
5193    /// and side-step the [`std::str::FromStr`]-collision clippy
5194    /// (`clippy::should_implement_trait`) the plain `from_str` name
5195    /// carries; a future explicit [`std::str::FromStr`] impl can layer
5196    /// on top by delegating to this canonical arm-dispatch method.
5197    ///
5198    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
5199    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
5200    /// picks the diagnostic form appropriate for its use site — a
5201    /// future `feira app placement --set` CLI-side arg-parse that wants
5202    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
5203    /// Sharded)"` diagnostic builds one on top by iterating
5204    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
5205    /// path folds `None` onto its per-CR structured refusal body.
5206    #[must_use]
5207    pub fn from_wire(s: &str) -> Option<Self> {
5208        match s {
5209            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
5210            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
5211            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
5212            _ => None,
5213        }
5214    }
5215
5216    /// Substrate-canonical per-arm predicate naming the cross-slot
5217    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
5218    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
5219    /// consumes the paired [`Placement::shard_key`] axis (and therefore
5220    /// requires — and is the only strategy that permits — a non-empty
5221    /// `:shard-key` on the paired slot). Today the accept-set is the
5222    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
5223    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
5224    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
5225    /// distributed-app takeover — §II.1) and `Replicated` (active-active
5226    /// across every named cluster) have no hash-keyed routing axis to
5227    /// consume the slot and refuse a declared-but-inert `:shard-key`
5228    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
5229    ///
5230    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
5231    /// satisfies `placement.shard_key().is_some() ==
5232    /// placement.estrategia().requires_shard_key()` by construction — the
5233    /// cross-slot partition the pin
5234    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
5235    /// locks load-bearing, so every downstream consumer that reaches for
5236    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5237    /// CR materializer's per-CR shard-key resolver, the future
5238    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
5239    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
5240    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
5241    /// shard-key requirement probe, a future author-facing tatara-lisp
5242    /// linter that flags `(:placement (:estrategia Replicated :shard-key
5243    /// "tenantId"))` shapes before `feira lint` reaches
5244    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
5245    /// the substrate primitive — the predicate names *the cross-slot
5246    /// invariant*, not the arm identity.
5247    ///
5248    /// Prior to this lift the "does this strategy consume `:shard-key`"
5249    /// classification lived under the `gen_platform::IsVariant`-derived
5250    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
5251    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
5252    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
5253    /// } else { None }` cascade, the
5254    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
5255    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
5256    /// "tenantId".to_string())` cascade, and the
5257    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
5258    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
5259    /// cascade). Each site conflated two semantically distinct questions:
5260    /// "is the variant `Sharded`?" (arm-identity, what
5261    /// [`Self::is_sharded`] answers) and "does the variant consume
5262    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
5263    /// The two questions land on the same three-way answer under today's
5264    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
5265    /// future arm addition that consumed `:shard-key` under a different
5266    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
5267    /// §II.5 roadmap-hint names that hash-partitions across the cluster
5268    /// pool by client-IP hash rather than an author-declared extractor
5269    /// expression, a hypothetical `WeightedShard` variant that carries a
5270    /// shard-key + per-cluster weight table under a promoted M5
5271    /// adaptive-placement engine) or an addition that did *not* consume
5272    /// `:shard-key` on a semantically Sharded-shaped arm would silently
5273    /// split the two questions. Any consumer that read
5274    /// `.is_sharded().then(…)` for the shard-key requirement gate would
5275    /// silently misclassify the new arm as non-consuming — a fixture
5276    /// builder would omit `:shard-key` where the new arm required one and
5277    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
5278    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
5279    /// commit, a future M4 CR materializer would fall through the
5280    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
5281    /// silently emit an empty extractor at the Akka reconciler layer.
5282    ///
5283    /// Lifting the classification as a substrate-primitive method on the
5284    /// closed-set typed enum names the cross-slot invariant on the
5285    /// primitive that owns the partition: every future arm addition
5286    /// declares its `:shard-key` consumption in one place (this predicate's
5287    /// `match self` arm-set), and every downstream consumer that reaches
5288    /// for the paired shape reads through one typed dispatch. Same
5289    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
5290    /// per-arm predicate on the pre-projection WIT-shape axis and the
5291    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
5292    /// paired predicate on the post-projection typed-view axis — a
5293    /// per-arm semantic-classification predicate paired with the
5294    /// arm-identity predicate the derive already emits, closing the drift
5295    /// footgun on the cross-slot invariant axis.
5296    ///
5297    /// Method-named `requires_shard_key` (not `has_shard_key`, not
5298    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
5299    /// invariant reads as "this strategy *requires* the paired
5300    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
5301    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
5302    /// merely omit it. The `has_*` framing would read as an accessor
5303    /// (returning the presence of an already-carried value) rather than a
5304    /// requirement (naming the invariant the paired slot must satisfy).
5305    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
5306    /// shape as the sibling [`WitContract::is_capability`] /
5307    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
5308    /// arm-family, so every consumer reaches for `.requires_shard_key()`
5309    /// as a drop-in replacement for the `.is_sharded()` conflated read
5310    /// without a return-shape migration.
5311    #[must_use]
5312    pub const fn requires_shard_key(self) -> bool {
5313        match self {
5314            Self::Sharded => true,
5315            Self::SingleNode | Self::Replicated => false,
5316        }
5317    }
5318}
5319
5320// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5321// cross-slot-invariant per-arm predicate: the module-scope const-eval
5322// assertions below trip at caixa-core build time (not test time) if a
5323// future edit rewires the predicate's arm-set away from the singleton
5324// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5325// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5326// runtime pin covers the same truth-table with a more descriptive
5327// diagnostic on failure; these const-eval items add a build-time failure
5328// surface strictly stronger than the runtime pin (a downstream renderer's
5329// `const`-context reader that composed against a rebound predicate would
5330// still surface here before the test suite even ran) and side-step the
5331// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5332// would otherwise accumulate on the caixa-core module baseline.
5333const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5334const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5335const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5336
5337/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5338/// the pretty-printed byte-string every consumer that formats the strategy
5339/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5340/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5341/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5342/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5343/// admission-webhook rejection body) reaches for the same lifted
5344/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5345/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5346/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5347/// `Serialize` derive already emits under
5348/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5349/// [`PlacementStrategy::as_str`] helper already returns.
5350///
5351/// Until this lift landed the sibling OTP-shape typed enums —
5352/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5353/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5354/// so [`std::fmt::Display`] routes through the same discriminant string
5355/// the wire format emits) — carried a stable [`std::fmt::Display`]
5356/// surface but [`PlacementStrategy`] did not; every consumer reaching
5357/// for a strategy byte-string past the wire format had to pick between
5358/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5359/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5360/// derive), any two of which a future variant rename or
5361/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5362/// desynchronize — with the failure surfacing as a downstream renderer /
5363/// operator's per-strategy dispatch reading one spelling while the wire
5364/// format emitted another, far from the source rebrand commit and with
5365/// no field naming the drift. Routing `Display` through
5366/// [`PlacementStrategy::as_str`] makes the three paths
5367/// (`Debug` for structural inspection, `Display` for user-facing text,
5368/// `Serialize` for the wire format) converge on the same lifted
5369/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
5370/// the diagnostic byte-string, and the pretty-printed byte-string move
5371/// as a single unit through one canonical declaration each, by
5372/// construction. Same trajectory as [`PlacementStrategy::as_str`]
5373/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
5374/// closes the third path.
5375///
5376/// Pin tests
5377/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
5378/// and
5379/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
5380/// assert the three paths agree byte-for-byte on every variant, so a
5381/// future variant rename or per-arm serde attribute drift is a build
5382/// error visible at caixa-core test time, not a silent per-consumer
5383/// dispatch miss at apply / reconcile time.
5384impl std::fmt::Display for PlacementStrategy {
5385    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5386        f.write_str(self.as_str())
5387    }
5388}
5389
5390/// Where the Aplicacao runs.
5391#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5392#[serde(rename_all = "camelCase")]
5393pub struct Placement {
5394    /// Distribution strategy.
5395    #[serde(default)]
5396    pub estrategia: PlacementStrategy,
5397
5398    /// Named clusters that host this Aplicacao. Required for
5399    /// `Replicated` and `SingleNode`; for `Sharded` declares the
5400    /// shard pool.
5401    #[serde(default)]
5402    pub clusters: Vec<String>,
5403
5404    /// Optional hint to the placement engine: `"data-locality"`,
5405    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
5406    #[serde(default, skip_serializing_if = "Option::is_none")]
5407    pub affinity: Option<String>,
5408
5409    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
5410    #[serde(default, skip_serializing_if = "Option::is_none")]
5411    pub shard_key: Option<String>,
5412}
5413
5414impl Placement {
5415    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
5416    /// `:shard-key` extractor-expression scalar accessor every consumer
5417    /// of the Aplicacao's hash-keyed distribution routing keys off —
5418    /// returns the author-declared `:placement :shard-key` byte-string
5419    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
5420    /// own `Option<String>` storage; `None` when the slot is absent
5421    /// (the canonical shape under `:estrategia Replicated` /
5422    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
5423    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
5424    /// partition — `validate` refuses any `Placement` past this call
5425    /// that lands `Some` on a non-`Sharded` strategy or `None` on
5426    /// `Sharded`).
5427    ///
5428    /// The `:placement :shard-key` slot carries the Akka-style
5429    /// cluster-sharding entity-id extractor expression
5430    /// (MESH-COMPOSITION §II.4) — validated by
5431    /// [`validate_placement_shard_key`] to be a non-empty printable-
5432    /// ASCII single-token reference (`tenantId`, `$tenantId`,
5433    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
5434    /// future M4 Akka-style cluster-sharding reconciler hashes without
5435    /// re-validating at the runtime layer), and every downstream
5436    /// consumer that reads the key keys off this scalar (the
5437    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
5438    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5439    /// declared-but-inert refusal diagnostic, the caixa-mesh
5440    /// per-Aplicacao `placement.shardKey` emit path the substrate
5441    /// operator's per-entity hash-routing reader consumes, the future
5442    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5443    /// per-shard-key resolver).
5444    ///
5445    /// Prior to this lift the `.shard_key` field was accessed inline at
5446    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
5447    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
5448    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
5449    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
5450    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
5451    /// — two open-coded field-accesses that expressed no compile-time
5452    /// link back to the typed slot. A future extension of the
5453    /// `:placement :shard-key` axis to a richer author surface — a
5454    /// per-cluster override the operator pins through a future
5455    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
5456    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
5457    /// alias table the M4 CR materializer resolves per-CR, a
5458    /// per-Aplicacao dynamic `:shard-key` derivation the future
5459    /// adaptive placement engine computes from `:affinity` weights —
5460    /// would have had to be threaded through both open-coded copies in
5461    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
5462    /// arm refusal would silently disagree on which extractor
5463    /// expression a given Placement resolves to. Lifting the resolution
5464    /// rule to a typed method on the substrate primitive means every
5465    /// downstream consumer of the Aplicacao's per-`:placement`
5466    /// hash-key surface reaches for exactly one typed dispatch — the
5467    /// resolver's accept-set migrates as a unit on any future axis
5468    /// addition.
5469    ///
5470    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
5471    /// [`WitContract::destination`] / [`WitContract::world_ref`]
5472    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
5473    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
5474    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
5475    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
5476    /// typed dispatch on the substrate primitive, thin projections at
5477    /// each consumer" discipline extended onto the per-`:placement`
5478    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
5479    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
5480    /// — opens the "optional per-slot scalar" projection pattern the
5481    /// sibling per-`:placement` `:affinity`, per-`:politicas`
5482    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
5483    /// match the storage field's name; the accessor's identity name
5484    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
5485    /// slot's docstring already carries.
5486    #[must_use]
5487    pub const fn shard_key(&self) -> Option<&str> {
5488        match &self.shard_key {
5489            Some(s) => Some(s.as_str()),
5490            None => None,
5491        }
5492    }
5493
5494    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
5495    /// compression-hint scalar accessor every weighting-consumer of the
5496    /// Aplicacao's per-hint routing surface keys off — returns the
5497    /// author-declared `:placement :affinity` byte-string verbatim as
5498    /// an `Option<&str>`, borrowed from the typed slot's own
5499    /// `Option<String>` storage; `None` when the slot is absent (the
5500    /// canonical shape of an Aplicacao that leaves the compression
5501    /// weighting up to the placement engine's cluster-default arm — no
5502    /// author-authored `data-locality` / `low-latency` / etc. hint
5503    /// biases the routing).
5504    ///
5505    /// The `:placement :affinity` slot carries the M3 Adaptive-
5506    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
5507    /// by [`validate_placement_affinity`] to be a DNS-1123 label
5508    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
5509    /// K8s-conformant label-selector shape every apiserver-side pod-
5510    /// affinity / node-affinity materializer already gates on
5511    /// admission), and every downstream consumer that reads the hint
5512    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
5513    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
5514    /// `placement.affinity` overlay emit path the substrate operator's
5515    /// per-hint weighting-consumer reads, the future M4
5516    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
5517    /// pod-affinity / node-affinity selector resolver).
5518    ///
5519    /// Prior to this lift the `.affinity` field was accessed inline at
5520    /// the sole caixa-core site — the
5521    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
5522    /// `if let Some(a) = &self.placement.affinity { …
5523    /// validate_placement_affinity(a)? … }` cascade — one open-coded
5524    /// field-access that expressed no compile-time link back to the
5525    /// typed slot. A future extension of the `:placement :affinity`
5526    /// axis to a richer author surface — a per-cluster override the
5527    /// operator pins through a future `:placement :affinity-overrides`
5528    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
5529    /// tenant hint alias table the M4 CR materializer resolves per-CR,
5530    /// a per-Aplicacao dynamic `:affinity` derivation the future
5531    /// adaptive placement engine computes from `:clusters` topology —
5532    /// would have had to be threaded through the open-coded copy in
5533    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
5534    /// materializer reader that landed on the axis, or the per-hint
5535    /// value-shape gate and its downstream weighting consumers would
5536    /// silently disagree on which hint a given Placement resolves to.
5537    /// Lifting the resolution rule to a typed method on the substrate
5538    /// primitive means every downstream consumer of the Aplicacao's
5539    /// per-`:placement` compression-hint surface reaches for exactly
5540    /// one typed dispatch — the resolver's accept-set migrates as a
5541    /// unit on any future axis addition.
5542    ///
5543    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
5544    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
5545    /// optional-scalar axis — same "one typed dispatch on the substrate
5546    /// primitive, thin projections at each consumer" discipline extended
5547    /// onto the per-`:placement` M3-Adaptive-compression-hint
5548    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
5549    /// return accessor on the M3 mesh-slot family; closes the last
5550    /// un-lifted per-`:placement` `Option<String>` axis. Named
5551    /// `affinity()` to match the storage field's name; the accessor's
5552    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
5553    /// vocabulary the slot's docstring already carries.
5554    #[must_use]
5555    pub const fn affinity(&self) -> Option<&str> {
5556        match &self.affinity {
5557            Some(s) => Some(s.as_str()),
5558            None => None,
5559        }
5560    }
5561
5562    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
5563    /// strategy scalar accessor every consumer that dispatches on the
5564    /// Aplicacao's per-cluster distribution shape keys off — returns the
5565    /// author-declared `:placement :estrategia` variant verbatim as a
5566    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
5567    /// `PlacementStrategy` storage.
5568    ///
5569    /// The `:placement :estrategia` slot carries the closed-set
5570    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
5571    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
5572    /// `Replicated` — active-active across every named cluster; `Sharded`
5573    /// — Akka-style hash-keyed entity distribution across the cluster pool
5574    /// per §II.4) that every downstream consumer of the Aplicacao's
5575    /// per-cluster fan-out shape keys off. Validated by
5576    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
5577    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
5578    /// matches!(estrategia, Sharded)` — the cross-slot partition the
5579    /// [`Placement::shard_key`] accessor's docstring pins), and every
5580    /// downstream consumer that reads the strategy keys off this scalar
5581    /// (the [`AplicacaoSpec::validate_placement`]
5582    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
5583    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
5584    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
5585    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5586    /// declared-but-inert refusal's
5587    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
5588    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
5589    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
5590    /// emit path the substrate operator's per-strategy fan-out reader
5591    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5592    /// materializer's per-strategy admission-webhook resolver).
5593    ///
5594    /// Prior to this lift the `.estrategia` field was accessed inline at
5595    /// four sites — the [`AplicacaoSpec::validate_placement`]
5596    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
5597    /// `estrategia: self.placement.estrategia`, the same method's
5598    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
5599    /// partition dispatch, the non-`Sharded`-arm
5600    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
5601    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
5602    /// per-Aplicacao strategy print line at
5603    /// `println!("… {} …", spec.placement.estrategia, …)`
5604    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
5605    /// expressed no compile-time link back to the typed slot. A future
5606    /// extension of the `:placement :estrategia` axis to a richer author
5607    /// surface (a per-cluster override the operator pins through a future
5608    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
5609    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
5610    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
5611    /// derivation the future adaptive placement engine computes from
5612    /// `:affinity` + `:clusters` topology) would have had to be threaded
5613    /// through every open-coded copy in lockstep — one consumer reading
5614    /// the raw variant while a peer read the operator-resolved variant
5615    /// would silently split the `PlacementWithoutClusters` /
5616    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
5617    /// partition-dispatch input, a two-consumer split at the validator
5618    /// far from the source `caixa.lisp` with no field naming the
5619    /// strategy-drift root cause. Lifting the resolution rule to a typed
5620    /// method on the substrate primitive means every downstream consumer
5621    /// of the Aplicacao's per-`:placement` distribution-strategy surface
5622    /// reaches for exactly one typed dispatch — the resolver's accept-set
5623    /// migrates as a unit on any future axis addition.
5624    ///
5625    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
5626    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
5627    /// same "one typed dispatch on the substrate primitive, thin
5628    /// projections at each consumer" discipline extended onto the
5629    /// per-`:placement` distribution-strategy `Copy`-composite-enum
5630    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
5631    /// family; first `Copy`-return accessor on the M3 mesh-slot
5632    /// `Placement` type — companion to the sibling per-`:placement`
5633    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5634    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
5635    /// optional-scalar axes, closing the last unlifted per-`:placement`
5636    /// scalar-value axis (the closed-set `PlacementStrategy`
5637    /// distribution-strategy discriminator) so every downstream
5638    /// per-`:placement` reader now routes through a typed dispatch on
5639    /// the substrate primitive. Named `estrategia()` to match the storage
5640    /// field's name; the accessor's identity name maps onto the
5641    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
5642    /// already carries. Declared `pub const fn` (matching the peer M3
5643    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5644    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5645    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5646    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5647    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5648    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5649    /// [`RateLimit`] — every one a `pub const fn`) so every future
5650    /// substrate-side `const`-context consumer of the resolved
5651    /// distribution-strategy variant (a `const _: () = assert!(…)`
5652    /// module-scope invariant pin on a per-fixture typed [`Placement`],
5653    /// a future M4 admission-webhook `const fn` resolver over a typed
5654    /// [`Placement`], any `const fn` composer that fans on the strategy
5655    /// at compile time) reaches through the same typed dispatch on the
5656    /// substrate primitive at const-eval time as at runtime. Pinned by
5657    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
5658    /// const-eval posture at module scope via `const _:() = …` items so
5659    /// any future accidental downgrade to non-`const` trips at caixa-core
5660    /// build time.
5661    #[must_use]
5662    pub const fn estrategia(&self) -> PlacementStrategy {
5663        self.estrategia
5664    }
5665
5666    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
5667    /// per-cluster distribution-target slice accessor every consumer that
5668    /// walks the Aplicacao's declared cluster-pool keys off — returns the
5669    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
5670    /// `&[String]` slice-view, borrowed from the typed slot's own
5671    /// `Vec<String>` storage (a zero-copy slice-view over the same
5672    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5673    /// through). Non-optional: the empty slice is the load-bearing
5674    /// pre-validation sentinel every downstream consumer of the paired
5675    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
5676    /// off — every strategy in the closed
5677    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
5678    /// requires a non-empty list (`SingleNode` / `Replicated` use the
5679    /// list as hosting / takeover candidates per Erlang/OTP distributed-
5680    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
5681    /// shard pool per Akka cluster-sharding convention, §II.4), so the
5682    /// `.is_empty()` probe is the shared pre-condition every
5683    /// [`AplicacaoSpec::validate_placement`] arm heads on.
5684    ///
5685    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
5686    /// 1123-label per-cluster distribution-target list — the same
5687    /// set-not-multiset shape the sibling `:membros :caixa` /
5688    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
5689    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
5690    /// pins the shape). Every downstream consumer that fans on the list
5691    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
5692    /// pre-flight `.is_empty()` probe that trips
5693    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
5694    /// per-cluster value-shape + duplicate-detection fan-out loop, the
5695    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
5696    /// that materializes the list verbatim onto every
5697    /// programs.yaml entry the substrate operator's per-cluster
5698    /// `placement.clusters | contains .Values.cluster` filter reads,
5699    /// the `feira app graph` per-Aplicacao cluster print line, the
5700    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5701    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
5702    /// placement engine's cluster-topology reader).
5703    ///
5704    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
5705    /// inline at three production sites — the
5706    /// [`AplicacaoSpec::validate_placement`] pre-flight
5707    /// `self.placement.clusters.is_empty()` refusal probe, the same
5708    /// method's per-cluster validate loop's
5709    /// `for c in &self.placement.clusters` traversal head, and the
5710    /// `feira app graph` per-Aplicacao print line's
5711    /// `spec.placement.clusters` `{:?}` formatter argument
5712    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
5713    /// that expressed no compile-time link back to the typed slot. A
5714    /// future extension of the `:placement :clusters` axis to a richer
5715    /// author surface (a per-tenant cluster-pool overlay the operator
5716    /// pins through a future `:placement :clusters-overrides` slot the
5717    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
5718    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
5719    /// the future M5 adaptive-placement engine computes from
5720    /// `:affinity` weights + live cluster-topology probes, a promotion
5721    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
5722    /// partition once the substrate operator's cluster-membership
5723    /// reconciler comes into typed scope) would have had to be threaded
5724    /// through all three open-coded copies in lockstep or one consumer
5725    /// would silently disagree with the peers on which cluster-pool a
5726    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
5727    /// reading the raw slot while the peer per-cluster validate loop
5728    /// read an operator-resolved slot would silently split the paired
5729    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
5730    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
5731    /// input from the pre-flight input, a three-consumer split at the
5732    /// validator and formatter far from the source `caixa.lisp` with
5733    /// no field naming the cluster-pool-drift root cause. Lifting the
5734    /// resolution rule to a typed method on the substrate primitive
5735    /// means every downstream consumer of the Aplicacao's
5736    /// per-`:placement` cluster-pool surface reaches for exactly one
5737    /// typed dispatch — the resolver's accept-set migrates as a unit
5738    /// on any future axis addition.
5739    ///
5740    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
5741    /// slot — sibling to the seed M2
5742    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
5743    /// slice-return accessor on the peer per-`:supervisor` static-
5744    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
5745    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
5746    /// primitive, thin projections at each consumer" discipline. The
5747    /// three peer `Vec`-carry axes still unlifted at the time of this
5748    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
5749    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
5750    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
5751    /// [`crate::UpgradeFromEntry::instructions`]
5752    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5753    /// — inherit this accessor's discipline as future compounding runs
5754    /// migrate their consumers onto the shared slice-return shape.
5755    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
5756    /// type, sibling to the two `Option<&str>`-return
5757    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5758    /// (74ec2d3) accessors and the `Copy`-return
5759    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
5760    /// unlifted per-`:placement` field axis (the `Vec<String>`
5761    /// distribution-target-list carrier) so every downstream
5762    /// per-`:placement` reader now routes through a typed dispatch on
5763    /// the substrate primitive. Named `clusters()` to match the storage
5764    /// field's name verbatim and the tatara-lisp author-surface term
5765    /// (`:clusters`) the field's own docstring already carries; the
5766    /// accessor's identity maps onto the canonical MESH-COMPOSITION
5767    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
5768    /// for. Returns `&[String]` (not `&Vec<String>`) because every
5769    /// downstream consumer of the cluster list treats it as a read-only
5770    /// sequence — the slice-view is the narrowest borrow that supports
5771    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
5772    /// `.len()`) without leaking the backing `Vec`'s
5773    /// grow/push/reserve surface that no consumer of the typed view
5774    /// reaches for (the storage-side `Vec` remains reachable through
5775    /// the `pub clusters` field for the mutation-carrying serde
5776    /// round-trip and per-test fixture-mutation paths).
5777    #[must_use]
5778    pub const fn clusters(&self) -> &[String] {
5779        self.clusters.as_slice()
5780    }
5781}
5782
5783impl Default for Placement {
5784    fn default() -> Self {
5785        Self {
5786            // Route the struct-literal `estrategia` default arm through
5787            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
5788            // typed `pub const` rather than the transitively-derived
5789            // [`PlacementStrategy::default`] route — one source of truth
5790            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
5791            // active-active-across-every-named-cluster arm
5792            // (MESH-COMPOSITION §II.2) that both this struct-literal
5793            // altitude and the sibling [`Default for PlacementStrategy`]
5794            // impl already key off through the same substrate primitive.
5795            // Pinned by
5796            // `placement_default_estrategia_routes_through_lifted_default`.
5797            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
5798            clusters: Vec::new(),
5799            affinity: None,
5800            shard_key: None,
5801        }
5802    }
5803}
5804
5805// ── external entry point ─────────────────────────────────────────────
5806
5807/// External entry point — what an outside caller sees. Renders to a
5808/// Gateway / Ingress + a route to the named member Servico.
5809#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5810#[serde(rename_all = "camelCase")]
5811pub struct Entrada {
5812    /// Public hostname (e.g. `"checkout.quero.cloud"`).
5813    pub host: String,
5814
5815    /// Member Servico the gateway routes to. Must be in `:membros`.
5816    pub para: String,
5817
5818    /// Optional path filter — if set, only matching paths route to
5819    /// this Aplicacao (the rest fall through to other route rules).
5820    #[serde(default)]
5821    pub paths: Vec<String>,
5822
5823    /// Default port on the destination Servico (the trigger.service.port).
5824    #[serde(default = "default_port")]
5825    pub port: u16,
5826}
5827
5828impl Entrada {
5829    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
5830    /// every HTTPRoute-aware renderer keys off — returns the author-
5831    /// declared `:entrada :paths` list verbatim when non-empty, and the
5832    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
5833    /// all fallback otherwise (so an Aplicacao author who declares an
5834    /// external `:entrada` block but no per-path rule surface still
5835    /// gets a route whose sole `HTTPPathMatch` matches every incoming
5836    /// request under the paired
5837    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
5838    ///
5839    /// Prior to this lift the "if `:entrada :paths` is empty use the
5840    /// substrate catch-all; else return each declared path verbatim"
5841    /// cascade lived inline at
5842    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
5843    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
5844    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
5845    /// substrate ships today, with no typed method on the substrate
5846    /// primitive that named the rule. A future path-resolution axis
5847    /// addition — a per-cluster `:entrada :default-path` override the
5848    /// operator pins through a future `:placement`-scoped slot, an
5849    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5850    /// admission-webhook floor that materializes the catch-all before
5851    /// the CR lands, a future per-`:entrada :paths` overlay from a
5852    /// per-cluster policy the future `feira app deploy` pipeline
5853    /// consumes — would have to be threaded through every renderer's
5854    /// inline copy of the cascade in lockstep or one consumer would
5855    /// silently disagree with the peers on which path list a given
5856    /// `:entrada` block resolves to. Lifting the rule to a typed
5857    /// method on the substrate primitive means every downstream
5858    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
5859    /// per-cluster overlay resolver, every future per-Aplicacao
5860    /// snapshot renderer) reaches for exactly one typed dispatch —
5861    /// the resolver's accept-set moves as a unit on any future axis
5862    /// addition.
5863    ///
5864    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
5865    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
5866    /// per-`:entrada` scalar-value axes — extends the "one typed
5867    /// dispatch on the substrate primitive, thin projections at each
5868    /// consumer" discipline onto the per-`:entrada` path-list
5869    /// resolution axis every HTTPRoute-aware renderer consumes. Same
5870    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
5871    /// sibling `:politicas` primitive — one typed method on the
5872    /// substrate primitive that names the cascade every renderer
5873    /// otherwise re-inlines.
5874    #[must_use]
5875    pub fn resolved_paths(&self) -> Vec<&str> {
5876        // Route the internal cascade-head + per-entry projection reads
5877        // through the lifted [`Self::paths`] slice accessor rather than
5878        // the raw `self.paths` field access — the substrate-primitive
5879        // per-`:entrada` path-list resolver's two internal reads now
5880        // key off the canonical raw-slot surface every downstream
5881        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
5882        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
5883        // entrada summary line's `{:?}` Debug print) routes through, so
5884        // any future rebrand on the typed slot's raw-slot reader lands
5885        // at exactly one place. Same two-consumer coherence discipline
5886        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
5887        // the peer M3 mesh-slot `Vec<String>`-carry axis.
5888        if self.paths().is_empty() {
5889            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
5890        } else {
5891            self.paths().iter().map(String::as_str).collect()
5892        }
5893    }
5894
5895    /// Substrate-canonical per-`:entrada` DNS-hostname singular
5896    /// accessor every Gateway-API `Listener.hostname` reader keys off
5897    /// — returns the author-declared `:entrada :host` byte-string
5898    /// verbatim as a `&str`, borrowed from the typed slot's own
5899    /// [`String`] storage.
5900    ///
5901    /// Named the "singular" half of the DNS-hostname resolver pair on
5902    /// the substrate primitive: the parent-Gateway per-listener
5903    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
5904    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
5905    /// hostname per listener), and this accessor is the typed dispatch
5906    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
5907    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
5908    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
5909    /// per-Aplicacao ingress-hostname surface projects onto.
5910    ///
5911    /// Prior to this lift the `entrada.host.clone()` byte-string was
5912    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
5913    /// per-listener singular `hostname:` axis
5914    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
5915    /// per-HTTPRoute plural `spec.hostnames[]` axis
5916    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
5917    /// consumers read the same `entrada.host` field but the two-site
5918    /// duplication expressed no compile-time contract that the singular
5919    /// Gateway-listener filter and the plural `HTTPRoute` filter list
5920    /// stay in lockstep on future extensions of the `:entrada` slot to
5921    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
5922    /// overlay, a per-cluster SNI fan-out the operator pins through a
5923    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
5924    /// Aplicacao` CR materializer's per-listener virtual-host filter
5925    /// admission-webhook overlay). Any such extension would have to be
5926    /// threaded through every renderer's inline copy of the resolution
5927    /// in lockstep or the Gateway listener's `hostname:` filter would
5928    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
5929    /// — a Gateway-API-conformance divergence whose apply-time symptom
5930    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
5931    /// `NoMatchingParent` — the API server rejects the route because
5932    /// its `hostnames[]` filter doesn't intersect the parent listener's
5933    /// `hostname` filter) is far from the source `caixa.lisp` and never
5934    /// surfaces in the emitted YAML. Lifting the singular and plural
5935    /// resolvers to typed methods on the substrate primitive means
5936    /// every consumer of the Aplicacao's ingress-hostname surface
5937    /// reaches for exactly one typed dispatch, and the pair-invariant
5938    /// `hostnames() == vec![hostname()]` pinned by the sibling
5939    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
5940    /// keeps the two axes in lockstep by construction.
5941    ///
5942    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
5943    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
5944    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
5945    /// the substrate primitive, thin projections at each consumer"
5946    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5947    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5948    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5949    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
5950    /// `:entrada` scalar-value + list-value axes.
5951    #[must_use]
5952    pub const fn hostname(&self) -> &str {
5953        self.host.as_str()
5954    }
5955
5956    /// Substrate-canonical per-`:entrada` DNS-hostname plural
5957    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
5958    /// keys off — returns the singleton `[hostname()]` list under
5959    /// today's single-hostname-per-Aplicacao author surface, and the
5960    /// authoritative multi-hostname list under a future
5961    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
5962    ///
5963    /// Plural half of the DNS-hostname resolver pair — see the
5964    /// companion [`Entrada::hostname`] docstring for the two-consumer
5965    /// lift + pair-invariant discipline (`hostnames() ==
5966    /// vec![hostname()]`, pinned load-bearing by the sibling
5967    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
5968    /// test).
5969    ///
5970    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
5971    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
5972    /// per-rule path-list axis — same `Vec<&str>` shape, same
5973    /// substrate-primitive-owns-the-resolver discipline extended to
5974    /// the per-HTTPRoute virtual-host filter-list axis.
5975    #[must_use]
5976    pub fn hostnames(&self) -> Vec<&str> {
5977        vec![self.hostname()]
5978    }
5979
5980    /// Substrate-canonical per-`:entrada` destination-Servico scalar
5981    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
5982    /// the author-declared `:entrada :para` byte-string verbatim as a
5983    /// `&str`, borrowed from the typed slot's own [`String`] storage.
5984    ///
5985    /// The `:entrada :para` slot names the single member Servico the
5986    /// external Gateway routes to (validated by
5987    /// [`AplicacaoSpec::validate`] to be a
5988    /// [`Membro::caixa`] the Aplicacao declares — a stray
5989    /// `:para` that doesn't name a member is
5990    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
5991    /// backend-attachment miss at cluster-apply time). Under today's
5992    /// single-destination author surface `:entrada :para` is the ingress
5993    /// apex Servico's canonical identity; under a hypothetical
5994    /// future multi-backend author surface (a `:entrada
5995    /// :split :backends` weighted-fan-out overlay for canary /
5996    /// blue-green traffic-split rollouts, per-path override for
5997    /// path-based per-Servico routing beyond the single-apex model,
5998    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5999    /// per-CR admission-webhook that promotes the scalar to a
6000    /// weighted list) this accessor is the substrate primitive's typed
6001    /// dispatch every downstream `HTTPRoute`-aware consumer routes
6002    /// through, so the resolution shape migrates as a unit on one
6003    /// caixa-core edit rather than a coordinated rewrite across every
6004    /// renderer's inline field-access.
6005    ///
6006    /// Prior to this lift the `entrada.para` byte-string was accessed
6007    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
6008    /// `metadata.name` composer's per-destination discriminator arg
6009    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
6010    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
6011    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
6012    /// (`entrada.para.clone()`,
6013    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
6014    /// consumers read the same `entrada.para` field but the two-site
6015    /// duplication expressed no compile-time contract that the HTTPRoute
6016    /// name-discriminator and the per-rule backend name stay in
6017    /// lockstep on future extensions of the `:entrada` slot to a
6018    /// multi-destination author surface. Any such extension would have
6019    /// to be threaded through every renderer's inline copy of the
6020    /// destination projection in lockstep or the HTTPRoute
6021    /// `metadata.name` would silently reference a different destination
6022    /// than its own `backendRefs[]` — an operator-side
6023    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
6024    /// grep-by-name lookup would land on a route whose `backendRefs[]`
6025    /// silently point at a peer Servico, dropping every external
6026    /// `:entrada` flow at the gateway with the destination-drift root
6027    /// cause invisible in the emitted YAML.
6028    ///
6029    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
6030    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
6031    /// the per-listener singular / per-HTTPRoute plural filter axes and
6032    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
6033    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
6034    /// typed dispatch on the substrate primitive, thin projections at
6035    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6036    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6037    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6038    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
6039    /// sibling per-`:entrada` scalar-value + list-value axes — this
6040    /// accessor closes the last unlifted per-`:entrada` scalar axis
6041    /// (the destination-Servico byte-string) so every downstream
6042    /// per-`:entrada` reader now routes through a typed dispatch on
6043    /// the substrate primitive.
6044    #[must_use]
6045    pub const fn destination(&self) -> &str {
6046        self.para.as_str()
6047    }
6048
6049    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
6050    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
6051    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
6052    /// reader keys off — returns the author-declared `:entrada :port`
6053    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
6054    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
6055    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
6056    /// [`AplicacaoError::EntradaPortZero`], not a silent
6057    /// admission-webhook rejection at cluster-apply time).
6058    ///
6059    /// The `:entrada :port` slot carries the destination Servico's
6060    /// canonical in-cluster L4 listener port (`trigger.service.port` on
6061    /// the `pleme-computeunit` library chart), and every downstream
6062    /// consumer that reads the port keys off this scalar (the
6063    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
6064    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
6065    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
6066    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6067    /// CR materializer's per-Aplicacao gateway port resolver).
6068    ///
6069    /// Prior to this lift the `.port` field was accessed inline at two
6070    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
6071    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
6072    /// the [`AplicacaoSpec::port_for_destination`] resolver's
6073    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
6074    /// open-coded field-accesses that expressed no compile-time link
6075    /// back to the typed slot. A future extension of the `:entrada :port`
6076    /// axis to a richer author surface — a per-cluster override the
6077    /// operator pins through a future `:placement :default-port` slot the
6078    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
6079    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
6080    /// heterogeneous listener ports, an M4
6081    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6082    /// admission-webhook floor that promotes the scalar to a
6083    /// per-destination map — would have had to be threaded through both
6084    /// open-coded copies in lockstep or the structural-floor validator
6085    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
6086    /// silently disagree on which port a given [`Entrada`] resolves to.
6087    /// Lifting the resolution rule to a typed method on the substrate
6088    /// primitive means every downstream consumer of the Aplicacao's
6089    /// per-`:entrada` L4-port surface reaches for exactly one typed
6090    /// dispatch — the resolver's accept-set migrates as a unit on any
6091    /// future axis addition.
6092    ///
6093    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
6094    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
6095    /// accessors on the per-`:entrada` scalar-value axis — same "one
6096    /// typed dispatch on the substrate primitive, thin projections at
6097    /// each consumer" discipline extended onto the per-`:entrada`
6098    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
6099    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
6100    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
6101    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
6102    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
6103    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
6104    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
6105    /// storage field's name; the accessor's identity name maps onto the
6106    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
6107    /// already carries. Declared `pub const fn` (matching the peer M3
6108    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6109    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6110    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6111    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6112    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6113    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6114    /// [`RateLimit`], and the sibling per-`:placement`
6115    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
6116    /// enum scalar axis — every one a `pub const fn`) so every future
6117    /// substrate-side `const`-context consumer of the resolved
6118    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
6119    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
6120    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
6121    /// admission-webhook `const fn` per-CR gateway-port floor over a
6122    /// typed [`Entrada`], any `const fn` composer that fans on the port
6123    /// at compile time) reaches through the same typed dispatch on the
6124    /// substrate primitive at const-eval time as at runtime. Pinned by
6125    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
6126    /// const-eval posture at module scope via `const _:() = …` items so
6127    /// any future accidental downgrade to non-`const` trips at caixa-core
6128    /// build time.
6129    #[must_use]
6130    pub const fn port(&self) -> u16 {
6131        self.port
6132    }
6133
6134    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
6135    /// slice accessor every HTTPRoute-aware renderer keys off when it
6136    /// wants the raw author-declared path-list (not the fallback-
6137    /// applied projection [`Self::resolved_paths`] returns) — returns
6138    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
6139    /// borrowed from the typed slot's own [`Vec<String>`] storage.
6140    ///
6141    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
6142    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
6143    /// (1449891) closes the fallback-applying arm every per-Aplicacao
6144    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
6145    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
6146    /// catch-all; non-empty slot → per-entry verbatim projection); this
6147    /// accessor closes the raw-slot arm every consumer that must see the
6148    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
6149    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
6150    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
6151    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
6152    /// external-gateway summary line's `{:?}` Debug print — which must
6153    /// name the author's declaration, not the substrate's fallback, so
6154    /// an author reading their graph output can grep their caixa.lisp
6155    /// for the exact list they authored) routes through.
6156    ///
6157    /// Prior to this lift the `.paths` field was accessed inline at four
6158    /// production sites: the two internal reads in [`Self::resolved_paths`]
6159    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
6160    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
6161    /// value-shape gate's `for p in &e.paths` traversal head, and the
6162    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
6163    /// Debug print — four open-coded field-accesses that expressed no
6164    /// compile-time link back to the typed slot. A future extension of
6165    /// the `:entrada :paths` axis to a richer author surface — a
6166    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
6167    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
6168    /// spec supports through `matches[].method`), a per-path per-header
6169    /// filter overlay (`matches[].headers[]`), a per-cluster override
6170    /// the operator pins through a future `:placement :path-overlay`
6171    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6172    /// per-CR admission-webhook that normalized the list at admission
6173    /// time — would have had to be threaded through every open-coded
6174    /// copy in lockstep or the validator's per-entry gate would silently
6175    /// disagree with the renderer's per-entry emit on which list a given
6176    /// `:entrada` block resolves to. Lifting the resolution to a typed
6177    /// method on the substrate primitive means every downstream consumer
6178    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
6179    /// exactly one typed dispatch — the resolver's accept-set migrates
6180    /// as a unit on any future axis addition.
6181    ///
6182    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
6183    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
6184    /// carry axis — same "one typed dispatch on the substrate primitive,
6185    /// thin projections at each consumer" discipline extended onto the
6186    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
6187    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
6188    /// carrier) so every downstream per-`:entrada` reader now routes
6189    /// through a typed dispatch on the substrate primitive. Returns
6190    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
6191    /// treats the list as a read-only sequence — the slice-view is the
6192    /// narrowest borrow that supports every present + roadmapped consumer
6193    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
6194    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
6195    /// view reaches for (the storage-side `Vec` remains reachable through
6196    /// the `pub paths` field for the mutation-carrying serde round-trip
6197    /// and per-test fixture-mutation paths).
6198    #[must_use]
6199    pub const fn paths(&self) -> &[String] {
6200        self.paths.as_slice()
6201    }
6202}
6203
6204/// Canonical default L4 port every typed Servico exposes on its
6205/// in-cluster K8s Service (the `trigger.service.port` axis the
6206/// `pleme-computeunit` library chart emits, the `:entrada :port` author
6207/// surface defaults to when the author omits the slot, and the
6208/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
6209/// `:entrada` block matches the per-`:contratos` destination Servico).
6210/// The single source of truth all three typed-port consumers reach for:
6211///
6212///   - [`Entrada::port`]'s serde default (via the
6213///     [`default_port`] helper this constant feeds); the author surface
6214///     `(:entrada (:host … :para …))` without an explicit `:port` slot
6215///     reads back as a typed [`Entrada`] carrying this exact value;
6216///   - the
6217///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
6218///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
6219///     fallback, fired when the typed `:entrada` block doesn't name
6220///     the per-`:contratos` destination Servico — the typed
6221///     `:contratos` graph carries no per-destination port axis (the
6222///     destination port is the destination Servico's
6223///     `lareira-<nome>` chart's `trigger.service.port`, which the
6224///     Aplicacao-level renderer has no visibility into without a
6225///     resolver round-trip), so the renderer falls back to the
6226///     substrate's canonical Servico-port assumption — by
6227///     construction the same value the destination's own
6228///     `pleme-computeunit` chart emits, the same value the
6229///     destination's own typed `:entrada :port` slot defaults to;
6230///   - every future per-Servico renderer the absorption-roadmap
6231///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6232///     CR materializer's per-edge port resolver, the future
6233///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
6234///     emitter's per-route bucket key, the future caixa-otel
6235///     collector-pipeline emitter's per-Servico scrape port).
6236///
6237/// Until this lift landed the value `8080` lived at two production-code
6238/// call-sites: the [`default_port`] helper at
6239/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
6240/// and the `.unwrap_or(8080)` literal at
6241/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
6242/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
6243/// resolver). A future Servico-port rebrand — the substrate moving the
6244/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
6245/// gateway grows direct `:80` listeners, to `8443` once the substrate
6246/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
6247/// override the operator pins through a future
6248/// `:placement :default-port` slot — without a coordinated edit on
6249/// both sides would silently emit Servicos listening on one port and
6250/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
6251/// The CNP's apply-time symptom (the policy is admitted but every L4
6252/// flow on the destination Servico's actual port silently drops because
6253/// it doesn't match the whitelisted port) is far from the rebrand
6254/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
6255/// in hubble traces, not in `kubectl describe`. Lifting the literal to
6256/// a shared constant closes the drift footgun structurally — both
6257/// consumers read from the same `u16`, so any rebrand reaches both
6258/// sites by construction.
6259///
6260/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
6261/// per-renderer canonical-K8s-axis constant — the namespace string
6262/// and the canonical Servico port both lived as duplicated literals
6263/// across caixa-core / caixa-mesh / caixa-flux before their respective
6264/// lifts. Same "the typed constant lives in one place" discipline the
6265/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
6266/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
6267/// shared-string axes.
6268///
6269/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
6270pub const DEFAULT_SERVICO_PORT: u16 = 8080;
6271
6272/// Structural floor for the typed `:entrada :port` axis — every
6273/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
6274/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
6275///
6276/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
6277/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
6278/// interprets as "let the kernel pick a free port at bind time", not a
6279/// well-defined destination the substrate's per-`:entrada` Gateway API
6280/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
6281/// carrying `port: 0` degenerates to a nominal-only routing target: the
6282/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
6283/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
6284/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
6285/// at build time rather than at `kubectl apply` time), and the
6286/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
6287/// (caixa-mesh/src/lib.rs:2657 through
6288/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
6289/// [`Entrada::port`] typed value — silently emits a policy whose
6290/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
6291/// actual listener, dropping every L4 flow at the eBPF data plane far
6292/// from the source caixa.lisp with no field naming the port-zero-drift
6293/// root cause.
6294///
6295/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
6296/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
6297/// on the top edge (unlike the peer capped-`u32` `:politicas` /
6298/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
6299/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
6300/// well below `u32::MAX` and therefore need explicit typed caps).
6301///
6302/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
6303/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
6304/// scalar every `(:entrada (:host … :para …))` slot without an explicit
6305/// `:port` inherits through the serde default hook; this constant names
6306/// the accept-set floor every declared port must satisfy. The pair is
6307/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
6308/// substrate's default must satisfy its own accept-set floor by
6309/// construction) — a future rebrand that accidentally moved
6310/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
6311/// negative-cast typo, a per-cluster override the operator pins through
6312/// a future `:placement :default-port` slot that lands out-of-range)
6313/// would silently invalidate the serde-default emission at every
6314/// author-side `(:entrada (:host … :para …))` slot — the compile-time
6315/// invariant pin
6316/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
6317/// closes the drift footgun at caixa-core build time.
6318///
6319/// Lifted as a typed `pub const` (rather than an inline `0` literal at
6320/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
6321/// has exactly one source of truth — the future M4
6322/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6323/// gateway resolver, the future per-Servico
6324/// `computeunit.trigger.service.port` renderer's per-CR port-value
6325/// validator, and every downstream test-fixture navigator asserting
6326/// the accept-set floor all read from one place. Same shape every
6327/// other typed bracket-floor / bracket-ceiling in this crate carries
6328/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6329/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6330/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6331/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6332/// [`POLICY_RATE_LIMIT_MAX`]).
6333pub const SERVICO_PORT_MIN: u16 = 1;
6334
6335const fn default_port() -> u16 {
6336    DEFAULT_SERVICO_PORT
6337}
6338
6339// ── the typed view ───────────────────────────────────────────────────
6340
6341/// Typed composition view of the flat Aplicacao slots on
6342/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6343/// validation + downstream renderer consumption.
6344#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6345#[serde(rename_all = "camelCase")]
6346pub struct AplicacaoSpec {
6347    pub membros: Vec<Membro>,
6348    pub contratos: Vec<WitContract>,
6349    pub politicas: MeshPolicy,
6350    pub placement: Placement,
6351    pub entrada: Option<Entrada>,
6352}
6353
6354impl AplicacaoSpec {
6355    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6356    /// per-Aplicacao member-list slice-return accessor every
6357    /// per-Aplicacao member-list reader keys off — returns the author-
6358    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6359    /// over the same backing buffer the raw `self.membros.as_slice()`
6360    /// field access borrows from.
6361    ///
6362    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6363    /// member list — the load-bearing identity of the application graph
6364    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
6365    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
6366    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
6367    /// accessor) with a `:versao` semver-requirement string (through
6368    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
6369    /// and every downstream consumer that fans on the member-set keys
6370    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
6371    /// membership-lookup `HashSet<&str>` seed's collect input, the
6372    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
6373    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
6374    /// per-member DNS-1123 / semver-requirement / duplicate-detection
6375    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
6376    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
6377    /// programs.yaml per-`:membros` fan-out emitter's per-entry
6378    /// mapping-composition loop, the `feira app graph` per-Aplicacao
6379    /// member-count print line and per-member tree traversal,
6380    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
6381    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
6382    /// placement engine's per-member weight-topology reader).
6383    ///
6384    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
6385    /// inline at six production sites — the [`AplicacaoSpec::validate`]
6386    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
6387    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
6388    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
6389    /// probe, the same method's per-member `for m in &self.membros`
6390    /// validate-loop traversal head, the
6391    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6392    /// `for m in &self.membros` adjacency-list seed, the
6393    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
6394    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
6395    /// paired with the peer `for m in &spec.membros` per-entry fan-out
6396    /// loop, and the `feira app graph` per-Aplicacao print line's
6397    /// `spec.membros.len()` count formatter argument paired with the
6398    /// peer `for m in &spec.membros` per-member tree traversal — six
6399    /// open-coded field-accesses that expressed no compile-time link
6400    /// back to the typed slot. A future extension of the `:membros`
6401    /// axis to a richer author surface (a per-cluster member-set
6402    /// overlay the operator pins through a future
6403    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
6404    /// roadmap acknowledges, a per-tenant member-alias table the M4
6405    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
6406    /// CR at admission time, a per-Aplicacao dynamic member-set
6407    /// derivation the future adaptive-placement engine computes from
6408    /// weighted membership topology, a promotion of the plain
6409    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
6410    /// Orleans-style virtual-actor dynamic-membership comes into typed
6411    /// scope) would have had to be threaded through all six open-coded
6412    /// copies in lockstep or one consumer would silently disagree with
6413    /// the peers on which member-set a given Aplicacao resolves to —
6414    /// the `HashSet<&str>` name-set seed reading the raw slot while
6415    /// the peer `.is_empty()` refusal probe read an operator-resolved
6416    /// slot would silently split the `:contratos` membership-lookup
6417    /// input from the pre-flight-refusal input, a six-consumer split
6418    /// at the validator + programs.yaml emitter + graph printer far
6419    /// from the source `caixa.lisp` with no field naming the member-
6420    /// set-drift root cause. Lifting the resolution rule to a typed
6421    /// method on the substrate primitive means every downstream
6422    /// consumer of the Aplicacao's per-`:membros` member-list surface
6423    /// reaches for exactly one typed dispatch — the resolver's accept-
6424    /// set migrates as a unit on any future axis addition.
6425    ///
6426    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
6427    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6428    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6429    /// static-child-list `Vec`-carry axis, and to the M3
6430    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6431    /// on the peer per-`:placement` distribution-target-list `Vec`-
6432    /// carry axis. Same "one typed dispatch on the substrate primitive,
6433    /// thin projections at each consumer" discipline. The two peer
6434    /// `Vec`-carry axes still unlifted at the time of this lift —
6435    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
6436    /// WIT-typed edge list) and
6437    /// [`crate::UpgradeFromEntry::instructions`]
6438    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6439    /// — inherit this accessor's discipline as future compounding runs
6440    /// migrate their consumers onto the shared slice-return shape.
6441    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
6442    /// `AplicacaoSpec` type itself, extending the discipline beyond
6443    /// the inner per-slot types ([`crate::Placement`],
6444    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
6445    /// view every renderer consumes. Named `membros()` to match the
6446    /// storage field's name verbatim and the tatara-lisp author-
6447    /// surface term (`:membros`) the field's own docstring already
6448    /// carries; the accessor's identity maps onto the canonical
6449    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
6450    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
6451    /// every downstream consumer of the member list treats it as a
6452    /// read-only sequence — the slice-view is the narrowest borrow
6453    /// that supports every present + roadmapped consumer
6454    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6455    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6456    /// the typed view reaches for (the storage-side `Vec` remains
6457    /// reachable through the `pub membros` field for the mutation-
6458    /// carrying serde round-trip and per-test fixture-mutation paths).
6459    #[must_use]
6460    pub const fn membros(&self) -> &[Membro] {
6461        self.membros.as_slice()
6462    }
6463
6464    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
6465    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
6466    /// accessor every per-Aplicacao contract-list reader keys off —
6467    /// returns the author-declared `:contratos` list verbatim as a
6468    /// `&[WitContract]` slice-view over the same backing buffer the raw
6469    /// `self.contratos.as_slice()` field access borrows from.
6470    ///
6471    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
6472    /// WIT-typed edge list — the load-bearing set of directed edges
6473    /// on the application graph whose nodes are the `:membros` entries
6474    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
6475    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
6476    /// six-tuple is the edge identity every downstream duplicate gate
6477    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
6478    /// Servico caller name + a `:para` destination-Servico callee name
6479    /// (through the lifted [`WitContract::source`] +
6480    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
6481    /// caller/callee-Servico axis) with a `:wit` world-reference
6482    /// (through the lifted [`WitContract::world_ref`] (0804823)
6483    /// accessor) and the target-shape-appropriate payload-carrier
6484    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
6485    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
6486    /// (ed22b66) accessor on the per-target-shape payload-carrier
6487    /// axis). Every downstream consumer that fans on the edge-set
6488    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
6489    /// name-set / self-edge / target-shape / dedup fan-out loop, the
6490    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
6491    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
6492    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
6493    /// grouping loop, the `feira app graph` per-Aplicacao contract-
6494    /// count print line and per-contract tree traversal, every future
6495    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
6496    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
6497    /// mesh-policy overlay resolver's per-contract typed-edge weight
6498    /// reader).
6499    ///
6500    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
6501    /// accessed inline at four production sites — the
6502    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
6503    /// per-edge validate-loop traversal head (which drives every
6504    /// per-edge name-set membership lookup, self-edge check,
6505    /// target-shape dispatch, and dedup `HashSet` insert), the
6506    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6507    /// `for c in &self.contratos` adjacency-list seed head (which
6508    /// drives every per-edge sync-vs-pub-sub partition and per-edge
6509    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
6510    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
6511    /// `BTreeMap` grouping loop head (which drives every per-CNP
6512    /// fan-out emit), and the `feira app graph` per-Aplicacao print
6513    /// line's `spec.contratos.len()` count formatter argument paired
6514    /// with the peer `for c in &spec.contratos` per-contract tree
6515    /// traversal — four open-coded field-accesses that expressed no
6516    /// compile-time link back to the typed slot. A future extension
6517    /// of the `:contratos` axis to a richer author surface (a
6518    /// per-cluster contract overlay the operator pins through a
6519    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
6520    /// federation roadmap acknowledges, a per-tenant edge-policy
6521    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6522    /// materializer resolves per-CR at admission time, a per-edge
6523    /// weight scalar the future adaptive-placement engine reads to
6524    /// bias sync-subgraph routing, a promotion of the plain
6525    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
6526    /// once virtual-actor-style dynamic-edge composition comes into
6527    /// typed scope) would have had to be threaded through all four
6528    /// open-coded copies in lockstep or one consumer would silently
6529    /// disagree with the peers on which edge-set a given Aplicacao
6530    /// resolves to — the validator's per-edge dedup `HashSet` seed
6531    /// reading the raw slot while the peer sync-cycle adjacency-list
6532    /// seed read an operator-resolved slot would silently split the
6533    /// build-time edge-set gate from the runtime deadlock-detection
6534    /// gate, a four-consumer split at the validator, the cycle
6535    /// detector, the CNP emitter, and the graph printer far from
6536    /// the source `caixa.lisp` with no field naming the edge-set-
6537    /// drift root cause. Lifting the resolution rule to a typed method on the
6538    /// substrate primitive means every downstream consumer of the
6539    /// Aplicacao's per-`:contratos` edge-list surface reaches for
6540    /// exactly one typed dispatch — the resolver's accept-set
6541    /// migrates as a unit on any future axis addition.
6542    ///
6543    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
6544    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6545    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6546    /// static-child-list `Vec`-carry axis, to the M3
6547    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6548    /// on the peer per-`:placement` distribution-target-list `Vec`-
6549    /// carry axis, and to the immediately-adjacent sibling M3
6550    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
6551    /// the peer per-`:membros` node-list `Vec`-carry axis — the
6552    /// per-`:contratos` edge-list accessor is the natural pair of
6553    /// the per-`:membros` node-list accessor (graph edges over graph
6554    /// nodes; every graph-shaped consumer reads both). Same "one
6555    /// typed dispatch on the substrate primitive, thin projections
6556    /// at each consumer" discipline. The last remaining `Vec`-carry
6557    /// axis still unlifted at the time of this lift —
6558    /// [`crate::UpgradeFromEntry::instructions`]
6559    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
6560    /// list) — inherits this accessor's discipline as future
6561    /// compounding runs migrate its consumers onto the shared slice-
6562    /// return shape. Second `&[T]`-return accessor on the top-level
6563    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
6564    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
6565    /// `:contratos` are the two `Vec` fields on the outer typed
6566    /// composition view — `:politicas`, `:placement`, `:entrada` are
6567    /// scalar/option-shaped and already route through their per-slot
6568    /// accessor families). Named `contratos()` to match the storage
6569    /// field's name verbatim and the tatara-lisp author-surface term
6570    /// (`:contratos`) the field's own docstring already carries; the
6571    /// accessor's identity maps onto the canonical MESH-COMPOSITION
6572    /// §III.1 vocabulary the slot's docstring already reaches for.
6573    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
6574    /// every downstream consumer of the contract list treats it as a
6575    /// read-only sequence — the slice-view is the narrowest borrow
6576    /// that supports every present + roadmapped consumer
6577    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6578    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6579    /// the typed view reaches for (the storage-side `Vec` remains
6580    /// reachable through the `pub contratos` field for the mutation-
6581    /// carrying serde round-trip and per-test fixture-mutation paths).
6582    #[must_use]
6583    pub const fn contratos(&self) -> &[WitContract] {
6584        self.contratos.as_slice()
6585    }
6586
6587    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
6588    /// per-Aplicacao mesh-policy composite-reference accessor every
6589    /// per-Aplicacao policy-block reader keys off — returns the author-
6590    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
6591    /// reference over the same backing storage the raw `&self.politicas`
6592    /// field access borrows from.
6593    ///
6594    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
6595    /// mesh-policy composite — the load-bearing container of every
6596    /// mesh-level operational-policy axis every downstream mesh-artifact
6597    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
6598    /// mesh-policy overlay is the single typed surface a
6599    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
6600    /// from). Every per-`:politicas` axis threads through a lifted
6601    /// per-slot accessor on the [`MeshPolicy`] type: the
6602    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
6603    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
6604    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
6605    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
6606    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
6607    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
6608    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
6609    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
6610    /// accessor. Every downstream consumer that reaches for a policy
6611    /// axis first passes through this outer accessor onto the composite
6612    /// and then dispatches onto the per-axis accessor — the two-level
6613    /// dispatch means every per-`:politicas` reader now routes through
6614    /// a typed dispatch on the substrate primitive at both altitudes.
6615    ///
6616    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
6617    /// accessed inline at four production sites — the
6618    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
6619    /// &self.politicas;` traversal seed (which drives every per-axis
6620    /// zero-floor + upper-cap + canonical-form bracket dispatch through
6621    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
6622    /// `p.rate_limit()` on the axis-level lifted accessors), the
6623    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
6624    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
6625    /// chain (which drives every per-`(:de, :para)` CNP
6626    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
6627    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
6628    /// timeout + retry overlay emitter's paired
6629    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
6630    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
6631    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
6632    /// open-coded outer-field accesses that expressed no compile-time
6633    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
6634    /// future extension of the `:politicas` outer axis to a richer
6635    /// author surface (a per-cluster policy overlay the operator pins
6636    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
6637    /// §V federation roadmap acknowledges, a per-tenant policy-alias
6638    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6639    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6640    /// policy-composite derivation the future adaptive-placement engine
6641    /// computes from a per-cluster load-topology reader, a promotion of
6642    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
6643    /// partition once virtual-actor-style dynamic-mesh-policy
6644    /// composition comes into typed scope) would have had to be threaded
6645    /// through all four open-coded copies in lockstep or one consumer
6646    /// would silently disagree with the peers on which mesh-policy
6647    /// composite a given Aplicacao resolves to — the validator's
6648    /// per-axis bracket-dispatch seed reading the raw slot while the
6649    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
6650    /// would silently split the build-time policy-shape gate from the
6651    /// runtime CNP-emission gate, a four-consumer split at the
6652    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
6653    /// the source `caixa.lisp` with no field naming the policy-drift
6654    /// root cause. Lifting the resolution rule to a typed method on the
6655    /// substrate primitive means every downstream consumer of the
6656    /// Aplicacao's per-`:politicas` mesh-policy composite surface
6657    /// reaches for exactly one typed dispatch — the resolver's accept-
6658    /// set migrates as a unit on any future axis addition.
6659    ///
6660    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
6661    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
6662    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6663    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
6664    /// close the two `Vec`-carry axes on the outer typed composition
6665    /// view; the outer `:politicas` composite-reference axis is the
6666    /// natural pair to the paired outer `Vec`-carry accessors on the
6667    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
6668    /// emitter reads all four axes as one unit (graph nodes + graph
6669    /// edges + mesh policy + placement pool). Peer to the same
6670    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
6671    /// slot: every M2 `SupervisorSpec`-scoped composite reader
6672    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
6673    /// `restart_window`, `children`) already routes through the M2
6674    /// `SupervisorSpec` accessor family — this lift extends the same
6675    /// "one typed dispatch on the substrate primitive at the outer
6676    /// composition altitude" discipline to the M3 mesh-slot
6677    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
6678    /// remaining peer outer-composite axes still unlifted at the time
6679    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
6680    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
6681    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
6682    /// inherit this accessor's discipline as future compounding runs
6683    /// migrate their consumers onto the shared reference-return shape.
6684    /// Named `politicas()` to match the storage field's name verbatim
6685    /// and the tatara-lisp author-surface term (`:politicas`) the
6686    /// field's own docstring already carries; the accessor's identity
6687    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
6688    /// slot's docstring already reaches for. Returns `&MeshPolicy`
6689    /// (not the owning composite by copy or clone) because every
6690    /// downstream consumer of the mesh-policy composite treats it as a
6691    /// read-only per-axis dispatch source — the reference-view is the
6692    /// narrowest borrow that supports every present + roadmapped
6693    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
6694    /// emptiness probe) without cloning the composite through every
6695    /// consumer's fast path.
6696    #[must_use]
6697    pub const fn politicas(&self) -> &MeshPolicy {
6698        &self.politicas
6699    }
6700
6701    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
6702    /// per-Aplicacao distribution-composite composite-reference accessor
6703    /// every per-Aplicacao placement-block reader keys off — returns the
6704    /// author-declared `:placement` composite verbatim as a `&Placement`
6705    /// reference over the same backing storage the raw `&self.placement`
6706    /// field access borrows from.
6707    ///
6708    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
6709    /// distribution composite — the load-bearing container of every
6710    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
6711    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
6712    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
6713    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
6714    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
6715    /// `:affinity` hint). Every per-`:placement` axis threads through a
6716    /// lifted per-slot accessor on the [`Placement`] type: the
6717    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
6718    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
6719    /// per-cluster distribution-target slice-return accessor, the
6720    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
6721    /// optional-scalar accessor, and the [`Placement::shard_key`]
6722    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
6723    /// downstream consumer that reaches for a placement axis first passes
6724    /// through this outer accessor onto the composite and then dispatches
6725    /// onto the per-axis accessor — the two-level dispatch means every
6726    /// per-`:placement` reader now routes through a typed dispatch on the
6727    /// substrate primitive at both altitudes.
6728    ///
6729    /// Prior to this lift the `.placement` `Placement` composite was
6730    /// accessed inline at three production sites — the
6731    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
6732    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
6733    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
6734    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
6735    /// cluster `.clusters()` validate-loop traversal head, the per-
6736    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
6737    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
6738    /// paired with the shape-gate cascade's `.shard_key()` /
6739    /// `.estrategia()` diagnostic-carry pair), the
6740    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
6741    /// per-entry placement-block emitter's outer
6742    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
6743    /// seed (which fans onto every per-cluster `programs[]` entry as a
6744    /// self-describing distribution overlay the aggregator filters by),
6745    /// and the `feira app graph` per-Aplicacao print line's paired
6746    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
6747    /// then-inner-accessor chains (which drive the human-readable
6748    /// distribution summary of the typed Aplicacao view) — three open-
6749    /// coded outer-field accesses that expressed no compile-time link
6750    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
6751    /// extension of the `:placement` outer axis to a richer author surface
6752    /// (a per-cluster placement overlay the operator pins through a
6753    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
6754    /// federation roadmap acknowledges, a per-tenant placement-alias
6755    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6756    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6757    /// placement-composite derivation the future M5 adaptive-placement
6758    /// engine computes from a per-cluster load-topology reader, a
6759    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
6760    /// partition once Orleans-style virtual-actor dynamic-placement comes
6761    /// into typed scope) would have had to be threaded through all three
6762    /// open-coded copies in lockstep or one consumer would silently
6763    /// disagree with the peers on which placement composite a given
6764    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
6765    /// seed reading the raw slot while the peer
6766    /// `programs_for_aplicacao` emitter read an operator-resolved slot
6767    /// would silently split the build-time distribution-shape gate from
6768    /// the runtime programs.yaml distribution-annotation gate, a three-
6769    /// consumer split at the validator, the programs.yaml emitter, and
6770    /// the `feira app graph` printer far from the source `caixa.lisp`
6771    /// with no field naming the placement-drift root cause. Lifting the
6772    /// resolution rule to a typed method on the substrate primitive
6773    /// means every downstream consumer of the Aplicacao's per-
6774    /// `:placement` distribution composite surface reaches for exactly
6775    /// one typed dispatch — the resolver's accept-set migrates as a unit
6776    /// on any future axis addition.
6777    ///
6778    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
6779    /// `AplicacaoSpec` type itself — sibling to the seed
6780    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
6781    /// composite-reference accessor on the peer per-`:politicas` outer-
6782    /// composite axis, and to the paired slice-return accessors
6783    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6784    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
6785    /// the two `Vec`-carry axes on the outer typed composition view; the
6786    /// outer `:placement` composite-reference axis is the natural pair
6787    /// to the peer `:politicas` composite-reference axis on the two
6788    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
6789    /// how-to-run policy overlay, `:placement` carries the where-to-run
6790    /// distribution composite — every whole-Aplicacao mesh-artifact
6791    /// emitter reads both as one unit). Same "one typed dispatch on the
6792    /// substrate primitive, thin projections at each consumer"
6793    /// discipline the peer per-`:politicas` composite-reference axis
6794    /// already routes through. The one remaining outer-composite axis
6795    /// still unlifted at the time of this lift —
6796    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
6797    /// external-gateway composite) — inherits this accessor's discipline
6798    /// as the next compounding run migrates its consumers onto the shared
6799    /// reference-return shape, closing the outer-composite altitude on
6800    /// every M3 mesh-slot axis. Named `placement()` to match the storage
6801    /// field's name verbatim and the tatara-lisp author-surface term
6802    /// (`:placement`) the field's own docstring already carries; the
6803    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
6804    /// vocabulary the slot's docstring already reaches for. Returns
6805    /// `&Placement` (not the owning composite by copy or clone) because
6806    /// every downstream consumer of the placement composite treats it as
6807    /// a read-only per-axis dispatch source — the reference-view is the
6808    /// narrowest borrow that supports every present + roadmapped consumer
6809    /// (per-axis accessor dispatch, serde composite-serialization) without
6810    /// cloning the composite through every consumer's fast path.
6811    #[must_use]
6812    pub const fn placement(&self) -> &Placement {
6813        &self.placement
6814    }
6815
6816    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
6817    /// per-Aplicacao external-gateway composite optional-composite-
6818    /// reference accessor every per-Aplicacao gateway-block reader
6819    /// keys off — returns the author-declared `:entrada` composite
6820    /// verbatim as an `Option<&Entrada>` reference over the same
6821    /// backing storage the raw `self.entrada.as_ref()` field access
6822    /// borrows from, with `None` naming the internal-only mesh shape
6823    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
6824    /// gateway_routes emitter treats as "emit nothing" and the peer
6825    /// `feira app graph` printer treats as "internal-only mesh").
6826    ///
6827    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
6828    /// external-gateway composite — the load-bearing container of
6829    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
6830    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
6831    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
6832    /// hostname axis, §III.4 for the `:para` destination-Servico
6833    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
6834    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
6835    /// axis threads through a lifted per-slot accessor on the
6836    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
6837    /// Gateway-API `Listener.hostname` scalar accessor, the paired
6838    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
6839    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
6840    /// backendRefs destination-Servico scalar accessor, the
6841    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
6842    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
6843    /// scalar accessor. Every downstream consumer that reaches for
6844    /// an entrada axis first passes through this outer accessor onto
6845    /// the composite and then dispatches onto the per-axis accessor
6846    /// — the two-level dispatch means every per-`:entrada` reader
6847    /// now routes through a typed dispatch on the substrate primitive
6848    /// at both altitudes.
6849    ///
6850    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
6851    /// was accessed inline at four production sites — the
6852    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
6853    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
6854    /// (which drives every per-axis refusal on the composite: the
6855    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
6856    /// `EntradaMemberMissing` membership lookup against the
6857    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
6858    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
6859    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
6860    /// per-path shape gate on each entry of `e.paths`), the
6861    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
6862    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
6863    /// composite-projection seed (which drives the destination-
6864    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
6865    /// backendRefs port emitter fans on), the
6866    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
6867    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
6868    /// early-return seed (which drives the "no `:entrada` ⇒ no
6869    /// external artifacts" partition on the whole-Aplicacao Gateway-
6870    /// API emitter's fan-out), and the `feira app graph` per-
6871    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
6872    /// external-gateway summary emitter (which drives the human-
6873    /// readable `entrada: host → para (paths=…, port=…)` /
6874    /// `entrada: (internal-only mesh)` partition on the typed
6875    /// Aplicacao view) — four open-coded outer-field accesses that
6876    /// expressed no compile-time link back to the typed slot at the
6877    /// [`AplicacaoSpec`] altitude. A future extension of the
6878    /// `:entrada` outer axis to a richer author surface (a
6879    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
6880    /// at admission time so an Aplicacao can expose a public-web +
6881    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
6882    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
6883    /// operator can pin a per-cluster hostname override without
6884    /// re-authoring the `caixa.lisp`, a promotion of the plain
6885    /// `Option<Entrada>` to a richer `{single, multi}` partition once
6886    /// the multi-`:entrada` roadmap lands) would have had to be
6887    /// threaded through all four open-coded copies in lockstep or one
6888    /// consumer would silently disagree with the peers on which
6889    /// entrada composite a given Aplicacao resolves to — the
6890    /// validator's per-axis bracket-dispatch seed reading the raw
6891    /// slot while the peer `gateway_routes` emitter read an
6892    /// operator-resolved slot would silently split the build-time
6893    /// gateway-shape gate from the runtime Gateway + HTTPRoute
6894    /// emission gate, a four-consumer split at the validator, the
6895    /// `port_for_destination` L4-port resolver, the `gateway_routes`
6896    /// emitter, and the `feira app graph` printer far from the
6897    /// source `caixa.lisp` with no field naming the entrada-drift
6898    /// root cause. Lifting the resolution rule to a typed method on
6899    /// the substrate primitive means every downstream consumer of
6900    /// the Aplicacao's per-`:entrada` external-gateway composite
6901    /// surface reaches for exactly one typed dispatch — the
6902    /// resolver's accept-set migrates as a unit on any future axis
6903    /// addition.
6904    ///
6905    /// Third and final `&Composite`-return accessor on the top-level
6906    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
6907    /// unlifted outer-composite axis on the outer typed composition
6908    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
6909    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
6910    /// accessor on the per-`:politicas` outer-composite axis and to
6911    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
6912    /// distribution-composite composite-reference accessor on the
6913    /// per-`:placement` outer-composite axis; extends the outer-
6914    /// composite reference-return discipline the two peers already
6915    /// route through onto the last unlifted per-`AplicacaoSpec`
6916    /// outer-composite axis. The `:entrada` outer-composite axis is
6917    /// the natural pair to the two peer outer-composite axes on the
6918    /// three operationally-symmetric M3 mesh-slot outer composites
6919    /// (`:politicas` carries the how-to-run policy overlay,
6920    /// `:placement` carries the where-to-run distribution composite,
6921    /// `:entrada` carries the who-can-reach-it external-gateway
6922    /// composite — every whole-Aplicacao mesh-artifact emitter reads
6923    /// all three as one unit). Same "one typed dispatch on the
6924    /// substrate primitive, thin projections at each consumer"
6925    /// discipline the peer outer-composite axes already route through.
6926    /// Named `entrada()` to match the storage field's name verbatim
6927    /// and the tatara-lisp author-surface term (`:entrada`) the
6928    /// field's own docstring already carries; the accessor's
6929    /// identity maps onto the canonical MESH-COMPOSITION §III.4
6930    /// vocabulary the slot's docstring already reaches for. Returns
6931    /// `Option<&Entrada>` (not the owning composite by copy or
6932    /// clone) because every downstream consumer of the entrada
6933    /// composite treats it as a read-only per-axis dispatch source
6934    /// — the reference-view is the narrowest borrow that supports
6935    /// every present + roadmapped consumer (per-axis accessor
6936    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
6937    /// port-fallback projection, early-return partition on the
6938    /// `None` arm) without cloning the composite through every
6939    /// consumer's fast path. The `Option` half of the return-type
6940    /// preserves the load-bearing "author-omitted `:entrada` ⇒
6941    /// internal-only mesh" partition (not a default composite the
6942    /// downstream must reject on emptiness) — the accessor projects
6943    /// the raw `Option<Entrada>` slot's presence bit through the
6944    /// reference-return unchanged.
6945    #[must_use]
6946    pub const fn entrada(&self) -> Option<&Entrada> {
6947        self.entrada.as_ref()
6948    }
6949
6950    /// Validate the typed shape:
6951    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
6952    ///     and a non-empty `:versao`; no two entries share the same
6953    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
6954    ///     not a multiset)
6955    ///   - every `:contratos` :de + :para must be in `:membros`
6956    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
6957    ///     contract is an inter-Servico edge, so a Servico contracting
6958    ///     with itself is a build error under every WIT shape
6959    ///     (MESH-COMPOSITION §III.1)
6960    ///   - no two `:contratos` entries agree on
6961    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
6962    ///     edges are a set, not a multiset (peer of the `:membros` /
6963    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
6964    ///   - `:entrada :para` must be in `:membros`
6965    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
6966    ///     `:placement Replicated`/`SingleNode` must NOT declare
6967    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
6968    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
6969    ///     between strategy and shard-key is symmetric: every validated
6970    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
6971    ///     Sharded`
6972    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
6973    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
6974    ///     the shard pool (MESH-COMPOSITION §III.1)
6975    ///   - every `:clusters` entry is non-empty and unique
6976    ///   - `:placement :affinity`, when set, is non-empty
6977    ///   - the synchronous-`:contratos` subgraph is acyclic
6978    ///     (MESH-COMPOSITION §III.3)
6979    ///   - every declared `:politicas` value is operationally meaningful
6980    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
6981    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
6982    ///     omit the field instead to express "no policy on this axis")
6983    pub fn validate(&self) -> Result<(), AplicacaoError> {
6984        self.validate_membros()?;
6985        let names: std::collections::HashSet<&str> =
6986            self.membros().iter().map(Membro::nome).collect();
6987
6988        // Identity key for the typed-edge duplicate gate below: every
6989        // field that distinguishes one contract from another. Two
6990        // entries that agree on all six are *the same edge declared
6991        // twice*, the typed-graph analogue of duplicate `:membros` /
6992        // `:placement :clusters` / `:entrada :paths` entries (which
6993        // are already build errors at this layer). Rejecting it at the
6994        // validate gate closes a renderer-side footgun: caixa-mesh's
6995        // `cilium_network_policies` keys each emitted policy by
6996        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
6997        // (de, para) and identical payload would land as two K8s
6998        // objects with colliding `metadata.name`, rejected at apply
6999        // time far from the source caixa.lisp.
7000        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
7001            std::collections::HashSet::new();
7002        for c in self.contratos() {
7003            // Per-axis value-shape gate on every `:contratos` name
7004            // reference, before any graph-membership lookup. Empty +
7005            // DNS-1123-malformed `:de`/`:para` values silently fell
7006            // through to `ContratoMemberMissing` at the lookup arm
7007            // because every `:membros :caixa` is shape-validated
7008            // (3f9d7a0), so the `names` set structurally cannot contain
7009            // an empty / malformed string and the membership-lookup
7010            // diagnostic always misframed the root cause as
7011            // "this caixa is not in `:membros`". The shape gate runs
7012            // ahead of the lookup so structurally-impossible-to-match
7013            // inputs route through the narrower self-locating
7014            // diagnostic, preserving the legitimate "well-shaped
7015            // phantom reference" arm. `:de` runs before `:para` per
7016            // the canonical edge-direction order the existing
7017            // membership lookup, self-edge check, target dispatch,
7018            // and diagnostic strings already use.
7019            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
7020            // + the paired [`AplicacaoError::ContratoMemberMissing`]
7021            // diagnostic's `caixa:` carrier through the lifted
7022            // [`WitContract::source`] / [`WitContract::destination`]
7023            // scalar accessors rather than the raw `&c.de` / `&c.para`
7024            // `&String`-borrow arg site + the raw `c.de.clone()` /
7025            // `c.para.clone()` field-access `String`-carry sites — the
7026            // last unlifted per-`:contratos` raw-field-access sites in
7027            // the M3 mesh-slot validator's per-edge per-arm shape-gate
7028            // arg + phantom-name diagnostic wrap-envelope emit surface.
7029            // `c.source()` is byte-identical to `&c.de` (pinned by the
7030            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
7031            // + `wit_contract_source_borrows_from_de_storage` accessor
7032            // tests) and `c.destination()` is byte-identical to `&c.para`
7033            // (pinned by the sibling
7034            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
7035            // + `wit_contract_destination_borrows_from_para_storage`
7036            // accessor tests) — so a future rebrand of either underlying
7037            // storage flows through the accessor's one body without a
7038            // coordinated per-consumer rewrite across the M3 mesh
7039            // validator's per-edge shape-gate + phantom-name refusal
7040            // arms. Peer of the sibling per-`:contratos` self-loop
7041            // arm's `.source().to_string()` / `.world_ref().to_string()`
7042            // `String`-carry sites the earlier convergence lifted onto
7043            // the same accessor pair.
7044            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
7045            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
7046            if !names.contains(c.source()) {
7047                return Err(AplicacaoError::ContratoMemberMissing {
7048                    caixa: c.source().to_string(),
7049                });
7050            }
7051            if !names.contains(c.destination()) {
7052                return Err(AplicacaoError::ContratoMemberMissing {
7053                    caixa: c.destination().to_string(),
7054                });
7055            }
7056            // A `:contratos` entry is an *inter*-Servico contract
7057            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
7058            // typed edge between two distinct graph nodes. An edge whose
7059            // `:de` equals its `:para` is a Servico contracting with
7060            // itself — a degenerate edge under every WIT shape. The
7061            // synchronous shapes were caught only incidentally, and with
7062            // a misleading diagnostic: `detect_sync_cycles` reported
7063            // `cart → cart` as a `ContratoCycle` whose path is
7064            // `["cart", "cart"]` — framing a self-edge as a multi-node
7065            // deadlock. The pub-sub shape slipped through entirely
7066            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
7067            // `nats:pub-sub` edge from a member to itself silently
7068            // validated, then rendered a `CiliumNetworkPolicy` whose
7069            // endpointSelector and fromEndpoints both name the same
7070            // program — a self-allow rule that is a no-op, since
7071            // intra-pod traffic never traverses the mesh). A self-edge's
7072            // runtime meaning is an in-process call, which doesn't go
7073            // through the mesh at all, so no `:contratos` edge can carry
7074            // it. Firing the gate before the `:wit`/`target()` shape
7075            // checks means the structural "this edge can't exist" error
7076            // precedes the narrower payload-shape diagnostics, and shape-
7077            // agnostically covers all four `WitTarget` arms (HTTP / Store
7078            // / Capability / PubSub) at one point — closing the pub-sub
7079            // hole and replacing the misleading cycle diagnostic in one
7080            // gate. Peer of the duplicate-`:contratos` / duplicate-
7081            // `:membros` set gates: both reject a structurally
7082            // ill-formed graph at the typed surface, before the renderer
7083            // emits a K8s object that fails or no-ops far from the source
7084            // caixa.lisp.
7085            // Route the per-`:contratos` structural self-edge probe
7086            // through the lifted [`WitContract::is_self_loop`] typed
7087            // predicate rather than the raw `c.de == c.para` field-
7088            // equality check — the one production consumer of the per-
7089            // `:contratos` caller-equals-callee endpoint-equality axis
7090            // now keys off exactly one typed dispatch on the substrate
7091            // primitive, so any future rebrand of the axis (an M4-typed-
7092            // caller enum whose identity comparison rule the predicate
7093            // could route through, a per-cluster caller/callee-alias
7094            // table the M4 CR materializer resolves per-CR before the
7095            // equality probe) migrates as a single caixa-core edit
7096            // rather than a coordinated rewrite of the gate + every
7097            // downstream self-edge consumer. Peer of the sibling
7098            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
7099            // [`WitContract::is_store`] shape-predicate routing on the
7100            // `:wit` world-ref axis, extended onto the per-edge
7101            // endpoint-equality axis.
7102            //
7103            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
7104            // diagnostic's `caixa:` / `wit:` carriers through the
7105            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
7106            // scalar accessors rather than the raw `c.de.clone()` /
7107            // `c.wit.clone()` field-access `String`-carry sites — the
7108            // last unlifted per-`:contratos` raw-field-access
7109            // `.clone()` sites in the M3 mesh-slot validator's self-
7110            // edge refusal arm. `.source().to_string()` is byte-
7111            // identical to `.de.clone()` (pinned by the sibling
7112            // `source_returns_de_byte_equal_across_permutations` accessor
7113            // test), and `.world_ref().to_string()` is byte-identical
7114            // to `.wit.clone()` (pinned by the sibling
7115            // `world_ref_returns_wit_byte_equal_across_permutations`
7116            // accessor test) — so a future rebrand of either underlying
7117            // storage flows through the accessor's one body without a
7118            // coordinated per-consumer rewrite across the M3 mesh
7119            // validator.
7120            if c.is_self_loop() {
7121                return Err(AplicacaoError::ContratoSelfLoop {
7122                    caixa: c.source().to_string(),
7123                    wit: c.world_ref().to_string(),
7124                });
7125            }
7126            if c.world_ref().is_empty() {
7127                let (de, para) = c.edge_pair();
7128                return Err(AplicacaoError::EmptyWit { de, para });
7129            }
7130            // Shape ↔ target consistency — surfaces "HTTP wit without
7131            // :endpoint", "NATS wit with :endpoint set", etc. as named
7132            // build errors instead of silent renderer drops. Threaded
7133            // through the duplicate-edge diagnostic below (via
7134            // [`WitTarget::label`]) so the "which typed target arm did
7135            // the duplicate carry" question is answered by the typed
7136            // enum's variant discriminator, not by re-probing the raw
7137            // `Option<String>` payload fields.
7138            let target_view = c.target()?;
7139            // Contract identity: (de, para, wit, endpoint, subject, slot).
7140            // Two contracts that match on all six are the same typed edge
7141            // declared twice — author error, not a legitimate variant of
7142            // "same caller-callee pair, different payload" (e.g.
7143            // cart→catalog at /products vs /search), which keeps distinct
7144            // identity keys via the differing endpoint payloads.
7145            //
7146            // Route the six-axis dedup key through the lifted
7147            // [`WitContract::identity`] composite-projection accessor
7148            // rather than the inline six-tuple builder — the two
7149            // substrate primitives on the per-`:contratos` identity axis
7150            // (the [`ContratoIdentity`] type alias's six axes, this
7151            // dedup-key's six tuple arms) now migrate as a unit on any
7152            // future axis addition. Peer of the sibling per-`:contratos`
7153            // composite-projection [`WitContract::edge_pair`] /
7154            // [`WitContract::edge_triple`] accessors on the
7155            // caller-callee / caller-callee-wit prefix axes; extends
7156            // the discipline onto the full-identity axis that carries
7157            // the three payload-shape arms too.
7158            let key = c.identity();
7159            crate::render::insert_first_seen(&mut seen_contracts, key, || {
7160                // Route the per-`:contratos` duplicate-gate diagnostic's
7161                // `(de, para, wit)` triple through the lifted
7162                // [`WitContract::edge_triple`] typed accessor rather
7163                // than pairing `edge_pair()` for the `(de, para)` prefix
7164                // with a raw `c.wit.clone()` for the `wit:` tail — the
7165                // paired-with-raw-field-access shape was the last
7166                // per-`:contratos` diagnostic constructor bypassing the
7167                // substrate-primitive composite projection, sibling to
7168                // the eight [`AplicacaoError::Contrato*`] triple-
7169                // carrying constructors [`WitContract::target`]'s edge
7170                // closure feeds through the same accessor.
7171                let (de, para, wit) = c.edge_triple();
7172                AplicacaoError::ContratoDuplicate {
7173                    de,
7174                    para,
7175                    wit,
7176                    target: target_view.label(),
7177                }
7178            })?;
7179        }
7180
7181        // Cycles in the synchronous-edge subgraph are build errors
7182        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
7183        // are "acyclic by construction" because the publisher fires
7184        // and forgets, so no caller blocks on a downstream that loops
7185        // back to it.
7186        self.detect_sync_cycles()?;
7187
7188        if let Some(e) = self.entrada() {
7189            // Route the per-`:entrada` composite-reference read
7190            // through the lifted [`AplicacaoSpec::entrada`] accessor
7191            // rather than the raw `&self.entrada` field access — the
7192            // shape-and-membership gate's traversal head is now the
7193            // canonical read-side surface every per-Aplicacao entrada
7194            // consumer routes through, closing the fourth of four
7195            // open-coded outer-field accesses on the per-`:entrada`
7196            // outer-composite axis.
7197            //
7198            // Shape gate on `:entrada :para` runs ahead of the
7199            // membership lookup. Every `:membros :caixa` past
7200            // `validate_membro_caixa` is a valid DNS-1123 label
7201            // (3f9d7a0), so the `names` set structurally cannot
7202            // contain an empty / malformed string and the membership-
7203            // lookup diagnostic always misframed the root cause as
7204            // "this caixa is not in `:membros`". The shape gate
7205            // routes structurally-impossible-to-match inputs through
7206            // the narrower self-locating diagnostic, preserving the
7207            // legitimate "well-shaped phantom reference" arm — the
7208            // same trajectory the peer `:membros :caixa` (3f9d7a0),
7209            // `:placement :clusters` (6c8c00b), and `:contratos :de`
7210            // / `:para` (8d5af6b) axes already follow. This closes
7211            // the fourth and last Aplicacao-level Servico-name
7212            // reference axis on the canonical DNS-1123 floor.
7213            // Route the per-`:entrada :para` byte-string reads through
7214            // the lifted [`Entrada::destination`] accessor rather than
7215            // the raw `e.para` field access — the three
7216            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
7217            // (shape-gate `validate_entrada_para` arg, membership
7218            // lookup, `EntradaMemberMissing` diagnostic carry) now key
7219            // off exactly one typed dispatch on the substrate
7220            // primitive, closing the last unlifted per-`:entrada :para`
7221            // raw-field-access axis on the M3 mesh-slot validator.
7222            // The `.destination().to_string()` at the diagnostic site
7223            // is byte-identical to `.para.clone()` — pinned by the
7224            // sibling `destination_returns_entrada_para_byte_equal` +
7225            // `destination_borrows_from_entrada_para_storage` accessor
7226            // tests — so a future rebrand of the underlying `:para`
7227            // storage (a lift from `String` to a typed
7228            // `ServicoName(String)` newtype, a per-Aplicacao interning
7229            // arena the M4 CR materializer authors, a
7230            // `smol_str::SmolStr` inline-buffer swap) flows through
7231            // the accessor's one body without a coordinated
7232            // per-consumer rewrite across the M3 mesh validator.
7233            validate_entrada_para(e.destination())?;
7234            if !names.contains(e.destination()) {
7235                return Err(AplicacaoError::EntradaMemberMissing {
7236                    para: e.destination().to_string(),
7237                });
7238            }
7239            // Route the per-`:entrada :host` byte-string reads through
7240            // the lifted [`Entrada::hostname`] accessor rather than
7241            // the raw `e.host` field access — the emptiness gate and
7242            // the shape-gate `validate_entrada_host` arg now key off
7243            // exactly one typed dispatch on the substrate primitive,
7244            // closing the last unlifted per-`:entrada :host` raw-
7245            // field-access axis on the M3 mesh-slot validator. Peer
7246            // of the sibling per-`:entrada :para` convergence above
7247            // and pinned by the existing
7248            // `hostname_returns_entrada_host_byte_equal` +
7249            // `hostnames_returns_singleton_of_hostname_accessor`
7250            // accessor tests, so any future
7251            // Gateway-API-shaped host renormalization (a wildcard-
7252            // label lift, a trailing-`.` FQDN substitution, an IDNA
7253            // Punycode round-trip the SNI fan-out overlay authors)
7254            // flows through the accessor's one body without a
7255            // coordinated per-consumer rewrite across the M3 mesh
7256            // validator.
7257            if e.hostname().is_empty() {
7258                return Err(AplicacaoError::EmptyEntradaHost);
7259            }
7260            // The `:host` lands verbatim as a K8s Gateway API v1
7261            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
7262            // both apiserver-validated against the same restrictive
7263            // pattern: lowercase RFC 1123 DNS subdomain, optional
7264            // single leading wildcard label (`*.`), max length 253,
7265            // per-label max length 63, no IP literals, no scheme,
7266            // no port. Until this gate landed `validate()` only
7267            // refused the empty string (`EmptyEntradaHost`); a
7268            // structurally invalid hostname (`"https://example.com"`,
7269            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
7270            // `"_underscored.example.com"`, `"FOO.example.com"`,
7271            // `"checkout.quero.cloud."`) silently passed validate
7272            // and the apiserver `field is invalid` error surfaced at
7273            // `kubectl apply` time, far from the source caixa.lisp.
7274            // Lifting the gate to caixa-build time mirrors the
7275            // `:entrada :paths` value-shape trajectory (eb3456d) and
7276            // closes the last unstructured `:entrada` axis.
7277            validate_entrada_host(e.hostname())?;
7278            // Structural-floor gate on `:entrada :port`: every
7279            // validated `Entrada::port` past this gate lies in
7280            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
7281            // type-inferred ceiling closes the top edge, so no companion
7282            // upper-cap arm is needed here — unlike the peer capped-
7283            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
7284            // `require_positive_bounded_u32` bracket covers both edges).
7285            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
7286            // accept-set-floor const rather than the prior inline
7287            // `if e.port == 0` byte-check so a future rebrand of the
7288            // accept-set floor (a hypothetical unprivileged-only
7289            // migration lifting the floor to `1024`, a per-cluster
7290            // scoping the operator pins through a future
7291            // `:placement :port-floor` slot as the M4 typed-slot
7292            // trajectory adds it, the future
7293            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7294            // per-Aplicacao gateway resolver reaching for the same
7295            // floor) is a one-line edit on the canonical
7296            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
7297            // rewrite across the emit site + the pin test + every
7298            // future per-target renderer the substrate adds.
7299            if e.port() < SERVICO_PORT_MIN {
7300                return Err(AplicacaoError::EntradaPortZero);
7301            }
7302            // Each `:entrada :paths` entry becomes a K8s Gateway API
7303            // HTTPRoute `matches[].path.value`. The Gateway API rejects
7304            // values that don't start with `/` for `type: PathPrefix`,
7305            // and an empty value is meaningless. Surface those as build
7306            // errors (MESH-COMPOSITION §III.3) rather than apply-time
7307            // failures. Empty `:paths` itself is fine — caixa-mesh
7308            // falls back to a single `/` catch-all.
7309            let mut seen = std::collections::HashSet::new();
7310            // Route the per-entry value-shape gate's traversal head
7311            // through the lifted [`Entrada::paths`] slice accessor
7312            // rather than the raw `&e.paths` field access — the
7313            // per-Aplicacao `:entrada :paths` validate loop now keys
7314            // off the canonical raw-slot surface every downstream
7315            // per-`:entrada` path-list consumer (the sibling
7316            // [`Entrada::resolved_paths`] fallback-applying resolver
7317            // internal reads, `feira app graph`'s per-Aplicacao entrada
7318            // summary line's `{:?}` Debug print) routes through, so any
7319            // future rebrand on the typed slot's raw-slot reader lands
7320            // at exactly one place. Same convergence discipline as the
7321            // sibling [`Placement::clusters`] (a6e18d7) reader-site
7322            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
7323            // axis.
7324            for p in e.paths() {
7325                if p.is_empty() {
7326                    return Err(AplicacaoError::EntradaPathEmpty);
7327                }
7328                if !p.starts_with('/') {
7329                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
7330                }
7331                // Per-entry value-shape gate: the path lands verbatim
7332                // as a K8s Gateway API HTTPRoute `matches[].path.value`
7333                // (caixa-mesh/src/lib.rs:498), apiserver-validated
7334                // against `maxLength: 1024` + the Gateway API webhook's
7335                // path-grammar rules (no `//`, no `/./`, no `/../`, no
7336                // query/fragment separators, no whitespace, no control
7337                // characters, no non-ASCII bytes). Until this gate
7338                // landed `validate` only refused the empty string and
7339                // missing-leading-slash (eb3456d); a structurally
7340                // invalid path (`"/api?q=1"`, `"/api#frag"`,
7341                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
7342                // 1025-byte URL-shaped slug) silently passed validate
7343                // and the failure surfaced at `kubectl apply` time as
7344                // a Gateway API webhook rejection, far from the source
7345                // caixa.lisp, with no field naming the offending
7346                // `:paths` entry. Lifting the gate to caixa-build time
7347                // mirrors the `:entrada :host` value-shape trajectory
7348                // (c7d05ec) on the sibling axis — every author surface
7349                // that emits a Gateway API field now matches the
7350                // apiserver's accepted set at validate time.
7351                validate_entrada_path(p)?;
7352                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
7353                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
7354                })?;
7355            }
7356        }
7357
7358        self.validate_placement()?;
7359
7360        self.validate_politicas()?;
7361
7362        Ok(())
7363    }
7364
7365    /// Reject `:membros` values that are operationally meaningless. The
7366    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
7367    /// every entry names a Servico that participates in the Aplicacao,
7368    /// and the rendered programs.yaml fan-out emits one entry per
7369    /// `:membros`. Three authoring footguns are closed here:
7370    ///
7371    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
7372    ///     a `programs:` entry whose `name:` is the empty string, which
7373    ///     downstream `lareira-fleet-programs` rejects at template time
7374    ///     with a non-localized error;
7375    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
7376    ///     an empty semver constraint, so the failure surfaces far from
7377    ///     the source caixa.lisp;
7378    ///   - duplicate `:caixa` names — two entries with the same name
7379    ///     produce duplicate programs.yaml entries (one silently
7380    ///     overwrites the other in the cluster's HelmRelease values), and
7381    ///     contract membership lookups against `:contratos` collapse the
7382    ///     two onto one node, masking authoring mistakes.
7383    ///
7384    /// Same value-shape discipline as `:placement :clusters` (where empty
7385    /// + duplicate cluster names are rejected) and `:entrada :paths`
7386    /// (where empty + duplicate path entries are rejected). Lifting these
7387    /// invariants to the typed surface mirrors the MESH-COMPOSITION
7388    /// §III.3 promise that the `:membros` set — the load-bearing identity
7389    /// of the application graph — is well-formed by construction.
7390    fn validate_membros(&self) -> Result<(), AplicacaoError> {
7391        if self.membros().is_empty() {
7392            return Err(AplicacaoError::NoMembros);
7393        }
7394        let mut seen = std::collections::HashSet::new();
7395        for m in self.membros() {
7396            // Route the `MembroCaixaEmpty` refusal-arm's per-member
7397            // empty-`:caixa` shape-gate through the typed
7398            // [`Membro::nome`] accessor rather than the raw `.caixa`
7399            // field access — the last un-lifted `.caixa` production-
7400            // code read site on the per-`:membros` member-caixa `:nome`
7401            // axis, sibling to the six caixa-core validator read sites
7402            // (member-set collector, per-member value-shape gate,
7403            // duplicate dedup key, cycle-detector adjacency-map seed,
7404            // self-loop gate) the 4a32abf lift already routed through
7405            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
7406            // per-`programs[]` entry-`name:` `String`-carry converge.
7407            // Prior to this converge the `MembroCaixaEmpty` refusal
7408            // arm was the solitary consumer bypassing the typed
7409            // dispatch — the same-loop iteration's very next call
7410            // `validate_membro_caixa(m.nome())` already routed through
7411            // the accessor, so an author landing an empty-`:caixa`
7412            // entry hit the accessor on the shape-gate line but
7413            // bypassed it on the emptiness line one line above. A
7414            // future extension of the `:membros :caixa` axis to a
7415            // richer author surface (a per-cluster alias table pinned
7416            // through a future `:placement`-scoped slot, a namespace-
7417            // qualified rewrite the M4 CR materializer applies per-CR,
7418            // a per-member overlay from the future `:membros
7419            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
7420            // that lands on the accessor would silently disagree
7421            // between the emptiness gate and every peer consumer —
7422            // an author-declared `:caixa "checkout"` value the
7423            // accessor rewrote to `""` under a future alias arm would
7424            // pass the raw `.is_empty()` gate here while the peer
7425            // `validate_membro_caixa(m.nome())` call one line below
7426            // (and every downstream emit-side consumer routing through
7427            // the accessor) tripped on the empty-value shape far from
7428            // this diagnostic. Pinned by the drift-detection test
7429            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
7430            // below.
7431            if m.nome().is_empty() {
7432                return Err(AplicacaoError::MembroCaixaEmpty);
7433            }
7434            // Every emitted cluster artifact's `metadata.name` derives
7435            // from a `:membros :caixa` value verbatim — the rendered
7436            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
7437            // the [`crate::LABEL_PROGRAM`] label value on every CNP
7438            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
7439            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
7440            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
7441            // `metadata.name` when the member is the `:entrada :para`
7442            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
7443            // schema enforces the DNS-1123 label rule on admission;
7444            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
7445            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
7446            // mistaken-identity slug) silently passes the prior empty-/
7447            // duplicate-only gate and the failure surfaces at `kubectl
7448            // apply` time as a `metadata.name: Invalid value` rejection,
7449            // far from the source caixa.lisp, with no field naming the
7450            // offending `:membros` entry. Lifting the gate to caixa-build
7451            // time mirrors the `:entrada :host` value-shape trajectory
7452            // (c7d05ec) on the peer axis — every author surface that
7453            // emits a K8s name now matches the apiserver's accepted set
7454            // at validate time.
7455            validate_membro_caixa(m.nome())?;
7456            // The author surface for `:versao` is the same Cargo-shaped
7457            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
7458            // `"*"`) every `:deps` entry carries — and the lacre pipeline
7459            // resolves both axes through the same
7460            // [`crate::version::parse_requirement`] entry-point. The
7461            // shared [`crate::render::require_valid_versao_requirement`]
7462            // helper brackets the empty-first + parse cascade both peer
7463            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
7464            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
7465            // route through, so drift between the three axes' accepted
7466            // requirement sets is structurally impossible and the parse-
7467            // side no-op the empty-first arm closes (semver's empty
7468            // parse yields an implicit `*`) lives in exactly one
7469            // predicate.
7470            crate::render::require_valid_versao_requirement(
7471                m.versao_requirement(),
7472                || AplicacaoError::MembroVersaoEmpty {
7473                    caixa: m.nome().to_string(),
7474                },
7475                |reason| AplicacaoError::MembroVersaoInvalid {
7476                    caixa: m.nome().to_string(),
7477                    versao: m.versao_requirement().to_string(),
7478                    reason,
7479                },
7480            )?;
7481            crate::render::insert_first_seen(&mut seen, m.nome(), || {
7482                AplicacaoError::MembroDuplicate {
7483                    caixa: m.nome().to_string(),
7484                }
7485            })?;
7486        }
7487        Ok(())
7488    }
7489
7490    /// Reject `:placement` values that are operationally meaningless or
7491    /// internally contradictory. Each strategy variant has the same
7492    /// invariants on `:clusters` (non-empty list, non-empty unique
7493    /// entries) — the §III.1 author surface is uniform on this axis,
7494    /// even though the *meaning* of the list differs by strategy
7495    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
7496    /// shard pool).
7497    ///
7498    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
7499    /// are the same authoring footgun closed for `:politicas` zero
7500    /// values and `:entrada` empty paths: the field is *declared* but
7501    /// carries no meaning, so downstream renderers either skip it
7502    /// silently (cluster-fanout drops the empty entry, no diagnostic)
7503    /// or apply it literally and fail at admission time. Lifting both
7504    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
7505    /// violation is a build error" promise.
7506    ///
7507    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
7508    /// is required exactly when `:estrategia Sharded` (hash-keyed
7509    /// distribution, Akka cluster-sharding convention, §II.4) and
7510    /// refused on `:estrategia Replicated`/`SingleNode` (where no
7511    /// hash-keyed routing axis consumes it). The partition closes the
7512    /// "I think I configured sharding" footgun where an author writes
7513    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
7514    /// the typed slot's value silently vanishes at the renderer layer
7515    /// — every validated `Placement` past this call satisfies
7516    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
7517    fn validate_placement(&self) -> Result<(), AplicacaoError> {
7518        // Every strategy needs at least one named cluster: `Replicated`
7519        // and `SingleNode` use the list as hosting/takeover candidates
7520        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
7521        // §II.1), while `Sharded` uses it as the shard pool
7522        // (Akka cluster-sharding convention — §II.4). An empty list is
7523        // meaningless under any of the three.
7524        //
7525        // Route the paired pre-flight `.is_empty()` refusal probe and
7526        // the per-cluster validate loop's traversal head through the
7527        // lifted [`Placement::clusters`] slice-return accessor rather
7528        // than the raw `self.placement.clusters` field access — the
7529        // two production consumers of the per-`:placement` cluster-
7530        // pool `Vec`-carry now key off exactly one typed dispatch on
7531        // the substrate primitive, so any future rebrand on the axis
7532        // (a per-tenant cluster-pool overlay the operator pins through
7533        // a future `:placement :clusters-overrides` slot, a per-
7534        // Aplicacao dynamic cluster-pool derivation the future M5
7535        // adaptive-placement engine computes from `:affinity` weights)
7536        // migrates as a single caixa-core edit rather than a
7537        // coordinated rewrite of the paired arms — sibling of the
7538        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
7539        // arm migration on the per-`:supervisor` static-child-list
7540        // `Vec`-carry axis.
7541        //
7542        // Route the per-`:placement` outer-composite reference read
7543        // through the lifted [`AplicacaoSpec::placement`] outer accessor
7544        // rather than the raw `&self.placement` field access — the
7545        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
7546        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
7547        // axis-level lifted accessor family) now routes through the
7548        // substrate-primitive typed dispatch at the outer composition
7549        // altitude, the same shape the peer caixa-mesh
7550        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
7551        // and the sibling `feira app graph` per-Aplicacao print line
7552        // now key off after this accessor lift.
7553        let p = self.placement();
7554        if p.clusters().is_empty() {
7555            return Err(AplicacaoError::PlacementWithoutClusters {
7556                estrategia: p.estrategia(),
7557            });
7558        }
7559        let mut seen = std::collections::HashSet::new();
7560        for c in p.clusters() {
7561            // Per-entry value-shape gate: the cluster name lands in
7562            // every K8s context / `lareira-fleet-programs` aggregator
7563            // filter / future M4 CR materializer's per-cluster axis
7564            // a validated `:clusters` entry passes through, each
7565            // enforcing the DNS-1123 label rule on admission. Same
7566            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
7567            // on the peer name axis — both axes' validated values
7568            // are guaranteed-accepted by the apiserver without
7569            // re-validation at any downstream renderer or admission
7570            // layer.
7571            validate_placement_cluster(c)?;
7572            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
7573                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
7574            })?;
7575        }
7576        // Route the per-`:placement :affinity` per-hint value-shape
7577        // gate through the typed [`Placement::affinity`] accessor rather
7578        // than the raw `&self.placement.affinity` field access — the
7579        // sole open-coded field-access site on the per-`:placement`
7580        // M3-Adaptive-compression-hint axis the accessor lift now owns.
7581        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
7582        // the accessor's `Option<&str>` return type;
7583        // [`validate_placement_affinity`]'s `&str` parameter accepts
7584        // the narrower borrow without a re-allocation, so the routing
7585        // change is byte-for-byte in the pass arm and remains
7586        // byte-for-byte in every failure diagnostic
7587        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
7588        // String` field is populated inside
7589        // [`validate_placement_affinity`] via the peer `.to_string()`
7590        // path on the same borrowed slice). Peer of the sibling
7591        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
7592        // routing through [`Placement::shard_key`] at the caixa-core
7593        // site above — extends the "read `:placement` optional-scalars
7594        // through the typed accessor" discipline to the second
7595        // `Option<String>`-shape slot on the M3 mesh-slot family.
7596        //
7597        // Per-hint value-shape gate: the `:affinity` value lands
7598        // verbatim in the M3 Adaptive compression overlay
7599        // (caixa-mesh's `placement.affinity` emission) and every
7600        // future M4 placement-engine routing axis keying off the
7601        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
7602        // selector — each enforces the DNS-1123 label rule on
7603        // admission. Same typed-shape trajectory as `:placement
7604        // :clusters` (6c8c00b) on the sibling slot and the four
7605        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
7606        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
7607        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
7608        // on the Aplicacao surface to land on the canonical
7609        // [`crate::render::is_dns_1123_label`] floor.
7610        if let Some(a) = p.affinity() {
7611            validate_placement_affinity(a)?;
7612        }
7613        match p.estrategia() {
7614            // Route the `Sharded`-arm shape-gate cascade through the
7615            // typed [`Placement::shard_key`] accessor rather than the
7616            // raw `&self.placement.shard_key` field access — one of the
7617            // two open-coded field-access sites on the per-`:placement`
7618            // Akka-cluster-sharding-key axis the accessor lift now
7619            // owns. The `Some(k)`-bound `k` narrows from `&String` to
7620            // `&str` under the accessor's `Option<&str>` return type;
7621            // `str::is_empty` and [`validate_placement_shard_key`]'s
7622            // `&str` parameter both accept the narrower borrow without
7623            // a re-allocation.
7624            PlacementStrategy::Sharded => match p.shard_key() {
7625                None => return Err(AplicacaoError::ShardedWithoutKey),
7626                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
7627                // Per-axis value-shape gate on the Akka-cluster-sharding
7628                // `:shard-key` extractor expression. The shape gate runs
7629                // after the more self-locating `ShardedKeyEmpty` arm so
7630                // a `:shard-key ""` surfaces the narrower empty
7631                // diagnostic first; every non-empty `:shard-key` past
7632                // this call is guaranteed to be a printable-ASCII
7633                // single-token reference the future M4 Akka-style
7634                // cluster-sharding reconciler can hash without
7635                // re-validating at the runtime layer. Mirrors the
7636                // payload-axis shape gates on the peer `:contratos`
7637                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
7638                // 63e18a0 / c4213a4) — each lifts the runtime parser's
7639                // intersection-floor to a caixa-build-time gate.
7640                Some(k) => validate_placement_shard_key(k)?,
7641            },
7642            // `:shard-key` is the Akka-cluster-sharding axis
7643            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
7644            // across the cluster pool. `Replicated` (active-active across
7645            // every named cluster) and `SingleNode` (Erlang/OTP
7646            // distributed-app takeover/failover, §II.1) have no hash-keyed
7647            // routing axis to consume the slot; downstream renderers
7648            // (caixa-mesh's `placement.shardKey` overlay at
7649            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
7650            // sharding reconciler) ignore `:shard-key` outside the
7651            // `Sharded` arm by construction. Until this gate landed an
7652            // author who wrote `:placement (:estrategia Replicated
7653            // :shard-key "tenantId")` (an off-by-one strategy typo, a
7654            // copy-paste from a Sharded sibling caixa, the "I think I
7655            // configured sharding" footgun) silently passed validate and
7656            // the typed slot's value vanished at the renderer layer with
7657            // no diagnostic — the canonical "declared-but-inert" footgun
7658            // the empty-:affinity / empty-shard-key / zero-:politicas /
7659            // empty-:contratos-target gates already close on every other
7660            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
7661            // Lifting the rejection to a build-time gate closes the
7662            // Sharded ↔ non-Sharded partition over the typed
7663            // `:placement` slot: every validated `Placement` past this
7664            // call has `shard_key.is_some()` iff `estrategia ==
7665            // Sharded`, structurally — the future Akka reconciler can
7666            // reach for `placement.shard_key` knowing it's `Some` exactly
7667            // when the strategy consumes it, without re-deriving the
7668            // partition from inline strategy probes.
7669            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
7670                // Route the non-`Sharded`-arm declared-but-inert refusal
7671                // through the typed [`Placement::shard_key`] accessor —
7672                // the second of the two open-coded field-access sites the
7673                // accessor lift now owns. The `Some(k)`-bound `k` narrows
7674                // from `&String` to `&str`; the `AplicacaoError::
7675                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
7676                // materializes the owned `String` via `k.to_string()`
7677                // (peer to the sibling per-Membro `String`-carry sites
7678                // 4127bb6 routed through `m.nome().to_string()` /
7679                // `m.versao_requirement().to_string()`), so the whole
7680                // `Sharded` ↔ non-`Sharded` partition on the
7681                // `:shard-key` axis now flows through the same typed
7682                // dispatch as the sibling `Sharded`-arm shape gate.
7683                if let Some(k) = p.shard_key() {
7684                    return Err(AplicacaoError::ShardKeyOnNonSharded {
7685                        estrategia: p.estrategia(),
7686                        shard_key: k.to_string(),
7687                    });
7688                }
7689            }
7690        }
7691        Ok(())
7692    }
7693
7694    /// Reject `:politicas` values that are operationally meaningless.
7695    /// Each axis is optional — omitting it expresses "no policy on this
7696    /// axis". Carrying a *zero* value for a declared axis is the bug
7697    /// this function rejects: zero is either
7698    ///
7699    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
7700    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
7701    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
7702    ///     "every Aplicacao declares :politicas :timeout (no infinite
7703    ///     blocking)", or
7704    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
7705    ///     first call; a 0-rate rate-limit denies every request).
7706    ///
7707    /// Lifting these "0 means the opposite of what you think" idioms to
7708    /// the typed Aplicacao surface as build errors mirrors the §III.3
7709    /// promise that contract drift, capability leaks, and cycles are all
7710    /// build errors — not runtime surprises.
7711    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
7712        // Route the per-`:politicas` composite-reference read through
7713        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
7714        // than the raw `&self.politicas` field access — the per-axis
7715        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
7716        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
7717        // the substrate-primitive typed dispatch at the outer
7718        // composition altitude AND at every per-axis altitude, matching
7719        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
7720        // timeout/retry-overlay emitters that already key off the same
7721        // per-axis accessor family. The four-axis fan-out is now
7722        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
7723        // `p.retries` field-access sites (co-resident with the peer
7724        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
7725        // b0e741a / 21a6c3b already lifted) now route through
7726        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
7727        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
7728        // access axis on the M3 mesh-slot family.
7729        let p = self.politicas();
7730        if let Some(t) = p.timeout() {
7731            // Zero-floor + integer-millisecond canonical-form +
7732            // upper-cap bracket on the typed `:timeout` axis. See
7733            // [`crate::render::require_positive_canonical_bounded_duration`]
7734            // for the full three-arm ordering discipline (zero-floor
7735            // strictly precedes the canonical-form arm so
7736            // `Duration::ZERO` surfaces the self-locating
7737            // `PolicyTimeoutZero` diagnostic naming the omit-axis
7738            // remediation; canonical-form strictly precedes the cap
7739            // arm so a sub-millisecond above-cap `Duration` surfaces
7740            // the more fundamental round-trip-shape diagnostic first)
7741            // and the four peer typed-`Duration` sites that now share
7742            // this canonical bracket. Every validated value lies in
7743            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
7744            // granularity — the same top-and-bottom-edge discipline
7745            // [`POLICY_RETRIES_MAX`] and
7746            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
7747            // capped-`u32` `:politicas` axes.
7748            crate::render::require_positive_canonical_bounded_duration(
7749                t,
7750                POLICY_TIMEOUT_MAX,
7751                || AplicacaoError::PolicyTimeoutZero,
7752                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
7753                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
7754            )?;
7755        }
7756        if let Some(r) = p.retries() {
7757            // Zero-floor + upper-cap bracket on the typed `:retries`
7758            // axis. See [`crate::render::require_positive_bounded_u32`]
7759            // for the ordering discipline (zero-floor arm strictly
7760            // precedes cap arm so `Some(0)` surfaces the self-locating
7761            // `PolicyRetriesZero` diagnostic with its omit-axis
7762            // remediation directly named, not the misleading
7763            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
7764            // this bracket landed the top edge ran all the way to
7765            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
7766            // Some(100_000), .. }` (or the equivalent author-surface
7767            // `(:retries 100000)` / `(:retries 4294967295)` typo
7768            // landing in the slot) silently passed validate. The
7769            // runtime substrate consuming the value (Envoy's
7770            // `retry_policy.num_retries`, the future
7771            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7772            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7773            // policy into a thundering-herd amplification vector —
7774            // the caller's one request fans out to `retries`
7775            // server-side calls per edge per traversal, multiplying
7776            // load by `(retries+1)^depth` across the
7777            // synchronous-`:contratos` subgraph at the precise moment
7778            // the substrate is already failing (transient failure is
7779            // the trigger), exactly the failure mode AWS App Mesh's
7780            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
7781            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
7782            // the sibling capped-`u32` `:politicas` axes
7783            // (`max_failures`, `rate_limit.rate`) and the peer capped-
7784            // `u32` axes in `:supervisor :max-restarts` +
7785            // `:limits :cpu`; all five now route through the same
7786            // canonical bracket helper.
7787            crate::render::require_positive_bounded_u32(
7788                r,
7789                POLICY_RETRIES_MAX,
7790                || AplicacaoError::PolicyRetriesZero,
7791                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
7792            )?;
7793        }
7794        if let Some(cb) = p.circuit_breaker() {
7795            // Zero-floor + upper-cap bracket on the typed
7796            // `:max-failures` axis. See
7797            // [`crate::render::require_positive_bounded_u32`] for the
7798            // ordering discipline (zero-floor arm strictly precedes
7799            // cap arm so `max_failures == 0` surfaces the
7800            // self-locating `PolicyBreakerZeroFailures` diagnostic
7801            // with its omit-axis remediation directly named, not the
7802            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
7803            // false` cap-arm miss). Until this bracket landed the top
7804            // edge ran all the way to `u32::MAX` and a struct-literal
7805            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
7806            // equivalent author-surface `(:max-failures 100000)` /
7807            // `(:max-failures 4294967295)` typo landing in the slot)
7808            // silently passed validate. The runtime substrate
7809            // consuming the value (Envoy's
7810            // `outlier_detection.consecutive_5xx`, the future
7811            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7812            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7813            // breaker policy into a no-op — the trip threshold is
7814            // structurally so high that no realistic
7815            // failures-per-`:window` traffic shape can reach it, the
7816            // breaker never trips, and every typed-slot consumer
7817            // emits an Envoy / Cilium L7 overlay carrying a
7818            // protection that is structurally never enforced. The
7819            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
7820            // peer with `retries` and `rate_limit.rate` on the same
7821            // helper.
7822            crate::render::require_positive_bounded_u32(
7823                cb.max_failures(),
7824                POLICY_BREAKER_MAX_FAILURES_MAX,
7825                || AplicacaoError::PolicyBreakerZeroFailures,
7826                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
7827            )?;
7828            // Zero-floor + integer-millisecond canonical-form +
7829            // upper-cap bracket on the typed `:window` axis. See
7830            // [`crate::render::require_positive_canonical_bounded_duration`]
7831            // for the full three-arm ordering discipline (peer to the
7832            // `:timeout` site immediately above); every validated
7833            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
7834            // (1ms..=1h), integer-millisecond granularity — the same
7835            // top-and-bottom-edge discipline
7836            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
7837            // duration-typed `:politicas :timeout` axis.
7838            crate::render::require_positive_canonical_bounded_duration(
7839                cb.window(),
7840                POLICY_BREAKER_WINDOW_MAX,
7841                || AplicacaoError::PolicyBreakerZeroWindow,
7842                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
7843                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
7844            )?;
7845        }
7846        if let Some(rl) = p.rate_limit() {
7847            // Zero-floor + upper-cap bracket on the typed
7848            // `:rate-limit` rate axis. See
7849            // [`crate::render::require_positive_bounded_u32`] for the
7850            // ordering discipline (zero-floor arm strictly precedes
7851            // cap arm so `rl.rate == 0` surfaces the self-locating
7852            // `PolicyRateLimitZero` diagnostic with its omit-axis
7853            // remediation directly named, not the misleading
7854            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
7855            // Until this bracket landed the top edge ran all the way
7856            // to `u32::MAX` and a struct-literal
7857            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
7858            // author-surface `(:rate-limit "4294967295/s")` /
7859            // `(:rate-limit "100000000/m")` typo landing in the slot)
7860            // silently passed validate. The runtime substrate
7861            // consuming the value (Envoy's
7862            // `local_rate_limit.token_bucket.max_tokens`, the future
7863            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7864            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7865            // rate-limit policy into a no-op limiter: the bucket
7866            // capacity is structurally so high that no realistic
7867            // per-edge traffic shape can drain it, the limiter never
7868            // trips, and every typed-slot consumer emits a "rate
7869            // declared" L7 overlay carrying enforcement that is
7870            // structurally never reached — the canonical
7871            // declared-but-inert footgun the sibling
7872            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
7873            // the peer no-op-breaker shape. The bracket set is
7874            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
7875            // `max_failures` on the same helper. The rate bracket
7876            // strictly precedes the window-canonical gate so a
7877            // structurally absurd rate magnitude surfaces the more
7878            // fundamental amplification-shape diagnostic before the
7879            // narrower codec-round-trip-shape diagnostic on `:window`.
7880            crate::render::require_positive_bounded_u32(
7881                rl.rate(),
7882                POLICY_RATE_LIMIT_MAX,
7883                || AplicacaoError::PolicyRateLimitZero,
7884                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
7885            )?;
7886            // The `:rate-limit` author surface is the canonical
7887            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
7888            // accepts exactly the three-unit set (1s/60s/3600s) the
7889            // [`rate_limit_codec::render`] formatter emits the canonical
7890            // unit suffix for. A `RateLimit` whose `:window` is anything
7891            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
7892            // programmatically (struct literals in Rust + the typed
7893            // `Duration` field) but renders to a `<n>/<k>s` fragment
7894            // (the codec's fall-through) the parser then rejects on
7895            // round-trip — silently breaking the THEORY.md §V.2.7
7896            // render-determinism contract for any consumer that
7897            // serializes-then-deserializes the typed slot. Lifting the
7898            // canonical-window invariant to a build-time gate at
7899            // `validate_politicas` makes the codec's round-trip property
7900            // a structural property of the validated typed value:
7901            // every `RateLimit` past `AplicacaoSpec::validate` has a
7902            // window the codec round-trips losslessly, so the next
7903            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
7904            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
7905            // §III.2 #3) reaches for `rate_limit.window` knowing the
7906            // value is in the codec's accepted set without re-validating
7907            // at the renderer layer. Same trajectory as c4213a4 (typed
7908            // WitContract endpoint/subject/slot value-shape gates) and
7909            // the b0c8389 :behavior + :upgrade-from script-path lifts:
7910            // the typed slot's valid set matches its codec's accepted
7911            // set, structurally.
7912            // Route the canonical-window shape-gate through the substrate
7913            // primitive [`RateLimit::canonical_unit`] rather than the free
7914            // module-private [`is_canonical_rate_limit_window`] predicate:
7915            // both projections resolve `Duration → Option<RateLimitUnit>`
7916            // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
7917            // arm on the closed-set typed enum), but the accessor is the
7918            // typed method every downstream consumer of the validated slot
7919            // ([`rate_limit_codec::render`]'s canonical arm above, the
7920            // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7921            // per-`:politicas :rate-limit` admission webhook, the future
7922            // per-`:contratos`-edge rate-limit-override overlay
7923            // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
7924            // production consumers of the canonical-unit axis (the codec
7925            // render and this validate gate) now key off exactly one typed
7926            // dispatch on the substrate primitive, so any future extension
7927            // to `canonical_unit` (a per-cluster canonical-window overlay
7928            // the operator pins through a future `:contratos :rate-limit
7929            // -unit-overrides` slot, a per-tenant unit-alias table the M4
7930            // CR materializer resolves per-CR) reaches both consumers by
7931            // construction rather than a coordinated rewrite of every
7932            // free-helper call site.
7933            if rl.canonical_unit().is_none() {
7934                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
7935                    window: rl.window(),
7936                });
7937            }
7938        }
7939        Ok(())
7940    }
7941
7942    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
7943    /// A synchronous edge is any contract whose typed [`WitTarget`] is
7944    /// `Http`, `Store`, or `Capability` — the caller blocks on the
7945    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
7946    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
7947    /// block on its subscribers, so they can never close a sync loop.
7948    ///
7949    /// Iterative DFS with three-coloring; the reported cycle is the
7950    /// path of caixa names traversed from the back-edge target around
7951    /// to itself, in declaration order. Adjacency lists and DFS roots
7952    /// are visited in `BTreeMap` key order so the diagnostic is
7953    /// deterministic across runs.
7954    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
7955        use std::collections::{BTreeMap, BTreeSet};
7956
7957        #[derive(Clone, Copy, PartialEq, Eq)]
7958        enum Mark {
7959            White,
7960            Gray,
7961            Black,
7962        }
7963
7964        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
7965        for m in self.membros() {
7966            adj.entry(m.nome()).or_default();
7967        }
7968        for c in self.contratos() {
7969            // target() was already called by validate(); re-running here
7970            // keeps detect_sync_cycles self-contained for callers that
7971            // reuse it (M4 per-edge policy resolver) without revalidating.
7972            //
7973            // The pub-sub-arm check routes through the lifted
7974            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
7975            // arm-discriminator predicate rather than a raw `matches!(…,
7976            // WitTarget::PubSub { .. })` on the variant so a future
7977            // rebrand on the axis (an M4 per-edge WIT registry split of
7978            // [`WitTarget::PubSub`] into shape-specific peers, a
7979            // per-consumer rename that the accept-set already carries)
7980            // reaches this call site through the derive rather than a
7981            // scattered per-arm `matches!` rewrite — same
7982            // `IsVariant`-derived-arm-discriminator discipline the
7983            // peer closed-set typed enums ([`crate::CaixaKind`] via
7984            // f5bba80, [`PlacementStrategy`] via 766ec63,
7985            // [`crate::supervisor::RestartStrategy`] +
7986            // [`crate::supervisor::RestartPolicy`],
7987            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
7988            // already route through on the substrate's other typed-enum
7989            // arm-discriminator axes.
7990            if c.target()?.is_pubsub() {
7991                continue;
7992            }
7993            adj.entry(c.source()).or_default().insert(c.destination());
7994        }
7995
7996        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
7997        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
7998
7999        // Stable DFS root order — BTreeMap iteration is sorted by key.
8000        let roots: Vec<&str> = adj.keys().copied().collect();
8001
8002        // Frame: (node, sorted-neighbours snapshot, next-edge index).
8003        for root in roots {
8004            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
8005                continue;
8006            }
8007            let root_neighbors: Vec<&str> = adj
8008                .get(root)
8009                .map(|s| s.iter().copied().collect())
8010                .unwrap_or_default();
8011            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
8012            color.insert(root, Mark::Gray);
8013
8014            loop {
8015                // Read+advance the top frame in one borrow scope so we
8016                // can later mutate the stack (push/pop) without holding
8017                // a borrow across.
8018                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
8019                    let node = top.0;
8020                    if top.2 >= top.1.len() {
8021                        (node, None)
8022                    } else {
8023                        let nxt = top.1[top.2];
8024                        top.2 += 1;
8025                        (node, Some(nxt))
8026                    }
8027                });
8028                let Some((node, nxt_opt)) = step else { break };
8029                let Some(nxt) = nxt_opt else {
8030                    color.insert(node, Mark::Black);
8031                    stack.pop();
8032                    continue;
8033                };
8034                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
8035                match nxt_color {
8036                    Mark::Gray => {
8037                        // Reconstruct the cycle from `node` back through
8038                        // the parent chain to `nxt`, then close.
8039                        let mut cycle = Vec::new();
8040                        let mut cur = node;
8041                        cycle.push(cur.to_string());
8042                        while cur != nxt {
8043                            match parent.get(cur).copied() {
8044                                Some(p) => {
8045                                    cur = p;
8046                                    cycle.push(cur.to_string());
8047                                }
8048                                None => break,
8049                            }
8050                        }
8051                        cycle.reverse();
8052                        cycle.push(nxt.to_string());
8053                        return Err(AplicacaoError::ContratoCycle { cycle });
8054                    }
8055                    Mark::White => {
8056                        parent.insert(nxt, node);
8057                        color.insert(nxt, Mark::Gray);
8058                        let nxt_neighbors: Vec<&str> = adj
8059                            .get(nxt)
8060                            .map(|s| s.iter().copied().collect())
8061                            .unwrap_or_default();
8062                        stack.push((nxt, nxt_neighbors, 0));
8063                    }
8064                    Mark::Black => {}
8065                }
8066            }
8067        }
8068        Ok(())
8069    }
8070
8071    /// Substrate-canonical destination-facing TCP port every emitted
8072    /// per-Aplicacao artifact must key `destination`-shaped port axes
8073    /// off. Returns the typed `:entrada :port` scalar when this
8074    /// Aplicacao's `:entrada` block names `destination` under its
8075    /// `:para` axis (the destination Servico *is* the ingress apex, so
8076    /// the substrate honors the author-declared listener port
8077    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8078    /// fallback otherwise (every non-apex destination — the internal
8079    /// mesh Servicos `:contratos` reach across, the future per-edge
8080    /// policy resolver's per-destination probe targets, the
8081    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8082    /// L4 port resolver — reads the same substrate-canonical port floor
8083    /// by construction).
8084    ///
8085    /// Prior to this lift the "if :entrada matches this destination use
8086    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8087    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8088    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8089    /// prior to this lift), with no typed method on the substrate primitive
8090    /// that named the rule. A future per-destination port axis addition
8091    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8092    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8093    /// per-Servico listener ports land, a per-cluster override the operator
8094    /// pins through a future `:placement :default-port` slot — would have
8095    /// to be threaded through every renderer's inline cascade in lockstep
8096    /// or one consumer would silently disagree on which port a given
8097    /// destination Servico's ingress lands at. Lifting the rule to a
8098    /// typed method on the substrate primitive means the M4 CR
8099    /// materializer, the future per-edge policy resolver, and every
8100    /// downstream test-fixture navigator reach for exactly one typed
8101    /// dispatch — the resolver's accept-set moves as a unit on any
8102    /// future axis addition.
8103    ///
8104    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8105    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8106    /// the typed primitive, thin projections at each consumer"
8107    /// discipline lifts on the sibling `:contratos` payload / `:politicas
8108    /// :rate-limit` unit-suffix axes; extends the discipline onto the
8109    /// destination-facing port-resolution axis every per-Aplicacao
8110    /// L4-fallback renderer consumes.
8111    #[must_use]
8112    pub fn port_for_destination(&self, destination: &str) -> u16 {
8113        // Route the per-`:entrada` composite-reference read through
8114        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8115        // the raw `self.entrada.as_ref()` field access — the
8116        // per-destination L4-port fallback resolver's composite-
8117        // projection seed is now the canonical read-side surface
8118        // every per-Aplicacao entrada consumer routes through, peer
8119        // of the sibling `validate` per-`:entrada` shape-and-
8120        // membership gate migration on the same outer-composite
8121        // axis.
8122        // Route the per-`:entrada` apex-destination membership probe
8123        // through the lifted [`Entrada::destination`] accessor rather
8124        // than the raw `e.para == destination` field access — the last
8125        // un-lifted `.para` production-code read site on the per-
8126        // `:entrada` `:para` axis, sibling to the four caixa-core
8127        // consumer sites the peer 15ddd8c converge already routed
8128        // through the accessor (the three
8129        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8130        // membership gate sites: the `validate_entrada_para` DNS-1123
8131        // shape gate, the per-`:membros` membership lookup, and the
8132        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8133        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8134        // `entrada.para`-projection converge at
8135        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8136        // route-name projection site). Prior to this converge the
8137        // `port_for_destination` resolver was the solitary consumer
8138        // bypassing the typed dispatch on the `.para` axis — the two
8139        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8140        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8141        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8142        // reach through the same accessor family compose with this
8143        // resolver at the emit boundary via the apex-identity
8144        // invariant `spec.port_for_destination(entrada.destination())
8145        // == entrada.port` the sibling
8146        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8147        // pin pins across four permutations. A future extension of the
8148        // `:entrada :para` axis to a richer author surface (a per-
8149        // cluster alias overlay the operator pins through a future
8150        // `:placement`-scoped slot, a namespace-qualified rewrite the
8151        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8152        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8153        // §III.2 acknowledges) that lands on the accessor would silently
8154        // disagree between this resolver and the two `caixa-mesh` emit
8155        // sites — an author-declared `:para "cart"` value the accessor
8156        // rewrote to `"cart-v2"` under a future canary arm would leave
8157        // the resolver's membership arm falling through to
8158        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8159        // `.para`) while the peer emit-site consumers landed on the
8160        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8161        // silently disagreed on which destination port a given typed
8162        // `:entrada` resolves to at cluster-apply time. Pinned by the
8163        // drift-detection test
8164        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8165        // below.
8166        self.entrada()
8167            .filter(|e| e.destination() == destination)
8168            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8169    }
8170}
8171
8172/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8173/// entry may name the Aplicacao's own `:nome`.
8174///
8175/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8176/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8177/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8178/// Servicos that compose the app; an Aplicacao is never its own constituent),
8179/// and the lacre pipeline's closure-resolution would otherwise be handed a
8180/// node that is its own parent: a one-node cycle it either rejects far from
8181/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8182/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8183/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8184/// label + lacre closure root), a member whose `:caixa` equals the
8185/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8186/// peer.
8187///
8188/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8189/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8190/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8191/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8192/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8193/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8194/// (the Aplicacao :membros set; the supervision-tree :children list was the
8195/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8196/// every validated Supervisor's children are distinct from its `:nome`,
8197/// every validated Aplicacao's membros are distinct from its `:nome`. The
8198/// transitive consequence is that `:entrada :para` and `:contratos`
8199/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8200/// name the Aplicacao itself, without re-deriving the partition.
8201pub fn validate_no_self_membership(
8202    membros: &[Membro],
8203    parent_nome: &str,
8204) -> Result<(), AplicacaoError> {
8205    for m in membros {
8206        if m.nome() == parent_nome {
8207            return Err(AplicacaoError::MembroIsSelfAplicacao {
8208                caixa: parent_nome.to_string(),
8209            });
8210        }
8211    }
8212    Ok(())
8213}
8214
8215#[derive(Debug, Error, PartialEq, Eq)]
8216pub enum AplicacaoError {
8217    #[error("Aplicacao must declare at least one :membros entry")]
8218    NoMembros,
8219    #[error(
8220        ":membros entry has empty :caixa (every member must name a Servico; \
8221         omit the entry instead of carrying an empty name)"
8222    )]
8223    MembroCaixaEmpty,
8224    #[error(
8225        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8226         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8227         name / label value the member name lands in; use a lowercase \
8228         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8229    )]
8230    MembroCaixaInvalid { caixa: String, reason: String },
8231    #[error(
8232        ":membros entry {caixa:?} has empty :versao (every member must pin a \
8233         semver constraint that resolves through the lacre pipeline)"
8234    )]
8235    MembroVersaoEmpty { caixa: String },
8236    #[error(
8237        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8238         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8239         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8240         carries; the lacre pipeline resolves both through the same parser)"
8241    )]
8242    MembroVersaoInvalid {
8243        caixa: String,
8244        versao: String,
8245        reason: String,
8246    },
8247    #[error(
8248        ":membros entry {caixa:?} appears more than once (the graph node set \
8249         is a set, not a multiset; duplicate members produce duplicate \
8250         programs.yaml entries and ambiguous :contratos membership lookups)"
8251    )]
8252    MembroDuplicate { caixa: String },
8253    #[error(
8254        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8255         never its own constituent Servico (the application graph is a DAG rooted \
8256         at the Aplicacao; :membros names the *other* caixas that compose the \
8257         app, not the app itself). Since every :nome is a globally-unique \
8258         substrate identity, a member naming the Aplicacao's own :nome is a \
8259         one-node lacre-closure recursion, not a coincidentally-named peer; \
8260         drop the self-referential :membros entry or rename it to the actual \
8261         constituent caixa."
8262    )]
8263    MembroIsSelfAplicacao { caixa: String },
8264    #[error(
8265        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8266         caixa declared in :membros; omit the contract or fill the {slot} field with a \
8267         member name)"
8268    )]
8269    ContratoCaixaEmpty { slot: &'static str },
8270    #[error(
8271        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8272         :contratos {slot} value names a member of :membros, which is itself a \
8273         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8274         object the member name lands in — Service, Pod, identity-based Cilium \
8275         selector; use a lowercase alphanumeric + hyphen identifier like \
8276         `\"checkout\"` or `\"cart-v2\"`)"
8277    )]
8278    ContratoCaixaInvalid {
8279        slot: &'static str,
8280        caixa: String,
8281        reason: String,
8282    },
8283    #[error("contrato references caixa {caixa:?} not declared in :membros")]
8284    ContratoMemberMissing { caixa: String },
8285    #[error(
8286        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8287         entry is an inter-Servico contract whose :de and :para must name distinct \
8288         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8289         the contract, or point :para at the member it actually calls)"
8290    )]
8291    ContratoSelfLoop { caixa: String, wit: String },
8292    #[error("contrato {de:?} → {para:?} has empty :wit")]
8293    EmptyWit { de: String, para: String },
8294    #[error(
8295        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8296         {reason} (the substrate dispatches `:wit` values on the canonical \
8297         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8298         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8299         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8300         kebab-case identifier per segment)"
8301    )]
8302    ContratoWitInvalid {
8303        de: String,
8304        para: String,
8305        wit: String,
8306        reason: String,
8307    },
8308    #[error(
8309        ":entrada :para is empty (every :entrada must route to a caixa declared in \
8310         :membros; fill the :para field with a member name)"
8311    )]
8312    EntradaParaEmpty,
8313    #[error(
8314        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8315         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8316         label per the K8s apiserver's `metadata.name` rule on every object the \
8317         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8318         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8319         `\"checkout\"` or `\"cart-v2\"`)"
8320    )]
8321    EntradaParaInvalid { para: String, reason: String },
8322    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8323    EntradaMemberMissing { para: String },
8324    #[error(":entrada must declare a non-empty :host")]
8325    EmptyEntradaHost,
8326    #[error(
8327        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8328         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8329         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8330         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8331    )]
8332    EntradaHostInvalid { host: String, reason: String },
8333    #[error(":entrada :port must be in 1..=65535, got 0")]
8334    EntradaPortZero,
8335    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8336    EntradaPathEmpty,
8337    #[error(
8338        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8339    )]
8340    EntradaPathNotAbsolute { path: String },
8341    #[error(
8342        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8343         value: {reason} (the K8s apiserver enforces the same shape on \
8344         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8345         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8346         requires percent-encoding `%XX` for non-ASCII and whitespace)"
8347    )]
8348    EntradaPathInvalid { path: String, reason: String },
8349    #[error(":entrada :paths entry {path:?} appears more than once")]
8350    EntradaPathDuplicate { path: String },
8351    #[error(
8352        ":placement {estrategia} requires at least one :clusters entry \
8353         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8354    )]
8355    PlacementWithoutClusters { estrategia: PlacementStrategy },
8356    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8357    PlacementClusterEmpty,
8358    #[error(
8359        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8360         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8361         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8362         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8363         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8364         identifier like `\"rio\"` or `\"mar-east\"`)"
8365    )]
8366    PlacementClusterInvalid { cluster: String, reason: String },
8367    #[error(":placement :clusters entry {cluster:?} appears more than once")]
8368    PlacementClusterDuplicate { cluster: String },
8369    #[error(
8370        ":placement :affinity must be non-empty when set (omit :affinity to express \
8371         `no placement hint`)"
8372    )]
8373    PlacementAffinityEmpty,
8374    #[error(
8375        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8376         (placement hints land verbatim in the M3 Adaptive compression overlay's \
8377         `placement.affinity` field and in every future M4 placement-engine routing \
8378         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8379         selector — both enforce the DNS-1123 label rule on admission; use a \
8380         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8381         `\"low-latency\"`, or `\"anti-affinity\"`)"
8382    )]
8383    PlacementAffinityInvalid { affinity: String, reason: String },
8384    #[error(":placement Sharded requires :shard-key")]
8385    ShardedWithoutKey,
8386    #[error(
8387        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8388         hashes every entity onto the same shard, defeating sharding entirely)"
8389    )]
8390    ShardedKeyEmpty,
8391    #[error(
8392        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8393         entity-id extractor expression: {reason} (the future M4 Akka-style \
8394         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8395         as a single-token property reference and hashes the extracted entity ID \
8396         to compute shard placement; use a printable-ASCII extractor expression \
8397         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8398         `\"${{tenant}}\"`)"
8399    )]
8400    ShardKeyInvalid { shard_key: String, reason: String },
8401    #[error(
8402        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8403         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8404         convention); :estrategia Replicated runs every cluster active-active and \
8405         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8406         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8407         to :estrategia Sharded if hash-keyed routing is the intent"
8408    )]
8409    ShardKeyOnNonSharded {
8410        estrategia: PlacementStrategy,
8411        shard_key: String,
8412    },
8413    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8414    ContratoMissingTarget {
8415        de: String,
8416        para: String,
8417        wit: String,
8418        expected: &'static str,
8419    },
8420    #[error(
8421        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8422         expected `:{expected}` only"
8423    )]
8424    ContratoWrongTarget {
8425        de: String,
8426        para: String,
8427        wit: String,
8428        expected: &'static str,
8429    },
8430    #[error(
8431        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8432         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8433         that matches no traffic and silently drops every request)"
8434    )]
8435    ContratoEndpointEmpty { de: String, para: String },
8436    #[error(
8437        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8438         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8439         :entrada :paths)"
8440    )]
8441    ContratoEndpointNotAbsolute {
8442        de: String,
8443        para: String,
8444        endpoint: String,
8445    },
8446    #[error(
8447        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8448         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8449         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8450         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8451         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8452         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8453         and whitespace)"
8454    )]
8455    ContratoEndpointInvalid {
8456        de: String,
8457        para: String,
8458        endpoint: String,
8459        reason: String,
8460    },
8461    #[error(
8462        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8463         subject is a no-op subscribe; omit :subject only if the WIT world is not \
8464         pub-sub-shaped)"
8465    )]
8466    ContratoSubjectEmpty { de: String, para: String },
8467    #[error(
8468        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8469         NATS subject: {reason} (the NATS server's subject parser enforces the \
8470         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8471         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8472         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8473         `\"orders.*.completed\"` — a malformed subject silently drops every \
8474         message at runtime far from the source caixa.lisp)"
8475    )]
8476    ContratoSubjectInvalid {
8477        de: String,
8478        para: String,
8479        subject: String,
8480        reason: String,
8481    },
8482    #[error(
8483        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8484         addresses the bucket root, defeating the per-key isolation the slot exists \
8485         for; omit :slot only if the WIT world is not store-shaped)"
8486    )]
8487    ContratoSlotEmpty { de: String, para: String },
8488    #[error(
8489        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8490         WASI keyvalue store slot template: {reason} (the substrate enforces \
8491         the printable-ASCII intersection-floor every kv backend admits — \
8492         use a single-token path / template expression like `\"checkout/$orderId\"`, \
8493         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8494         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8495         slot either gets rejected on write by strict backends or silently \
8496         corrupts the next read on permissive ones, far from the source caixa.lisp)"
8497    )]
8498    ContratoSlotInvalid {
8499        de: String,
8500        para: String,
8501        slot: String,
8502        reason: String,
8503    },
8504    #[error(
8505        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
8506         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
8507        cycle.join(" → ")
8508    )]
8509    ContratoCycle { cycle: Vec<String> },
8510    #[error(
8511        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
8512         than once (the typed graph edges are a set, not a multiset; duplicate \
8513         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
8514         values that K8s admission rejects far from the source caixa.lisp)"
8515    )]
8516    ContratoDuplicate {
8517        de: String,
8518        para: String,
8519        wit: String,
8520        target: String,
8521    },
8522    #[error(
8523        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
8524         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
8525         express `no per-call deadline on this axis`"
8526    )]
8527    PolicyTimeoutZero,
8528    #[error(
8529        ":politicas :retries must be > 0 when set; omit :retries to express \
8530         `no retries on transient failure`"
8531    )]
8532    PolicyRetriesZero,
8533    #[error(
8534        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
8535         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
8536         retry policy into a thundering-herd amplification vector on transient \
8537         failure (one caller request fans out to `(retries+1)^depth` server-side \
8538         calls across the synchronous-:contratos subgraph), exactly the failure \
8539         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
8540         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
8541         or omit :retries to disable retries entirely"
8542    )]
8543    PolicyRetriesExceedsCap { retries: u32 },
8544    #[error(
8545        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
8546         breaker trips on the first call); omit :circuit-breaker to disable it"
8547    )]
8548    PolicyBreakerZeroFailures,
8549    #[error(
8550        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
8551         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
8552         above this cap turns the typed breaker policy into a no-op: the trip \
8553         threshold is structurally so high that no realistic failures-per-:window \
8554         traffic shape can reach it, so the breaker never trips and every typed-slot \
8555         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
8556         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
8557         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
8558         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
8559         omit :circuit-breaker to disable the breaker entirely"
8560    )]
8561    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
8562    #[error(
8563        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
8564         tracks no failures); omit :circuit-breaker to disable it"
8565    )]
8566    PolicyBreakerZeroWindow,
8567    #[error(
8568        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
8569         request); omit :rate-limit to disable rate limiting"
8570    )]
8571    PolicyRateLimitZero,
8572    #[error(
8573        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
8574         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
8575         rate-limit policy into a no-op limiter: the token-bucket capacity is \
8576         structurally so high that no realistic per-edge traffic shape can drain it, \
8577         so the limiter never trips and every typed-slot consumer (the future \
8578         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8579         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
8580         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
8581         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
8582         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
8583         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
8584         to disable rate limiting entirely"
8585    )]
8586    PolicyRateLimitExceedsCap { rate: u32 },
8587    #[error(
8588        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
8589         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
8590         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
8591         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
8592         three canonical windows)"
8593    )]
8594    PolicyRateLimitWindowNotCanonical { window: Duration },
8595    #[error(
8596        ":politicas :timeout must be an integer number of milliseconds — the canonical \
8597         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
8598         duration codec round-trips losslessly; got {timeout:?} which carries a \
8599         sub-millisecond residue that either truncates to a different `Duration` on \
8600         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
8601         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
8602         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
8603         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
8604    )]
8605    PolicyTimeoutNotCanonical { timeout: Duration },
8606    #[error(
8607        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
8608         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
8609         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
8610         overlays carry a deadline so long no realistic synchronous-:contratos \
8611         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
8612         CSE invariant degenerates to enforcement only at the per-Servico \
8613         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
8614         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
8615         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
8616         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
8617         maxes out at the same `3600s` ceiling) or omit :timeout to express \
8618         `no per-call deadline on this axis` (the synchronous-call deadline then \
8619         relies entirely on the per-Servico `:limits :wall-clock` axis)"
8620    )]
8621    PolicyTimeoutExceedsCap { timeout: Duration },
8622    #[error(
8623        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
8624         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
8625         the shared duration codec round-trips losslessly; got {window:?} which carries a \
8626         sub-millisecond residue that either truncates to a different `Duration` on \
8627         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
8628         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
8629    )]
8630    PolicyBreakerWindowNotCanonical { window: Duration },
8631    #[error(
8632        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
8633         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
8634         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
8635         is structurally so long that transient failures are never forgotten, the breaker \
8636         trips once and stays tripped for the lifetime of the component, and every typed-slot \
8637         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8638         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
8639         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
8640         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
8641         the breaker entirely"
8642    )]
8643    PolicyBreakerWindowExceedsCap { window: Duration },
8644}
8645
8646#[cfg(test)]
8647mod tests {
8648    use super::*;
8649
8650    fn membro(name: &str, ver: &str) -> Membro {
8651        Membro {
8652            caixa: name.into(),
8653            versao: ver.into(),
8654        }
8655    }
8656
8657    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
8658        WitContract {
8659            de: de.into(),
8660            para: para.into(),
8661            wit: "wasi:http/proxy".into(),
8662            endpoint: Some(ep.into()),
8663            subject: None,
8664            slot: None,
8665        }
8666    }
8667
8668    fn three_member_spec() -> AplicacaoSpec {
8669        AplicacaoSpec {
8670            membros: vec![
8671                membro("catalog", "^0.1"),
8672                membro("cart", "^0.1"),
8673                membro("payment", "^0.2"),
8674            ],
8675            contratos: vec![
8676                contract_http("cart", "catalog", "/products/:id"),
8677                contract_http("cart", "payment", "/charge"),
8678            ],
8679            politicas: MeshPolicy {
8680                timeout: Some(Duration::from_secs(30)),
8681                retries: Some(3),
8682                mtls_required: Some(true),
8683                ..Default::default()
8684            },
8685            placement: Placement {
8686                estrategia: PlacementStrategy::Replicated,
8687                clusters: vec!["rio".into(), "mar".into()],
8688                affinity: Some("data-locality".into()),
8689                shard_key: None,
8690            },
8691            entrada: Some(Entrada {
8692                host: "checkout.quero.cloud".into(),
8693                para: "cart".into(),
8694                paths: vec!["/api/cart".into(), "/api/products".into()],
8695                port: 8080,
8696            }),
8697        }
8698    }
8699
8700    #[test]
8701    fn happy_path_validates() {
8702        three_member_spec().validate().unwrap();
8703    }
8704
8705    #[test]
8706    fn rejects_empty_membros() {
8707        let mut s = three_member_spec();
8708        s.membros = vec![];
8709        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
8710    }
8711
8712    #[test]
8713    fn rejects_empty_membro_caixa() {
8714        // A `:caixa ""` entry has no name to render into programs.yaml
8715        // and no caixa.lisp to resolve at lacre time.
8716        let mut s = three_member_spec();
8717        s.membros[1].caixa = String::new();
8718        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
8719    }
8720
8721    #[test]
8722    fn rejects_empty_membro_versao() {
8723        // A `:versao ""` entry can't pin a semver constraint, so the
8724        // lacre pipeline fails far from the source.
8725        let mut s = three_member_spec();
8726        s.membros[2].versao = String::new();
8727        let err = s.validate().unwrap_err();
8728        assert!(
8729            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
8730            "got {err:?}"
8731        );
8732    }
8733
8734    #[test]
8735    fn rejects_duplicate_membro_caixa() {
8736        // Two `:membros` entries with the same `:caixa` collapse to one
8737        // node in the membership HashSet, which masks `:contratos`
8738        // membership errors and produces duplicate programs.yaml entries.
8739        let mut s = three_member_spec();
8740        s.membros.push(membro("cart", "^0.2"));
8741        let err = s.validate().unwrap_err();
8742        assert!(
8743            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8744            "got {err:?}"
8745        );
8746    }
8747
8748    #[test]
8749    fn rejects_invalid_membro_versao_requirement() {
8750        // The fail-before-pass-after pin: a non-empty but malformed
8751        // semver requirement (`"^bad-version"`) silently passed
8752        // `validate()` on every pre-gate codebase because the prior
8753        // shape only refused the empty string. The parse failure
8754        // surfaced far downstream at lacre-resolve time with a
8755        // `semver::Error` that didn't name which `:membros` entry
8756        // carried the typo. The new gate moves the check to caixa-build
8757        // time at the source caixa.lisp.
8758        let mut s = three_member_spec();
8759        s.membros[2].versao = "^bad-version".into();
8760        let err = s.validate().unwrap_err();
8761        assert!(
8762            matches!(
8763                err,
8764                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8765                    if caixa == "payment" && versao == "^bad-version"
8766            ),
8767            "got {err:?}"
8768        );
8769    }
8770
8771    #[test]
8772    fn rejects_membro_versao_with_double_caret_typo() {
8773        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
8774        // Cargo-shaped requirement on first glance but fails the parser
8775        // because semver doesn't accept stacked operators. Pin this
8776        // adjacent-shape footgun explicitly so a future relaxation that
8777        // accepts "looks-canonical-but-isn't" forms surfaces here.
8778        let mut s = three_member_spec();
8779        s.membros[0].versao = "^^0.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 == "catalog" && versao == "^^0.1"
8786            ),
8787            "got {err:?}"
8788        );
8789    }
8790
8791    #[test]
8792    fn rejects_membro_versao_with_v_prefixed_tag() {
8793        // `"v0.1"` is the canonical "git-tag-shape leaking into the
8794        // semver requirement slot" typo — an author copies the
8795        // publish-side git-tag string verbatim into `:versao`, but
8796        // Cargo's semver parser rejects the leading `v` (only digits +
8797        // canonical operators are valid in the major-version
8798        // position). The gate's diagnostic names which member entry
8799        // carried the v-prefix so the fix is one edit, not a grep
8800        // through every member's `:versao`. (Note: bare `x`-glob
8801        // shorthands like `^0.1.x` are *accepted* by the semver crate
8802        // as an `*` wildcard on the patch axis — they're a Cargo-side
8803        // valid shape, not a typo, so the gate intentionally lets them
8804        // through.)
8805        let mut s = three_member_spec();
8806        s.membros[1].versao = "v0.1".into();
8807        let err = s.validate().unwrap_err();
8808        assert!(
8809            matches!(
8810                err,
8811                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8812                    if caixa == "cart" && versao == "v0.1"
8813            ),
8814            "got {err:?}"
8815        );
8816    }
8817
8818    #[test]
8819    fn accepts_canonical_membro_versao_forms() {
8820        // The four Cargo-shaped requirement forms `:deps :versao`
8821        // already accepts via `crate::parse_requirement` must pass the
8822        // membros gate without re-validating at the resolver layer.
8823        // Pin every leg so a future tightening of the canonical set
8824        // surfaces here as a test failure.
8825        for form in [
8826            "^0.1",      // caret — minor-range pin (the most common shape)
8827            "~0.1.2",    // tilde — patch-range pin
8828            "0.1.0",     // exact — single-version pin
8829            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
8830            ">=0.1, <2", // multi-range — comma-separated comparators
8831        ] {
8832            let mut s = three_member_spec();
8833            for m in &mut s.membros {
8834                m.versao = form.into();
8835            }
8836            s.validate()
8837                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8838        }
8839    }
8840
8841    #[test]
8842    fn membro_versao_empty_takes_precedence_over_invalid() {
8843        // Order pin: the existing `MembroVersaoEmpty` diagnostic
8844        // (which doesn't try to parse) fires before the new
8845        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
8846        // `:versao` keeps its narrower error message — `parse_requirement`
8847        // would also reject `""`, but the empty-string arm is the more
8848        // self-locating diagnostic for the author.
8849        let mut s = three_member_spec();
8850        s.membros[1].versao = String::new();
8851        let err = s.validate().unwrap_err();
8852        assert!(
8853            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
8854            "got {err:?}"
8855        );
8856    }
8857
8858    #[test]
8859    fn membro_versao_invalid_fires_before_duplicate_check() {
8860        // Order pin: a malformed requirement on a non-duplicate entry
8861        // surfaces *its own* diagnostic (which names the offending
8862        // `:versao` string), even when a later entry would otherwise
8863        // collapse onto an earlier name. The per-entry shape gate runs
8864        // inline before the duplicate-key insert, parallel to
8865        // `membros_validation_runs_before_contratos_membership_check`
8866        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
8867        let mut s = three_member_spec();
8868        s.membros[0].versao = "^bad".into();
8869        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8870        let err = s.validate().unwrap_err();
8871        assert!(
8872            matches!(
8873                err,
8874                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
8875            ),
8876            "got {err:?}"
8877        );
8878    }
8879
8880    #[test]
8881    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
8882        // The diagnostic-shape pin: the error names the offending
8883        // `:versao` value verbatim so the author can grep their
8884        // caixa.lisp without re-running the build, and carries a
8885        // non-empty `reason` from `semver::VersionReq::parse` so the
8886        // parser's own wording flows through to the diagnostic.
8887        let mut s = three_member_spec();
8888        s.membros[2].versao = "not-a-req".into();
8889        let err = s.validate().unwrap_err();
8890        let AplicacaoError::MembroVersaoInvalid {
8891            caixa,
8892            versao,
8893            reason,
8894        } = err
8895        else {
8896            panic!("expected MembroVersaoInvalid, got other variant");
8897        };
8898        assert_eq!(caixa, "payment");
8899        assert_eq!(versao, "not-a-req");
8900        assert!(
8901            !reason.is_empty(),
8902            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
8903        );
8904    }
8905
8906    #[test]
8907    fn membro_versao_invalid_runs_before_contratos_check() {
8908        // A malformed `:versao` on any member must surface its own
8909        // diagnostic (which names *which* member to fix) before any
8910        // `:contratos` membership lookup raises `ContratoMemberMissing`.
8911        // The `:contratos` gate runs after `validate_membros`, so this
8912        // is structurally guaranteed — pin it explicitly so a future
8913        // refactor that reorders the gates surfaces here.
8914        let mut s = three_member_spec();
8915        s.membros[1].versao = "^^0.1".into();
8916        // Add a contrato whose `:para` doesn't exist — would normally
8917        // raise ContratoMemberMissing at the membership lookup, but
8918        // the membros gate must fire first.
8919        s.contratos
8920            .push(contract_http("cart", "phantom", "/never-reached"));
8921        let err = s.validate().unwrap_err();
8922        assert!(
8923            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
8924            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
8925        );
8926    }
8927
8928    #[test]
8929    fn membros_validation_runs_before_contratos_membership_check() {
8930        // If `:membros` carries a duplicate, the membership-collapse
8931        // would silently accept a `:contratos :para "phantom"` so long
8932        // as some entry hashes to "phantom". Pinning order: the
8933        // duplicate-membros error fires first, regardless of whether
8934        // contratos reference real members.
8935        let mut s = three_member_spec();
8936        s.membros = vec![
8937            membro("cart", "^0.1"),
8938            membro("cart", "^0.2"),
8939            membro("catalog", "^0.1"),
8940            membro("payment", "^0.1"),
8941        ];
8942        let err = s.validate().unwrap_err();
8943        assert!(
8944            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8945            "got {err:?}"
8946        );
8947    }
8948
8949    #[test]
8950    fn distinct_membros_validate() {
8951        // Pin the happy-path: every `:membros` entry has a non-empty
8952        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
8953        // The fixture already satisfies this; this test makes the
8954        // invariant explicit so a future refactor of the fixture can't
8955        // silently break the guarantee.
8956        three_member_spec().validate().unwrap();
8957    }
8958
8959    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
8960
8961    #[test]
8962    fn rejects_membro_caixa_with_uppercase() {
8963        // The canonical "I copied the Servico's display name verbatim"
8964        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
8965        // but author tools often round-trip a TitleCase or CamelCase
8966        // identifier from an ADR or a sketch. Pin the diagnostic names
8967        // the offending name and suggests the lower-cased fix in one
8968        // edit, mirroring the `rejects_entrada_host_with_uppercase`
8969        // gate's shape (c7d05ec).
8970        let mut s = three_member_spec();
8971        s.membros[1].caixa = "Cart".into();
8972        let err = s.validate().unwrap_err();
8973        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8974            panic!("expected MembroCaixaInvalid, got other variant");
8975        };
8976        assert_eq!(caixa, "Cart");
8977        assert!(
8978            reason.contains("uppercase"),
8979            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8980        );
8981        assert!(
8982            reason.contains("\"cart\""),
8983            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
8984        );
8985    }
8986
8987    #[test]
8988    fn rejects_membro_caixa_with_underscore() {
8989        // The canonical "I'm thinking of a Python module / Postgres
8990        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
8991        // label schema. K8s rejects `metadata.name: my_cart` at admission
8992        // time with an opaque `field is invalid` (no source-citing
8993        // diagnostic). The gate moves it to caixa-build time.
8994        let mut s = three_member_spec();
8995        s.membros[0].caixa = "my_cart".into();
8996        let err = s.validate().unwrap_err();
8997        assert!(
8998            matches!(
8999                err,
9000                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9001                    if caixa == "my_cart" && reason.contains('_')
9002            ),
9003            "got {err:?}"
9004        );
9005    }
9006
9007    #[test]
9008    fn rejects_membro_caixa_with_dot() {
9009        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
9010        // subdomain — even though K8s `metadata.name` itself accepts
9011        // dots (DNS-1123 subdomain rule), this string also lands as a
9012        // K8s Service name (DNS-1035 label — no dots) and as a label
9013        // value on identity-based Cilium selectors. The strictest floor
9014        // among the use sites wins. The "I want to namespace my member
9015        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
9016        let mut s = three_member_spec();
9017        s.membros[2].caixa = "team.cart".into();
9018        let err = s.validate().unwrap_err();
9019        assert!(
9020            matches!(
9021                err,
9022                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9023                    if caixa == "team.cart" && reason.contains('.')
9024            ),
9025            "got {err:?}"
9026        );
9027    }
9028
9029    #[test]
9030    fn rejects_membro_caixa_with_leading_hyphen() {
9031        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
9032        // with an alphanumeric. The K8s apiserver rejects `-cart`
9033        // outright; the renderer would emit a `metadata.name: "-cart"`
9034        // that fails admission far from the source caixa.lisp.
9035        let mut s = three_member_spec();
9036        s.membros[0].caixa = "-cart".into();
9037        let err = s.validate().unwrap_err();
9038        assert!(
9039            matches!(
9040                err,
9041                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9042                    if caixa == "-cart" && reason.contains("start and end")
9043            ),
9044            "got {err:?}"
9045        );
9046    }
9047
9048    #[test]
9049    fn rejects_membro_caixa_with_trailing_hyphen() {
9050        // The symmetric arm of the boundary rule. Pin separately so
9051        // both ends of the label are covered against a future relaxation
9052        // that only checks one boundary.
9053        let mut s = three_member_spec();
9054        s.membros[1].caixa = "cart-".into();
9055        let err = s.validate().unwrap_err();
9056        assert!(
9057            matches!(
9058                err,
9059                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9060                    if caixa == "cart-"
9061            ),
9062            "got {err:?}"
9063        );
9064    }
9065
9066    #[test]
9067    fn rejects_membro_caixa_with_unicode() {
9068        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9069        // (`xn--…`) by the author before it reaches K8s. The byte-by-
9070        // byte ASCII validity check rejects multi-byte UTF-8 sequences
9071        // by the first byte that fails the `[a-z0-9-]` predicate.
9072        let mut s = three_member_spec();
9073        s.membros[2].caixa = "café".into();
9074        let err = s.validate().unwrap_err();
9075        assert!(
9076            matches!(
9077                err,
9078                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9079                    if caixa == "café"
9080            ),
9081            "got {err:?}"
9082        );
9083    }
9084
9085    #[test]
9086    fn rejects_membro_caixa_with_whitespace() {
9087        // Whitespace is the canonical "I pasted from a sketch / doc"
9088        // footgun. The apiserver rejects every `metadata.name` value
9089        // carrying whitespace; pin the gate fires at the right boundary.
9090        let mut s = three_member_spec();
9091        s.membros[0].caixa = "my cart".into();
9092        let err = s.validate().unwrap_err();
9093        assert!(
9094            matches!(
9095                err,
9096                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9097                    if caixa == "my cart"
9098            ),
9099            "got {err:?}"
9100        );
9101    }
9102
9103    #[test]
9104    fn rejects_membro_caixa_too_long() {
9105        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
9106        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
9107        // exactly. The gate's reason names both the cap and the actual
9108        // length so the author can shorten in one edit.
9109        let mut s = three_member_spec();
9110        let too_long = "a".repeat(64);
9111        s.membros[1].caixa = too_long.clone();
9112        let err = s.validate().unwrap_err();
9113        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9114            panic!("expected MembroCaixaInvalid");
9115        };
9116        assert_eq!(caixa, too_long);
9117        assert!(
9118            reason.contains("63") && reason.contains("64"),
9119            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
9120        );
9121    }
9122
9123    #[test]
9124    fn membro_caixa_max_length_validates() {
9125        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
9126        // so a future tightening (e.g. dropping to 62) surfaces here as
9127        // a regression, mirroring `entrada_host_max_length_validates`
9128        // (c7d05ec).
9129        let mut s = three_member_spec();
9130        s.membros[2].caixa = "a".repeat(63);
9131        s.entrada.as_mut().unwrap().para = "a".repeat(63);
9132        // remove contratos referencing the renamed member; they'd
9133        // raise ContratoMemberMissing otherwise
9134        s.contratos
9135            .retain(|c| c.de != "payment" && c.para != "payment");
9136        s.validate().unwrap();
9137    }
9138
9139    #[test]
9140    fn accepts_canonical_membro_caixa_forms() {
9141        // The DNS-1123 label shapes a caixa author is realistically
9142        // going to write: single-word lowercase, hyphen-joined, ending
9143        // in a digit-suffixed version (`cart-v2`), starting with a
9144        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
9145        // DNS-1035 which requires a letter at position 0), single-
9146        // character (`a` — boundary). Pin every leg so a future
9147        // tightening that bans (e.g.) digit-start identifiers surfaces
9148        // here.
9149        for form in [
9150            "checkout",
9151            "cart",
9152            "cart-v2",
9153            "a",
9154            "c0",
9155            "3rd-party-shim",
9156            "x-1-2-3-4",
9157        ] {
9158            let mut s = three_member_spec();
9159            // Renaming a member also requires updating downstream refs;
9160            // drop everything else and rebuild a minimal spec around
9161            // just the one renamed member.
9162            s.membros = vec![membro(form, "^0.1")];
9163            s.contratos = vec![];
9164            s.entrada = None;
9165            s.validate()
9166                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
9167        }
9168    }
9169
9170    #[test]
9171    fn membro_caixa_empty_takes_precedence_over_invalid() {
9172        // Order pin: the existing `MembroCaixaEmpty` diagnostic
9173        // (which doesn't try to parse) fires before the new
9174        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
9175        // `:caixa` keeps its narrower error message — the new gate
9176        // would also reject `""`, but the empty-string arm is the more
9177        // self-locating diagnostic for the author. Mirrors the
9178        // `entrada_host_empty_takes_precedence_over_invalid` pin
9179        // (c7d05ec).
9180        let mut s = three_member_spec();
9181        s.membros[1].caixa = String::new();
9182        let err = s.validate().unwrap_err();
9183        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
9184    }
9185
9186    #[test]
9187    fn membro_caixa_invalid_fires_before_versao_check() {
9188        // Order pin: an invalid-shape `:caixa` surfaces *its own*
9189        // diagnostic (which names the offending caixa name), even when
9190        // the same entry's `:versao` is also empty/invalid. The shape
9191        // gate runs first because the diagnostic is more self-locating —
9192        // an empty/invalid `:versao` on an invalid-shape caixa name is
9193        // a downstream-fix-after-the-caixa-rename concern.
9194        let mut s = three_member_spec();
9195        s.membros[1].caixa = "Cart".into();
9196        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
9197        let err = s.validate().unwrap_err();
9198        assert!(
9199            matches!(
9200                err,
9201                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
9202            ),
9203            "got {err:?}"
9204        );
9205    }
9206
9207    #[test]
9208    fn membro_caixa_invalid_fires_before_duplicate_check() {
9209        // Order pin: a malformed-shape `:caixa` on an earlier entry
9210        // surfaces *its own* diagnostic, even when a later entry would
9211        // otherwise collapse onto a duplicate name. The per-entry shape
9212        // gate runs inline before the duplicate-key insert, parallel
9213        // to `membro_versao_invalid_fires_before_duplicate_check`.
9214        let mut s = three_member_spec();
9215        s.membros[0].caixa = "Catalog".into();
9216        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
9217        let err = s.validate().unwrap_err();
9218        assert!(
9219            matches!(
9220                err,
9221                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
9222            ),
9223            "got {err:?}"
9224        );
9225    }
9226
9227    #[test]
9228    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
9229        // The diagnostic-shape pin: the error names the offending
9230        // `:caixa` value verbatim so the author can grep their
9231        // caixa.lisp without re-running the build, and carries a
9232        // non-empty `reason` naming the specific violation. Same
9233        // shape every typed-shape gate enshrines (c7d05ec's
9234        // `entrada_host_diagnostic_carries_offending_host`,
9235        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
9236        let mut s = three_member_spec();
9237        s.membros[2].caixa = "BAD_NAME".into();
9238        let err = s.validate().unwrap_err();
9239        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9240            panic!("expected MembroCaixaInvalid");
9241        };
9242        assert_eq!(caixa, "BAD_NAME");
9243        assert!(
9244            !reason.is_empty(),
9245            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
9246        );
9247    }
9248
9249    #[test]
9250    fn rejects_contrato_with_unknown_de() {
9251        let mut s = three_member_spec();
9252        s.contratos.push(contract_http("phantom", "catalog", "/x"));
9253        let err = s.validate().unwrap_err();
9254        assert!(
9255            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9256        );
9257    }
9258
9259    #[test]
9260    fn rejects_contrato_with_unknown_para() {
9261        let mut s = three_member_spec();
9262        s.contratos.push(contract_http("cart", "phantom", "/x"));
9263        let err = s.validate().unwrap_err();
9264        assert!(
9265            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9266        );
9267    }
9268
9269    #[test]
9270    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
9271        // The read-path pin: the phantom-`:de` refusal arm's
9272        // `ContratoMemberMissing.caixa` carrier must be observed through
9273        // the lifted [`WitContract::source`] accessor, not the raw
9274        // `.de.clone()` field-access `String`-carry. Peer of the sibling
9275        // per-`:contratos` self-loop arm's `.source().to_string()` /
9276        // `.world_ref().to_string()` `String`-carry sites the earlier
9277        // convergence lifted onto the same accessor pair. A future
9278        // silent detour that reintroduced the raw `.de.clone()` at the
9279        // wrap envelope while the shape-gate and membership lookup
9280        // routed through the accessor would surface here as a byte-equal
9281        // miss between the fired diagnostic's `caixa:` field and the
9282        // offending edge's `.source()` — pinning the accessor as the
9283        // sole read path across the phantom-name refusal arm's arg +
9284        // wrap-envelope emit surface.
9285        let mut s = three_member_spec();
9286        let phantom = contract_http("phantom", "catalog", "/x");
9287        s.contratos.push(phantom.clone());
9288        let err = s.validate().unwrap_err();
9289        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9290            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
9291        };
9292        assert_eq!(
9293            caixa,
9294            phantom.source(),
9295            "ContratoMemberMissing.caixa on the phantom-:de arm must \
9296             byte-equal WitContract::source — the wrap envelope must \
9297             route through the lifted accessor rather than the raw \
9298             .de.clone() field-access String-carry"
9299        );
9300    }
9301
9302    #[test]
9303    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9304        // The symmetric read-path pin on the `:para` phantom-name
9305        // refusal arm — same shape as the sibling `:de` pin above but
9306        // on the callee-Servico axis. Pins the wrap envelope's
9307        // `caixa:` field is observed through the lifted
9308        // [`WitContract::destination`] accessor, not the raw
9309        // `.para.clone()` field-access `String`-carry.
9310        let mut s = three_member_spec();
9311        let phantom = contract_http("cart", "phantom", "/x");
9312        s.contratos.push(phantom.clone());
9313        let err = s.validate().unwrap_err();
9314        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9315            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
9316        };
9317        assert_eq!(
9318            caixa,
9319            phantom.destination(),
9320            "ContratoMemberMissing.caixa on the phantom-:para arm must \
9321             byte-equal WitContract::destination — the wrap envelope \
9322             must route through the lifted accessor rather than the raw \
9323             .para.clone() field-access String-carry"
9324        );
9325    }
9326
9327    #[test]
9328    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
9329        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
9330        // refusal arm — the `validate_contrato_caixa` arg must be
9331        // observed through the lifted [`WitContract::source`] accessor,
9332        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
9333        // value routes through the shared
9334        // [`crate::render::require_valid_dns_1123_label`] floor with the
9335        // accessor-projected value; the fired
9336        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
9337        // the offending edge's `.source()`, pinning that the arg + the
9338        // downstream `caixa: caixa.to_string()` wrap route through the
9339        // same accessor's read path.
9340        let mut s = three_member_spec();
9341        let malformed = contract_http("BAD_NAME", "catalog", "/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 :de, got {err:?}");
9346        };
9347        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9348        assert_eq!(
9349            caixa,
9350            malformed.source(),
9351            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
9352             byte-equal WitContract::source — the shape-gate arg + wrap \
9353             envelope must route through the lifted accessor rather \
9354             than the raw &c.de &String-borrow"
9355        );
9356    }
9357
9358    #[test]
9359    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9360        // Symmetric arm to the sibling `:de` malformed-shape pin above,
9361        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
9362        // route through the lifted [`WitContract::destination`]
9363        // accessor. `:para` runs after the `:de` shape gate in the
9364        // canonical edge-direction order, so the `:de` value must be
9365        // well-shaped for the `:para` gate to fire — the `cart` :de is
9366        // canonical.
9367        let mut s = three_member_spec();
9368        let malformed = contract_http("cart", "BAD_NAME", "/x");
9369        s.contratos.push(malformed.clone());
9370        let err = s.validate().unwrap_err();
9371        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9372            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
9373        };
9374        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9375        assert_eq!(
9376            caixa,
9377            malformed.destination(),
9378            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
9379             byte-equal WitContract::destination — the shape-gate arg + \
9380             wrap envelope must route through the lifted accessor \
9381             rather than the raw &c.para &String-borrow"
9382        );
9383    }
9384
9385    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
9386
9387    #[test]
9388    fn rejects_contrato_de_empty() {
9389        // `:de ""` previously fell through to `ContratoMemberMissing`
9390        // (with `caixa: ""`) because the validated `:membros :caixa`
9391        // set never contains the empty string. The narrower
9392        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
9393        // the offending slot.
9394        let mut s = three_member_spec();
9395        s.contratos.push(contract_http("", "catalog", "/x"));
9396        let err = s.validate().unwrap_err();
9397        assert_eq!(
9398            err,
9399            AplicacaoError::ContratoCaixaEmpty {
9400                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9401            },
9402            "got {err:?}"
9403        );
9404    }
9405
9406    #[test]
9407    fn rejects_contrato_para_empty() {
9408        // Symmetric arm to `:de ""` — `:para ""` previously fell
9409        // through to `ContratoMemberMissing { caixa: "" }`.
9410        let mut s = three_member_spec();
9411        s.contratos.push(contract_http("cart", "", "/x"));
9412        let err = s.validate().unwrap_err();
9413        assert_eq!(
9414            err,
9415            AplicacaoError::ContratoCaixaEmpty {
9416                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9417            },
9418            "got {err:?}"
9419        );
9420    }
9421
9422    #[test]
9423    fn rejects_contrato_de_with_uppercase() {
9424        // The canonical "I copied the Servico's TitleCase display
9425        // name from an ADR" typo. Until this gate landed `:de "Cart"`
9426        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
9427        // as "this caixa isn't in `:membros`" when the root cause is
9428        // "this `:de` value's shape can never legitimately match a
9429        // validated member (DNS-1123 labels are lowercase)". The
9430        // narrower diagnostic names the offending slot, the value
9431        // verbatim, and the parser-shaped reason.
9432        let mut s = three_member_spec();
9433        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9434        let err = s.validate().unwrap_err();
9435        let AplicacaoError::ContratoCaixaInvalid {
9436            slot,
9437            caixa,
9438            reason,
9439        } = err
9440        else {
9441            panic!("expected ContratoCaixaInvalid, got other variant");
9442        };
9443        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9444        assert_eq!(caixa, "Cart");
9445        assert!(
9446            reason.contains("uppercase"),
9447            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9448        );
9449    }
9450
9451    #[test]
9452    fn rejects_contrato_para_with_underscore() {
9453        // The canonical "I'm thinking of a Python module" leak —
9454        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9455        // Pin the `:para` axis surfaces the same diagnostic shape as
9456        // the `:de` axis on the underscore violation.
9457        let mut s = three_member_spec();
9458        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
9459        let err = s.validate().unwrap_err();
9460        assert!(
9461            matches!(
9462                err,
9463                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9464                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
9465            ),
9466            "got {err:?}"
9467        );
9468    }
9469
9470    #[test]
9471    fn rejects_contrato_de_with_dot() {
9472        // A `:contratos :de` value is a single DNS-1123 *label*, not
9473        // a subdomain — mirroring the `:membros :caixa` floor. The
9474        // strictest floor among the use sites wins.
9475        let mut s = three_member_spec();
9476        s.contratos
9477            .push(contract_http("team.cart", "catalog", "/x"));
9478        let err = s.validate().unwrap_err();
9479        assert!(
9480            matches!(
9481                err,
9482                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9483                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
9484            ),
9485            "got {err:?}"
9486        );
9487    }
9488
9489    #[test]
9490    fn rejects_contrato_para_with_unicode() {
9491        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9492        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
9493        // validity check rejects multi-byte UTF-8 by the first
9494        // non-`[a-z0-9-]` byte.
9495        let mut s = three_member_spec();
9496        s.contratos.push(contract_http("cart", "café", "/x"));
9497        let err = s.validate().unwrap_err();
9498        assert!(
9499            matches!(
9500                err,
9501                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9502                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
9503            ),
9504            "got {err:?}"
9505        );
9506    }
9507
9508    #[test]
9509    fn rejects_contrato_de_with_leading_hyphen() {
9510        // DNS-1123 boundary rule: labels must start and end with an
9511        // alphanumeric. K8s rejects `-cart` outright; the narrower
9512        // shape diagnostic now names the violation at caixa-build
9513        // time rather than the misframed membership-lookup arm.
9514        let mut s = three_member_spec();
9515        s.contratos.push(contract_http("-cart", "catalog", "/x"));
9516        let err = s.validate().unwrap_err();
9517        assert!(
9518            matches!(
9519                err,
9520                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9521                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
9522            ),
9523            "got {err:?}"
9524        );
9525    }
9526
9527    #[test]
9528    fn contrato_de_empty_takes_precedence_over_invalid() {
9529        // Order pin: the `ContratoCaixaEmpty` arm fires before the
9530        // `ContratoCaixaInvalid` parse-side arm — same empty-first
9531        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9532        // / `validate_entrada_host` already establish on their peer
9533        // name axes. The empty string is a structurally distinct
9534        // authoring footgun (the author left the field blank, vs.
9535        // typed a malformed value), so it gets its own diagnostic.
9536        let mut s = three_member_spec();
9537        s.contratos.push(contract_http("", "catalog", "/x"));
9538        let err = s.validate().unwrap_err();
9539        assert_eq!(
9540            err,
9541            AplicacaoError::ContratoCaixaEmpty {
9542                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9543            }
9544        );
9545    }
9546
9547    #[test]
9548    fn contrato_de_shape_fires_before_para_shape() {
9549        // Per-axis order pin: within one `:contratos` entry, the `:de`
9550        // shape gate fires before the `:para` shape gate — same
9551        // edge-direction order the existing `ContratoMemberMissing` /
9552        // `ContratoSelfLoop` / target-dispatch checks use, so the
9553        // diagnostic for a contract with both `:de` and `:para`
9554        // malformed is stable. Authors fixing the surfaced `:de`
9555        // first will see `:para`'s diagnostic on re-run.
9556        let mut s = three_member_spec();
9557        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
9558        let err = s.validate().unwrap_err();
9559        assert!(
9560            matches!(
9561                err,
9562                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9563                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9564            ),
9565            "got {err:?}"
9566        );
9567    }
9568
9569    #[test]
9570    fn contrato_shape_fires_before_membership_lookup() {
9571        // The load-bearing pin: an invalid-shape `:de` surfaces its
9572        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
9573        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9574        // an invalid-shape `:de` could never legitimately match any
9575        // member — the prior `ContratoMemberMissing` diagnostic was
9576        // a structural impossibility framed as a graph-membership
9577        // failure. The shape gate now routes every such input through
9578        // the narrower self-locating diagnostic.
9579        let mut s = three_member_spec();
9580        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9581        let err = s.validate().unwrap_err();
9582        assert!(
9583            matches!(
9584                err,
9585                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
9586            ),
9587            "got {err:?}"
9588        );
9589        // And the symmetric case: an invalid-shape `:para` surfaces
9590        // its own diagnostic too, even when `:de` is well-shaped.
9591        let mut s = three_member_spec();
9592        s.contratos.push(contract_http("cart", "Catalog", "/x"));
9593        let err = s.validate().unwrap_err();
9594        assert!(
9595            matches!(
9596                err,
9597                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
9598            ),
9599            "got {err:?}"
9600        );
9601    }
9602
9603    #[test]
9604    fn contrato_shape_fires_before_self_edge_check() {
9605        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
9606        // bugs: the shape violation (uppercase) and the self-edge
9607        // violation. The narrower per-axis shape diagnostic surfaces
9608        // first because fixing the shape may reveal that the author
9609        // also meant to point `:para` at a different member — the
9610        // self-edge framing is only useful once both endpoints have
9611        // valid shape.
9612        let mut s = three_member_spec();
9613        s.contratos.push(contract_http("Cart", "Cart", "/x"));
9614        let err = s.validate().unwrap_err();
9615        assert!(
9616            matches!(
9617                err,
9618                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9619                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9620            ),
9621            "got {err:?}"
9622        );
9623    }
9624
9625    #[test]
9626    fn contrato_well_shaped_phantom_still_raises_member_missing() {
9627        // Strict-improvement pin: a well-shaped `:de` that simply
9628        // isn't in `:membros` (a phantom reference — author meant
9629        // to add the member but didn't, or renamed and missed an
9630        // update) still surfaces `ContratoMemberMissing`, unchanged.
9631        // The shape gate only intercepts inputs that could never
9632        // legitimately match a validated member; legitimately-shaped
9633        // phantom references remain on the graph-membership axis.
9634        let mut s = three_member_spec();
9635        s.contratos
9636            .push(contract_http("phantom-shim", "catalog", "/x"));
9637        let err = s.validate().unwrap_err();
9638        assert!(
9639            matches!(
9640                err,
9641                AplicacaoError::ContratoMemberMissing { ref caixa }
9642                    if caixa == "phantom-shim"
9643            ),
9644            "got {err:?}"
9645        );
9646    }
9647
9648    #[test]
9649    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
9650        // The diagnostic-shape pin: the error names the offending
9651        // slot (`:de` or `:para`) verbatim and the offending value
9652        // verbatim plus a non-empty parser-shaped reason, so the
9653        // author can grep their caixa.lisp for `:de "<name>"` /
9654        // `:para "<name>"` and fix it in one edit. Same diagnostic
9655        // shape as `MembroCaixaInvalid` (3f9d7a0) and
9656        // `PlacementClusterInvalid` (6c8c00b).
9657        let mut s = three_member_spec();
9658        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
9659        let err = s.validate().unwrap_err();
9660        let AplicacaoError::ContratoCaixaInvalid {
9661            slot,
9662            caixa,
9663            reason,
9664        } = err
9665        else {
9666            panic!("expected ContratoCaixaInvalid, got {err:?}");
9667        };
9668        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9669        assert_eq!(caixa, "BAD_NAME");
9670        assert!(
9671            !reason.is_empty(),
9672            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
9673        );
9674    }
9675
9676    #[test]
9677    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
9678        // Scalar-value pin: the two author-facing kebab-case labels the
9679        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
9680        // admits on the `:contratos` per-entry endpoint-shape axis,
9681        // one arm per typed sub-slot. Mirrors the peer scalar-value
9682        // pin the sibling top-level M2 / M3 / Supervisor
9683        // author-facing-label consts carry
9684        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
9685        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
9686        // slot itself), so every altitude of the typed-slot algebra
9687        // shares the same "one canonical byte-string per arm"
9688        // discipline. A future rebrand (`:de` → `:from` matching the
9689        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
9690        // sibling, `:para` → `:to` matching the same, or
9691        // `:de`/`:para` → `:source`/`:target` matching the WIT
9692        // world's `import`/`export` half-vocabulary) lands as an
9693        // edit to exactly one const, and every consumer that reaches
9694        // for the label picks it up at build time rather than at
9695        // runtime as a downstream `ContratoCaixaEmpty` /
9696        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
9697        // diagnostic mismatch far from the rename's commit.
9698        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
9699        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
9700    }
9701
9702    #[test]
9703    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
9704        // Production-through-const pin: the two per-axis labels the
9705        // per-`:contratos` entry endpoint-shape gate at
9706        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
9707        // argument to [`validate_contrato_caixa`] route through the
9708        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
9709        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
9710        // future rebrand that reaches the const but not the gate (or
9711        // vice versa) surfaces here at build time rather than at
9712        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
9713        // `slot: <stale-kebab-case>` diagnostic far from the rename's
9714        // commit. Mirror of the peer
9715        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
9716        // pin (882f498) on the sibling M3 top-level slot axis.
9717        let mut s = three_member_spec();
9718        s.contratos.push(contract_http("", "catalog", "/x"));
9719        assert_eq!(
9720            s.validate().unwrap_err(),
9721            AplicacaoError::ContratoCaixaEmpty {
9722                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9723            }
9724        );
9725        let mut s = three_member_spec();
9726        s.contratos.push(contract_http("cart", "", "/x"));
9727        assert_eq!(
9728            s.validate().unwrap_err(),
9729            AplicacaoError::ContratoCaixaEmpty {
9730                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9731            }
9732        );
9733    }
9734
9735    #[test]
9736    fn accepts_canonical_contrato_caixa_forms() {
9737        // The DNS-1123 label shapes a caixa author is realistically
9738        // going to write on a `:contratos :de` / `:para`. Pin every
9739        // leg so a future tightening that bans (e.g.) digit-start
9740        // identifiers surfaces here, mirroring
9741        // `accepts_canonical_membro_caixa_forms` on the peer name
9742        // axis.
9743        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9744            let mut s = three_member_spec();
9745            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
9746            s.contratos = vec![contract_http("checkout", form, "/x")];
9747            s.entrada = None;
9748            s.validate().unwrap_or_else(|e| {
9749                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
9750            });
9751
9752            let mut s = three_member_spec();
9753            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9754            s.contratos = vec![contract_http(form, "catalog", "/x")];
9755            s.entrada = None;
9756            s.validate().unwrap_or_else(|e| {
9757                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
9758            });
9759        }
9760    }
9761
9762    #[test]
9763    fn rejects_empty_wit() {
9764        let mut s = three_member_spec();
9765        s.contratos.push(WitContract {
9766            de: "cart".into(),
9767            para: "catalog".into(),
9768            wit: "".into(),
9769            endpoint: None,
9770            subject: None,
9771            slot: None,
9772        });
9773        let err = s.validate().unwrap_err();
9774        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
9775    }
9776
9777    #[test]
9778    fn rejects_entrada_to_unknown_member() {
9779        let mut s = three_member_spec();
9780        s.entrada.as_mut().unwrap().para = "phantom".into();
9781        assert!(matches!(
9782            s.validate().unwrap_err(),
9783            AplicacaoError::EntradaMemberMissing { .. }
9784        ));
9785    }
9786
9787    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
9788
9789    #[test]
9790    fn rejects_entrada_para_empty() {
9791        // `:para ""` previously fell through to
9792        // `EntradaMemberMissing { para: "" }` because the validated
9793        // `:membros :caixa` set never contains the empty string. The
9794        // narrower `EntradaParaEmpty` diagnostic now names the
9795        // offending slot directly — same empty-first cascade
9796        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
9797        // `ContratoCaixaEmpty` establish on the peer name axes.
9798        let mut s = three_member_spec();
9799        s.entrada.as_mut().unwrap().para = String::new();
9800        let err = s.validate().unwrap_err();
9801        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
9802    }
9803
9804    #[test]
9805    fn rejects_entrada_para_with_uppercase() {
9806        // The canonical "I copied the Servico's TitleCase display
9807        // name from an ADR" typo. Until this gate landed `:para "Cart"`
9808        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
9809        // as "this caixa isn't in `:membros`" when the root cause is
9810        // "this `:para` value's shape can never legitimately match a
9811        // validated member (DNS-1123 labels are lowercase)". The
9812        // narrower diagnostic names the value verbatim plus the
9813        // parser-shaped reason.
9814        let mut s = three_member_spec();
9815        s.entrada.as_mut().unwrap().para = "Cart".into();
9816        let err = s.validate().unwrap_err();
9817        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9818            panic!("expected EntradaParaInvalid, got other variant");
9819        };
9820        assert_eq!(para, "Cart");
9821        assert!(
9822            reason.contains("uppercase"),
9823            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9824        );
9825    }
9826
9827    #[test]
9828    fn rejects_entrada_para_with_underscore() {
9829        // The canonical "I'm thinking of a Python module" leak —
9830        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9831        let mut s = three_member_spec();
9832        s.entrada.as_mut().unwrap().para = "my_cart".into();
9833        let err = s.validate().unwrap_err();
9834        assert!(
9835            matches!(
9836                err,
9837                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9838                    if para == "my_cart" && reason.contains('_')
9839            ),
9840            "got {err:?}"
9841        );
9842    }
9843
9844    #[test]
9845    fn rejects_entrada_para_with_dot() {
9846        // An `:entrada :para` value is a single DNS-1123 *label*, not
9847        // a subdomain — mirroring the `:membros :caixa` floor. The
9848        // strictest floor among the use sites wins.
9849        let mut s = three_member_spec();
9850        s.entrada.as_mut().unwrap().para = "team.cart".into();
9851        let err = s.validate().unwrap_err();
9852        assert!(
9853            matches!(
9854                err,
9855                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9856                    if para == "team.cart" && reason.contains('.')
9857            ),
9858            "got {err:?}"
9859        );
9860    }
9861
9862    #[test]
9863    fn rejects_entrada_para_with_unicode() {
9864        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9865        // (`xn--…`) before it reaches K8s.
9866        let mut s = three_member_spec();
9867        s.entrada.as_mut().unwrap().para = "café".into();
9868        let err = s.validate().unwrap_err();
9869        assert!(
9870            matches!(
9871                err,
9872                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
9873            ),
9874            "got {err:?}"
9875        );
9876    }
9877
9878    #[test]
9879    fn rejects_entrada_para_with_leading_hyphen() {
9880        // DNS-1123 boundary rule: labels must start and end with an
9881        // alphanumeric. K8s rejects `-cart` outright.
9882        let mut s = three_member_spec();
9883        s.entrada.as_mut().unwrap().para = "-cart".into();
9884        let err = s.validate().unwrap_err();
9885        assert!(
9886            matches!(
9887                err,
9888                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9889                    if para == "-cart" && reason.contains("start and end")
9890            ),
9891            "got {err:?}"
9892        );
9893    }
9894
9895    #[test]
9896    fn rejects_entrada_para_with_trailing_hyphen() {
9897        // Symmetric boundary arm.
9898        let mut s = three_member_spec();
9899        s.entrada.as_mut().unwrap().para = "cart-".into();
9900        let err = s.validate().unwrap_err();
9901        assert!(
9902            matches!(
9903                err,
9904                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9905                    if para == "cart-" && reason.contains("start and end")
9906            ),
9907            "got {err:?}"
9908        );
9909    }
9910
9911    #[test]
9912    fn rejects_entrada_para_too_long() {
9913        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
9914        // bytes per label. K8s rejects longer names at admission on
9915        // every `metadata.name` axis.
9916        let mut s = three_member_spec();
9917        s.entrada.as_mut().unwrap().para = "a".repeat(64);
9918        let err = s.validate().unwrap_err();
9919        assert!(
9920            matches!(
9921                err,
9922                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9923                    if para.len() == 64 && reason.contains("max length")
9924            ),
9925            "got {err:?}"
9926        );
9927    }
9928
9929    #[test]
9930    fn entrada_para_empty_takes_precedence_over_invalid() {
9931        // Order pin: the `EntradaParaEmpty` arm fires before the
9932        // `EntradaParaInvalid` parse-side arm — same empty-first
9933        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9934        // / `validate_contrato_caixa` already establish.
9935        let mut s = three_member_spec();
9936        s.entrada.as_mut().unwrap().para = String::new();
9937        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
9938    }
9939
9940    #[test]
9941    fn entrada_para_shape_fires_before_membership_lookup() {
9942        // The load-bearing pin: an invalid-shape `:para` surfaces its
9943        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
9944        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9945        // an invalid-shape `:para` could never legitimately match any
9946        // member — the prior `EntradaMemberMissing` diagnostic framed
9947        // a structural impossibility as a graph-membership failure.
9948        let mut s = three_member_spec();
9949        s.entrada.as_mut().unwrap().para = "Cart".into();
9950        let err = s.validate().unwrap_err();
9951        assert!(
9952            matches!(
9953                err,
9954                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9955            ),
9956            "got {err:?}"
9957        );
9958    }
9959
9960    #[test]
9961    fn entrada_para_shape_fires_before_host_gate() {
9962        // Per-`:entrada` order pin: the `:para` shape gate fires
9963        // before the `:host` gate, mirroring the existing
9964        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
9965        // ordering where the member-lookup arm preceded the host gate.
9966        // The shape gate slots ahead of that, so a malformed `:para`
9967        // surfaces its own diagnostic even when `:host` is also wrong.
9968        let mut s = three_member_spec();
9969        let e = s.entrada.as_mut().unwrap();
9970        e.para = "Cart".into();
9971        e.host = "BAD HOST".into();
9972        let err = s.validate().unwrap_err();
9973        assert!(
9974            matches!(
9975                err,
9976                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9977            ),
9978            "got {err:?}"
9979        );
9980    }
9981
9982    #[test]
9983    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
9984        // Strict-improvement pin: a well-shaped `:para` that simply
9985        // isn't in `:membros` (a phantom reference — author meant to
9986        // add the member but didn't, or renamed and missed an
9987        // update) still surfaces `EntradaMemberMissing`, unchanged.
9988        // The shape gate only intercepts inputs that could never
9989        // legitimately match a validated member.
9990        let mut s = three_member_spec();
9991        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
9992        let err = s.validate().unwrap_err();
9993        assert!(
9994            matches!(
9995                err,
9996                AplicacaoError::EntradaMemberMissing { ref para }
9997                    if para == "phantom-shim"
9998            ),
9999            "got {err:?}"
10000        );
10001    }
10002
10003    #[test]
10004    fn entrada_para_invalid_diagnostic_carries_offending_para() {
10005        // The diagnostic-shape pin: the error names the offending
10006        // `:para` value verbatim plus a non-empty parser-shaped
10007        // reason, so the author can grep their caixa.lisp for
10008        // `:para "<name>"` and fix it in one edit. Same diagnostic
10009        // shape as `MembroCaixaInvalid` (3f9d7a0),
10010        // `PlacementClusterInvalid` (6c8c00b), and
10011        // `ContratoCaixaInvalid` (8d5af6b).
10012        let mut s = three_member_spec();
10013        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
10014        let err = s.validate().unwrap_err();
10015        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
10016            panic!("expected EntradaParaInvalid, got {err:?}");
10017        };
10018        assert_eq!(para, "BAD_NAME");
10019        assert!(
10020            !reason.is_empty(),
10021            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
10022        );
10023    }
10024
10025    #[test]
10026    fn accepts_canonical_entrada_para_forms() {
10027        // Positive-control sweep covering the DNS-1123 label shapes a
10028        // caixa author is realistically going to write on `:entrada
10029        // :para`. Pin every leg so a future tightening that bans
10030        // (e.g.) digit-start identifiers surfaces here, mirroring
10031        // `accepts_canonical_membro_caixa_forms` and
10032        // `accepts_canonical_contrato_caixa_forms` on the peer name
10033        // axes.
10034        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
10035            let mut s = three_member_spec();
10036            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
10037            s.contratos = vec![contract_http(form, "catalog", "/x")];
10038            s.entrada = Some(Entrada {
10039                host: "checkout.quero.cloud".into(),
10040                para: form.into(),
10041                paths: vec!["/api".into()],
10042                port: 8080,
10043            });
10044            s.validate().unwrap_or_else(|e| {
10045                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
10046            });
10047        }
10048    }
10049
10050    #[test]
10051    fn rejects_replicated_without_clusters() {
10052        let mut s = three_member_spec();
10053        s.placement.clusters = vec![];
10054        assert!(matches!(
10055            s.validate().unwrap_err(),
10056            AplicacaoError::PlacementWithoutClusters { .. }
10057        ));
10058    }
10059
10060    #[test]
10061    fn rejects_sharded_without_key() {
10062        let mut s = three_member_spec();
10063        s.placement.estrategia = PlacementStrategy::Sharded;
10064        s.placement.shard_key = None;
10065        s.placement.clusters = vec!["rio".into()];
10066        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
10067    }
10068
10069    #[test]
10070    fn sharded_with_key_validates() {
10071        let mut s = three_member_spec();
10072        s.placement.estrategia = PlacementStrategy::Sharded;
10073        s.placement.shard_key = Some("$tenantId".into());
10074        s.validate().unwrap();
10075    }
10076
10077    #[test]
10078    fn round_trip_via_json_preserves_shape() {
10079        let s = three_member_spec();
10080        let json = serde_json::to_string(&s.membros).unwrap();
10081        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
10082        assert_eq!(back, s.membros);
10083
10084        let json = serde_json::to_string(&s.contratos).unwrap();
10085        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
10086        assert_eq!(back, s.contratos);
10087
10088        let json = serde_json::to_string(&s.placement).unwrap();
10089        let back: Placement = serde_json::from_str(&json).unwrap();
10090        assert_eq!(back, s.placement);
10091
10092        let json = serde_json::to_string(&s.entrada).unwrap();
10093        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
10094        assert_eq!(back, s.entrada);
10095    }
10096
10097    #[test]
10098    fn rate_limit_round_trip_seconds() {
10099        let policy = MeshPolicy {
10100            rate_limit: Some(RateLimit {
10101                rate: 100,
10102                window: Duration::from_secs(1),
10103            }),
10104            ..Default::default()
10105        };
10106        let json = serde_json::to_string(&policy).unwrap();
10107        assert!(json.contains("\"100/s\""));
10108        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10109        assert_eq!(back.rate_limit.unwrap().rate, 100);
10110        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
10111    }
10112
10113    #[test]
10114    fn rate_limit_round_trip_minutes() {
10115        let policy = MeshPolicy {
10116            rate_limit: Some(RateLimit {
10117                rate: 5000,
10118                window: Duration::from_secs(60),
10119            }),
10120            ..Default::default()
10121        };
10122        let json = serde_json::to_string(&policy).unwrap();
10123        assert!(json.contains("\"5000/m\""));
10124    }
10125
10126    #[test]
10127    fn circuit_breaker_round_trip() {
10128        let policy = MeshPolicy {
10129            circuit_breaker: Some(CircuitBreaker {
10130                max_failures: 5,
10131                window: Duration::from_secs(60),
10132            }),
10133            ..Default::default()
10134        };
10135        let json = serde_json::to_string(&policy).unwrap();
10136        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10137        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
10138        assert_eq!(
10139            back.circuit_breaker.unwrap().window,
10140            Duration::from_secs(60)
10141        );
10142    }
10143
10144    #[test]
10145    fn rejects_http_contrato_without_endpoint() {
10146        let mut s = three_member_spec();
10147        s.contratos.push(WitContract {
10148            de: "cart".into(),
10149            para: "catalog".into(),
10150            wit: "wasi:http/proxy".into(),
10151            endpoint: None,
10152            subject: None,
10153            slot: None,
10154        });
10155        let err = s.validate().unwrap_err();
10156        assert!(matches!(
10157            err,
10158            AplicacaoError::ContratoMissingTarget {
10159                expected: WitTarget::HTTP_FIELD_NAME,
10160                ..
10161            }
10162        ));
10163    }
10164
10165    #[test]
10166    fn rejects_http_contrato_with_subject() {
10167        let mut s = three_member_spec();
10168        s.contratos.push(WitContract {
10169            de: "cart".into(),
10170            para: "catalog".into(),
10171            wit: "wasi:http/proxy".into(),
10172            endpoint: Some("/x".into()),
10173            subject: Some("not.allowed.here".into()),
10174            slot: None,
10175        });
10176        let err = s.validate().unwrap_err();
10177        assert!(matches!(
10178            err,
10179            AplicacaoError::ContratoWrongTarget {
10180                expected: WitTarget::HTTP_FIELD_NAME,
10181                ..
10182            }
10183        ));
10184    }
10185
10186    #[test]
10187    fn rejects_pubsub_contrato_without_subject() {
10188        let mut s = three_member_spec();
10189        s.contratos.push(WitContract {
10190            de: "cart".into(),
10191            para: "catalog".into(),
10192            wit: "nats:pub-sub".into(),
10193            endpoint: None,
10194            subject: None,
10195            slot: None,
10196        });
10197        let err = s.validate().unwrap_err();
10198        assert!(matches!(
10199            err,
10200            AplicacaoError::ContratoMissingTarget {
10201                expected: WitTarget::PUBSUB_FIELD_NAME,
10202                ..
10203            }
10204        ));
10205    }
10206
10207    #[test]
10208    fn rejects_pubsub_contrato_with_endpoint() {
10209        let mut s = three_member_spec();
10210        s.contratos.push(WitContract {
10211            de: "cart".into(),
10212            para: "catalog".into(),
10213            wit: "kafka:topic".into(),
10214            endpoint: Some("/wrong".into()),
10215            subject: Some("topic.x".into()),
10216            slot: None,
10217        });
10218        let err = s.validate().unwrap_err();
10219        assert!(matches!(
10220            err,
10221            AplicacaoError::ContratoWrongTarget {
10222                expected: WitTarget::PUBSUB_FIELD_NAME,
10223                ..
10224            }
10225        ));
10226    }
10227
10228    #[test]
10229    fn rejects_store_contrato_without_slot() {
10230        let mut s = three_member_spec();
10231        s.contratos.push(WitContract {
10232            de: "cart".into(),
10233            para: "catalog".into(),
10234            wit: "wasi:keyvalue/store".into(),
10235            endpoint: None,
10236            subject: None,
10237            slot: None,
10238        });
10239        let err = s.validate().unwrap_err();
10240        assert!(matches!(
10241            err,
10242            AplicacaoError::ContratoMissingTarget {
10243                expected: WitTarget::STORE_FIELD_NAME,
10244                ..
10245            }
10246        ));
10247    }
10248
10249    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
10250
10251    #[test]
10252    fn rejects_http_contrato_with_empty_endpoint() {
10253        // `Some("")` for an HTTP endpoint passes the presence check
10254        // (target() previously returned WitTarget::Http { endpoint: "" })
10255        // but renders as a `path: ""` Cilium L7 rule that matches no
10256        // traffic. Same value-shape footgun closed for :entrada :paths
10257        // entries (eb3456d).
10258        let mut s = three_member_spec();
10259        s.contratos.push(WitContract {
10260            de: "cart".into(),
10261            para: "catalog".into(),
10262            wit: "wasi:http/proxy".into(),
10263            endpoint: Some(String::new()),
10264            subject: None,
10265            slot: None,
10266        });
10267        let err = s.validate().unwrap_err();
10268        assert!(
10269            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
10270                if de == "cart" && para == "catalog"),
10271            "got {err:?}"
10272        );
10273    }
10274
10275    #[test]
10276    fn rejects_http_contrato_with_relative_endpoint() {
10277        // Cilium L7 :path + Gateway API PathPrefix both require a
10278        // leading `/`. Same shape required of :entrada :paths
10279        // (eb3456d). Lifted into target() so every consumer of the
10280        // typed WitTarget view inherits the guarantee.
10281        let mut s = three_member_spec();
10282        s.contratos.push(WitContract {
10283            de: "cart".into(),
10284            para: "catalog".into(),
10285            wit: "wasi:http/proxy".into(),
10286            endpoint: Some("products/:id".into()),
10287            subject: None,
10288            slot: None,
10289        });
10290        let err = s.validate().unwrap_err();
10291        assert!(
10292            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10293                if endpoint == "products/:id"),
10294            "got {err:?}"
10295        );
10296    }
10297
10298    #[test]
10299    fn rejects_pubsub_contrato_with_empty_subject() {
10300        // NATS / Kafka publish without a subject is a no-op subscribe;
10301        // never the author's intent. Same empty-string rejection as
10302        // :membros :caixa, :placement :clusters entries, :entrada
10303        // :paths entries — every value carried by every typed slot is
10304        // value-shape-checked at validate().
10305        let mut s = three_member_spec();
10306        s.contratos.push(WitContract {
10307            de: "cart".into(),
10308            para: "catalog".into(),
10309            wit: "nats:pub-sub".into(),
10310            endpoint: None,
10311            subject: Some(String::new()),
10312            slot: None,
10313        });
10314        let err = s.validate().unwrap_err();
10315        assert!(
10316            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
10317                if de == "cart" && para == "catalog"),
10318            "got {err:?}"
10319        );
10320    }
10321
10322    #[test]
10323    fn rejects_store_contrato_with_empty_slot() {
10324        // An empty slot template addresses the bucket root, defeating
10325        // the per-key isolation the slot exists for — a footgun on
10326        // `wasi:keyvalue/store` whose closest analog is the empty
10327        // shard-key rejected on :placement Sharded (c7c7799).
10328        let mut s = three_member_spec();
10329        s.contratos.push(WitContract {
10330            de: "cart".into(),
10331            para: "catalog".into(),
10332            wit: "wasi:keyvalue/store".into(),
10333            endpoint: None,
10334            subject: None,
10335            slot: Some(String::new()),
10336        });
10337        let err = s.validate().unwrap_err();
10338        assert!(
10339            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
10340                if de == "cart" && para == "catalog"),
10341            "got {err:?}"
10342        );
10343    }
10344
10345    #[test]
10346    fn http_contrato_root_endpoint_validates() {
10347        // Pin the boundary case: a single-`/` endpoint is the catch-all
10348        // form the Gateway HTTPRoute renderer falls back to when
10349        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
10350        // must remain a valid contrato endpoint too.
10351        let mut s = three_member_spec();
10352        s.contratos.push(contract_http("cart", "catalog", "/"));
10353        s.validate().unwrap();
10354    }
10355
10356    // ── :contratos :endpoint value-shape gate ────────────────────────────
10357    //
10358    // Mirrors the `:entrada :paths` value-shape suite on the peer
10359    // HTTP-path axis. Until this gate landed `WitContract::target()`
10360    // only refused the empty string + the missing-leading-`/` form
10361    // (c4213a4); a structurally invalid endpoint passed validate and
10362    // landed verbatim as a Cilium L7 `path:` rule
10363    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
10364    // traffic or was rejected at apply time by Cilium policy admission.
10365    // Every authoring footgun the K8s Gateway API webhook / Cilium
10366    // policy validator would catch on admission now becomes a caixa-
10367    // build-time `ContratoEndpointInvalid` with the offending
10368    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
10369    // shape as `EntradaPathInvalid` on the sibling axis; same shared
10370    // predicate (`crate::render::is_gateway_api_http_path`) ensures
10371    // drift between the two axes' rule enforcement is a build error
10372    // at the predicate.
10373
10374    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
10375        // Fresh spec per call so the would-be-duplicate edge
10376        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
10377        // `three_member_spec`'s pre-existing
10378        // `(cart, catalog, …, /products/:id)` entry — only the
10379        // endpoint payload differs.
10380        let mut s = three_member_spec();
10381        s.contratos.push(contract_http("cart", "catalog", ep));
10382        s.validate().unwrap_err()
10383    }
10384
10385    #[test]
10386    fn rejects_http_contrato_endpoint_with_query() {
10387        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
10388        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
10389        // rule the L7 matcher would never satisfy.
10390        let err = contrato_endpoint_err("/charge?token=X");
10391        assert!(
10392            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10393                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
10394            "got {err:?}"
10395        );
10396    }
10397
10398    #[test]
10399    fn rejects_http_contrato_endpoint_with_fragment() {
10400        let err = contrato_endpoint_err("/charge#frag");
10401        assert!(
10402            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10403                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
10404            "got {err:?}"
10405        );
10406    }
10407
10408    #[test]
10409    fn rejects_http_contrato_endpoint_with_whitespace() {
10410        let err = contrato_endpoint_err("/foo bar");
10411        assert!(
10412            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10413                if endpoint == "/foo bar" && reason.contains("whitespace")),
10414            "got {err:?}"
10415        );
10416    }
10417
10418    #[test]
10419    fn rejects_http_contrato_endpoint_with_control_char() {
10420        let err = contrato_endpoint_err("/api/\x01bar");
10421        assert!(
10422            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10423                if endpoint == "/api/\x01bar" && reason.contains("control character")),
10424            "got {err:?}"
10425        );
10426    }
10427
10428    #[test]
10429    fn rejects_http_contrato_endpoint_with_non_ascii() {
10430        let err = contrato_endpoint_err("/api/café");
10431        assert!(
10432            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10433                if endpoint == "/api/café" && reason.contains("non-ASCII")),
10434            "got {err:?}"
10435        );
10436    }
10437
10438    #[test]
10439    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
10440        let err = contrato_endpoint_err("/api//cart");
10441        assert!(
10442            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10443                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
10444            "got {err:?}"
10445        );
10446    }
10447
10448    #[test]
10449    fn rejects_http_contrato_endpoint_with_dot_segment() {
10450        let err = contrato_endpoint_err("/api/./cart");
10451        assert!(
10452            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10453                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
10454            "got {err:?}"
10455        );
10456    }
10457
10458    #[test]
10459    fn rejects_http_contrato_endpoint_with_parent_segment() {
10460        // Path-traversal in a contrato endpoint is the canonical
10461        // "L7 rule that the workload's HTTP server's path-resolution
10462        // logic interprets differently than the policy enforcer"
10463        // footgun. Rejected outright at validate time.
10464        let err = contrato_endpoint_err("/api/../etc");
10465        assert!(
10466            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10467                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
10468            "got {err:?}"
10469        );
10470    }
10471
10472    #[test]
10473    fn rejects_http_contrato_endpoint_too_long() {
10474        // 1025-byte endpoint — one over the Gateway API
10475        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
10476        // path matcher has no inherent length limit but the policy
10477        // CR itself rides through the K8s apiserver, which enforces
10478        // ConfigMap-shaped limits; sharing the Gateway API cap is the
10479        // conservative floor.
10480        let big = format!("/api/{}", "a".repeat(1020));
10481        assert_eq!(big.len(), 1025);
10482        let err = contrato_endpoint_err(&big);
10483        assert!(
10484            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10485                if endpoint == &big && reason.contains("max length of 1024")),
10486            "got {err:?}"
10487        );
10488    }
10489
10490    #[test]
10491    fn http_contrato_endpoint_max_length_validates() {
10492        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
10493        // in the cap surfaces here and at
10494        // `rejects_http_contrato_endpoint_too_long` simultaneously,
10495        // mirroring `entrada_path_max_length_validates` on the peer
10496        // axis.
10497        let big = format!("/api/{}", "a".repeat(1019));
10498        assert_eq!(big.len(), 1024);
10499        let mut s = three_member_spec();
10500        s.contratos.push(contract_http("cart", "catalog", &big));
10501        s.validate().unwrap();
10502    }
10503
10504    #[test]
10505    fn http_contrato_endpoint_accepts_canonical_forms() {
10506        // Positive-set sweep: every canonical HTTP-path shape the
10507        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
10508        // plain paths, hidden-file-style `.config` segments distinct
10509        // from the `.` segment, digit-bearing segments, the canonical
10510        // route-template `:param` form, trailing-slash form,
10511        // percent-encoded segments, the `/foo..bar` interior-`..`-
10512        // substring forms that are NOT `..` segments) must remain a
10513        // valid contrato endpoint too. Drift between this list and
10514        // the entrada path positive sweep surfaces at the shared
10515        // `is_gateway_api_http_path` substrate-side suite — one
10516        // source of truth. Uses a fresh `(payment, catalog)` edge so
10517        // none of the swept endpoints collide with the pre-existing
10518        // `(cart, catalog, /products/:id)` / `(cart, payment,
10519        // /charge)` entries in `three_member_spec`.
10520        for ep in [
10521            "/",
10522            "/charge",
10523            "/v1/charge",
10524            "/api/.config",
10525            "/products/:id",
10526            "/api/cart/",
10527            "/api/caf%C3%A9",
10528            "/foo..bar",
10529            "/...",
10530        ] {
10531            let mut s = three_member_spec();
10532            s.contratos.push(contract_http("payment", "catalog", ep));
10533            s.validate()
10534                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
10535        }
10536    }
10537
10538    #[test]
10539    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
10540        // Ordering pin: `ContratoEndpointEmpty` is the more self-
10541        // locating diagnostic on `""` and must lead — the value-
10542        // shape gate is only reached after the empty-check fires.
10543        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
10544        // on the peer axis.
10545        let mut s = three_member_spec();
10546        s.contratos.push(WitContract {
10547            de: "cart".into(),
10548            para: "catalog".into(),
10549            wit: "wasi:http/proxy".into(),
10550            endpoint: Some(String::new()),
10551            subject: None,
10552            slot: None,
10553        });
10554        let err = s.validate().unwrap_err();
10555        assert!(
10556            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
10557            "got {err:?}"
10558        );
10559    }
10560
10561    #[test]
10562    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
10563        // Ordering pin: an endpoint without a leading `/` surfaces the
10564        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
10565        // value-shape gate is only consulted on endpoints that already
10566        // satisfy the absolute-prefix invariant. Mirrors
10567        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
10568        let err = contrato_endpoint_err("bad path");
10569        assert!(
10570            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10571                if endpoint == "bad path"),
10572            "got {err:?}"
10573        );
10574    }
10575
10576    #[test]
10577    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
10578        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
10579        // `:para` + a non-empty reason flow through verbatim so the
10580        // author can grep their caixa.lisp for the offending contrato
10581        // block and fix it in one edit. Same shape as
10582        // `entrada_path_diagnostic_carries_offending_path`.
10583        let err = contrato_endpoint_err("/api?q=1");
10584        match err {
10585            AplicacaoError::ContratoEndpointInvalid {
10586                de,
10587                para,
10588                endpoint,
10589                reason,
10590            } => {
10591                assert_eq!(de, "cart");
10592                assert_eq!(para, "catalog");
10593                assert_eq!(endpoint, "/api?q=1");
10594                assert!(!reason.is_empty(), "reason field must be non-empty");
10595            }
10596            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
10597        }
10598    }
10599
10600    #[test]
10601    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
10602        // The compounding theorem: every &str inside a WitTarget
10603        // returned by target() is non-empty (and absolute, for Http).
10604        // Renderers downstream of typed_view() can rely on this
10605        // without re-checking — the type system carries the proof.
10606        let http = contract_http("cart", "catalog", "/x");
10607        match http.target().unwrap() {
10608            WitTarget::Http { endpoint } => {
10609                assert!(!endpoint.is_empty());
10610                assert!(endpoint.starts_with('/'));
10611            }
10612            other => panic!("expected Http, got {other:?}"),
10613        }
10614        let nats = WitContract {
10615            de: "a".into(),
10616            para: "b".into(),
10617            wit: "nats:pub-sub".into(),
10618            endpoint: None,
10619            subject: Some("topic.x".into()),
10620            slot: None,
10621        };
10622        match nats.target().unwrap() {
10623            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
10624            other => panic!("expected PubSub, got {other:?}"),
10625        }
10626        let kv = WitContract {
10627            de: "a".into(),
10628            para: "b".into(),
10629            wit: "wasi:keyvalue/store".into(),
10630            endpoint: None,
10631            subject: None,
10632            slot: Some("checkout/$orderId".into()),
10633        };
10634        match kv.target().unwrap() {
10635            WitTarget::Store { slot } => assert!(!slot.is_empty()),
10636            other => panic!("expected Store, got {other:?}"),
10637        }
10638    }
10639
10640    #[test]
10641    fn target_diagnostic_names_offending_endpoint_value() {
10642        // When the malformed endpoint string is non-trivial, the
10643        // diagnostic carries the actual value back to the author —
10644        // not a generic "endpoint malformed" error.
10645        let bad = WitContract {
10646            de: "src".into(),
10647            para: "dst".into(),
10648            wit: "wasi:http/proxy".into(),
10649            endpoint: Some("api/v1/charge".into()),
10650            subject: None,
10651            slot: None,
10652        };
10653        match bad.target().unwrap_err() {
10654            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
10655                assert_eq!(de, "src");
10656                assert_eq!(para, "dst");
10657                assert_eq!(endpoint, "api/v1/charge");
10658            }
10659            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
10660        }
10661    }
10662
10663    #[test]
10664    fn rejects_unknown_wit_with_target_set() {
10665        let mut s = three_member_spec();
10666        s.contratos.push(WitContract {
10667            de: "cart".into(),
10668            para: "catalog".into(),
10669            wit: "custom:exchange".into(),
10670            endpoint: Some("/leaked".into()),
10671            subject: None,
10672            slot: None,
10673        });
10674        let err = s.validate().unwrap_err();
10675        assert!(matches!(
10676            err,
10677            AplicacaoError::ContratoWrongTarget {
10678                expected: WitTarget::CAPABILITY_EXPECTED,
10679                ..
10680            }
10681        ));
10682    }
10683
10684    #[test]
10685    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
10686        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
10687        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
10688        // fourth arm of the same "which payload field name goes in the
10689        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
10690        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10691        // consts cover on the peer HTTP / PubSub / Store arms
10692        // (`wit_target_field_name_pins_per_variant`). Until this lift
10693        // landed the byte-string sat twice — once inline in the
10694        // [`WitContract::target`] Capability-arm rejection at the
10695        // production dispatch, once in `rejects_unknown_wit_with_target_set`
10696        // pinning against the same literal — with no compile-time link
10697        // between them. Same "one canonical declaration, next to the
10698        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
10699        // lift established for the payload-less arm's human-readable
10700        // label axis; this test is the shape peer of
10701        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
10702        // pair (routes-through-const + scalar-value pin) on the
10703        // wrong-target diagnostic-scalar axis.
10704        //
10705        // Fail-before-pass-after was verified locally by mutating the
10706        // const declaration to `"capability"` — the scalar-value pin
10707        // below fires (`"capability" != "none"`) and the routes-through
10708        // assertion below still holds (production and const walk in
10709        // lockstep), which is the correct behavior: a rename on the
10710        // const drifts here first, not at a downstream consumer.
10711        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
10712
10713        let mut s = three_member_spec();
10714        s.contratos.push(WitContract {
10715            de: "cart".into(),
10716            para: "catalog".into(),
10717            wit: "custom:exchange".into(),
10718            endpoint: Some("/leaked".into()),
10719            subject: None,
10720            slot: None,
10721        });
10722        match s.validate().unwrap_err() {
10723            AplicacaoError::ContratoWrongTarget { expected, .. } => {
10724                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
10725            }
10726            other => panic!("expected ContratoWrongTarget, got {other:?}"),
10727        }
10728    }
10729
10730    #[test]
10731    fn unknown_wit_capability_only_validates() {
10732        let mut s = three_member_spec();
10733        s.contratos.push(WitContract {
10734            de: "cart".into(),
10735            para: "catalog".into(),
10736            // A WIT world we haven't yet shaped — accept it as a typed
10737            // capability edge so authors aren't blocked while the WIT
10738            // registry catches up. No payload field may be carried.
10739            wit: "custom:exchange".into(),
10740            endpoint: None,
10741            subject: None,
10742            slot: None,
10743        });
10744        s.validate().unwrap();
10745        let added = s.contratos.last().unwrap();
10746        assert_eq!(added.target().unwrap(), WitTarget::Capability);
10747    }
10748
10749    #[test]
10750    fn target_typed_view_round_trips_each_shape() {
10751        let http = contract_http("cart", "catalog", "/products/:id");
10752        assert_eq!(
10753            http.target().unwrap(),
10754            WitTarget::Http {
10755                endpoint: "/products/:id"
10756            }
10757        );
10758        let nats = WitContract {
10759            de: "a".into(),
10760            para: "b".into(),
10761            wit: "nats:pub-sub".into(),
10762            endpoint: None,
10763            subject: Some("topic.x".into()),
10764            slot: None,
10765        };
10766        assert_eq!(
10767            nats.target().unwrap(),
10768            WitTarget::PubSub { subject: "topic.x" }
10769        );
10770        let kv = WitContract {
10771            de: "a".into(),
10772            para: "b".into(),
10773            wit: "wasi:keyvalue/store".into(),
10774            endpoint: None,
10775            subject: None,
10776            slot: Some("checkout/$orderId".into()),
10777        };
10778        assert_eq!(
10779            kv.target().unwrap(),
10780            WitTarget::Store {
10781                slot: "checkout/$orderId"
10782            }
10783        );
10784    }
10785
10786    #[test]
10787    fn wit_contract_kind_predicates() {
10788        let http = contract_http("a", "b", "/x");
10789        assert!(http.is_http());
10790        assert!(!http.is_pubsub());
10791        assert!(!http.is_store());
10792        assert!(!http.is_capability());
10793
10794        let nats = WitContract {
10795            de: "a".into(),
10796            para: "b".into(),
10797            wit: "nats:pub-sub".into(),
10798            endpoint: None,
10799            subject: Some("topic.x".into()),
10800            slot: None,
10801        };
10802        assert!(nats.is_pubsub());
10803        assert!(!nats.is_http());
10804        assert!(!nats.is_capability());
10805
10806        let kv = WitContract {
10807            de: "a".into(),
10808            para: "b".into(),
10809            wit: "wasi:keyvalue/store".into(),
10810            endpoint: None,
10811            subject: None,
10812            slot: Some("checkout/$orderId".into()),
10813        };
10814        assert!(kv.is_store());
10815        assert!(!kv.is_http());
10816        assert!(!kv.is_capability());
10817
10818        // Fourth arm on the paired closed-set predicate family: the
10819        // payload-less capability edge that projects to the payload-
10820        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
10821        // Extends the 3-arm predicate sweep this test opened to cover
10822        // the closed 4-way partition [`WitContract::is_capability`]
10823        // closes on the pre-projection WIT-shape axis, matched with the
10824        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
10825        // 4-arm predicate set.
10826        let cap = WitContract {
10827            de: "a".into(),
10828            para: "b".into(),
10829            wit: "custom:capability-only".into(),
10830            endpoint: None,
10831            subject: None,
10832            slot: None,
10833        };
10834        assert!(cap.is_capability());
10835        assert!(!cap.is_http());
10836        assert!(!cap.is_pubsub());
10837        assert!(!cap.is_store());
10838    }
10839
10840    // ── :contratos :wit value-shape gate ─────────────────────────────────
10841    //
10842    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
10843    // dispatch-discriminator axis. Until this gate landed
10844    // `WitContract::target()` accepted any non-empty string and
10845    // silently demoted unrecognized shapes to a capability-only L4
10846    // edge — the canonical "I thought I had L7 HTTP routing, got
10847    // L4-only" footgun. Every authoring footgun the WIT registry's
10848    // own grammar rejects (uppercase, hyphen-for-colon typo,
10849    // whitespace, empty package, doubled `@`, …) now becomes a
10850    // caixa-build-time `ContratoWitInvalid` with the offending
10851    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
10852    // as `ContratoEndpointInvalid` on the sibling axis; same shared
10853    // predicate (`crate::render::is_wit_world_ref`) ensures drift
10854    // between any two axes' rule enforcement is a build error at the
10855    // predicate, not piecemeal across renderers.
10856
10857    fn contrato_wit_err(wit: &str) -> AplicacaoError {
10858        // Fresh spec per call so the new contract doesn't collide on
10859        // identity with `three_member_spec`'s pre-existing entries.
10860        // The new edge uses `(payment, catalog)` — a pair the fixture
10861        // doesn't already declare — with no payload field set, so the
10862        // wit-shape gate fires before any payload-shape arm.
10863        let mut s = three_member_spec();
10864        s.contratos.push(WitContract {
10865            de: "payment".into(),
10866            para: "catalog".into(),
10867            wit: wit.into(),
10868            endpoint: None,
10869            subject: None,
10870            slot: None,
10871        });
10872        s.validate().unwrap_err()
10873    }
10874
10875    #[test]
10876    fn rejects_wit_with_uppercase_namespace() {
10877        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
10878        // didn't match the lowercase `wasi:http/` prefix is_http() keys
10879        // off, so the dispatch fell through to the capability arm and
10880        // the contract silently rendered as an L4-only Cilium edge.
10881        // The new gate surfaces the uppercase typo at validate time
10882        // with the offending `:wit` named.
10883        let err = contrato_wit_err("WASI:http/proxy");
10884        assert!(
10885            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10886                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
10887            "got {err:?}"
10888        );
10889    }
10890
10891    #[test]
10892    fn rejects_wit_with_hyphen_for_colon_typo() {
10893        // The canonical "I forgot the `:` separator" typo — pre-gate
10894        // this passed as Capability silently, so the renderer emitted
10895        // an L4-only policy where the author expected L7 HTTP rules.
10896        let err = contrato_wit_err("wasi-http/proxy");
10897        assert!(
10898            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10899                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
10900            "got {err:?}"
10901        );
10902    }
10903
10904    #[test]
10905    fn rejects_wit_with_multiple_colons() {
10906        // Doubled `:` — the namespace/package split has nowhere to
10907        // anchor, so the dispatch silently demotes to Capability.
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("exactly one `:`")),
10912            "got {err:?}"
10913        );
10914    }
10915
10916    #[test]
10917    fn rejects_wit_with_empty_package() {
10918        // `wasi:` — namespace alone with no package. Pre-gate this
10919        // failed neither the is_http nor is_pubsub nor is_store
10920        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
10921        // a bare `wasi:`), so it silently demoted to Capability.
10922        let err = contrato_wit_err("wasi:");
10923        assert!(
10924            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10925                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
10926            "got {err:?}"
10927        );
10928    }
10929
10930    #[test]
10931    fn rejects_wit_with_underscore() {
10932        // Underscore — WIT identifiers are kebab-case, same rule
10933        // DNS-1123 enforces on its peer axes. The diagnostic carries
10934        // the explicit "use `-` instead" remediation.
10935        let err = contrato_wit_err("wasi:http_proxy");
10936        assert!(
10937            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10938                if wit == "wasi:http_proxy" && reason.contains('_')),
10939            "got {err:?}"
10940        );
10941    }
10942
10943    #[test]
10944    fn rejects_wit_with_whitespace() {
10945        // Whitespace mid-token — the prefix check matches but the
10946        // package-and-onward parse silently demoted to Capability.
10947        let err = contrato_wit_err("wasi:http proxy");
10948        assert!(
10949            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10950                if wit == "wasi:http proxy" && reason.contains("whitespace")),
10951            "got {err:?}"
10952        );
10953    }
10954
10955    #[test]
10956    fn rejects_wit_with_non_ascii() {
10957        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10958        // the package name from a doc with smart quotes / accented
10959        // characters" footgun.
10960        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
10961        assert!(
10962            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10963                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
10964            "got {err:?}"
10965        );
10966    }
10967
10968    #[test]
10969    fn rejects_wit_with_consecutive_hyphens() {
10970        // `pub--sub` — WIT identifiers join words with single hyphens.
10971        let err = contrato_wit_err("nats:pub--sub");
10972        assert!(
10973            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10974                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
10975            "got {err:?}"
10976        );
10977    }
10978
10979    #[test]
10980    fn rejects_wit_with_trailing_at_no_version() {
10981        // `wasi:http/proxy@` — the version-suffix author started to
10982        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
10983        // parser would reject this; surface it at validate time.
10984        let err = contrato_wit_err("wasi:http/proxy@");
10985        assert!(
10986            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10987                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
10988            "got {err:?}"
10989        );
10990    }
10991
10992    #[test]
10993    fn rejects_wit_too_long() {
10994        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
10995        // The legitimate-shape arms all pass (lowercase, single `:`,
10996        // kebab-case identifiers); only the cap arm fires. Surfaces
10997        // the paste-from-binary / accidental-multi-line-blob landing
10998        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10999        // on the peer axis.
11000        let big = format!("wasi:{}", "a".repeat(124));
11001        assert_eq!(big.len(), 129);
11002        let err = contrato_wit_err(&big);
11003        assert!(
11004            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11005                if wit == &big && reason.contains("max length of 128")),
11006            "got {err:?}"
11007        );
11008    }
11009
11010    #[test]
11011    fn wit_max_length_validates() {
11012        // 128-byte WIT reference — exactly the cap. Boundary pin:
11013        // drift in the cap surfaces here and at `rejects_wit_too_long`
11014        // simultaneously, mirroring
11015        // `http_contrato_endpoint_max_length_validates` on the peer
11016        // axis.
11017        let big = format!("wasi:{}", "a".repeat(123));
11018        assert_eq!(big.len(), 128);
11019        let mut s = three_member_spec();
11020        s.contratos.push(WitContract {
11021            de: "payment".into(),
11022            para: "catalog".into(),
11023            wit: big,
11024            endpoint: None,
11025            subject: None,
11026            slot: None,
11027        });
11028        s.validate().unwrap();
11029    }
11030
11031    #[test]
11032    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
11033        // Positive-set sweep through the AplicacaoSpec::validate
11034        // surface (rather than the substrate-side predicate directly)
11035        // — pins every shape the existing test fixtures + the
11036        // checkout-aplicacao example carry, so the gate's accept-set
11037        // matches the substrate's emit-set. Drift between this list
11038        // and `render::tests::wit_world_ref_accepts_canonical_forms`
11039        // surfaces at the substrate layer's positive sweep — one
11040        // source of truth for the rule.
11041        for wit in [
11042            "wasi:http/proxy",
11043            "wasi:keyvalue/store",
11044            "nats:pub-sub",
11045            "kafka:topic",
11046            "custom:exchange",
11047            "pleme:cap/audit",
11048            "wasi:http/proxy@0.2.0",
11049        ] {
11050            // Payload field paired to the dispatched WIT shape so the
11051            // shape-↔-target arm doesn't fire instead of the wit-shape
11052            // arm we're exercising. Routes off the same
11053            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
11054            // `wit_shape_is_store` free functions the production
11055            // `WitContract::is_http` / `is_pubsub` / `is_store`
11056            // methods delegate to (both consult the lifted
11057            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
11058            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
11059            // future prefix addition to the routing accept-set
11060            // reaches this test's payload-dispatch arm by
11061            // construction — no per-test-site drift can hide a
11062            // shape-→-target-slot mismatch that would silently
11063            // demote a canonical `:wit` value to the
11064            // `(None, None, None)` capability-only arm and let the
11065            // `AplicacaoSpec::validate` positive sweep pass on a
11066            // shape it should exercise as HTTP / pub-sub / store.
11067            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
11068                (Some("/x".into()), None, None)
11069            } else if wit_shape_is_pubsub(wit) {
11070                (None, Some("topic.x".into()), None)
11071            } else if wit_shape_is_store(wit) {
11072                (None, None, Some("bucket/$key".into()))
11073            } else {
11074                (None, None, None)
11075            };
11076            let mut s = three_member_spec();
11077            s.contratos.push(WitContract {
11078                de: "payment".into(),
11079                para: "catalog".into(),
11080                wit: wit.into(),
11081                endpoint,
11082                subject,
11083                slot,
11084            });
11085            s.validate()
11086                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
11087        }
11088    }
11089
11090    #[test]
11091    fn wit_shape_predicates_accept_canonical_prefix_set() {
11092        // Positive-set sweep pinning every prefix in
11093        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
11094        // WIT_STORE_SHAPE_PREFIXES against the three free-function
11095        // dispatch predicates. The six prefixes are the load-bearing
11096        // routing keys the substrate's WIT-shape dispatch consults
11097        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
11098        // key/value-store-slot admission); any drift between the
11099        // free-function accept-set and this list surfaces here
11100        // rather than at apply time as a silent
11101        // shape-→-capability-only demotion.
11102        assert!(wit_shape_is_http("wasi:http/proxy"));
11103        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
11104        assert!(wit_shape_is_http("http:incoming"));
11105
11106        assert!(wit_shape_is_pubsub("nats:pub-sub"));
11107        assert!(wit_shape_is_pubsub("kafka:topic"));
11108
11109        assert!(wit_shape_is_store("wasi:keyvalue/store"));
11110        assert!(wit_shape_is_store("kv:cache/session"));
11111    }
11112
11113    #[test]
11114    fn wit_shape_predicates_reject_uncanonical_forms() {
11115        // Negative-set pin: the six canonical prefixes are
11116        // lowercase-only (mirrors the `is_wit_world_ref` substrate
11117        // predicate's lowercase invariant — see its docstring on the
11118        // "I thought I had L7 HTTP routing, got L4-only" footgun).
11119        // The empty string, an uppercase-prefixed form, a hyphen-
11120        // instead-of-colon typo, and a bare kebab identifier all miss
11121        // every shape arm — reachable-by-construction only via the
11122        // `is_wit_world_ref` gate that admission-checks the `:wit`
11123        // value first, but pinned here so any future
11124        // free-function change (e.g. a case-insensitive
11125        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
11126        // this unit level.
11127        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
11128            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
11129            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
11130            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
11131        }
11132    }
11133
11134    #[test]
11135    fn wit_shape_predicates_partition_canonical_set() {
11136        // Every canonical prefix routes to exactly one shape arm —
11137        // the three prefix sets are pairwise disjoint. Pins the
11138        // routing property [`WitContract::target`] relies on: an
11139        // `is_http()` return of `true` guarantees `is_pubsub()` and
11140        // `is_store()` return `false`, so the shape-→-target-slot
11141        // dispatch (endpoint vs subject vs slot) is unambiguous.
11142        // Drift (e.g. a future `"kv:"` moved into the HTTP set
11143        // without removal from the store set) would silently route
11144        // one prefix to two arms and the first-matching-arm order
11145        // becomes load-bearing — this pin surfaces it as a build
11146        // error instead.
11147        for prefix in WIT_HTTP_SHAPE_PREFIXES {
11148            let sample = format!("{prefix}x");
11149            assert!(wit_shape_is_http(&sample));
11150            assert!(!wit_shape_is_pubsub(&sample));
11151            assert!(!wit_shape_is_store(&sample));
11152        }
11153        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
11154            let sample = format!("{prefix}x");
11155            assert!(!wit_shape_is_http(&sample));
11156            assert!(wit_shape_is_pubsub(&sample));
11157            assert!(!wit_shape_is_store(&sample));
11158        }
11159        for prefix in WIT_STORE_SHAPE_PREFIXES {
11160            let sample = format!("{prefix}x");
11161            assert!(!wit_shape_is_http(&sample));
11162            assert!(!wit_shape_is_pubsub(&sample));
11163            assert!(wit_shape_is_store(&sample));
11164        }
11165    }
11166
11167    #[test]
11168    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
11169        // Positive pin: [`wit_shape_matches`] is exactly the
11170        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
11171        // parameterized on the accept-set. Two-prefix accept-set,
11172        // one-prefix accept-set, and empty accept-set (which must
11173        // reject everything, including the empty string — an empty
11174        // `any()` fold returns `false`) all pinned so a future
11175        // reimplementation that swaps `starts_with` for `contains`,
11176        // `==`, or a case-folded comparator surfaces at unit-test
11177        // time.
11178        let two = &["wasi:http/", "http:"];
11179        assert!(wit_shape_matches("wasi:http/proxy", two));
11180        assert!(wit_shape_matches("http:incoming", two));
11181        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
11182
11183        let one = &["nats:"];
11184        assert!(wit_shape_matches("nats:pub-sub", one));
11185        assert!(!wit_shape_matches("kafka:topic", one));
11186
11187        // Empty accept-set matches nothing — the identity element
11188        // for the disjunctive `any()` fold across the prefix set.
11189        // Reachable via a future `wit_shape_is_<name>` const paired
11190        // to a still-empty prefix table on a nascent shape-arm draft.
11191        let empty: &[&str] = &[];
11192        assert!(!wit_shape_matches("wasi:http/proxy", empty));
11193        assert!(!wit_shape_matches("", empty));
11194
11195        // starts_with, not contains: a prefix embedded mid-string
11196        // never matches. Pins the routing invariant [`WitContract::target`]
11197        // relies on (an authored `:wit "custom:wasi:http/"` string
11198        // does not silently route through the HTTP arm just because
11199        // it happens to contain the canonical HTTP prefix).
11200        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
11201    }
11202
11203    #[test]
11204    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
11205        // Equivalence pin: each per-shape predicate is exactly
11206        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
11207        // every canonical prefix + the empty string + one negative
11208        // sample against every peer so a future predicate that grew
11209        // its own inline `iter().any(starts_with)` (rather than
11210        // delegating through the lifted combinator) drifts loudly here
11211        // — the peer-const table's contents must agree with the
11212        // predicate's accept-set by construction.
11213        let samples = [
11214            String::new(),
11215            "wasi:http/proxy".to_string(),
11216            "http:incoming".to_string(),
11217            "nats:pub-sub".to_string(),
11218            "kafka:topic".to_string(),
11219            "wasi:keyvalue/store".to_string(),
11220            "kv:cache/session".to_string(),
11221            "custom-shape".to_string(),
11222            "WASI:HTTP/proxy".to_string(),
11223        ];
11224        for wit in &samples {
11225            assert_eq!(
11226                wit_shape_is_http(wit),
11227                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11228                "wit_shape_is_http drifted from combinator on {wit:?}",
11229            );
11230            assert_eq!(
11231                wit_shape_is_pubsub(wit),
11232                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
11233                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
11234            );
11235            assert_eq!(
11236                wit_shape_is_store(wit),
11237                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
11238                "wit_shape_is_store drifted from combinator on {wit:?}",
11239            );
11240        }
11241    }
11242
11243    #[test]
11244    fn wit_contract_shape_methods_delegate_to_free_functions() {
11245        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
11246        // `is_store` are `&self` conveniences on top of the free
11247        // functions — for every canonical prefix the method's return
11248        // matches its free-function peer. Sweeps the union of the
11249        // three prefix sets so a future method that grew its own
11250        // inline prefix logic (rather than delegating) drifts loudly
11251        // here on the first prefix the free function accepts and the
11252        // method doesn't.
11253        for shape_set in [
11254            WIT_HTTP_SHAPE_PREFIXES,
11255            WIT_PUBSUB_SHAPE_PREFIXES,
11256            WIT_STORE_SHAPE_PREFIXES,
11257        ] {
11258            for prefix in shape_set {
11259                let c = WitContract {
11260                    de: "cart".into(),
11261                    para: "catalog".into(),
11262                    wit: format!("{prefix}x"),
11263                    endpoint: None,
11264                    subject: None,
11265                    slot: None,
11266                };
11267                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
11268                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
11269                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
11270                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11271            }
11272        }
11273        // Capability-arm delegation sweep: two representative
11274        // Capability-shaped `:wit` values (a bare non-prefix-matching
11275        // WIT world, the deliberately-shaped empty string
11276        // [`WitContract::is_capability`]'s docstring calls out as
11277        // syntactically Capability). Extends the free-function
11278        // delegation pin onto the fourth arm so a future
11279        // [`WitContract::is_capability`] rewrite that grew an inline
11280        // prefix-set scan (rather than delegating through
11281        // [`wit_shape_is_capability`]) drifts loudly here on the first
11282        // Capability-shaped sample.
11283        for wit in ["custom:capability-only", ""] {
11284            let c = WitContract {
11285                de: "cart".into(),
11286                para: "catalog".into(),
11287                wit: wit.into(),
11288                endpoint: None,
11289                subject: None,
11290                slot: None,
11291            };
11292            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11293        }
11294    }
11295
11296    #[test]
11297    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
11298        // 4-way partition-witness pin on the raw `&str` axis: for every
11299        // canonical prefix in the three payload-arm accept-sets,
11300        // exactly one of the four [`wit_shape_is_http`] /
11301        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11302        // [`wit_shape_is_capability`] free functions returns `true` and
11303        // the other three return `false` — the four-arm partition
11304        // witness that locks the free-function WIT-shape-classifier
11305        // family into a partition of the `:contratos :wit` axis
11306        // load-bearing. Peer of the sibling [`WitContract`]-surface
11307        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
11308        // partition pin — extends the discipline onto the raw `&str`
11309        // axis so any future arm addition (a hypothetical
11310        // `wasi:sockets/*` transport-layer shape, an `oci:*`
11311        // capability-import carrier per the sibling
11312        // [`wit_shape_matches`] docstring's trajectory bullet) that
11313        // landed on one of the payload-arm free functions without
11314        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
11315        // here as two arms returning `true` simultaneously at
11316        // caixa-core build time rather than a silent per-consumer
11317        // misclassification at renderer emit time.
11318        for shape_set in [
11319            WIT_HTTP_SHAPE_PREFIXES,
11320            WIT_PUBSUB_SHAPE_PREFIXES,
11321            WIT_STORE_SHAPE_PREFIXES,
11322        ] {
11323            for prefix in shape_set {
11324                let wit = format!("{prefix}x");
11325                let hits = [
11326                    wit_shape_is_http(&wit),
11327                    wit_shape_is_pubsub(&wit),
11328                    wit_shape_is_store(&wit),
11329                    wit_shape_is_capability(&wit),
11330                ]
11331                .iter()
11332                .filter(|&&b| b)
11333                .count();
11334                assert_eq!(
11335                    hits,
11336                    1,
11337                    "raw-&str WIT-shape 4-way predicate partition must \
11338                     admit exactly one arm per canonical prefix; got {hits} \
11339                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
11340                     is_capability={})",
11341                    wit_shape_is_http(&wit),
11342                    wit_shape_is_pubsub(&wit),
11343                    wit_shape_is_store(&wit),
11344                    wit_shape_is_capability(&wit),
11345                );
11346            }
11347        }
11348        // Capability-arm sweep on the raw `&str` axis: two
11349        // representative Capability-shaped `:wit` values (a bare non-
11350        // prefix-matching WIT world, the deliberately-shaped empty
11351        // string the pure classifier still admits per
11352        // [`wit_shape_is_capability`]'s docstring). Both must land on
11353        // the fourth arm exclusively so the partition witness holds
11354        // across the full 4-arm closure on the raw `&str` axis.
11355        for wit in ["custom:capability-only", ""] {
11356            let hits = [
11357                wit_shape_is_http(wit),
11358                wit_shape_is_pubsub(wit),
11359                wit_shape_is_store(wit),
11360                wit_shape_is_capability(wit),
11361            ]
11362            .iter()
11363            .filter(|&&b| b)
11364            .count();
11365            assert_eq!(
11366                hits, 1,
11367                "raw-&str WIT-shape 4-way predicate partition must \
11368                 admit exactly one arm on Capability-shaped wit={wit:?}"
11369            );
11370            assert!(
11371                wit_shape_is_capability(wit),
11372                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
11373            );
11374        }
11375    }
11376
11377    #[test]
11378    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
11379        // Composition-witness pin: [`wit_shape_is_capability`] is the
11380        // exact-inverse disjunction of the sibling payload-arm free-
11381        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
11382        // / [`wit_shape_is_store`]. A future reimplementation that
11383        // grew its own prefix-set scan (e.g. inlining a fourth
11384        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
11385        // not own today) rather than delegating to the sibling trio
11386        // would drift loudly here — the composition contract binds the
11387        // fourth-arm free-function predicate to the exact-inverse of
11388        // the three payload-arm free-function predicates, so any
11389        // rebrand of any prefix-set const flows through
11390        // [`wit_shape_is_capability`] by construction without a
11391        // coordinated per-consumer rewrite. Peer of the sibling
11392        // [`WitContract`]-surface
11393        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
11394        // composition pin — extends the discipline onto the raw
11395        // `&str` axis.
11396        let mut cases: Vec<String> = Vec::new();
11397        for shape_set in [
11398            WIT_HTTP_SHAPE_PREFIXES,
11399            WIT_PUBSUB_SHAPE_PREFIXES,
11400            WIT_STORE_SHAPE_PREFIXES,
11401        ] {
11402            for prefix in shape_set {
11403                cases.push(format!("{prefix}x"));
11404            }
11405        }
11406        cases.push("custom:capability-only".to_string());
11407        cases.push(String::new());
11408        for wit in cases {
11409            assert_eq!(
11410                wit_shape_is_capability(&wit),
11411                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
11412                "wit_shape_is_capability must equal \
11413                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
11414                 at wit={wit:?}"
11415            );
11416        }
11417    }
11418
11419    #[test]
11420    fn wit_shape_classifier_family_is_const_fn() {
11421        // Fail-before-pass-after pin on the 4-arm free-function WIT-
11422        // shape classifier family's `const`-eval posture. Each of the
11423        // four peer classifiers ([`wit_shape_is_http`] /
11424        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11425        // [`wit_shape_is_capability`]) and the underlying combinator
11426        // [`wit_shape_matches`] must be `pub const fn` — any future
11427        // accidental downgrade to non-`const` fails the `const fn`
11428        // wrappers below at caixa-core build time with E0015
11429        // (`cannot call non-const function`), strictly stronger than
11430        // a runtime `assert!` and strictly stronger than the module-
11431        // scope `const _: () = assert!(…)` pins immediately after the
11432        // classifier declarations (those anchor specific accept-set
11433        // truth-table entries; this pin anchors the `const` posture
11434        // itself via `const fn` wrappers that are only well-formed
11435        // when the callee is itself `const fn`).
11436        //
11437        // Verified fail-before-pass-after by locally reverting
11438        // `pub const fn` → `pub fn` on each classifier and observing
11439        // E0015 at every corresponding wrapper call site (build
11440        // error, no test-time surface), then restoring `pub const fn`
11441        // and observing the pin pass at test time. Peer of the
11442        // sibling M3
11443        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11444        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11445        // M2
11446        // [`child_spec_restart_accessor_is_const_fn`] /
11447        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11448        // and M3
11449        // [`placement_estrategia_accessor_is_const_fn`] /
11450        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11451        // sibling `const`-eval-surface-pass axes.
11452        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
11453            wit_shape_matches(wit, prefixes)
11454        }
11455        const fn http_via_const_fn(wit: &str) -> bool {
11456            wit_shape_is_http(wit)
11457        }
11458        const fn pubsub_via_const_fn(wit: &str) -> bool {
11459            wit_shape_is_pubsub(wit)
11460        }
11461        const fn store_via_const_fn(wit: &str) -> bool {
11462            wit_shape_is_store(wit)
11463        }
11464        const fn capability_via_const_fn(wit: &str) -> bool {
11465            wit_shape_is_capability(wit)
11466        }
11467        // Sweep one canonical accept-set sample per arm plus the
11468        // payload-less/empty capability samples, asserting the
11469        // wrapper and direct dispatches agree byte-for-byte across
11470        // the closed 4-arm partition.
11471        let cases: [(&str, bool, bool, bool, bool); 6] = [
11472            ("wasi:http/proxy", true, false, false, false),
11473            ("http:incoming", true, false, false, false),
11474            ("nats:events", false, true, false, false),
11475            ("kafka:topic", false, true, false, false),
11476            ("wasi:keyvalue/store", false, false, true, false),
11477            ("kv:cache", false, false, true, false),
11478        ];
11479        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
11480            assert_eq!(
11481                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
11482                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11483                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
11484            );
11485            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
11486            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
11487            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
11488            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11489            assert_eq!(wit_shape_is_http(wit), is_http);
11490            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
11491            assert_eq!(wit_shape_is_store(wit), is_store);
11492        }
11493        // Payload-less capability arm (the 4th partition arm).
11494        let capability_samples: [&str; 3] =
11495            ["wasi:filesystem/preopens", "custom:capability-only", ""];
11496        for wit in capability_samples {
11497            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11498            assert!(wit_shape_is_capability(wit));
11499            assert!(!wit_shape_is_http(wit));
11500            assert!(!wit_shape_is_pubsub(wit));
11501            assert!(!wit_shape_is_store(wit));
11502        }
11503    }
11504
11505    #[test]
11506    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
11507        // Composition-witness pin: [`wit_shape_matches`] agrees with
11508        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
11509        // dispatch (the prior non-`const` implementation) across
11510        // boundary lengths — empty `wit`, empty prefix, one-byte
11511        // slack, prefix longer than `wit`, one-byte trailing slack.
11512        // The rewrite to a byte-level manual starts_with loop (the
11513        // enabler for the `pub const fn` posture) must not change any
11514        // truth-table entry on the canonical accept-set — this pin
11515        // sweeps a targeted boundary corpus and asserts byte-for-byte
11516        // agreement, locking the const-fn rewrite's semantics against
11517        // the prior iterator body by construction.
11518        let prefixes = &["wasi:http/", "http:"][..];
11519        let cases: [(&str, bool); 12] = [
11520            ("wasi:http/proxy", true),
11521            ("wasi:http/", true), // exact-length match on prefix
11522            ("wasi:http", false), // one byte short
11523            ("http:", true),
11524            ("http:incoming", true),
11525            ("http", false), // one byte short
11526            ("", false),
11527            ("wasi:https/proxy", false),
11528            ("nats:events", false),
11529            ("HTTPS:", false), // uppercase — no case-fold in classifier
11530            ("wasi:HTTP/proxy", false),
11531            ("wasi:http", false),
11532        ];
11533        for (wit, expected) in cases {
11534            assert_eq!(
11535                wit_shape_matches(wit, prefixes),
11536                expected,
11537                "wit_shape_matches disagrees with reference at wit={wit:?}",
11538            );
11539            // Byte-equal to the iterator body it replaced.
11540            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
11541            assert_eq!(
11542                wit_shape_matches(wit, prefixes),
11543                via_iter,
11544                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
11545            );
11546        }
11547        // Empty prefix set → always false regardless of `wit`.
11548        let empty: &[&str] = &[];
11549        assert!(!wit_shape_matches("", empty));
11550        assert!(!wit_shape_matches("wasi:http/proxy", empty));
11551        // Empty prefix inside a non-empty set → always true (every
11552        // string starts with the empty string, matching the
11553        // iterator body's semantics on `str::starts_with("")`).
11554        let contains_empty: &[&str] = &["nats:", ""];
11555        assert!(wit_shape_matches("", contains_empty));
11556        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
11557    }
11558
11559    #[test]
11560    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
11561        // 4-way partition-witness pin: for every canonical prefix in
11562        // the payload-arm accept-sets, exactly one of the four
11563        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11564        // [`WitContract::is_store`] / [`WitContract::is_capability`]
11565        // predicates returns `true` and the other three return `false`
11566        // — the four-arm partition witness that locks the substrate's
11567        // WIT-shape-space closure on the pre-projection axis load-
11568        // bearing. A future arm addition (a hypothetical fourth
11569        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
11570        // shape) that landed on one of the payload-arm predicates
11571        // without shrinking [`WitContract::is_capability`]'s accept-set
11572        // would surface here as two arms returning `true` simultaneously
11573        // — a partition-witness break the pin catches at caixa-core
11574        // build time rather than a silent per-consumer misclassification
11575        // at renderer emit time. Peer of the sibling `WitTarget`-side
11576        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
11577        // partition-witness pin on the post-projection payload-scalar
11578        // arm-set — extends the discipline onto the pre-projection
11579        // 4-arm shape-space.
11580        for shape_set in [
11581            WIT_HTTP_SHAPE_PREFIXES,
11582            WIT_PUBSUB_SHAPE_PREFIXES,
11583            WIT_STORE_SHAPE_PREFIXES,
11584        ] {
11585            for prefix in shape_set {
11586                let c = WitContract {
11587                    de: "cart".into(),
11588                    para: "catalog".into(),
11589                    wit: format!("{prefix}x"),
11590                    endpoint: None,
11591                    subject: None,
11592                    slot: None,
11593                };
11594                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11595                    .iter()
11596                    .filter(|&&b| b)
11597                    .count();
11598                assert_eq!(
11599                    hits,
11600                    1,
11601                    "WitContract WIT-shape 4-way predicate partition must \
11602                     admit exactly one arm per canonical prefix; got {hits} \
11603                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
11604                     is_capability={})",
11605                    c.wit,
11606                    c.is_http(),
11607                    c.is_pubsub(),
11608                    c.is_store(),
11609                    c.is_capability(),
11610                );
11611            }
11612        }
11613        // Capability-arm sweep: two representative capability shapes
11614        // (a bare WIT world outside the three payload-arm prefix sets,
11615        // and the deliberately-shaped empty string that
11616        // [`crate::render::is_wit_world_ref`] rejects at
11617        // [`WitContract::target`] time but which the pure classifier
11618        // still admits — see the method docstring's "purely syntactic
11619        // classification" note). Both must land on the fourth arm
11620        // exclusively, so the partition witness holds across the full
11621        // 4-arm closure.
11622        for wit in ["custom:capability-only", ""] {
11623            let c = WitContract {
11624                de: "cart".into(),
11625                para: "catalog".into(),
11626                wit: wit.into(),
11627                endpoint: None,
11628                subject: None,
11629                slot: None,
11630            };
11631            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11632                .iter()
11633                .filter(|&&b| b)
11634                .count();
11635            assert_eq!(
11636                hits, 1,
11637                "WitContract WIT-shape 4-way predicate partition must \
11638                 admit exactly one arm on Capability-shaped wit={wit:?}"
11639            );
11640            assert!(
11641                c.is_capability(),
11642                "wit={wit:?} must project onto the Capability arm"
11643            );
11644        }
11645    }
11646
11647    #[test]
11648    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
11649        // Composition-witness pin: [`WitContract::is_capability`] is the
11650        // exact-inverse disjunction of the sibling payload-arm predicate
11651        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11652        // [`WitContract::is_store`]. A future reimplementation that
11653        // grew its own prefix-set scan (e.g. inlining a fourth
11654        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
11655        // own today) rather than delegating to the sibling trio would
11656        // drift loudly here — the composition contract binds the
11657        // fourth-arm predicate to the exact-inverse of the three
11658        // payload-arm predicates, so any rebrand of any prefix-set const
11659        // flows through this method by construction without a
11660        // coordinated per-consumer rewrite. Sweeps the union of the
11661        // three payload-arm prefix sets plus two Capability-shaped
11662        // shapes (a bare non-prefix-matching WIT world, the deliberately-
11663        // empty string the pure classifier still admits per the method
11664        // docstring's "purely syntactic classification" note).
11665        let mut cases: Vec<String> = Vec::new();
11666        for shape_set in [
11667            WIT_HTTP_SHAPE_PREFIXES,
11668            WIT_PUBSUB_SHAPE_PREFIXES,
11669            WIT_STORE_SHAPE_PREFIXES,
11670        ] {
11671            for prefix in shape_set {
11672                cases.push(format!("{prefix}x"));
11673            }
11674        }
11675        cases.push("custom:capability-only".to_string());
11676        cases.push(String::new());
11677        for wit in cases {
11678            let c = WitContract {
11679                de: "cart".into(),
11680                para: "catalog".into(),
11681                wit: wit.clone(),
11682                endpoint: None,
11683                subject: None,
11684                slot: None,
11685            };
11686            assert_eq!(
11687                c.is_capability(),
11688                !c.is_http() && !c.is_pubsub() && !c.is_store(),
11689                "WitContract::is_capability must equal \
11690                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
11691            );
11692        }
11693    }
11694
11695    #[test]
11696    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
11697        // Cross-projection-witness pin: whenever [`WitContract::target`]
11698        // succeeds, the pre-projection [`WitContract::is_capability`]
11699        // classification agrees with the post-projection
11700        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
11701        // predicate — the 4-arm typed partition on the substrate's
11702        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
11703        // partition on the pre-projection axis line up by construction.
11704        // A future divergence between the two axes (a peer
11705        // [`WitTarget`] variant addition that landed on the typed-view
11706        // surface without a peer prefix-set + [`WitContract`] predicate
11707        // extension, or vice versa) would surface here at caixa-core
11708        // build time rather than a silent per-consumer split at renderer
11709        // emit time. Peer of the sibling pre-/post-projection
11710        // agreement pins the payload-carrier trio
11711        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
11712        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
11713        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
11714        // post-projection — b11bb49 trio lift) already carry across the
11715        // three payload arms — this pin closes the pair on the fourth
11716        // payload-less arm.
11717        let http = WitContract {
11718            de: "cart".into(),
11719            para: "catalog".into(),
11720            wit: "wasi:http/proxy".into(),
11721            endpoint: Some("/x".into()),
11722            subject: None,
11723            slot: None,
11724        };
11725        assert!(!http.is_capability());
11726        assert!(!http.target().unwrap().is_capability());
11727
11728        let nats = WitContract {
11729            de: "cart".into(),
11730            para: "catalog".into(),
11731            wit: "nats:pub-sub".into(),
11732            endpoint: None,
11733            subject: Some("events.x".into()),
11734            slot: None,
11735        };
11736        assert!(!nats.is_capability());
11737        assert!(!nats.target().unwrap().is_capability());
11738
11739        let kv = WitContract {
11740            de: "cart".into(),
11741            para: "catalog".into(),
11742            wit: "wasi:keyvalue/store".into(),
11743            endpoint: None,
11744            subject: None,
11745            slot: Some("checkout/$orderId".into()),
11746        };
11747        assert!(!kv.is_capability());
11748        assert!(!kv.target().unwrap().is_capability());
11749
11750        let cap = WitContract {
11751            de: "cart".into(),
11752            para: "catalog".into(),
11753            wit: "custom:capability-only".into(),
11754            endpoint: None,
11755            subject: None,
11756            slot: None,
11757        };
11758        assert!(cap.is_capability());
11759        assert!(cap.target().unwrap().is_capability());
11760    }
11761
11762    #[test]
11763    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
11764        // Fail-before-pass-after pin on the [`WitContract`] pre-
11765        // projection accessor family's `const`-eval-surface posture.
11766        // Each of the three per-`:contratos` byte-string scalar
11767        // accessors ([`WitContract::source`] / [`WitContract::destination`]
11768        // / [`WitContract::world_ref`], each projecting through
11769        // `String::as_str` — const-stable since Rust 1.87, well within
11770        // the workspace MSRV) and each of the four peer WIT-shape
11771        // predicates ([`WitContract::is_http`] /
11772        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
11773        // [`WitContract::is_capability`], each composing
11774        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
11775        // free-function classifier family the sibling
11776        // [`wit_shape_classifier_family_is_const_fn`] pin already
11777        // anchors on the raw `&str → bool` axis) must be `pub const fn`
11778        // — any future accidental downgrade to non-`const` fails the
11779        // `const fn` wrappers below at caixa-core build time with E0015
11780        // (`cannot call non-const function`), strictly stronger than a
11781        // runtime `assert!` and strictly stronger than a
11782        // module-scope `const _: () = assert!(…)` pin (which cannot be
11783        // formed on a `&WitContract` fixture because the type's
11784        // `String` / `Option<String>` carriers rule out `const`-context
11785        // construction; the `const fn` wrapper is the load-bearing
11786        // shape that side-steps the destructor-in-const restriction on
11787        // the value axis while still pinning the `const`-fn posture on
11788        // the callee).
11789        //
11790        // Peer of the sibling free-function classifier pin
11791        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
11792        // raw `&str → bool` axis — this pin extends the same
11793        // `const`-eval-surface discipline onto the peer method surface
11794        // that composes through those free-function classifiers, and
11795        // simultaneously onto the underlying per-`:contratos`
11796        // byte-string scalar-accessor trio each predicate reads
11797        // through. Sibling of the peer M3
11798        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11799        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11800        // M2
11801        // [`child_spec_restart_accessor_is_const_fn`] /
11802        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11803        // and M3
11804        // [`placement_estrategia_accessor_is_const_fn`] /
11805        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11806        // sibling `const`-eval-surface-pass axes.
11807        const fn source_via_const_fn(c: &WitContract) -> &str {
11808            c.source()
11809        }
11810        const fn destination_via_const_fn(c: &WitContract) -> &str {
11811            c.destination()
11812        }
11813        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
11814            c.world_ref()
11815        }
11816        const fn is_http_via_const_fn(c: &WitContract) -> bool {
11817            c.is_http()
11818        }
11819        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
11820            c.is_pubsub()
11821        }
11822        const fn is_store_via_const_fn(c: &WitContract) -> bool {
11823            c.is_store()
11824        }
11825        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
11826            c.is_capability()
11827        }
11828        // Sweep one canonical accept-set sample per WIT-shape arm plus
11829        // a payload-less capability sample, asserting the wrapper and
11830        // direct dispatches agree byte-for-byte across the closed
11831        // 4-arm partition on both the scalar-accessor trio and the
11832        // WIT-shape-predicate family.
11833        for (wit, is_http, is_pubsub, is_store, is_capability) in [
11834            ("wasi:http/proxy", true, false, false, false),
11835            ("http:incoming", true, false, false, false),
11836            ("nats:events", false, true, false, false),
11837            ("kafka:topic", false, true, false, false),
11838            ("wasi:keyvalue/store", false, false, true, false),
11839            ("kv:cache", false, false, true, false),
11840            ("custom:capability-only", false, false, false, true),
11841            ("", false, false, false, true),
11842        ] {
11843            let c = WitContract {
11844                de: "cart".into(),
11845                para: "catalog".into(),
11846                wit: wit.into(),
11847                endpoint: None,
11848                subject: None,
11849                slot: None,
11850            };
11851            assert_eq!(source_via_const_fn(&c), c.source());
11852            assert_eq!(destination_via_const_fn(&c), c.destination());
11853            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
11854            assert_eq!(is_http_via_const_fn(&c), c.is_http());
11855            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
11856            assert_eq!(is_store_via_const_fn(&c), c.is_store());
11857            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
11858            assert_eq!(c.source(), "cart");
11859            assert_eq!(c.destination(), "catalog");
11860            assert_eq!(c.world_ref(), wit);
11861            assert_eq!(c.is_http(), is_http);
11862            assert_eq!(c.is_pubsub(), is_pubsub);
11863            assert_eq!(c.is_store(), is_store);
11864            assert_eq!(c.is_capability(), is_capability);
11865        }
11866    }
11867
11868    #[test]
11869    fn wit_contract_identity_projection_accessor_is_const_fn() {
11870        // Fail-before-pass-after pin on the [`WitContract::identity`]
11871        // six-arm composite-projection accessor's `const`-eval-surface
11872        // posture. The accessor projects the typed edge's six identity
11873        // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
11874        // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
11875        // every callee is itself `pub const fn` ([`WitContract::source`]
11876        // / [`WitContract::destination`] / [`WitContract::world_ref`]
11877        // through `String::as_str`, const-stable since Rust 1.87;
11878        // [`WitContract::endpoint`] / [`WitContract::subject`] /
11879        // [`WitContract::slot`] through the sibling `match &self
11880        // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
11881        // 0650f64 closed the const-eval surface on) and the tuple
11882        // constructor from borrowed-reference / `Option`-of-borrowed-
11883        // reference arms is trivially const. Any future accidental
11884        // downgrade fails the `identity_via_const_fn` wrapper at
11885        // caixa-core build time with E0015 (`cannot call non-const
11886        // method`), strictly stronger than a runtime `assert!` and
11887        // strictly stronger than a module-scope `const _: () =
11888        // assert!(…)` pin (which cannot be formed on a `&WitContract`
11889        // fixture because the type's `String` / `Option<String>`
11890        // carriers rule out `const`-context value construction; the
11891        // `const fn` wrapper is the load-bearing shape that side-steps
11892        // the destructor-in-const restriction on the value axis while
11893        // still pinning the `const`-fn posture on the callee — mirror
11894        // of the sibling
11895        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
11896        // pin's discipline verbatim on the peer scalar-accessor
11897        // surface).
11898        //
11899        // Peer of the sibling
11900        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
11901        // (279823b) pin on the six per-`:contratos` scalar-accessor
11902        // callees this composite-projection reads through — where that
11903        // pin anchors the const-eval surface at the six individual
11904        // scalar-accessor arms, this pin extends the same posture onto
11905        // the composite six-tuple projection every consumer that dedups
11906        // typed edges on the [`ContratoIdentity`] axis keys off (the
11907        // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
11908        // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
11909        // materializer's per-edge identity-based admission webhook; a
11910        // future L7 policy-emitter that shards CNPs by identity-tuple
11911        // rather than by name). Same fail-before-pass-after wrapper
11912        // discipline as the peer M2 / M3 accessor-family pins on the
11913        // sibling `const`-eval-surface passes.
11914        const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
11915            c.identity()
11916        }
11917        // Sweep one canonical WIT-shape sample per payload-carrier arm
11918        // plus a payload-less capability sample so the pin exercises
11919        // both `Some(_)`-carrying and `None`-carrying arms on all three
11920        // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
11921        // / `:slot`) — every wrapper dispatch must agree byte-for-byte
11922        // with the direct method call on every arm of the closed WIT-
11923        // shape partition.
11924        for (wit, endpoint, subject, slot) in [
11925            ("wasi:http/proxy", Some("/checkout"), None, None),
11926            ("http:incoming", Some("/api"), None, None),
11927            ("nats:events", None, Some("orders.placed"), None),
11928            ("kafka:topic", None, Some("orders.stream"), None),
11929            ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
11930            ("kv:cache", None, None, Some("session/{token}")),
11931            ("custom:capability-only", None, None, None),
11932        ] {
11933            let c = WitContract {
11934                de: "cart".into(),
11935                para: "catalog".into(),
11936                wit: wit.into(),
11937                endpoint: endpoint.map(str::to_string),
11938                subject: subject.map(str::to_string),
11939                slot: slot.map(str::to_string),
11940            };
11941            assert_eq!(identity_via_const_fn(&c), c.identity());
11942            assert_eq!(
11943                c.identity(),
11944                ("cart", "catalog", wit, endpoint, subject, slot,),
11945            );
11946        }
11947    }
11948
11949    #[test]
11950    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
11951        // Fail-before-pass-after pin on the four M3 mesh-slot
11952        // `String → &str` scalar accessors ([`Membro::nome`] /
11953        // [`Membro::versao_requirement`] on the per-`:membros` axis,
11954        // [`Entrada::hostname`] / [`Entrada::destination`] on the
11955        // per-`:entrada` axis) — each projects the typed slot's
11956        // [`String`] storage through the `pub const fn`
11957        // [`String::as_str`] (const-stable since Rust 1.87, well
11958        // within the workspace MSRV) and any future accidental
11959        // downgrade to non-`const` fails the corresponding
11960        // `<name>_via_const_fn` wrapper at caixa-core build time with
11961        // E0015 (`cannot call non-const method`), strictly stronger
11962        // than a runtime `assert!` and strictly stronger than a
11963        // module-scope `const _: () = assert!(…)` pin (which cannot
11964        // be formed on `&Membro` / `&Entrada` fixtures because the
11965        // types' `String` carriers rule out `const`-context value
11966        // construction; the `const fn` wrapper is the load-bearing
11967        // shape that side-steps the destructor-in-const restriction
11968        // on the value axis while still pinning the `const`-fn
11969        // posture on the callee — mirror of the sibling
11970        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
11971        // (279823b) pin on the per-`:contratos` axis). Peer of the
11972        // sibling per-M2/M3/universal-axis `String → &str` accessor
11973        // family pins on the sibling `const`-eval-surface passes
11974        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
11975        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
11976        // typed-newtype wrapper,
11977        // [`crate::supervisor::ChildSpec::nome`] /
11978        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
11979        // M2 supervisor-tree axis,
11980        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
11981        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
11982        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
11983        // axis, and the sibling per-`:contratos`
11984        // [`WitContract::source`] / [`WitContract::destination`] /
11985        // [`WitContract::world_ref`] trio at 279823b).
11986        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
11987            m.nome()
11988        }
11989        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
11990            m.versao_requirement()
11991        }
11992        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
11993            e.hostname()
11994        }
11995        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
11996            e.destination()
11997        }
11998        for (caixa, versao) in [
11999            ("cart", "^0.1"),
12000            ("catalog-v2", "~0.2.3"),
12001            ("checkout", "*"),
12002        ] {
12003            let m = Membro {
12004                caixa: caixa.into(),
12005                versao: versao.into(),
12006            };
12007            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
12008            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
12009            assert_eq!(m.nome(), caixa);
12010            assert_eq!(m.versao_requirement(), versao);
12011        }
12012        for (host, para) in [
12013            ("cart.example.com", "cart"),
12014            ("api.checkout.io", "checkout"),
12015        ] {
12016            let e = Entrada {
12017                host: host.into(),
12018                para: para.into(),
12019                paths: vec![],
12020                port: DEFAULT_SERVICO_PORT,
12021            };
12022            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
12023            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
12024            assert_eq!(e.hostname(), host);
12025            assert_eq!(e.destination(), para);
12026        }
12027    }
12028
12029    #[test]
12030    fn m3_option_string_scalar_accessor_family_is_const_fn() {
12031        // Fail-before-pass-after pin on the five M3 mesh-slot
12032        // `Option<String> → Option<&str>` scalar accessors
12033        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
12034        // [`WitContract::slot`] on the per-`:contratos` HTTP /
12035        // pub-sub / key-value payload-carrier trio,
12036        // [`Placement::shard_key`] / [`Placement::affinity`] on the
12037        // per-`:placement` Akka-sharding-key + Adaptive-compression-
12038        // hint pair). Each accessor destructures the typed slot's
12039        // `Option<String>` storage through the `match &self.<field> {
12040        // Some(s) => Some(s.as_str()), None => None }` shape —
12041        // routing through [`String::as_str`] (const-stable since Rust
12042        // 1.87, well within the workspace MSRV) rather than the
12043        // non-const [`Option::as_deref`] the pre-lift bodies carried
12044        // — and any future accidental downgrade to non-`const` fails
12045        // the corresponding `<name>_via_const_fn` wrapper at
12046        // caixa-core build time with E0015 (`cannot call non-const
12047        // method`), strictly stronger than a runtime `assert!` and
12048        // strictly stronger than a module-scope `const _: () =
12049        // assert!(…)` pin (which cannot be formed on `&WitContract`
12050        // / `&Placement` fixtures because the types' `String` /
12051        // `Option<String>` carriers rule out `const`-context value
12052        // construction; the `const fn` wrapper is the load-bearing
12053        // shape that side-steps the destructor-in-const restriction
12054        // on the value axis while still pinning the `const`-fn
12055        // posture on the callee — mirror of the sibling
12056        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
12057        // (279823b) and
12058        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
12059        // (29c5d7e) pins on the peer `String → &str` axes at the same
12060        // structs).
12061        //
12062        // Peer of the sibling per-`Caixa` `Option<String> →
12063        // Option<&str>` accessor family pin
12064        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
12065        // on the top-level manifest's optional universal-axis surface
12066        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
12067        // `:restart-window`).
12068        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
12069            w.endpoint()
12070        }
12071        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
12072            w.subject()
12073        }
12074        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
12075            w.slot()
12076        }
12077        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
12078            p.shard_key()
12079        }
12080        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
12081            p.affinity()
12082        }
12083        // Sweep every closed shape-arm partition on the
12084        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
12085        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
12086        // pair None), key-value (`:slot` Some, sibling pair None),
12087        // and Capability (all three None) so each accessor's
12088        // Some/None arm carries a pin through the const dispatch.
12089        for (wit, endpoint, subject, slot) in [
12090            ("wasi:http/proxy", Some("/api"), None, None),
12091            ("nats:pub-sub", None, Some("orders.paid"), None),
12092            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
12093            ("custom:capability-only", None, None, None),
12094        ] {
12095            let c = WitContract {
12096                de: "cart".into(),
12097                para: "catalog".into(),
12098                wit: wit.into(),
12099                endpoint: endpoint.map(str::to_string),
12100                subject: subject.map(str::to_string),
12101                slot: slot.map(str::to_string),
12102            };
12103            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
12104            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
12105            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
12106            assert_eq!(c.endpoint(), endpoint);
12107            assert_eq!(c.subject(), subject);
12108            assert_eq!(c.slot(), slot);
12109        }
12110        // Sweep both `Some`/`None` arms on each per-`:placement`
12111        // optional-scalar so the shard-key + affinity pair carries a
12112        // const-dispatch pin on both arms.
12113        for (shard_key, affinity) in [
12114            (Some("tenantId"), Some("data-locality")),
12115            (Some("$tenantId"), None),
12116            (None, Some("low-latency")),
12117            (None, None),
12118        ] {
12119            let p = Placement {
12120                estrategia: PlacementStrategy::default(),
12121                clusters: vec![],
12122                affinity: affinity.map(str::to_string),
12123                shard_key: shard_key.map(str::to_string),
12124            };
12125            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
12126            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
12127            assert_eq!(p.shard_key(), shard_key);
12128            assert_eq!(p.affinity(), affinity);
12129        }
12130    }
12131
12132    #[test]
12133    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
12134        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
12135        // composite `Vec → &[String]` slice-return accessors on
12136        // [`Placement::clusters`] and [`Entrada::paths`]. Each
12137        // destructures the typed slot's `Vec<String>` storage through
12138        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
12139        // 1.66, well within the workspace MSRV) — any future accidental
12140        // downgrade to non-`const` fails the corresponding
12141        // `<name>_via_const_fn` wrapper at caixa-core build time with
12142        // E0015 (`cannot call non-const method`), strictly stronger
12143        // than a runtime `assert!`. Sibling of the peer
12144        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
12145        // pin on the outer-`AplicacaoSpec` reference-return family
12146        // (`:membros` / `:contratos` slice-return + `:politicas` /
12147        // `:placement` / `:entrada` composite-reference), and of the
12148        // peer M2 slice-return axis pins
12149        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
12150        // (on `SupervisorSpec::children`) and
12151        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
12152        // (on `UpgradeFromEntry::instructions`). Together the four
12153        // pins close the last unlifted reference-return accessor
12154        // family across the substrate primitive.
12155        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
12156            p.clusters()
12157        }
12158        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
12159            e.paths()
12160        }
12161        // Sweep both the empty-Vec (no author-declared entries) and
12162        // the populated-Vec arms on every slice-return accessor so
12163        // each carries a const-dispatch pin on both arms.
12164        let p_empty = Placement {
12165            estrategia: PlacementStrategy::default(),
12166            clusters: vec![],
12167            affinity: None,
12168            shard_key: None,
12169        };
12170        let p_full = Placement {
12171            estrategia: PlacementStrategy::default(),
12172            clusters: vec!["prod-a".into(), "prod-b".into()],
12173            affinity: None,
12174            shard_key: None,
12175        };
12176        assert_eq!(
12177            placement_clusters_via_const_fn(&p_empty),
12178            p_empty.clusters()
12179        );
12180        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
12181        assert!(p_empty.clusters().is_empty());
12182        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
12183        let e_empty = Entrada {
12184            host: "web.example.com".into(),
12185            para: "web".into(),
12186            paths: vec![],
12187            port: DEFAULT_SERVICO_PORT,
12188        };
12189        let e_full = Entrada {
12190            host: "web.example.com".into(),
12191            para: "web".into(),
12192            paths: vec!["/api".into(), "/health".into()],
12193            port: DEFAULT_SERVICO_PORT,
12194        };
12195        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
12196        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
12197        assert!(e_empty.paths().is_empty());
12198        assert_eq!(e_full.paths(), &["/api", "/health"]);
12199    }
12200
12201    #[test]
12202    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
12203        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
12204        // reference-return accessors — the two `Vec → &[T]` slice-
12205        // return accessors on [`AplicacaoSpec::membros`] and
12206        // [`AplicacaoSpec::contratos`] (each routes through the
12207        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
12208        // 1.66), the two `&Composite` composite-reference accessors
12209        // on [`AplicacaoSpec::politicas`] and
12210        // [`AplicacaoSpec::placement`] (each routes through a raw
12211        // `&self.<field>` borrow, trivially const), and the one
12212        // `Option<&Composite>` optional-composite-reference accessor
12213        // on [`AplicacaoSpec::entrada`] (routes through the
12214        // `pub const fn` [`Option::as_ref`], const-stable since Rust
12215        // 1.83). Any future accidental downgrade to non-`const` fails
12216        // the corresponding `<name>_via_const_fn` wrapper at caixa-
12217        // core build time with E0015 (`cannot call non-const
12218        // method`), strictly stronger than a runtime `assert!`.
12219        // Sibling of the peer inner-composite pin
12220        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
12221        // on the `Placement::clusters` + `Entrada::paths` slice-
12222        // return pair, and of the peer M2 axis pins on
12223        // [`crate::supervisor::SupervisorSpec::children`] and
12224        // [`crate::upgrade::UpgradeFromEntry::instructions`].
12225        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
12226            s.membros()
12227        }
12228        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
12229            s.contratos()
12230        }
12231        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
12232            s.politicas()
12233        }
12234        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
12235            s.placement()
12236        }
12237        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
12238            s.entrada()
12239        }
12240        // Construct both a minimal "no :entrada" (internal-only
12241        // mesh) and a full "with :entrada" (external-gateway)
12242        // fixture so the family pins both the `None`-arm (author-
12243        // omitted `:entrada`) and the `Some`-arm (author-declared
12244        // `:entrada`) on the optional-composite axis.
12245        let membro = Membro {
12246            caixa: "web".into(),
12247            versao: "^0.1".into(),
12248        };
12249        let entrada_full = Entrada {
12250            host: "web.example.com".into(),
12251            para: "web".into(),
12252            paths: vec!["/api".into()],
12253            port: DEFAULT_SERVICO_PORT,
12254        };
12255        let internal_only = AplicacaoSpec {
12256            membros: vec![membro.clone()],
12257            contratos: vec![],
12258            politicas: MeshPolicy::default(),
12259            placement: Placement::default(),
12260            entrada: None,
12261        };
12262        let with_entrada = AplicacaoSpec {
12263            membros: vec![membro],
12264            contratos: vec![],
12265            politicas: MeshPolicy::default(),
12266            placement: Placement::default(),
12267            entrada: Some(entrada_full),
12268        };
12269        assert_eq!(
12270            aplicacao_membros_via_const_fn(&internal_only),
12271            internal_only.membros()
12272        );
12273        assert_eq!(
12274            aplicacao_membros_via_const_fn(&with_entrada),
12275            with_entrada.membros()
12276        );
12277        assert_eq!(
12278            aplicacao_contratos_via_const_fn(&internal_only),
12279            internal_only.contratos()
12280        );
12281        assert!(std::ptr::eq(
12282            aplicacao_politicas_via_const_fn(&internal_only),
12283            internal_only.politicas(),
12284        ));
12285        assert!(std::ptr::eq(
12286            aplicacao_placement_via_const_fn(&internal_only),
12287            internal_only.placement(),
12288        ));
12289        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
12290        match (
12291            aplicacao_entrada_via_const_fn(&with_entrada),
12292            with_entrada.entrada(),
12293        ) {
12294            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
12295            _ => panic!(
12296                "aplicacao_entrada_via_const_fn must agree with \
12297                 AplicacaoSpec::entrada on the Some-arm reference"
12298            ),
12299        }
12300    }
12301
12302    #[test]
12303    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
12304        // Load-bearing contract pin: on every canonical
12305        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
12306        // [`WitContract::target_projected`] returns byte-equal to
12307        // [`WitContract::target`]`().unwrap()` — the post-validation
12308        // projection accessor is a thin panicking wrapper over the
12309        // pre-validation validator, no extra work in the projection
12310        // path. Any future divergence (a validator-side normalization
12311        // the projection doesn't route through, an accessor-side
12312        // caching layer the validator doesn't populate) would surface
12313        // here at caixa-core build time rather than a silent per-consumer
12314        // split at renderer emit time. Sweeps the closed 4-arm
12315        // [`WitTarget`] partition ([`WitTarget::Http`] /
12316        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
12317        // [`WitTarget::Capability`]) so every arm carries a byte-equality
12318        // pin on the two-accessor pair.
12319        for (wit, endpoint, subject, slot) in [
12320            ("wasi:http/proxy", Some("/x"), None, None),
12321            ("nats:pub-sub", None, Some("events.x"), None),
12322            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
12323            ("custom:capability-only", None, None, None),
12324        ] {
12325            let c = WitContract {
12326                de: "cart".into(),
12327                para: "catalog".into(),
12328                wit: wit.into(),
12329                endpoint: endpoint.map(str::to_string),
12330                subject: subject.map(str::to_string),
12331                slot: slot.map(str::to_string),
12332            };
12333            assert_eq!(
12334                c.target_projected(),
12335                c.target().unwrap(),
12336                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
12337            );
12338        }
12339    }
12340
12341    #[test]
12342    #[should_panic(expected = "validated by typed_view")]
12343    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
12344        // Panic-path pin: [`WitContract::target_projected`] threads the
12345        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
12346        // through its expect-panic when called on a contract whose
12347        // (`:wit`, payload) shape has not been crossed by
12348        // [`AplicacaoSpec::validate`] — a contract with a structurally-
12349        // invalid `:wit` (hyphen-for-colon typo) that would surface
12350        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
12351        // A future rebrand on the panic-message axis would land at one
12352        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
12353        // and this pin's [`should_panic(expected = …)`] literal would
12354        // migrate alongside — the pin catches drift between the const
12355        // and the accessor's `expect(…)` call by construction.
12356        let c = WitContract {
12357            de: "cart".into(),
12358            para: "catalog".into(),
12359            // Hyphen-for-colon typo: `WitContract::target` returns
12360            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
12361            // driving the [`WitContract::target_projected`] expect-panic.
12362            wit: "wasi-http/proxy".into(),
12363            endpoint: Some("/x".into()),
12364            subject: None,
12365            slot: None,
12366        };
12367        let _ = c.target_projected();
12368    }
12369
12370    #[test]
12371    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
12372        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
12373        // carries the exact byte-string the two prior open-coded
12374        // `.target().expect("validated by typed_view")` production
12375        // consumers threaded through inline before this lift converged
12376        // them onto [`WitContract::target_projected`] — the caixa-mesh
12377        // per-`(:de, :para)` CNP L7 introspection branch at
12378        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
12379        // graph` per-`:contratos` payload-column printer at
12380        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
12381        // byte-string load-bearing so a well-meaning const-side rebrand
12382        // that didn't carry a matched pin migration would surface here
12383        // at caixa-core build time rather than a silent per-consumer
12384        // panic-message drift at cluster-apply time. Peer of the
12385        // sibling [`WitTarget::CAPABILITY_LABEL`] /
12386        // [`WitTarget::CAPABILITY_EXPECTED`] /
12387        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
12388        // the paired payload-less-arm scalar-const family.
12389        assert_eq!(
12390            WitContract::PROJECTED_INVARIANT_MSG,
12391            "validated by typed_view"
12392        );
12393    }
12394
12395    #[test]
12396    fn empty_wit_takes_precedence_over_invalid() {
12397        // Ordering pin: `EmptyWit` is the more self-locating
12398        // diagnostic on `""` and must lead — the value-shape gate is
12399        // only reached after the empty-check fires. Mirrors
12400        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12401        // the peer payload axis.
12402        let mut s = three_member_spec();
12403        s.contratos.push(WitContract {
12404            de: "payment".into(),
12405            para: "catalog".into(),
12406            wit: String::new(),
12407            endpoint: None,
12408            subject: None,
12409            slot: None,
12410        });
12411        let err = s.validate().unwrap_err();
12412        assert!(
12413            matches!(err, AplicacaoError::EmptyWit { .. }),
12414            "got {err:?}"
12415        );
12416    }
12417
12418    #[test]
12419    fn wit_invalid_fires_before_payload_shape_arm() {
12420        // Ordering pin: a malformed `:wit` surfaces *its own*
12421        // diagnostic (which names the offending wit verbatim) before
12422        // any payload-field check — a contrato whose wit is
12423        // structurally invalid AND carries a wrong target field
12424        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
12425        // because the dispatch on the wit is what decides which
12426        // payload field is "right" in the first place. Without this
12427        // ordering, the author would see "wrong target field" for a
12428        // wit that hasn't even been parsed, which doesn't name the
12429        // root cause.
12430        let mut s = three_member_spec();
12431        s.contratos.push(WitContract {
12432            de: "payment".into(),
12433            para: "catalog".into(),
12434            // Hyphen-for-colon typo + endpoint set: pre-gate this
12435            // raised `ContratoWrongTarget { expected: "none" }` (the
12436            // Capability arm rejecting the endpoint), masking the
12437            // real authoring mistake (the wit isn't `wasi:http/proxy`).
12438            wit: "wasi-http/proxy".into(),
12439            endpoint: Some("/x".into()),
12440            subject: None,
12441            slot: None,
12442        });
12443        let err = s.validate().unwrap_err();
12444        assert!(
12445            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
12446                if wit == "wasi-http/proxy"),
12447            "got {err:?}"
12448        );
12449    }
12450
12451    #[test]
12452    fn wit_invalid_diagnostic_carries_offending_wit() {
12453        // Diagnostic-shape pin — the offending `:wit` + `:de` +
12454        // `:para` + a non-empty reason flow through verbatim so the
12455        // author can grep their caixa.lisp for the offending contrato
12456        // block and fix it in one edit. Same shape as
12457        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
12458        let err = contrato_wit_err("WASI:HTTP/proxy");
12459        match err {
12460            AplicacaoError::ContratoWitInvalid {
12461                de,
12462                para,
12463                wit,
12464                reason,
12465            } => {
12466                assert_eq!(de, "payment");
12467                assert_eq!(para, "catalog");
12468                assert_eq!(wit, "WASI:HTTP/proxy");
12469                assert!(!reason.is_empty(), "reason field must be non-empty");
12470            }
12471            other => panic!("expected ContratoWitInvalid, got {other:?}"),
12472        }
12473    }
12474
12475    // ── :contratos :subject value-shape gate ─────────────────────────────
12476    //
12477    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
12478    // suites on the peer payload axes. Until this gate landed
12479    // `WitContract::target()` only refused the empty string; a
12480    // structurally invalid subject silently passed validate and the
12481    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
12482    // Subject'` on publish / subscribe, or as a silent message drop,
12483    // far from the source caixa.lisp. Every authoring footgun the
12484    // NATS server's subject parser would catch on admission now
12485    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
12486    // offending `:subject` + `:de` + `:para` named verbatim. Same
12487    // diagnostic shape as `ContratoEndpointInvalid` /
12488    // `ContratoWitInvalid` on the peer payload axes; same shared
12489    // predicate (`crate::render::is_nats_subject`) ensures drift
12490    // between any two axes' rule enforcement is a build error at the
12491    // predicate, not piecemeal across renderers.
12492
12493    fn contrato_subject_err(subject: &str) -> AplicacaoError {
12494        // Fresh spec per call so the new contract doesn't collide on
12495        // identity with `three_member_spec`'s pre-existing entries.
12496        // The new edge uses `(payment, catalog)` — a pair the fixture
12497        // doesn't already declare — with `:wit "nats:pub-sub"` and the
12498        // varying `:subject`, so the subject-shape gate fires cleanly
12499        // after the wit-shape gate (which `"nats:pub-sub"` passes).
12500        let mut s = three_member_spec();
12501        s.contratos.push(WitContract {
12502            de: "payment".into(),
12503            para: "catalog".into(),
12504            wit: "nats:pub-sub".into(),
12505            endpoint: None,
12506            subject: Some(subject.into()),
12507            slot: None,
12508        });
12509        s.validate().unwrap_err()
12510    }
12511
12512    #[test]
12513    fn rejects_pubsub_contrato_subject_with_whitespace() {
12514        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
12515        // landed at the NATS server as a malformed subject the parser
12516        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
12517        // source caixa.lisp.
12518        let err = contrato_subject_err("foo bar");
12519        assert!(
12520            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12521                if subject == "foo bar" && reason.contains("whitespace")),
12522            "got {err:?}"
12523        );
12524    }
12525
12526    #[test]
12527    fn rejects_pubsub_contrato_subject_with_control_char() {
12528        let err = contrato_subject_err("foo\x01bar");
12529        assert!(
12530            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12531                if subject == "foo\x01bar" && reason.contains("control character")),
12532            "got {err:?}"
12533        );
12534    }
12535
12536    #[test]
12537    fn rejects_pubsub_contrato_subject_with_non_ascii() {
12538        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12539        // the subject from a doc with smart quotes / accented
12540        // characters" footgun.
12541        let err = contrato_subject_err("foo.caf\u{e9}");
12542        assert!(
12543            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12544                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
12545            "got {err:?}"
12546        );
12547    }
12548
12549    #[test]
12550    fn rejects_pubsub_contrato_subject_with_leading_dot() {
12551        // Empty leading token — NATS rejects.
12552        let err = contrato_subject_err(".foo");
12553        assert!(
12554            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12555                if subject == ".foo" && reason.contains("must not start with `.`")),
12556            "got {err:?}"
12557        );
12558    }
12559
12560    #[test]
12561    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
12562        // Empty trailing token — NATS rejects. The remediation
12563        // (use `>` instead) is in the reason string.
12564        let err = contrato_subject_err("foo.");
12565        assert!(
12566            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12567                if subject == "foo." && reason.contains("must not end with `.`")),
12568            "got {err:?}"
12569        );
12570    }
12571
12572    #[test]
12573    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
12574        // The canonical "I forgot to fill in the middle segment"
12575        // typo — `"foo..bar"`. NATS rejects empty tokens.
12576        let err = contrato_subject_err("foo..bar");
12577        assert!(
12578            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12579                if subject == "foo..bar" && reason.contains("consecutive `.`")),
12580            "got {err:?}"
12581        );
12582    }
12583
12584    #[test]
12585    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
12586        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
12587        // as the final segment. Pre-gate this passed as a typed edge
12588        // and surfaced at runtime as a NATS subscribe rejection.
12589        let err = contrato_subject_err("foo.>.bar");
12590        assert!(
12591            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12592                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
12593            "got {err:?}"
12594        );
12595    }
12596
12597    #[test]
12598    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
12599        // `foo*.bar` — NATS wildcards are standalone tokens. The
12600        // remediation is in the reason string.
12601        let err = contrato_subject_err("foo*.bar");
12602        assert!(
12603            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12604                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
12605            "got {err:?}"
12606        );
12607    }
12608
12609    #[test]
12610    fn rejects_pubsub_contrato_subject_with_invalid_char() {
12611        // `foo,bar` — comma is not a valid NATS subject character.
12612        // Pinned separately from the wildcard arms so the invalid-
12613        // character diagnostic is in force.
12614        let err = contrato_subject_err("foo,bar");
12615        assert!(
12616            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12617                if subject == "foo,bar" && reason.contains("invalid character")),
12618            "got {err:?}"
12619        );
12620    }
12621
12622    #[test]
12623    fn rejects_pubsub_contrato_subject_too_long() {
12624        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
12625        // The legitimate-shape arms all pass (one all-`a` token, no
12626        // `.`, no wildcards); only the cap arm fires. Surfaces the
12627        // paste-from-binary / accidental-multi-line-blob landing
12628        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
12629        // on the peer axis.
12630        let big = "a".repeat(257);
12631        assert_eq!(big.len(), 257);
12632        let err = contrato_subject_err(&big);
12633        assert!(
12634            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12635                if subject == &big && reason.contains("max length of 256")),
12636            "got {err:?}"
12637        );
12638    }
12639
12640    #[test]
12641    fn pubsub_contrato_subject_max_length_validates() {
12642        // 256-byte subject — exactly the cap. Boundary pin: drift in
12643        // the cap surfaces here and at
12644        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
12645        // mirroring `http_contrato_endpoint_max_length_validates` and
12646        // `wit_max_length_validates` on the peer axes.
12647        let big = "a".repeat(256);
12648        assert_eq!(big.len(), 256);
12649        let mut s = three_member_spec();
12650        s.contratos.push(WitContract {
12651            de: "payment".into(),
12652            para: "catalog".into(),
12653            wit: "nats:pub-sub".into(),
12654            endpoint: None,
12655            subject: Some(big),
12656            slot: None,
12657        });
12658        s.validate().unwrap();
12659    }
12660
12661    #[test]
12662    fn pubsub_contrato_subject_accepts_canonical_forms() {
12663        // Positive-set sweep: every canonical NATS subject shape the
12664        // substrate-side `is_nats_subject` predicate accepts (the
12665        // multi-dot `events.order.charged`, the snake_case / kebab-
12666        // case / mixed-case tokens, the digit-bearing tokens, the
12667        // single-token wildcard `*` at every segment position, and
12668        // the trailing `>` multi-token wildcard) must remain a valid
12669        // contrato subject too. Drift between this list and the
12670        // substrate-side `nats_subject_accepts_canonical_forms` sweep
12671        // surfaces at the shared predicate — one source of truth.
12672        // Uses a fresh `(payment, catalog)` edge so none of the swept
12673        // subjects collide with the pre-existing entries in
12674        // `three_member_spec`.
12675        for subject in [
12676            "checkout.events.charge.failed",
12677            "rio.events.order.charged",
12678            "orders",
12679            "orders.123",
12680            "snake_case.token",
12681            "kebab-case.token",
12682            "MixedCase.Token",
12683            "orders.*.charged",
12684            "*.events.*",
12685            "orders.>",
12686        ] {
12687            let mut s = three_member_spec();
12688            s.contratos.push(WitContract {
12689                de: "payment".into(),
12690                para: "catalog".into(),
12691                wit: "nats:pub-sub".into(),
12692                endpoint: None,
12693                subject: Some(subject.into()),
12694                slot: None,
12695            });
12696            s.validate()
12697                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
12698        }
12699    }
12700
12701    #[test]
12702    fn contrato_subject_empty_takes_precedence_over_invalid() {
12703        // Ordering pin: `ContratoSubjectEmpty` is the more self-
12704        // locating diagnostic on `""` and must lead — the value-shape
12705        // gate is only reached after the empty-check fires. Mirrors
12706        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12707        // the peer payload axis.
12708        let mut s = three_member_spec();
12709        s.contratos.push(WitContract {
12710            de: "payment".into(),
12711            para: "catalog".into(),
12712            wit: "nats:pub-sub".into(),
12713            endpoint: None,
12714            subject: Some(String::new()),
12715            slot: None,
12716        });
12717        let err = s.validate().unwrap_err();
12718        assert!(
12719            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
12720            "got {err:?}"
12721        );
12722    }
12723
12724    #[test]
12725    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
12726        // Diagnostic-shape pin — the offending `:subject` + `:de` +
12727        // `:para` + a non-empty reason flow through verbatim so the
12728        // author can grep their caixa.lisp for the offending contrato
12729        // block and fix it in one edit. Same shape as
12730        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12731        // and `wit_invalid_diagnostic_carries_offending_wit`.
12732        let err = contrato_subject_err("foo..bar");
12733        match err {
12734            AplicacaoError::ContratoSubjectInvalid {
12735                de,
12736                para,
12737                subject,
12738                reason,
12739            } => {
12740                assert_eq!(de, "payment");
12741                assert_eq!(para, "catalog");
12742                assert_eq!(subject, "foo..bar");
12743                assert!(!reason.is_empty(), "reason field must be non-empty");
12744            }
12745            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
12746        }
12747    }
12748
12749    #[test]
12750    fn target_view_pubsub_subject_passes_through_to_typed_view() {
12751        // The compounding theorem on the pub-sub axis: every
12752        // `WitTarget::PubSub { subject }` returned by `target()` carries
12753        // a NATS-server-accepted subject. Renderers downstream of
12754        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
12755        // NATS Stream/Consumer CR emitter, the future `feira app graph`
12756        // view's subject labeller) can rely on this without re-checking
12757        // — the type system carries the proof. Mirrors
12758        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
12759        // on the peer axes.
12760        let nats = WitContract {
12761            de: "a".into(),
12762            para: "b".into(),
12763            wit: "nats:pub-sub".into(),
12764            endpoint: None,
12765            subject: Some("orders.events.*.charged".into()),
12766            slot: None,
12767        };
12768        match nats.target().unwrap() {
12769            WitTarget::PubSub { subject } => {
12770                assert_eq!(subject, "orders.events.*.charged");
12771            }
12772            other => panic!("expected PubSub, got {other:?}"),
12773        }
12774    }
12775
12776    // ── :contratos :slot value-shape gate ────────────────────────────────
12777    //
12778    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
12779    // (63e18a0) value-shape suites on the peer payload axes. Until this
12780    // gate landed `WitContract::target()` only refused the empty string
12781    // for the Store arm; a structurally invalid slot (raw whitespace,
12782    // control character, non-ASCII byte, paste-from-binary multi-line
12783    // blob) silently passed validate and surfaced at runtime as a
12784    // per-backend kv write rejection or a silent next-read corruption,
12785    // far from the source caixa.lisp with no field naming which
12786    // `:contratos` edge carried the typo. Every authoring footgun the
12787    // kv backend intersection-floor would catch on write now becomes a
12788    // caixa-build-time `ContratoSlotInvalid` with the offending
12789    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
12790    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
12791    // peer payload axes; same shared predicate
12792    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
12793    // any two axes' rule enforcement is a build error at the
12794    // predicate, not piecemeal across renderers. Closes the typed
12795    // payload-axis value-shape trajectory across all three legs of the
12796    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
12797
12798    fn contrato_slot_err(slot: &str) -> AplicacaoError {
12799        // Fresh spec per call so the new contract doesn't collide on
12800        // identity with `three_member_spec`'s pre-existing entries
12801        // and doesn't close a synchronous cycle the cycle detector
12802        // would reject before the slot-shape gate fires. The new edge
12803        // uses `(payment, catalog)` — a pair the fixture doesn't
12804        // already declare in either direction (the fixture carries
12805        // `cart -> catalog` and `cart -> payment`, so `payment ->
12806        // catalog` doesn't form a cycle on the sync subgraph) — with
12807        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
12808        // slot-shape gate fires cleanly after the wit-shape gate
12809        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
12810        // peer `contrato_subject_err` helper uses (63e18a0).
12811        let mut s = three_member_spec();
12812        s.contratos.push(WitContract {
12813            de: "payment".into(),
12814            para: "catalog".into(),
12815            wit: "wasi:keyvalue/store".into(),
12816            endpoint: None,
12817            subject: None,
12818            slot: Some(slot.into()),
12819        });
12820        s.validate().unwrap_err()
12821    }
12822
12823    #[test]
12824    fn rejects_store_contrato_slot_with_whitespace() {
12825        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
12826        // silently landed at the kv backend with whitespace whose
12827        // runtime behavior varies unpredictably across backends (etcd
12828        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
12829        // rejects on write). Now caught at the source caixa.lisp.
12830        let err = contrato_slot_err("check out/$order");
12831        assert!(
12832            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12833                if slot == "check out/$order" && reason.contains("whitespace")),
12834            "got {err:?}"
12835        );
12836    }
12837
12838    #[test]
12839    fn rejects_store_contrato_slot_with_tab() {
12840        // Tab byte arm-pinned separately from the space arm so a
12841        // future relaxation that admits one but not the other surfaces
12842        // here.
12843        let err = contrato_slot_err("check\tout");
12844        assert!(
12845            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12846                if slot == "check\tout" && reason.contains("whitespace")),
12847            "got {err:?}"
12848        );
12849    }
12850
12851    #[test]
12852    fn rejects_store_contrato_slot_with_control_char() {
12853        // SOH (0x01) — distinct from the whitespace arm. Redis admits
12854        // and corrupts on RESP protocol framing; DynamoDB rejects on
12855        // write.
12856        let err = contrato_slot_err("checkout/\x01order");
12857        assert!(
12858            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12859                if slot == "checkout/\x01order" && reason.contains("control character")),
12860            "got {err:?}"
12861        );
12862    }
12863
12864    #[test]
12865    fn rejects_store_contrato_slot_with_newline() {
12866        // Embedded newline — the canonical "the paste-from-binary slug
12867        // spans multiple lines" footgun. Distinct from the whitespace
12868        // arm because `\n` is a control character (0x0A).
12869        let err = contrato_slot_err("checkout\norder");
12870        assert!(
12871            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12872                if slot == "checkout\norder" && reason.contains("control character")),
12873            "got {err:?}"
12874        );
12875    }
12876
12877    #[test]
12878    fn rejects_store_contrato_slot_with_non_ascii() {
12879        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12880        // the slot from a doc with accented characters" footgun. Each
12881        // kv backend re-encodes non-ASCII differently (etcd preserves
12882        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
12883        // rejects), so the typed slot's value set is the intersection-
12884        // floor every backend admits identically (printable ASCII).
12885        let err = contrato_slot_err("ch\u{e9}ckout/$order");
12886        assert!(
12887            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12888                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
12889            "got {err:?}"
12890        );
12891    }
12892
12893    #[test]
12894    fn rejects_store_contrato_slot_too_long() {
12895        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
12896        // legitimate-shape arms all pass (a single all-`a` token, no
12897        // separators); only the cap arm fires. Surfaces the paste-
12898        // from-binary / accidental-multi-line-blob landing footgun.
12899        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
12900        // `rejects_http_contrato_endpoint_too_long` on the peer
12901        // payload axes.
12902        let big = "a".repeat(513);
12903        assert_eq!(big.len(), 513);
12904        let err = contrato_slot_err(&big);
12905        assert!(
12906            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12907                if slot == &big && reason.contains("max length of 512")),
12908            "got {err:?}"
12909        );
12910    }
12911
12912    #[test]
12913    fn store_contrato_slot_max_length_validates() {
12914        // 512-byte slot — exactly the cap. Boundary pin: drift in the
12915        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
12916        // simultaneously, mirroring
12917        // `pubsub_contrato_subject_max_length_validates` and
12918        // `http_contrato_endpoint_max_length_validates` on the peer
12919        // payload axes.
12920        let big = "a".repeat(512);
12921        assert_eq!(big.len(), 512);
12922        let mut s = three_member_spec();
12923        s.contratos.push(WitContract {
12924            de: "payment".into(),
12925            para: "catalog".into(),
12926            wit: "wasi:keyvalue/store".into(),
12927            endpoint: None,
12928            subject: None,
12929            slot: Some(big),
12930        });
12931        s.validate().unwrap();
12932    }
12933
12934    #[test]
12935    fn store_contrato_slot_accepts_canonical_forms() {
12936        // Positive-set sweep: every canonical kv slot template the
12937        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
12938        // (single-token identifiers, path-namespaced `$`-templates,
12939        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
12940        // snake_case / kebab-case / MixedCase tokens, digit-bearing
12941        // tokens, percent-encoded fragments) must remain valid
12942        // contrato slots too. Drift between this list and the
12943        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
12944        // surfaces at the shared predicate — one source of truth.
12945        // Uses a fresh `(payment, catalog)` edge so none of the swept
12946        // slots collide with the pre-existing entries in
12947        // `three_member_spec`.
12948        for slot in [
12949            "checkout",
12950            "checkout/$orderId",
12951            "users:{tenant}/{id}",
12952            "session.<sid>",
12953            "session.tokens.<sid>",
12954            "snake_case_key",
12955            "kebab-case-key",
12956            "MixedCase",
12957            "shard0",
12958            "v2/key",
12959            "users/caf%C3%A9",
12960        ] {
12961            let mut s = three_member_spec();
12962            s.contratos.push(WitContract {
12963                de: "payment".into(),
12964                para: "catalog".into(),
12965                wit: "wasi:keyvalue/store".into(),
12966                endpoint: None,
12967                subject: None,
12968                slot: Some(slot.into()),
12969            });
12970            s.validate()
12971                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
12972        }
12973    }
12974
12975    #[test]
12976    fn contrato_slot_empty_takes_precedence_over_invalid() {
12977        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
12978        // diagnostic on `""` and must lead — the value-shape gate is
12979        // only reached after the empty-check fires. Mirrors
12980        // `contrato_subject_empty_takes_precedence_over_invalid` and
12981        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12982        // the peer payload axes.
12983        let mut s = three_member_spec();
12984        s.contratos.push(WitContract {
12985            de: "payment".into(),
12986            para: "catalog".into(),
12987            wit: "wasi:keyvalue/store".into(),
12988            endpoint: None,
12989            subject: None,
12990            slot: Some(String::new()),
12991        });
12992        let err = s.validate().unwrap_err();
12993        assert!(
12994            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
12995            "got {err:?}"
12996        );
12997    }
12998
12999    #[test]
13000    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
13001        // Diagnostic-shape pin — the offending `:slot` + `:de` +
13002        // `:para` + a non-empty reason flow through verbatim so the
13003        // author can grep their caixa.lisp for the offending contrato
13004        // block and fix it in one edit. Same shape as
13005        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
13006        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
13007        // on the peer payload axes.
13008        let err = contrato_slot_err("check out/$order");
13009        match err {
13010            AplicacaoError::ContratoSlotInvalid {
13011                de,
13012                para,
13013                slot,
13014                reason,
13015            } => {
13016                assert_eq!(de, "payment");
13017                assert_eq!(para, "catalog");
13018                assert_eq!(slot, "check out/$order");
13019                assert!(!reason.is_empty(), "reason field must be non-empty");
13020            }
13021            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
13022        }
13023    }
13024
13025    #[test]
13026    fn target_view_store_slot_passes_through_to_typed_view() {
13027        // The compounding theorem on the store axis: every
13028        // `WitTarget::Store { slot }` returned by `target()` carries a
13029        // kv-backend-accepted slot template. Renderers downstream of
13030        // `typed_view()` (the future per-Servico `:capabilities
13031        // wasi:keyvalue/store` axis emitter, the future `feira app
13032        // graph` view's slot labeller, the future kv-provider CR
13033        // materializer) can rely on this without re-checking — the
13034        // type system carries the proof. Mirrors
13035        // `target_view_pubsub_subject_passes_through_to_typed_view` on
13036        // the peer payload axis.
13037        let store = WitContract {
13038            de: "a".into(),
13039            para: "b".into(),
13040            wit: "wasi:keyvalue/store".into(),
13041            endpoint: None,
13042            subject: None,
13043            slot: Some("checkout/$orderId".into()),
13044        };
13045        match store.target().unwrap() {
13046            WitTarget::Store { slot } => {
13047                assert_eq!(slot, "checkout/$orderId");
13048            }
13049            other => panic!("expected Store, got {other:?}"),
13050        }
13051    }
13052
13053    #[test]
13054    fn rejects_self_loop_in_synchronous_contratos() {
13055        // A synchronous self-edge (`cart → cart` over HTTP) is now
13056        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
13057        // "this edge is degenerate" diagnostic — rather than incidentally
13058        // by the cycle detector framing it as a `["cart", "cart"]`
13059        // multi-node deadlock.
13060        let mut s = three_member_spec();
13061        s.contratos.push(contract_http("cart", "cart", "/loop"));
13062        let err = s.validate().unwrap_err();
13063        match err {
13064            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
13065                assert_eq!(caixa, "cart");
13066                assert_eq!(wit, "wasi:http/proxy");
13067            }
13068            other => panic!("expected ContratoSelfLoop, got {other:?}"),
13069        }
13070    }
13071
13072    #[test]
13073    fn rejects_self_loop_in_pubsub_contratos() {
13074        // The cycle detector excludes pub-sub edges (acyclic by
13075        // construction), so before the explicit gate a `nats:pub-sub`
13076        // self-edge silently validated and rendered a self-allow CNP.
13077        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
13078        let mut s = three_member_spec();
13079        s.contratos.push(WitContract {
13080            de: "payment".into(),
13081            para: "payment".into(),
13082            wit: "nats:pub-sub".into(),
13083            endpoint: None,
13084            subject: Some("rio.events.payment".into()),
13085            slot: None,
13086        });
13087        let err = s.validate().unwrap_err();
13088        match err {
13089            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
13090                assert_eq!(caixa, "payment");
13091                assert_eq!(wit, "nats:pub-sub");
13092            }
13093            other => panic!("expected ContratoSelfLoop, got {other:?}"),
13094        }
13095    }
13096
13097    #[test]
13098    fn self_loop_fires_before_payload_shape_check() {
13099        // The structural "this edge can't exist" error precedes the
13100        // narrower payload-shape diagnostics: a self-edge carrying an
13101        // otherwise-malformed endpoint still reports ContratoSelfLoop,
13102        // not ContratoEndpointInvalid.
13103        let mut s = three_member_spec();
13104        s.contratos.push(WitContract {
13105            de: "cart".into(),
13106            para: "cart".into(),
13107            wit: "wasi:http/proxy".into(),
13108            endpoint: Some("not-absolute".into()),
13109            subject: None,
13110            slot: None,
13111        });
13112        match s.validate().unwrap_err() {
13113            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
13114            other => panic!("expected ContratoSelfLoop, got {other:?}"),
13115        }
13116    }
13117
13118    #[test]
13119    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
13120        // A self-edge naming a non-member reports the more fundamental
13121        // ContratoMemberMissing first (the member doesn't exist), so the
13122        // self-loop gate is reached only once both endpoints resolve.
13123        let mut s = three_member_spec();
13124        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
13125        match s.validate().unwrap_err() {
13126            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
13127            other => panic!("expected ContratoMemberMissing, got {other:?}"),
13128        }
13129    }
13130
13131    #[test]
13132    fn rejects_two_node_synchronous_cycle() {
13133        let mut s = three_member_spec();
13134        // existing edges: cart → catalog, cart → payment
13135        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
13136        s.contratos
13137            .push(contract_http("catalog", "cart", "/refresh"));
13138        let err = s.validate().unwrap_err();
13139        match err {
13140            AplicacaoError::ContratoCycle { cycle } => {
13141                // Cycle traversal should mention both endpoints, with
13142                // the back-edge target appearing as both first and last
13143                // element to close the loop.
13144                assert!(cycle.len() >= 3);
13145                assert_eq!(cycle.first(), cycle.last());
13146                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
13147                assert!(body.contains("cart"));
13148                assert!(body.contains("catalog"));
13149            }
13150            other => panic!("expected ContratoCycle, got {other:?}"),
13151        }
13152    }
13153
13154    #[test]
13155    fn rejects_three_node_synchronous_cycle() {
13156        let mut s = three_member_spec();
13157        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
13158        s.contratos = vec![
13159            contract_http("catalog", "cart", "/x"),
13160            contract_http("cart", "payment", "/y"),
13161            contract_http("payment", "catalog", "/z"),
13162        ];
13163        let err = s.validate().unwrap_err();
13164        match err {
13165            AplicacaoError::ContratoCycle { cycle } => {
13166                assert_eq!(cycle.first(), cycle.last());
13167                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
13168                assert_eq!(body.len(), 3);
13169                assert!(body.contains("cart"));
13170                assert!(body.contains("catalog"));
13171                assert!(body.contains("payment"));
13172            }
13173            other => panic!("expected ContratoCycle, got {other:?}"),
13174        }
13175    }
13176
13177    #[test]
13178    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
13179        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
13180        // "acyclic by construction" — so a cycle whose closing edge
13181        // is pub-sub should NOT raise ContratoCycle.
13182        let mut s = three_member_spec();
13183        s.contratos = vec![
13184            contract_http("catalog", "cart", "/x"),
13185            contract_http("cart", "payment", "/y"),
13186            // Closing edge is pub-sub — async; not a sync deadlock.
13187            WitContract {
13188                de: "payment".into(),
13189                para: "catalog".into(),
13190                wit: "nats:pub-sub".into(),
13191                endpoint: None,
13192                subject: Some("checkout.events.charge.completed".into()),
13193                slot: None,
13194            },
13195        ];
13196        s.validate().expect("pub-sub edge breaks the sync cycle");
13197    }
13198
13199    #[test]
13200    fn store_edge_counts_as_synchronous_for_cycle_detection() {
13201        // wasi:keyvalue/store is request/response; a cycle through one
13202        // *is* a sync deadlock, just like HTTP.
13203        let mut s = three_member_spec();
13204        s.contratos = vec![
13205            contract_http("catalog", "cart", "/x"),
13206            WitContract {
13207                de: "cart".into(),
13208                para: "catalog".into(),
13209                wit: "wasi:keyvalue/store".into(),
13210                endpoint: None,
13211                subject: None,
13212                slot: Some("session/$id".into()),
13213            },
13214        ];
13215        let err = s.validate().unwrap_err();
13216        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
13217    }
13218
13219    #[test]
13220    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
13221        // Capability-only edges (unknown WIT shape, no payload) default
13222        // to synchronous — safer; authors with truly async capability
13223        // semantics can model them as pub-sub explicitly.
13224        let mut s = three_member_spec();
13225        s.contratos = vec![
13226            contract_http("catalog", "cart", "/x"),
13227            WitContract {
13228                de: "cart".into(),
13229                para: "catalog".into(),
13230                wit: "custom:exchange".into(),
13231                endpoint: None,
13232                subject: None,
13233                slot: None,
13234            },
13235        ];
13236        let err = s.validate().unwrap_err();
13237        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
13238    }
13239
13240    #[test]
13241    fn long_acyclic_chain_validates() {
13242        // A long sync chain (no back-edges) must validate even when
13243        // every node is reachable from the first.
13244        let mut s = three_member_spec();
13245        s.membros = vec![
13246            membro("a", "^0.1"),
13247            membro("b", "^0.1"),
13248            membro("c", "^0.1"),
13249            membro("d", "^0.1"),
13250            membro("e", "^0.1"),
13251        ];
13252        s.contratos = vec![
13253            contract_http("a", "b", "/1"),
13254            contract_http("b", "c", "/2"),
13255            contract_http("c", "d", "/3"),
13256            contract_http("d", "e", "/4"),
13257        ];
13258        s.entrada.as_mut().unwrap().para = "a".into();
13259        s.validate().unwrap();
13260    }
13261
13262    #[test]
13263    fn diamond_acyclic_validates() {
13264        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
13265        let mut s = three_member_spec();
13266        s.membros = vec![
13267            membro("a", "^0.1"),
13268            membro("b", "^0.1"),
13269            membro("c", "^0.1"),
13270            membro("d", "^0.1"),
13271        ];
13272        s.contratos = vec![
13273            contract_http("a", "b", "/1"),
13274            contract_http("a", "c", "/2"),
13275            contract_http("b", "d", "/3"),
13276            contract_http("c", "d", "/4"),
13277        ];
13278        s.entrada.as_mut().unwrap().para = "a".into();
13279        s.validate().unwrap();
13280    }
13281
13282    // ── duplicate-`:contratos` build-error gate ──────────────────────────
13283
13284    #[test]
13285    fn rejects_duplicate_http_contrato() {
13286        // Fail-before-pass-after pin: the fixture's `cart → catalog`
13287        // HTTP edge appears once. Push an identical entry — same
13288        // (de, para, wit, endpoint) — and validate() must reject it.
13289        // Until this gate landed the typed surface accepted the
13290        // duplicate silently and caixa-mesh's `cilium_network_policies`
13291        // emitted two ``CiliumNetworkPolicy`` objects with identical
13292        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
13293        // admission rejects on `kubectl apply` far from the source.
13294        let mut s = three_member_spec();
13295        s.contratos
13296            .push(contract_http("cart", "catalog", "/products/:id"));
13297        let err = s.validate().unwrap_err();
13298        assert!(
13299            matches!(
13300                err,
13301                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13302                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
13303            ),
13304            "got {err:?}"
13305        );
13306    }
13307
13308    #[test]
13309    fn rejects_duplicate_pubsub_contrato() {
13310        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
13311        // edges with identical (de, para, subject) are degenerate;
13312        // pin that the typed surface refuses both at validate time.
13313        let mut s = three_member_spec();
13314        let pubsub = WitContract {
13315            de: "payment".into(),
13316            para: "cart".into(),
13317            wit: "nats:pub-sub".into(),
13318            endpoint: None,
13319            subject: Some("checkout.events.charge.failed".into()),
13320            slot: None,
13321        };
13322        s.contratos.push(pubsub.clone());
13323        s.contratos.push(pubsub);
13324        let err = s.validate().unwrap_err();
13325        assert!(
13326            matches!(
13327                err,
13328                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13329                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
13330            ),
13331            "got {err:?}"
13332        );
13333    }
13334
13335    #[test]
13336    fn rejects_duplicate_store_contrato() {
13337        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
13338        // edges with identical (de, para, slot) collapse to one mesh-
13339        // policy edge; pin the build error.
13340        let mut s = three_member_spec();
13341        let store = WitContract {
13342            de: "cart".into(),
13343            para: "payment".into(),
13344            wit: "wasi:keyvalue/store".into(),
13345            endpoint: None,
13346            subject: None,
13347            slot: Some("checkout/$orderId".into()),
13348        };
13349        // Drop the conflicting HTTP `cart → payment` edge from the
13350        // fixture so the duplicate-store pair is the only one
13351        // distinguishable on this pair.
13352        s.contratos
13353            .retain(|c| !(c.de == "cart" && c.para == "payment"));
13354        s.contratos.push(store.clone());
13355        s.contratos.push(store);
13356        let err = s.validate().unwrap_err();
13357        assert!(
13358            matches!(
13359                err,
13360                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13361                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
13362            ),
13363            "got {err:?}"
13364        );
13365    }
13366
13367    #[test]
13368    fn rejects_duplicate_capability_contrato() {
13369        // Same gate on the pure-capability axis (no payload selector).
13370        // Two contracts with identical (de, para, wit) and no
13371        // endpoint/subject/slot are duplicate edges; pin so a future
13372        // `target_label` change can't accidentally collapse the
13373        // capability arm into a None-shaped key that compares equal
13374        // to a populated one.
13375        let mut s = three_member_spec();
13376        let capability = WitContract {
13377            de: "cart".into(),
13378            para: "catalog".into(),
13379            wit: "pleme:cap/audit".into(),
13380            endpoint: None,
13381            subject: None,
13382            slot: None,
13383        };
13384        s.contratos.push(capability.clone());
13385        s.contratos.push(capability);
13386        let err = s.validate().unwrap_err();
13387        match err {
13388            AplicacaoError::ContratoDuplicate {
13389                de,
13390                para,
13391                wit,
13392                target,
13393            } => {
13394                assert_eq!(de, "cart");
13395                assert_eq!(para, "catalog");
13396                assert_eq!(wit, "pleme:cap/audit");
13397                assert!(
13398                    target.contains("capability"),
13399                    "capability-edge duplicate diagnostic must surface the \
13400                     no-payload shape (got target = {target:?})"
13401                );
13402            }
13403            other => panic!("expected ContratoDuplicate, got {other:?}"),
13404        }
13405    }
13406
13407    #[test]
13408    fn accepts_distinct_http_paths_between_same_pair() {
13409        // Negative pin: two HTTP contracts cart → catalog at distinct
13410        // endpoints (`/products/:id` and `/search`) are *not*
13411        // duplicates — they're distinct typed edges differing on the
13412        // payload axis. The duplicate-gate must not over-match here,
13413        // since the cart-calls-catalog-on-multiple-paths shape is the
13414        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
13415        // example: cart calls catalog at /products/:id, payment at
13416        // /charge — same shape extends to two paths on one para).
13417        let mut s = three_member_spec();
13418        s.contratos
13419            .push(contract_http("cart", "catalog", "/search"));
13420        s.validate()
13421            .expect("distinct endpoints between same (de, para) must validate");
13422    }
13423
13424    #[test]
13425    fn accepts_same_endpoint_on_different_pairs() {
13426        // Negative pin: the same `/charge` endpoint reused on two
13427        // different (de, para) pairs is two distinct edges, not a
13428        // duplicate. Pinning this shape so the gate's identity key
13429        // includes both `de` and `para` (not just `(wit, endpoint)`).
13430        let mut s = three_member_spec();
13431        s.contratos
13432            .push(contract_http("payment", "catalog", "/charge"));
13433        s.validate()
13434            .expect("same endpoint reused on distinct (de, para) must validate");
13435    }
13436
13437    #[test]
13438    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
13439        // Pin the diagnostic shape: the duplicate-edge error names
13440        // *which* target field carried the conflict, so the author
13441        // doesn't have to re-grep the source caixa.lisp to find it.
13442        // Same self-locating diagnostic discipline as
13443        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
13444        let mut s = three_member_spec();
13445        s.contratos
13446            .push(contract_http("cart", "catalog", "/products/:id"));
13447        let err = s.validate().unwrap_err();
13448        let msg = format!("{err}");
13449        assert!(
13450            msg.contains("\"/products/:id\""),
13451            "duplicate-contrato diagnostic must name the offending \
13452             :endpoint payload (got: {msg:?})"
13453        );
13454        assert!(
13455            msg.contains("cart") && msg.contains("catalog"),
13456            "diagnostic must name both endpoints of the duplicate edge \
13457             (got: {msg:?})"
13458        );
13459    }
13460
13461    #[test]
13462    fn duplicate_contrato_gate_runs_after_membership_check() {
13463        // Order pin: a duplicate contract whose `:de` is *also* not in
13464        // `:membros` surfaces the membership error first — the
13465        // missing-member diagnostic is more locating than the
13466        // duplicate-edge one (the author has to fix the membership
13467        // before the duplicate is meaningful). Same ordering
13468        // discipline as `membros_validation_runs_before_contratos_membership_check`.
13469        let mut s = three_member_spec();
13470        s.contratos.push(contract_http("phantom", "catalog", "/x"));
13471        s.contratos.push(contract_http("phantom", "catalog", "/x"));
13472        let err = s.validate().unwrap_err();
13473        assert!(
13474            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
13475            "membership-missing must fire before duplicate-edge (got {err:?})"
13476        );
13477    }
13478
13479    #[test]
13480    fn duplicate_contrato_gate_runs_after_target_shape_check() {
13481        // Order pin: a contract with a malformed target (e.g. an HTTP
13482        // wit world with an empty :endpoint) surfaces the target-shape
13483        // error first, not the duplicate one. Even when two such
13484        // malformed entries are identical, the per-contract `target()`
13485        // check fires inside the loop *before* the duplicate-key
13486        // insert, so the diagnostic remains the most-locating one.
13487        let mut s = three_member_spec();
13488        let malformed = WitContract {
13489            de: "cart".into(),
13490            para: "catalog".into(),
13491            wit: "wasi:http/proxy".into(),
13492            endpoint: Some(String::new()),
13493            subject: None,
13494            slot: None,
13495        };
13496        s.contratos.push(malformed.clone());
13497        s.contratos.push(malformed);
13498        let err = s.validate().unwrap_err();
13499        assert!(
13500            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
13501            "endpoint-empty must fire before duplicate-edge (got {err:?})"
13502        );
13503    }
13504
13505    #[test]
13506    fn wit_target_label_pins_per_variant_format() {
13507        // Label format is the single source of truth every duplicate-
13508        // `:contratos` diagnostic + every future `feira app graph`
13509        // consumer routes through. Pin the shape per variant so a
13510        // future edit to `WitTarget::label` (e.g. a JSON emitter that
13511        // strips the leading `:`, or a rename from `endpoint` →
13512        // `path`) surfaces as a red-red test rather than as a silent
13513        // downstream diagnostic drift. Together with the exhaustive
13514        // `match` on `WitTarget` inside `label()`, adding a future
13515        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
13516        // peer, per-edge WIT registry variants) is a compile error at
13517        // the label site — not a fall-through into the `Capability`
13518        // "no payload" default the prior raw-field-probe helper
13519        // silently landed on.
13520        assert_eq!(
13521            WitTarget::Http {
13522                endpoint: "/charge",
13523            }
13524            .label(),
13525            "\
13526:endpoint \"/charge\""
13527        );
13528        assert_eq!(
13529            WitTarget::PubSub {
13530                subject: "events.checkout.paid",
13531            }
13532            .label(),
13533            "\
13534:subject \"events.checkout.paid\""
13535        );
13536        assert_eq!(
13537            WitTarget::Store {
13538                slot: "checkout/$order",
13539            }
13540            .label(),
13541            "\
13542:slot \"checkout/$order\""
13543        );
13544        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
13545        // Capability-arm label routes through the lifted
13546        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
13547        // declaration per arm, next to the variant" discipline the
13548        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
13549        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13550        // consts already carry extends to the payload-less arm; the
13551        // byte-string equality pin below plus this label-routes-
13552        // through-the-const pin make a future rebrand on either the
13553        // const declaration or the `label()` template a build error
13554        // here rather than a downstream consumer surprise.
13555        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
13556        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
13557    }
13558
13559    #[test]
13560    fn wit_target_display_routes_through_label_helper() {
13561        // Fail-before-pass-after pin on the fourth (and only remaining)
13562        // typed-shape-discriminator axis to converge onto the
13563        // three-path-convergence discipline the sibling M3
13564        // [`PlacementStrategy`] (0a2f653) and M2
13565        // [`crate::supervisor::RestartStrategy`] /
13566        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
13567        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
13568        // through [`WitTarget::label`], so every consumer reaching for
13569        // `format!("{v}")` on a typed payload target lands on the same
13570        // stable author-facing byte-string [`WitTarget::label`] returns
13571        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
13572        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
13573        // `:contratos` gate seeds via [`WitTarget::label`] at
13574        // aplicacao.rs:5491 already threads through.
13575        //
13576        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
13577        // through to the `Debug` derive's structural output
13578        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
13579        // rather than the [`WitTarget::label`] helper's stable byte-
13580        // string (`:endpoint "/charge"` — the author-facing `:contratos`
13581        // keyword form). Every future consumer that reaches for
13582        // `format!("{target}")` — the canonical shape every user-facing
13583        // pretty-print site on the sibling typed-enum axes
13584        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
13585        // [`crate::supervisor::RestartPolicy`]) already uses — would
13586        // silently land under a different byte-string than the
13587        // [`WitTarget::label`] callers that the duplicate-`:contratos`
13588        // diagnostic already threads through, with the mismatch
13589        // surfacing as a downstream diagnostic / graph / audit line
13590        // reading one spelling while the substrate's own gate emitted
13591        // another.
13592        //
13593        // Pin the routing here so a future
13594        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
13595        // that hand-rolls the per-arm formatting instead of delegating
13596        // to [`WitTarget::label`] fails at caixa-core build time.
13597        for variant in [
13598            WitTarget::Http {
13599                endpoint: "/charge",
13600            },
13601            WitTarget::PubSub {
13602                subject: "events.checkout.paid",
13603            },
13604            WitTarget::Store {
13605                slot: "checkout/$order",
13606            },
13607            WitTarget::Capability,
13608        ] {
13609            assert_eq!(
13610                variant.to_string(),
13611                variant.label(),
13612                "WitTarget::{variant:?} Display must route through \
13613                 WitTarget::label (single source of truth: the lifted \
13614                 payload_pair 4-arm dispatch the label helper already \
13615                 threads through)"
13616            );
13617        }
13618    }
13619
13620    #[test]
13621    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
13622        // Consumer-side pin on the three-path convergence:
13623        // [`std::fmt::Display`] agrees byte-for-byte with the
13624        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
13625        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
13626        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
13627        // Pre-lift the two paths were structurally independent — the
13628        // substrate-side gate reached for `target_view.label()` while a
13629        // future downstream diagnostic / graph / audit line reaching
13630        // for `format!("{target}")` would silently land on the `Debug`
13631        // derive's structural output. Pin the two paths byte-for-byte
13632        // here so any future variant addition (M4 `Rest`/`Grpc` split
13633        // of [`WitTarget::Http`], `Queue`-shaped peer of
13634        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
13635        // match error at [`WitTarget::payload_pair`] rather than a
13636        // silent per-consumer dispatch miss.
13637        for variant in [
13638            WitTarget::Http {
13639                endpoint: "/charge",
13640            },
13641            WitTarget::PubSub {
13642                subject: "events.checkout.paid",
13643            },
13644            WitTarget::Store {
13645                slot: "checkout/$order",
13646            },
13647            WitTarget::Capability,
13648        ] {
13649            assert_eq!(
13650                format!("{variant}"),
13651                variant.label(),
13652                "WitTarget::{variant:?} Display byte-string must match \
13653                 the AplicacaoError::ContratoDuplicate `target:` carrier \
13654                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
13655                 seeds via WitTarget::label — three-path convergence: \
13656                 Display + label + payload_pair all resolve to the same \
13657                 per-arm byte-string"
13658            );
13659        }
13660    }
13661
13662    #[test]
13663    fn wit_target_payload_pair_pins_per_variant() {
13664        // Pin the per-arm `(field-name, payload)` pair single-sourced
13665        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
13666        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
13667        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
13668        // and [`WitTarget::field_name`] (returns the first component)
13669        // route through. Until this lift landed [`WitTarget::label`]
13670        // dispatched on the same three arms with a per-arm
13671        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
13672        // paired [`WitTarget::HTTP_FIELD_NAME`] /
13673        // [`WitTarget::PUBSUB_FIELD_NAME`] /
13674        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
13675        // canonical "same shape, written N times" duplication
13676        // THEORY.md §I.3.5 promotes to a build-time concern. A future
13677        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
13678        // [`WitTarget::Http`], `Queue`-shaped peer of
13679        // [`WitTarget::Store`]) is one match-arm edit at
13680        // [`WitTarget::payload_pair`], visible here as a compile-time
13681        // exhaustiveness error on both this pin and the label-format
13682        // pin above.
13683        assert_eq!(
13684            WitTarget::Http {
13685                endpoint: "/charge"
13686            }
13687            .payload_pair(),
13688            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
13689        );
13690        assert_eq!(
13691            WitTarget::PubSub {
13692                subject: "events.x",
13693            }
13694            .payload_pair(),
13695            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
13696        );
13697        assert_eq!(
13698            WitTarget::Store {
13699                slot: "checkout/$order",
13700            }
13701            .payload_pair(),
13702            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
13703        );
13704        assert_eq!(WitTarget::Capability.payload_pair(), None);
13705    }
13706
13707    #[test]
13708    fn wit_target_field_name_pins_per_variant() {
13709        // Pin the per-arm author-facing `:contratos` payload field
13710        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
13711        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13712        // + returned by [`WitTarget::field_name`]. Every downstream
13713        // consumer (the [`WitContract::target`] gate's `expected:`
13714        // scalar, the [`WitTarget::label`] template's keyword prefix,
13715        // the `feira app graph` verb's `endpoint=…` prefix) routes
13716        // through the same three peer consts, so a rename on the
13717        // author-surface `(defcaixa … :contratos ((:de … :para …
13718        // :wit … :endpoint …)))` field lands in exactly one place.
13719        assert_eq!(
13720            WitTarget::Http {
13721                endpoint: "/charge"
13722            }
13723            .field_name(),
13724            Some(WitTarget::HTTP_FIELD_NAME),
13725        );
13726        assert_eq!(
13727            WitTarget::PubSub {
13728                subject: "events.x",
13729            }
13730            .field_name(),
13731            Some(WitTarget::PUBSUB_FIELD_NAME),
13732        );
13733        assert_eq!(
13734            WitTarget::Store {
13735                slot: "checkout/$order",
13736            }
13737            .field_name(),
13738            Some(WitTarget::STORE_FIELD_NAME),
13739        );
13740        // Capability arm carries no payload field — the diagnostic
13741        // never reports `expected: "capability"` because the gate's
13742        // Capability arm accepts no payload at all (it fires the
13743        // "expected: none" WrongTarget error instead), so the field-
13744        // name method returns None here rather than a placeholder.
13745        assert_eq!(WitTarget::Capability.field_name(), None);
13746
13747        // Peer const scalar values pinned so a rename on either side
13748        // (author-surface field name in the `(defcaixa …)` DSL, or
13749        // the diagnostic's `expected:` scalar) can't drift without
13750        // failing here first.
13751        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
13752        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
13753        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
13754    }
13755
13756    #[test]
13757    fn wit_target_payload_pins_per_variant() {
13758        // Pin the per-arm payload scalar single-sourced onto the
13759        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
13760        // [`WitTarget::payload`] — the peer per-half projection to
13761        // [`WitTarget::field_name`] on the paired sub-selector axis. The
13762        // three payload-carrying arms round-trip their author-declared
13763        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
13764        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
13765        // the payload-less [`WitTarget::Capability`] arm returns `None`.
13766        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
13767        // (c6ec2af) pin on the Component-0 projection axis, extended
13768        // onto the Component-1 projection axis so both per-half readers
13769        // on the paired dispatch carry their own byte-shape pin.
13770        assert_eq!(
13771            WitTarget::Http {
13772                endpoint: "/charge",
13773            }
13774            .payload(),
13775            Some("/charge"),
13776        );
13777        assert_eq!(
13778            WitTarget::PubSub {
13779                subject: "events.x",
13780            }
13781            .payload(),
13782            Some("events.x"),
13783        );
13784        assert_eq!(
13785            WitTarget::Store {
13786                slot: "checkout/$order",
13787            }
13788            .payload(),
13789            Some("checkout/$order"),
13790        );
13791        assert_eq!(WitTarget::Capability.payload(), None);
13792    }
13793
13794    #[test]
13795    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
13796        // Per-variant equivalence pin: for every arm of [`WitTarget`],
13797        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
13798        // byte-for-byte. Guards the drift surface where a future refactor
13799        // that split one accessor off the shared match onto its own
13800        // dispatch — a well-meaning "inline the pair back into per-half
13801        // fields for one crate-internal caller who only wanted one half"
13802        // or a scratch `impl` shadowing the derived projection — would
13803        // silently desynchronize [`WitTarget::payload`] from the
13804        // authoritative [`WitTarget::payload_pair`] dispatch, and every
13805        // downstream consumer that thinks "the payload half of the pair"
13806        // would drift from the diagnostic / graph consumers reading the
13807        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
13808        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
13809        // per-half projection pin (`gitrefspec_ref_pair_projects_
13810        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
13811        // FluxCD source-controller `spec.ref.<field>` axis — same "one
13812        // paired dispatch, both per-half projections agree byte-for-
13813        // byte" discipline extended onto the M3 `:contratos` payload-
13814        // arm surface.
13815        for variant in [
13816            WitTarget::Http {
13817                endpoint: "/charge",
13818            },
13819            WitTarget::PubSub {
13820                subject: "events.checkout.paid",
13821            },
13822            WitTarget::Store {
13823                slot: "checkout/$order",
13824            },
13825            WitTarget::Capability,
13826        ] {
13827            let via_projection = variant.payload();
13828            let via_pair = variant.payload_pair().map(|(_, p)| p);
13829            assert_eq!(
13830                via_projection, via_pair,
13831                "WitTarget::{variant:?} payload() must equal \
13832                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
13833                 regression that splits the two per-half projections off \
13834                 their shared match would silently desynchronize the \
13835                 payload accessor from the paired dispatch every \
13836                 diagnostic / graph consumer reads through",
13837            );
13838        }
13839    }
13840
13841    #[test]
13842    fn wit_target_http_endpoint_pins_per_variant() {
13843        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
13844        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
13845        // substrate-primitive per-arm post-projection accessor every
13846        // L7-HTTP-facing consumer routes through, sibling to the peer
13847        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
13848        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
13849        // arm round-trips its author-declared endpoint verbatim as
13850        // `Some("/charge")`; the three sibling arms
13851        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
13852        // [`WitTarget::Capability`]) each return `None` because they
13853        // carry no HTTP endpoint by definition. Same fail-before-pass-
13854        // after per-variant discipline as the sibling
13855        // `wit_target_payload_pins_per_variant` (5d6dc92) /
13856        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
13857        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
13858        // the peer pan-arm / per-half projection axes — extended onto
13859        // the per-arm HTTP-shape post-projection axis so a future
13860        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
13861        // [`WitTarget::Http`], a `Queue`-shaped peer of
13862        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
13863        // error on the sibling [`WitTarget::http_endpoint`] match arms
13864        // whose payload the L7-HTTP-shape accept-set is meant to bound.
13865        assert_eq!(
13866            WitTarget::Http {
13867                endpoint: "/charge",
13868            }
13869            .http_endpoint(),
13870            Some("/charge"),
13871        );
13872        assert_eq!(
13873            WitTarget::PubSub {
13874                subject: "events.checkout.paid",
13875            }
13876            .http_endpoint(),
13877            None,
13878        );
13879        assert_eq!(
13880            WitTarget::Store {
13881                slot: "checkout/$order",
13882            }
13883            .http_endpoint(),
13884            None,
13885        );
13886        assert_eq!(WitTarget::Capability.http_endpoint(), None);
13887    }
13888
13889    #[test]
13890    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
13891        // Per-variant coherence pin: for every arm of [`WitTarget`],
13892        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
13893        // arm (both project the same author-declared request-path
13894        // scalar), and returns `None` on every sibling arm regardless of
13895        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
13896        // Store carry their own payload the pan-arm accessor surfaces,
13897        // but that payload is not an HTTP endpoint — the per-arm
13898        // accessor must not leak it through the HTTP-shape channel).
13899        // Guards the drift surface where a future refactor that
13900        // conflated the per-arm HTTP projection with the pan-arm
13901        // [`WitTarget::payload`] projection — a well-meaning "one
13902        // accessor for the L7 branch, one for the graph" collapse that
13903        // routes both through the same 4-arm dispatch — would silently
13904        // widen the L7-HTTP-shape accept-set onto pub-sub / store
13905        // payloads at the caixa-mesh L7 emit branch, admitting a
13906        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
13907        // rule with the operator-side apply-time symptom (Cilium's
13908        // eBPF data-plane rejects every ingress edge whose L7 filter
13909        // doesn't match the wire-format HTTP request line) far from
13910        // the source refactor. Sibling to the peer
13911        // `wit_target_payload_matches_payload_pair_second_component_
13912        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
13913        // extended onto the per-arm HTTP specialization axis so both
13914        // the pan-arm and the per-arm projections carry their own
13915        // byte-shape coherence witness against the substrate's typed
13916        // arm-family accept-set.
13917        for variant in [
13918            WitTarget::Http {
13919                endpoint: "/charge",
13920            },
13921            WitTarget::PubSub {
13922                subject: "events.checkout.paid",
13923            },
13924            WitTarget::Store {
13925                slot: "checkout/$order",
13926            },
13927            WitTarget::Capability,
13928        ] {
13929            let per_arm = variant.http_endpoint();
13930            let pan_arm = variant.payload();
13931            if variant.is_http() {
13932                assert_eq!(
13933                    per_arm, pan_arm,
13934                    "WitTarget::{variant:?} http_endpoint() must equal \
13935                     payload() on the Http arm — a per-arm-vs-pan-arm \
13936                     split would silently drift the L7 emit branch's \
13937                     path-scalar source from the graph verb's payload \
13938                     scalar source",
13939                );
13940            } else {
13941                assert_eq!(
13942                    per_arm, None,
13943                    "WitTarget::{variant:?} http_endpoint() must return \
13944                     None on non-Http arms — a leak that surfaced a \
13945                     pub-sub :subject or a key/value :slot through the \
13946                     HTTP-endpoint accessor would silently widen the \
13947                     Cilium L7 HTTP `path:` rule accept-set onto \
13948                     protocol shapes Cilium's eBPF data-plane can't \
13949                     introspect",
13950                );
13951            }
13952        }
13953    }
13954
13955    #[test]
13956    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
13957        // Per-variant coherence pin: for every arm of [`WitTarget`],
13958        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
13959        // drift surface where a future extension of the
13960        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
13961        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
13962        // accessor to cover both peers) landed without a paired
13963        // extension of the [`gen_platform::IsVariant`]-derived
13964        // `is_http()` predicate's accept-set, or vice versa — a
13965        // regression that split the "which arms count as HTTP-shaped
13966        // for L7-path emission?" answer between two dispatch surfaces
13967        // the substrate ships. Sibling to the peer
13968        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
13969        // on the paired dispatch axis — extended onto the per-arm
13970        // predicate-vs-accessor coherence axis so the gen-platform
13971        // IsVariant predicate and the substrate-lifted per-arm
13972        // accessor carry one shared answer to "is this the HTTP arm?".
13973        for variant in [
13974            WitTarget::Http {
13975                endpoint: "/charge",
13976            },
13977            WitTarget::PubSub {
13978                subject: "events.checkout.paid",
13979            },
13980            WitTarget::Store {
13981                slot: "checkout/$order",
13982            },
13983            WitTarget::Capability,
13984        ] {
13985            assert_eq!(
13986                variant.http_endpoint().is_some(),
13987                variant.is_http(),
13988                "WitTarget::{variant:?} http_endpoint().is_some() must \
13989                 equal is_http() — a drift would split the L7 emit \
13990                 branch's arm-set gate from the substrate-derived \
13991                 shape-discrimination predicate on the same axis",
13992            );
13993        }
13994    }
13995
13996    #[test]
13997    fn wit_target_pubsub_subject_pins_per_variant() {
13998        // Fail-before-pass-after pin: the substrate-canonical per-arm
13999        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
14000        // is the single dispatch every future pub-sub-facing consumer
14001        // routes through, sibling to the peer [`WitContract::subject`]
14002        // (63e18a0) pre-projection scalar accessor on the raw-field
14003        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
14004        // post-projection per-arm accessor on the sibling HTTP-shape
14005        // axis. The [`WitTarget::PubSub`] arm round-trips its
14006        // author-declared subject verbatim as
14007        // `Some("events.checkout.paid")`; the three sibling arms each
14008        // return `None` because they carry no NATS-shaped subject by
14009        // definition. Same fail-before-pass-after per-variant discipline
14010        // as the sibling `wit_target_http_endpoint_pins_per_variant`
14011        // pin on the peer per-arm axis — extended onto the per-arm
14012        // pub-sub-shape post-projection axis so a future [`WitTarget`]
14013        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
14014        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
14015        // compile-time exhaustiveness error on the sibling
14016        // [`WitTarget::pubsub_subject`] match arms whose payload the
14017        // pub-sub-shape accept-set is meant to bound.
14018        assert_eq!(
14019            WitTarget::PubSub {
14020                subject: "events.checkout.paid",
14021            }
14022            .pubsub_subject(),
14023            Some("events.checkout.paid"),
14024        );
14025        assert_eq!(
14026            WitTarget::Http {
14027                endpoint: "/charge",
14028            }
14029            .pubsub_subject(),
14030            None,
14031        );
14032        assert_eq!(
14033            WitTarget::Store {
14034                slot: "checkout/$order",
14035            }
14036            .pubsub_subject(),
14037            None,
14038        );
14039        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
14040    }
14041
14042    #[test]
14043    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
14044        // Per-variant coherence pin: for every arm of [`WitTarget`],
14045        // `.pubsub_subject()` equals `.payload()` on the
14046        // [`WitTarget::PubSub`] arm (both project the same
14047        // author-declared subject scalar), and returns `None` on every
14048        // sibling arm regardless of whether [`WitTarget::payload`]
14049        // itself returns `Some` (Http / Store carry their own payload
14050        // the pan-arm accessor surfaces, but that payload is not a
14051        // pub-sub subject — the per-arm accessor must not leak it
14052        // through the pub-sub-shape channel). Sibling to the peer
14053        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
14054        // coherence pin on the per-arm HTTP-shape axis — extended onto
14055        // the per-arm pub-sub specialization axis so both per-arm
14056        // projections carry their own byte-shape coherence witness
14057        // against the substrate's typed arm-family accept-set.
14058        for variant in [
14059            WitTarget::Http {
14060                endpoint: "/charge",
14061            },
14062            WitTarget::PubSub {
14063                subject: "events.checkout.paid",
14064            },
14065            WitTarget::Store {
14066                slot: "checkout/$order",
14067            },
14068            WitTarget::Capability,
14069        ] {
14070            let per_arm = variant.pubsub_subject();
14071            let pan_arm = variant.payload();
14072            if variant.is_pubsub() {
14073                assert_eq!(
14074                    per_arm, pan_arm,
14075                    "WitTarget::{variant:?} pubsub_subject() must equal \
14076                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
14077                     split would silently drift the pub-sub-shape emit \
14078                     branch's subject-scalar source from the graph verb's \
14079                     payload scalar source",
14080                );
14081            } else {
14082                assert_eq!(
14083                    per_arm, None,
14084                    "WitTarget::{variant:?} pubsub_subject() must return \
14085                     None on non-PubSub arms — a leak that surfaced an \
14086                     HTTP :endpoint or a key/value :slot through the \
14087                     pub-sub-subject accessor would silently widen the \
14088                     downstream NATS-shape accept-set onto protocol \
14089                     shapes NATS servers can't route",
14090                );
14091            }
14092        }
14093    }
14094
14095    #[test]
14096    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
14097        // Per-variant coherence pin: for every arm of [`WitTarget`],
14098        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
14099        // drift surface where a future extension of the
14100        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
14101        // without a paired extension of the [`gen_platform::IsVariant`]-
14102        // derived `is_pubsub()` predicate's accept-set, or vice versa
14103        // — a regression that split the "which arms count as pub-sub-
14104        // shaped for subject emission?" answer between two dispatch
14105        // surfaces the substrate ships. Sibling to the peer
14106        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
14107        // pin on the per-arm HTTP-shape axis — extended onto the
14108        // per-arm pub-sub predicate-vs-accessor coherence axis so the
14109        // gen-platform IsVariant predicate and the substrate-lifted
14110        // per-arm accessor carry one shared answer to "is this the
14111        // PubSub arm?".
14112        for variant in [
14113            WitTarget::Http {
14114                endpoint: "/charge",
14115            },
14116            WitTarget::PubSub {
14117                subject: "events.checkout.paid",
14118            },
14119            WitTarget::Store {
14120                slot: "checkout/$order",
14121            },
14122            WitTarget::Capability,
14123        ] {
14124            assert_eq!(
14125                variant.pubsub_subject().is_some(),
14126                variant.is_pubsub(),
14127                "WitTarget::{variant:?} pubsub_subject().is_some() must \
14128                 equal is_pubsub() — a drift would split the pub-sub \
14129                 emit branch's arm-set gate from the substrate-derived \
14130                 shape-discrimination predicate on the same axis",
14131            );
14132        }
14133    }
14134
14135    #[test]
14136    fn wit_target_store_slot_pins_per_variant() {
14137        // Fail-before-pass-after pin: the substrate-canonical per-arm
14138        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
14139        // is the single dispatch every future store-facing consumer
14140        // routes through, sibling to the peer [`WitContract::slot`]
14141        // pre-projection scalar accessor on the raw-field axis and to
14142        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
14143        // [`WitTarget::pubsub_subject`] post-projection per-arm
14144        // accessors on the sibling per-payload-arm axes. The
14145        // [`WitTarget::Store`] arm round-trips its author-declared
14146        // slot verbatim as `Some("checkout/$order")`; the three
14147        // sibling arms each return `None` because they carry no
14148        // WASI-key/value slot by definition. Same fail-before-pass-
14149        // after per-variant discipline as the sibling
14150        // `wit_target_http_endpoint_pins_per_variant` +
14151        // `wit_target_pubsub_subject_pins_per_variant` pins on the
14152        // peer per-arm axes — extended onto the per-arm store-shape
14153        // post-projection axis so a future [`WitTarget`] variant
14154        // addition trips a compile-time exhaustiveness error on the
14155        // sibling [`WitTarget::store_slot`] match arms whose payload
14156        // the store-shape accept-set is meant to bound.
14157        assert_eq!(
14158            WitTarget::Store {
14159                slot: "checkout/$order",
14160            }
14161            .store_slot(),
14162            Some("checkout/$order"),
14163        );
14164        assert_eq!(
14165            WitTarget::Http {
14166                endpoint: "/charge",
14167            }
14168            .store_slot(),
14169            None,
14170        );
14171        assert_eq!(
14172            WitTarget::PubSub {
14173                subject: "events.checkout.paid",
14174            }
14175            .store_slot(),
14176            None,
14177        );
14178        assert_eq!(WitTarget::Capability.store_slot(), None);
14179    }
14180
14181    #[test]
14182    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
14183        // Per-variant coherence pin: for every arm of [`WitTarget`],
14184        // `.store_slot()` equals `.payload()` on the
14185        // [`WitTarget::Store`] arm (both project the same
14186        // author-declared slot scalar), and returns `None` on every
14187        // sibling arm regardless of whether [`WitTarget::payload`]
14188        // itself returns `Some`. Sibling to the peer
14189        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
14190        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
14191        // pins on the per-arm HTTP and PubSub axes — closes the
14192        // per-arm-vs-pan-arm byte-shape coherence trio across all
14193        // three payload arms.
14194        for variant in [
14195            WitTarget::Http {
14196                endpoint: "/charge",
14197            },
14198            WitTarget::PubSub {
14199                subject: "events.checkout.paid",
14200            },
14201            WitTarget::Store {
14202                slot: "checkout/$order",
14203            },
14204            WitTarget::Capability,
14205        ] {
14206            let per_arm = variant.store_slot();
14207            let pan_arm = variant.payload();
14208            if variant.is_store() {
14209                assert_eq!(
14210                    per_arm, pan_arm,
14211                    "WitTarget::{variant:?} store_slot() must equal \
14212                     payload() on the Store arm — a per-arm-vs-pan-arm \
14213                     split would silently drift the store-shape emit \
14214                     branch's slot-scalar source from the graph verb's \
14215                     payload scalar source",
14216                );
14217            } else {
14218                assert_eq!(
14219                    per_arm, None,
14220                    "WitTarget::{variant:?} store_slot() must return \
14221                     None on non-Store arms — a leak that surfaced an \
14222                     HTTP :endpoint or a NATS :subject through the \
14223                     key/value-slot accessor would silently widen the \
14224                     downstream WASI-key/value slot accept-set onto \
14225                     protocol shapes the kv backends can't route",
14226                );
14227            }
14228        }
14229    }
14230
14231    #[test]
14232    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
14233        // Per-variant coherence pin: for every arm of [`WitTarget`],
14234        // `.store_slot().is_some()` iff `.is_store()`. Guards the
14235        // drift surface where a future extension of the
14236        // [`WitTarget::store_slot`] accessor's accept-set landed
14237        // without a paired extension of the [`gen_platform::IsVariant`]-
14238        // derived `is_store()` predicate's accept-set. Sibling to the
14239        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
14240        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
14241        // pins — closes the per-arm predicate-vs-accessor coherence
14242        // trio across all three payload arms so the gen-platform
14243        // IsVariant predicate and the substrate-lifted per-arm
14244        // accessor carry one shared answer to "is this the Store arm?".
14245        for variant in [
14246            WitTarget::Http {
14247                endpoint: "/charge",
14248            },
14249            WitTarget::PubSub {
14250                subject: "events.checkout.paid",
14251            },
14252            WitTarget::Store {
14253                slot: "checkout/$order",
14254            },
14255            WitTarget::Capability,
14256        ] {
14257            assert_eq!(
14258                variant.store_slot().is_some(),
14259                variant.is_store(),
14260                "WitTarget::{variant:?} store_slot().is_some() must \
14261                 equal is_store() — a drift would split the store-shape \
14262                 emit branch's arm-set gate from the substrate-derived \
14263                 shape-discrimination predicate on the same axis",
14264            );
14265        }
14266    }
14267
14268    #[test]
14269    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
14270        // Fail-before-pass-after cross-axis pin on the trio
14271        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
14272        // payload-carrying arm of [`WitTarget`], exactly one per-arm
14273        // accessor returns `Some(payload)` and the two peers return
14274        // `None`; and on the payload-less [`WitTarget::Capability`]
14275        // arm, all three return `None`. Guards the drift surface where
14276        // a future extension of one per-arm accessor's accept-set (e.g.
14277        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
14278        // that widened `http_endpoint` to cover both peers without
14279        // narrowing the peer `pubsub_subject` / `store_slot` accept-
14280        // sets to keep the partition mutually exclusive) landed without
14281        // threading through the peer per-arm accessors — the resulting
14282        // silent overlap would land the same edge's payload on two
14283        // downstream per-shape emit branches at once, or leak a
14284        // pub-sub subject through the store-slot channel, at renderer
14285        // emit time far from the substrate primitive's arm-widening
14286        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
14287        // 3-way pin on the payload-field-name axis — extended onto the
14288        // per-arm-accessor payload-projection axis so the substrate-
14289        // owned partition invariant is load-bearing at every per-arm
14290        // consumer's read site.
14291        let payload_variants = [
14292            (
14293                WitTarget::Http {
14294                    endpoint: "/charge",
14295                },
14296                "http",
14297            ),
14298            (
14299                WitTarget::PubSub {
14300                    subject: "events.checkout.paid",
14301                },
14302                "pubsub",
14303            ),
14304            (
14305                WitTarget::Store {
14306                    slot: "checkout/$order",
14307                },
14308                "store",
14309            ),
14310        ];
14311        for (variant, own_arm_label) in payload_variants {
14312            let own_arm_hit = match own_arm_label {
14313                "http" => variant.is_http(),
14314                "pubsub" => variant.is_pubsub(),
14315                "store" => variant.is_store(),
14316                other => panic!("unknown own-arm label {other:?}"),
14317            };
14318            let per_arm_results = [
14319                ("http_endpoint", variant.http_endpoint()),
14320                ("pubsub_subject", variant.pubsub_subject()),
14321                ("store_slot", variant.store_slot()),
14322            ];
14323            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
14324            assert_eq!(
14325                some_count, 1,
14326                "WitTarget::{variant:?} must land exactly one per-arm \
14327                 post-projection accessor's Some result — the trio \
14328                 (http_endpoint, pubsub_subject, store_slot) must \
14329                 partition the payload arm-set; got {per_arm_results:?}",
14330            );
14331            assert!(
14332                own_arm_hit,
14333                "WitTarget::{variant:?} own-arm gen-platform predicate \
14334                 must return true on its own arm — a partition failure \
14335                 upstream of this pin",
14336            );
14337            assert!(
14338                variant.payload().is_some(),
14339                "WitTarget::{variant:?} pan-arm payload() must return \
14340                 Some on every payload-carrying arm the trio partitions",
14341            );
14342        }
14343        // The payload-less Capability arm must return None on every
14344        // per-arm accessor — the partition's terminal-fallback shape.
14345        let cap = WitTarget::Capability;
14346        assert_eq!(cap.http_endpoint(), None);
14347        assert_eq!(cap.pubsub_subject(), None);
14348        assert_eq!(cap.store_slot(), None);
14349        assert_eq!(
14350            cap.payload(),
14351            None,
14352            "WitTarget::Capability pan-arm payload() must return None — \
14353             the trio's payload-less-arm coherence witness",
14354        );
14355    }
14356
14357    #[test]
14358    fn wit_target_field_names_are_pairwise_distinct() {
14359        // Distinctness pin: if any two of the three payload-field-name
14360        // scalars ever collapse (e.g. an accidental `endpoint` copy-
14361        // paste over the `subject` const), the [`WitContract::target`]
14362        // gate's diagnostic would point authors at the wrong field —
14363        // an "expected `:endpoint`" error on a pub-sub edge would
14364        // silently misroute the fix. Same cross-axis-distinctness
14365        // discipline as the peer M3 `:placement :estrategia` variant-
14366        // discriminator scalar-value pins (cc8f749) applied to the
14367        // payload-field-name axis.
14368        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
14369        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
14370        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
14371    }
14372
14373    #[test]
14374    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
14375        // Fail-before-pass-after pin: the graph-verb payload column's
14376        // per-arm `{field}={payload}` byte-string is derived through the
14377        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
14378        // payload-carrying arms, not through a hand-rolled per-arm match
14379        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
14380        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14381        // inline. A future variant addition — the M4-and-later per-edge
14382        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
14383        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
14384        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
14385        // and both [`WitTarget::label`] (duplicate-`:contratos`
14386        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
14387        // payload column) pick up the new arm from the same dispatch.
14388        // Prior to this lift the graph verb open-coded the 4-arm match
14389        // in caixa-feira, so a variant addition would have to be threaded
14390        // through both projections in lockstep or the graph verb would
14391        // silently drop the new arm to `(capability-only)`.
14392        for variant in [
14393            WitTarget::Http {
14394                endpoint: "/charge",
14395            },
14396            WitTarget::PubSub {
14397                subject: "events.checkout.paid",
14398            },
14399            WitTarget::Store {
14400                slot: "checkout/$order",
14401            },
14402        ] {
14403            let (field, payload) = variant
14404                .payload_pair()
14405                .expect("payload arm must expose (field, payload)");
14406            assert_eq!(
14407                variant.graph_label(),
14408                format!("{field}={payload}"),
14409                "WitTarget::{variant:?} graph_label must route the \
14410                 `{{field}}={{payload}}` template through payload_pair — \
14411                 a regression to a hand-rolled per-arm match at the graph \
14412                 verb would silently disagree with a future variant \
14413                 addition landed only at payload_pair"
14414            );
14415        }
14416    }
14417
14418    #[test]
14419    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
14420        // Fail-before-pass-after pin on the payload-less arm: the graph
14421        // verb's `(capability-only)` byte-string routes through the
14422        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
14423        // [`WitTarget::Capability`] arm, not through an inline
14424        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
14425        // per-`:contratos` payload column. Peer of the sibling
14426        // [`wit_target_label_pins_per_variant_format`] Capability-arm
14427        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
14428        // extended here onto the third payload-less-arm consumer axis
14429        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
14430        // axis and the wrong-target diagnostic axis).
14431        assert_eq!(
14432            WitTarget::Capability.graph_label(),
14433            WitTarget::CAPABILITY_GRAPH_LABEL,
14434        );
14435        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
14436    }
14437
14438    #[test]
14439    fn wit_target_capability_graph_label_distinct_from_capability_label() {
14440        // Cross-consumer-axis distinctness pin: the graph-verb
14441        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
14442        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
14443        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
14444        // payload)`) surface the payload-less arm on two distinct
14445        // consumer axes; a collapse (an accidental rebrand that lands
14446        // one spelling on both consts, a copy-paste that unifies them
14447        // "for consistency") would silently merge the two byte-strings
14448        // and lose the vocabulary distinction the graph verb's
14449        // compact-column form and the diagnostic's descriptive-clause
14450        // form each carry on purpose. Peer of the sibling 4-way
14451        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
14452        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
14453        // extended here onto the cross-consumer-axis distinctness of the
14454        // two payload-less-arm consts.
14455        assert_ne!(
14456            WitTarget::CAPABILITY_GRAPH_LABEL,
14457            WitTarget::CAPABILITY_LABEL,
14458            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
14459             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
14460             diagnostic) must remain distinct — a collapse would silently \
14461             merge two consumer axes onto one spelling"
14462        );
14463    }
14464
14465    #[test]
14466    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
14467        // 4-way distinctness pin extending the sibling
14468        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
14469        // (which covers only the HTTP / PubSub / Store payload arms)
14470        // onto the fourth scalar the shared
14471        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
14472        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
14473        // (`"none"`), the payload-less Capability-arm rejection scalar.
14474        //
14475        // All four [`WitTarget::HTTP_FIELD_NAME`] /
14476        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14477        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
14478        // dispatch surface [`WitContract::target`] writes onto the
14479        // `ContratoWrongTarget::expected` field — the same `&'static
14480        // str` axis authors read as "this WIT world's shape admits
14481        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
14482        // downstream consumers rely on: an `expected: "endpoint"`
14483        // diagnostic on a Capability-shaped edge tells the author to
14484        // add a `:endpoint "…"` slot to a WIT world that admits none,
14485        // silently misrouting the fix. Until this pin landed the three
14486        // payload-arm consts were distinctness-guarded by the sibling
14487        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
14488        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
14489        // author-facing vocabulary shift from `"none"` to `"endpoint"`
14490        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
14491        // into per-shape peers) would have silently landed one
14492        // Capability-arm rejection on a payload-arm's `expected:` byte-
14493        // string and desynchronized the diagnostic from the author's
14494        // typed shape.
14495        //
14496        // Same 4-way pairwise-distinctness pin discipline as the peer
14497        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
14498        // (cc8f749) applies on the sibling M3 closed-set typed-enum
14499        // scalar-value dispatch axis; extends the pin trajectory the
14500        // sibling `wit_target_field_names_are_pairwise_distinct`
14501        // 3-way pin opened to cover the last unguarded corner on the
14502        // `ContratoWrongTarget::expected` scalar-value axis.
14503        //
14504        // Fail-before-pass-after locally verified by mutating
14505        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
14506        // — this pin fires as expected; restoring passes.
14507        let all = [
14508            WitTarget::HTTP_FIELD_NAME,
14509            WitTarget::PUBSUB_FIELD_NAME,
14510            WitTarget::STORE_FIELD_NAME,
14511            WitTarget::CAPABILITY_EXPECTED,
14512        ];
14513        for (i, a) in all.iter().enumerate() {
14514            for (j, b) in all.iter().enumerate() {
14515                if i != j {
14516                    assert_ne!(
14517                        a, b,
14518                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
14519                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
14520                         pairwise distinct — got duplicate {a:?} at indices \
14521                         {i} and {j}; all four scalars thread through the \
14522                         shared `AplicacaoError::ContratoWrongTarget::expected` \
14523                         &'static str axis, so a collapse silently misdirects \
14524                         the diagnostic on which typed shape the WIT world admits",
14525                    );
14526                }
14527            }
14528        }
14529    }
14530
14531    #[test]
14532    fn wit_target_is_variant_predicates_partition_the_arm_set() {
14533        // Fail-before-pass-after pin on the
14534        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
14535        // each of the four variants exactly one of the generated
14536        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
14537        // predicates returns `true` and the other three return
14538        // `false`. Prior to this derive the only production
14539        // arm-discriminator on [`WitTarget`] — the sync-cycle
14540        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
14541        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
14542        // the variant that expressed no compile-time link back to
14543        // the closed-set typed dispatch a future fifth
14544        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
14545        // split of [`WitTarget::PubSub`] into shape-specific peers,
14546        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
14547        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
14548        // to thread through in lockstep or the DFS exclusion would
14549        // silently disagree with the peer diagnostic templates on
14550        // which arms carry sync-versus-async semantics. Peer of the
14551        // sibling [`crate::CaixaKind`] (f5bba80),
14552        // [`PlacementStrategy`] (766ec63),
14553        // [`crate::supervisor::RestartStrategy`],
14554        // [`crate::supervisor::RestartPolicy`], and
14555        // [`crate::upgrade::UpgradeInstruction`] (915a934)
14556        // `IsVariant` derives on the sibling closed-set typed-enum
14557        // discriminator axes — extends the same one-typed-dispatch-
14558        // per-variant discipline onto the last unlifted closed-set
14559        // typed-enum discriminator on the caixa surface (the M3
14560        // mesh-slot per-`:contratos` target-arm axis), closing the
14561        // arm-discriminator convergence trajectory across every
14562        // closed-set typed enum in caixa-core.
14563        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
14564            (
14565                WitTarget::Http { endpoint: "/x" },
14566                [true, false, false, false],
14567            ),
14568            (
14569                WitTarget::PubSub {
14570                    subject: "events.x",
14571                },
14572                [false, true, false, false],
14573            ),
14574            (
14575                WitTarget::Store { slot: "kv/x" },
14576                [false, false, true, false],
14577            ),
14578            (WitTarget::Capability, [false, false, false, true]),
14579        ];
14580        for (variant, expected) in rows {
14581            let observed = [
14582                variant.is_http(),
14583                variant.is_pubsub(),
14584                variant.is_store(),
14585                variant.is_capability(),
14586            ];
14587            assert_eq!(
14588                observed, expected,
14589                "WitTarget::{variant:?} is_* predicates must partition \
14590                 the arm set (http, pubsub, store, capability); got {observed:?}"
14591            );
14592        }
14593    }
14594
14595    #[test]
14596    fn wit_target_is_variant_predicates_are_const_fn() {
14597        // The [`gen_platform::IsVariant`] derive emits `const fn`
14598        // predicates on the peer [`crate::CaixaKind`] +
14599        // [`crate::upgrade::UpgradeInstruction`] +
14600        // [`crate::supervisor::RestartStrategy`] +
14601        // [`crate::supervisor::RestartPolicy`] +
14602        // [`PlacementStrategy`] closed-set typed enums — pin the
14603        // same posture on [`WitTarget`] so a future accidental
14604        // downgrade to non-`const` (an added runtime helper reachable
14605        // only from a non-`const` context, a manual hand-rolled
14606        // `impl` that shadows the derive-generated method) trips at
14607        // caixa-core build time rather than surfacing as a downstream
14608        // `const`-context regression far from the derive declaration.
14609        //
14610        // Unlike the peer unit-variant enums (`CaixaKind` /
14611        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
14612        // whose `const` constructors need no arguments, the three
14613        // payload-carrying [`WitTarget`] arms are const-constructed
14614        // through `&'static str` payloads — the same `'static`
14615        // lifetime the closed-set typed enum's four-arm partition
14616        // pin above already threads through.
14617        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
14618        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
14619        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
14620        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
14621        const IS_HTTP: bool = HTTP.is_http();
14622        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
14623        const IS_STORE: bool = STORE.is_store();
14624        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
14625        assert!(IS_HTTP);
14626        assert!(IS_PUBSUB);
14627        assert!(IS_STORE);
14628        assert!(IS_CAPABILITY);
14629    }
14630
14631    #[test]
14632    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
14633        // Consumer-side pin on the sole production converge site:
14634        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
14635        // edges from the synchronous-subgraph DFS via the lifted
14636        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
14637        // predicate (rebound from the prior raw
14638        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
14639        // variant). Byte-equivalent today (`is_pubsub` is the
14640        // derive-generated `matches!(self, Self::PubSub { .. })` by
14641        // construction, the `#[is_variant(name = "pubsub")]` override
14642        // aliasing the auto-derived `is_pub_sub` back to the sibling
14643        // [`WitContract::is_pubsub`] name); pin the behavior so a
14644        // future accidental drift (a rebind onto a peer arm
14645        // predicate, a manual hand-rolled `impl` that shadows the
14646        // derive-generated method with different semantics, a peer
14647        // arm rename that shifts which variant carries sync-versus-
14648        // async semantics) trips at caixa-core test time rather than
14649        // at some downstream operator's runtime dispatch far from the
14650        // rebind commit.
14651        //
14652        // The fixture constructs a two-Servico Aplicacao with one
14653        // pub-sub edge that would close a sync-cycle if the DFS did
14654        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
14655        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
14656        // edge, which is not a cycle. A regression in the converge
14657        // (a rebind that reads the pub-sub arm as sync) would report
14658        // `AplicacaoError::ContratoCycle`.
14659        let s = AplicacaoSpec {
14660            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
14661            contratos: vec![
14662                // Pub-sub edge: DFS must skip via is_pubsub().
14663                WitContract {
14664                    de: "a".into(),
14665                    para: "b".into(),
14666                    wit: "nats:pub-sub".into(),
14667                    endpoint: None,
14668                    subject: Some("events.x".into()),
14669                    slot: None,
14670                },
14671                // HTTP edge: DFS must include.
14672                WitContract {
14673                    de: "b".into(),
14674                    para: "a".into(),
14675                    wit: "wasi:http/proxy".into(),
14676                    endpoint: Some("/x".into()),
14677                    subject: None,
14678                    slot: None,
14679                },
14680            ],
14681            politicas: MeshPolicy::default(),
14682            placement: Placement {
14683                estrategia: PlacementStrategy::Replicated,
14684                clusters: vec!["rio".into()],
14685                affinity: None,
14686                shard_key: None,
14687            },
14688            entrada: None,
14689        };
14690        s.validate()
14691            .expect("pub-sub edge must be excluded from sync-cycle DFS");
14692    }
14693
14694    #[test]
14695    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
14696        // Consumer-side pin: the same three peer consts thread through
14697        // both the [`WitTarget::label`] template (leading-`:` keyword
14698        // prefix in the duplicate-`:contratos` diagnostic) and the
14699        // [`WitContract::target`] gate's [`AplicacaoError::
14700        // ContratoMissingTarget`] `expected:` scalar (the field the
14701        // author needs to add). Pin both routes at once so a future
14702        // refactor can't accidentally split them onto separate string
14703        // literals — the "one place, everywhere reaches for it"
14704        // invariant the peer const set carries.
14705        let http_label = WitTarget::Http { endpoint: "/x" }.label();
14706        assert!(
14707            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
14708            "label must lead with :{} keyword (got {http_label:?})",
14709            WitTarget::HTTP_FIELD_NAME,
14710        );
14711
14712        let mut s = three_member_spec();
14713        s.contratos.push(WitContract {
14714            de: "cart".into(),
14715            para: "catalog".into(),
14716            wit: "kafka:topic".into(),
14717            endpoint: None,
14718            subject: None,
14719            slot: None,
14720        });
14721        match s.validate().unwrap_err() {
14722            AplicacaoError::ContratoMissingTarget { expected, .. } => {
14723                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
14724            }
14725            other => panic!("expected ContratoMissingTarget, got {other:?}"),
14726        }
14727    }
14728
14729    #[test]
14730    fn duplicate_pubsub_diagnostic_names_offending_subject() {
14731        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
14732        // on the pub-sub target axis: the duplicate-edge diagnostic
14733        // must name the `:subject` payload verbatim (not just the
14734        // `(de, para, wit)` triple). Prior to lifting the label onto
14735        // [`WitTarget::label`] the diagnostic derived the label from
14736        // raw [`WitContract`] `Option<String>` probes — a future
14737        // `WitTarget` variant addition (M4 per-edge WIT registry)
14738        // would silently fall through to the `Capability` "no
14739        // payload" default without a compiler warning. Pinning the
14740        // pub-sub arm's format closes the second of three
14741        // payload-carrying `WitTarget` arms this diagnostic threads
14742        // through.
14743        let mut s = three_member_spec();
14744        let pubsub = WitContract {
14745            de: "payment".into(),
14746            para: "cart".into(),
14747            wit: "nats:pub-sub".into(),
14748            endpoint: None,
14749            subject: Some("events.checkout.paid".into()),
14750            slot: None,
14751        };
14752        s.contratos.push(pubsub.clone());
14753        s.contratos.push(pubsub);
14754        let err = s.validate().unwrap_err();
14755        let msg = format!("{err}");
14756        assert!(
14757            msg.contains(":subject \"events.checkout.paid\""),
14758            "duplicate-pubsub diagnostic must name the offending \
14759             :subject payload (got: {msg:?})"
14760        );
14761    }
14762
14763    #[test]
14764    fn duplicate_store_diagnostic_names_offending_slot() {
14765        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
14766        // key-value target axis: the diagnostic must name the `:slot`
14767        // payload verbatim. Third of three payload-carrying
14768        // `WitTarget` arms this diagnostic threads through, closing
14769        // the per-arm label pin trilogy (`Http` — 6841,
14770        // `PubSub` + `Store` — this test + peer above).
14771        let mut s = three_member_spec();
14772        let store = WitContract {
14773            de: "cart".into(),
14774            para: "payment".into(),
14775            wit: "wasi:keyvalue/store".into(),
14776            endpoint: None,
14777            subject: None,
14778            slot: Some("checkout/$orderId".into()),
14779        };
14780        s.contratos
14781            .retain(|c| !(c.de == "cart" && c.para == "payment"));
14782        s.contratos.push(store.clone());
14783        s.contratos.push(store);
14784        let err = s.validate().unwrap_err();
14785        let msg = format!("{err}");
14786        assert!(
14787            msg.contains(":slot \"checkout/$orderId\""),
14788            "duplicate-store diagnostic must name the offending :slot \
14789             payload (got: {msg:?})"
14790        );
14791    }
14792
14793    #[test]
14794    fn rejects_entrada_path_without_leading_slash() {
14795        let mut s = three_member_spec();
14796        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
14797        let err = s.validate().unwrap_err();
14798        assert!(
14799            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
14800            "got {err:?}"
14801        );
14802    }
14803
14804    #[test]
14805    fn rejects_empty_entrada_path() {
14806        let mut s = three_member_spec();
14807        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
14808        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14809    }
14810
14811    #[test]
14812    fn rejects_duplicate_entrada_paths() {
14813        let mut s = three_member_spec();
14814        s.entrada.as_mut().unwrap().paths = vec![
14815            "/api/cart".into(),
14816            "/api/products".into(),
14817            "/api/cart".into(),
14818        ];
14819        let err = s.validate().unwrap_err();
14820        assert!(
14821            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
14822            "got {err:?}"
14823        );
14824    }
14825
14826    #[test]
14827    fn rejects_zero_entrada_port() {
14828        let mut s = three_member_spec();
14829        s.entrada.as_mut().unwrap().port = 0;
14830        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
14831    }
14832
14833    // ── :entrada :paths value-shape gate ─────────────────────────────
14834    //
14835    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
14836    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
14837    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
14838    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
14839    // time now becomes a caixa-build-time `EntradaPathInvalid` with
14840    // the offending `:paths` entry named verbatim.
14841
14842    #[test]
14843    fn rejects_entrada_path_with_query() {
14844        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
14845        // silently passed validate and the Gateway API webhook
14846        // rejected it at apply time with no source citation.
14847        let mut s = three_member_spec();
14848        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
14849        let err = s.validate().unwrap_err();
14850        assert!(
14851            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14852                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
14853            "got {err:?}"
14854        );
14855    }
14856
14857    #[test]
14858    fn rejects_entrada_path_with_fragment() {
14859        let mut s = three_member_spec();
14860        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
14861        let err = s.validate().unwrap_err();
14862        assert!(
14863            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14864                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
14865            "got {err:?}"
14866        );
14867    }
14868
14869    #[test]
14870    fn rejects_entrada_path_with_space() {
14871        let mut s = three_member_spec();
14872        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
14873        let err = s.validate().unwrap_err();
14874        assert!(
14875            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14876                if path == "/api/my cart" && reason.contains("whitespace")),
14877            "got {err:?}"
14878        );
14879    }
14880
14881    #[test]
14882    fn rejects_entrada_path_with_tab() {
14883        let mut s = three_member_spec();
14884        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
14885        let err = s.validate().unwrap_err();
14886        assert!(
14887            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14888                if path == "/api/\tcart" && reason.contains("whitespace")),
14889            "got {err:?}"
14890        );
14891    }
14892
14893    #[test]
14894    fn rejects_entrada_path_with_control_char() {
14895        // 0x01 (SOH) — a non-whitespace control char surfaces the
14896        // distinct "control character" reason arm, separate from
14897        // the whitespace arm. Pinned so a future refactor that
14898        // collapses the two arms can't accidentally drop the more
14899        // self-locating diagnostic.
14900        let mut s = three_member_spec();
14901        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
14902        let err = s.validate().unwrap_err();
14903        assert!(
14904            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14905                if path == "/api/\x01cart" && reason.contains("control character")),
14906            "got {err:?}"
14907        );
14908    }
14909
14910    #[test]
14911    fn rejects_entrada_path_with_non_ascii() {
14912        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
14913        // unreserved-set rule rejects. The Gateway API webhook
14914        // rejects literal non-ASCII bytes; percent-encoding is the
14915        // only way to author non-ASCII in a path.
14916        let mut s = three_member_spec();
14917        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
14918        let err = s.validate().unwrap_err();
14919        assert!(
14920            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14921                if path == "/api/café" && reason.contains("non-ASCII")),
14922            "got {err:?}"
14923        );
14924    }
14925
14926    #[test]
14927    fn rejects_entrada_path_with_consecutive_slashes() {
14928        let mut s = three_member_spec();
14929        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
14930        let err = s.validate().unwrap_err();
14931        assert!(
14932            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14933                if path == "/api//cart" && reason.contains("consecutive `/`")),
14934            "got {err:?}"
14935        );
14936    }
14937
14938    #[test]
14939    fn rejects_entrada_path_with_dot_segment() {
14940        let mut s = three_member_spec();
14941        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
14942        let err = s.validate().unwrap_err();
14943        assert!(
14944            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14945                if path == "/api/./cart" && reason.contains("`.` segment")),
14946            "got {err:?}"
14947        );
14948    }
14949
14950    #[test]
14951    fn rejects_entrada_path_with_trailing_dot_segment() {
14952        // The bare `/.` and the trailing `/foo/.` are both rejected
14953        // by the Gateway API webhook; pinned separately so a future
14954        // narrowing that catches only the inner form surfaces here.
14955        let mut s = three_member_spec();
14956        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
14957        let err = s.validate().unwrap_err();
14958        assert!(
14959            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14960                if path == "/api/." && reason.contains("`.` segment")),
14961            "got {err:?}"
14962        );
14963    }
14964
14965    #[test]
14966    fn rejects_entrada_path_with_parent_segment() {
14967        let mut s = three_member_spec();
14968        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
14969        let err = s.validate().unwrap_err();
14970        assert!(
14971            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14972                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
14973            "got {err:?}"
14974        );
14975    }
14976
14977    #[test]
14978    fn rejects_entrada_path_with_trailing_parent_segment() {
14979        // Trailing `/..` — symmetric arm of the parent-segment rule,
14980        // pinned separately so a future relaxation that only checks
14981        // the inner form (`/../`) surfaces here.
14982        let mut s = three_member_spec();
14983        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
14984        let err = s.validate().unwrap_err();
14985        assert!(
14986            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14987                if path == "/api/.." && reason.contains("`..` parent-segment")),
14988            "got {err:?}"
14989        );
14990    }
14991
14992    #[test]
14993    fn rejects_entrada_path_too_long() {
14994        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
14995        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
14996        // ASCII-alphanumeric body so only the length rule fires.
14997        let mut s = three_member_spec();
14998        let big = format!("/api/{}", "a".repeat(1020));
14999        assert_eq!(big.len(), 1025);
15000        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
15001        let err = s.validate().unwrap_err();
15002        assert!(
15003            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15004                if path == &big && reason.contains("max length of 1024")),
15005            "got {err:?}"
15006        );
15007    }
15008
15009    #[test]
15010    fn entrada_path_max_length_validates() {
15011        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
15012        // maxLength cap. Boundary pin: drift in the cap surfaces here
15013        // and at `rejects_entrada_path_too_long` simultaneously.
15014        let mut s = three_member_spec();
15015        let big = format!("/api/{}", "a".repeat(1019));
15016        assert_eq!(big.len(), 1024);
15017        s.entrada.as_mut().unwrap().paths = vec![big];
15018        s.validate().unwrap();
15019    }
15020
15021    #[test]
15022    fn entrada_accepts_canonical_paths() {
15023        // Positive-control sweep — every form the Gateway API
15024        // apiserver accepts must round-trip through validate. Covers
15025        // the root catch-all, plain paths, dot-prefixed segments
15026        // (hidden-file-style, distinct from `.` and `..` segments
15027        // which are rejected), digit-bearing segments, the canonical
15028        // route-template `:param` form (`:` is RFC 3986 reserved-set
15029        // valid in paths), trailing-slash form, percent-encoded
15030        // segments, and an interior `..` *substring* (`/foo..bar` is
15031        // not the `..` segment and is allowed).
15032        for path in [
15033            "/",
15034            "/api/cart",
15035            "/healthz",
15036            "/api/.config",
15037            "/v1/products",
15038            "/products/:id",
15039            "/api/cart/",
15040            "/api/caf%C3%A9",
15041            "/foo..bar",
15042            "/...",
15043        ] {
15044            let mut s = three_member_spec();
15045            s.entrada.as_mut().unwrap().paths = vec![path.into()];
15046            s.validate()
15047                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
15048        }
15049    }
15050
15051    #[test]
15052    fn entrada_path_empty_takes_precedence_over_invalid() {
15053        // Ordering pin: `EntradaPathEmpty` is the more self-locating
15054        // diagnostic on `""` and must lead — `validate_entrada_path`
15055        // is only reached after the empty-check fires at the call
15056        // site. (The predicate itself defends against direct
15057        // invocation by returning the same error on `""`.)
15058        let mut s = three_member_spec();
15059        s.entrada.as_mut().unwrap().paths = vec!["".into()];
15060        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
15061    }
15062
15063    #[test]
15064    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
15065        // Ordering pin: a path without a leading `/` surfaces the
15066        // narrower `EntradaPathNotAbsolute` diagnostic first; the
15067        // value-shape gate is only consulted on paths that already
15068        // satisfy the absolute-prefix invariant.
15069        let mut s = three_member_spec();
15070        // `bad path` would fire the whitespace rule under the
15071        // value-shape gate, but missing-leading-`/` is the more
15072        // self-locating diagnostic.
15073        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
15074        let err = s.validate().unwrap_err();
15075        assert!(
15076            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
15077            "got {err:?}"
15078        );
15079    }
15080
15081    #[test]
15082    fn entrada_path_invalid_fires_before_duplicate_check() {
15083        // Ordering pin: a malformed path on the *first* entry of a
15084        // would-be duplicate pair fires the value-shape gate before
15085        // the duplicate gate, mirroring the
15086        // `placement_cluster_invalid_fires_before_duplicate_check`
15087        // (6cbb900) pattern on the peer axis.
15088        let mut s = three_member_spec();
15089        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
15090        let err = s.validate().unwrap_err();
15091        assert!(
15092            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
15093            "got {err:?}"
15094        );
15095    }
15096
15097    #[test]
15098    fn entrada_path_diagnostic_carries_offending_path() {
15099        // Diagnostic-shape pin — the offending path + a non-empty
15100        // reason flow through verbatim so the author can grep their
15101        // caixa.lisp for `:paths` and fix it in one edit. Same shape
15102        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
15103        let mut s = three_member_spec();
15104        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
15105        let err = s.validate().unwrap_err();
15106        match err {
15107            AplicacaoError::EntradaPathInvalid { path, reason } => {
15108                assert_eq!(path, "/api?q=1");
15109                assert!(!reason.is_empty(), "reason field must be non-empty");
15110            }
15111            other => panic!("expected EntradaPathInvalid, got {other:?}"),
15112        }
15113    }
15114
15115    #[test]
15116    fn rejects_entrada_path_with_curly_brace_template_form() {
15117        // Per-axis pin on the shared `is_gateway_api_http_path`
15118        // reserved-byte arm: the canonical "I wrote an OpenAPI
15119        // path-template `{id}` instead of the Gateway API `:id` form"
15120        // footgun the K8s apiserver would otherwise catch at admission
15121        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
15122        // landing site, far from the caixa.lisp. Surfaces as
15123        // `EntradaPathInvalid` carrying the offending path verbatim
15124        // plus the canonical `%7B`/`%7D` percent-encoding remediation
15125        // — the substrate-side `gateway_api_http_path_rejects_every_
15126        // reserved_printable_ascii_byte` predicate-level sweep pins the
15127        // full eleven-byte set; this per-axis pin confirms the
15128        // diagnostic flows through to the `EntradaPathInvalid` variant.
15129        let mut s = three_member_spec();
15130        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
15131        let err = s.validate().unwrap_err();
15132        assert!(
15133            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15134                if path == "/api/cart/{id}"
15135                    && reason.contains("reserved character")
15136                    && reason.contains("'{'")
15137                    && reason.contains("%7B")),
15138            "got {err:?}"
15139        );
15140    }
15141
15142    #[test]
15143    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
15144        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
15145        // template_form` on the sibling `:contratos :endpoint` axis.
15146        // Same shared `is_gateway_api_http_path` reserved-byte arm
15147        // fires through `ContratoEndpointInvalid`, with the offending
15148        // endpoint + `:de` + `:para` + reason flowing through verbatim.
15149        // Pins that the lifted predicate's tightening lands on both
15150        // caller axes simultaneously — one source of truth for the
15151        // Gateway API HTTPPathMatch.value accepted set.
15152        let err = contrato_endpoint_err("/api/cart/{id}");
15153        assert!(
15154            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15155                if endpoint == "/api/cart/{id}"
15156                    && reason.contains("reserved character")
15157                    && reason.contains("'{'")
15158                    && reason.contains("%7B")),
15159            "got {err:?}"
15160        );
15161    }
15162
15163    // ── :entrada :host value-shape gate ──────────────────────────────
15164    //
15165    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
15166    // the sibling `:host` axis. Every authoring footgun the K8s
15167    // Gateway API v1 apiserver would catch at admission time becomes
15168    // a caixa-build-time `EntradaHostInvalid` with the offending
15169    // `:host` named verbatim. Same diagnostic shape as
15170    // `MembroVersaoInvalid` (9888b13).
15171
15172    #[test]
15173    fn rejects_entrada_host_with_scheme() {
15174        // Fail-before-pass-after pin — pre-gate codebases silently
15175        // accepted `https://…` and the apiserver rejected it at apply
15176        // time with no source citation.
15177        let mut s = three_member_spec();
15178        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
15179        let err = s.validate().unwrap_err();
15180        assert!(
15181            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15182                if host == "https://checkout.quero.cloud"),
15183            "got {err:?}"
15184        );
15185    }
15186
15187    #[test]
15188    fn rejects_entrada_host_with_port() {
15189        // The `:8080` port suffix is the canonical "I forgot the port
15190        // belongs in `:entrada :port`" footgun. The top-level `:` arm
15191        // (introduced after the per-label loop-only impl silently
15192        // surfaced a deep "label \"cloud:8080\" contains invalid
15193        // character ':'" leak) names the canonical fix verbatim — the
15194        // `:entrada :port` slot.
15195        let mut s = three_member_spec();
15196        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
15197        let err = s.validate().unwrap_err();
15198        assert!(
15199            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15200                if host == "checkout.quero.cloud:8080"
15201                && reason.contains(":entrada :port")),
15202            "got {err:?}"
15203        );
15204    }
15205
15206    #[test]
15207    fn rejects_entrada_host_with_trailing_colon() {
15208        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
15209        // edit) — the per-label loop would land it as a deep
15210        // "label \"com:\" must start and end with an alphanumeric"
15211        // / "contains invalid character ':'" leak. The top-level
15212        // `:` arm pre-empts with the canonical `:port` slot
15213        // diagnostic.
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, ref reason }
15219                if host == "checkout.quero.cloud:"
15220                && reason.contains(":entrada :port")),
15221            "got {err:?}"
15222        );
15223    }
15224
15225    #[test]
15226    fn rejects_entrada_host_unbracketed_ipv6_literal() {
15227        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
15228        // literals across the board (peer with `rejects_entrada_host_
15229        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
15230        // Before this top-level `:` arm landed the per-label loop
15231        // surfaced a single-label byte-class diagnostic that named the
15232        // `:` byte but not the IP-literal prohibition. The top-level
15233        // `:` arm names both the `:port` slot and the IP-literal
15234        // prohibition verbatim, so an author whose `:host "2001:..."`
15235        // value lands here gets a self-locating fix either way.
15236        let mut s = three_member_spec();
15237        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
15238        let err = s.validate().unwrap_err();
15239        assert!(
15240            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15241                if host == "2001:db8::1"
15242                && reason.contains("IPv6")),
15243            "got {err:?}"
15244        );
15245    }
15246
15247    #[test]
15248    fn rejects_entrada_host_wildcard_with_port() {
15249        // Wildcard host with port suffix — the `*.` strip and the
15250        // per-label loop on `["foo", "quero", "cloud:8080"]` would
15251        // surface the deep byte-class leak. The top-level `:` arm sits
15252        // upstream of the `*.` strip, so it names the canonical `:port`
15253        // fix verbatim regardless of whether the host is wildcard-led.
15254        let mut s = three_member_spec();
15255        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
15256        let err = s.validate().unwrap_err();
15257        assert!(
15258            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15259                if host == "*.quero.cloud:8080"
15260                && reason.contains(":entrada :port")),
15261            "got {err:?}"
15262        );
15263    }
15264
15265    #[test]
15266    fn rejects_entrada_host_with_path() {
15267        let mut s = three_member_spec();
15268        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
15269        let err = s.validate().unwrap_err();
15270        assert!(
15271            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15272                if host == "checkout.quero.cloud/api"),
15273            "got {err:?}"
15274        );
15275    }
15276
15277    #[test]
15278    fn rejects_entrada_host_with_uppercase() {
15279        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
15280        // rejected, not silently lower-cased.
15281        let mut s = three_member_spec();
15282        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
15283        let err = s.validate().unwrap_err();
15284        assert!(
15285            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15286                if reason.contains("uppercase")),
15287            "got {err:?}"
15288        );
15289    }
15290
15291    #[test]
15292    fn rejects_entrada_host_with_underscore() {
15293        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
15294        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
15295        let mut s = three_member_spec();
15296        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
15297        let err = s.validate().unwrap_err();
15298        assert!(
15299            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15300                if reason.contains('_')),
15301            "got {err:?}"
15302        );
15303    }
15304
15305    #[test]
15306    fn rejects_entrada_host_ipv4_literal() {
15307        // Gateway API v1 explicitly forbids IP literals as Hostnames.
15308        let mut s = three_member_spec();
15309        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
15310        let err = s.validate().unwrap_err();
15311        assert!(
15312            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15313                if reason.contains("IPv4")),
15314            "got {err:?}"
15315        );
15316    }
15317
15318    #[test]
15319    fn rejects_entrada_host_with_trailing_dot() {
15320        // The Gateway API regex anchors at end-of-string with no
15321        // trailing `.` allowance — the FQDN root-dot form is rejected.
15322        let mut s = three_member_spec();
15323        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
15324        let err = s.validate().unwrap_err();
15325        assert!(
15326            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15327                if host == "checkout.quero.cloud."),
15328            "got {err:?}"
15329        );
15330    }
15331
15332    #[test]
15333    fn rejects_entrada_host_with_leading_dot() {
15334        let mut s = three_member_spec();
15335        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
15336        let err = s.validate().unwrap_err();
15337        assert!(
15338            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15339                if reason.contains("empty label")),
15340            "got {err:?}"
15341        );
15342    }
15343
15344    #[test]
15345    fn rejects_entrada_host_with_consecutive_dots() {
15346        let mut s = three_member_spec();
15347        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
15348        let err = s.validate().unwrap_err();
15349        assert!(
15350            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15351                if reason.contains("empty label")),
15352            "got {err:?}"
15353        );
15354    }
15355
15356    #[test]
15357    fn rejects_entrada_host_with_leading_hyphen_label() {
15358        let mut s = three_member_spec();
15359        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
15360        let err = s.validate().unwrap_err();
15361        assert!(
15362            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15363                if reason.contains("alphanumeric")),
15364            "got {err:?}"
15365        );
15366    }
15367
15368    #[test]
15369    fn rejects_entrada_host_with_trailing_hyphen_label() {
15370        let mut s = three_member_spec();
15371        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
15372        let err = s.validate().unwrap_err();
15373        assert!(
15374            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15375                if reason.contains("alphanumeric")),
15376            "got {err:?}"
15377        );
15378    }
15379
15380    #[test]
15381    fn rejects_entrada_host_with_inner_wildcard() {
15382        // Gateway API allows `*` only as the first label (`*.foo`);
15383        // any inner or trailing `*` is rejected.
15384        let mut s = three_member_spec();
15385        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
15386        let err = s.validate().unwrap_err();
15387        assert!(
15388            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15389                if reason.contains("wildcard")),
15390            "got {err:?}"
15391        );
15392    }
15393
15394    #[test]
15395    fn rejects_entrada_host_bare_wildcard() {
15396        // `*.` with no domain is meaningless; Gateway API rejects it.
15397        let mut s = three_member_spec();
15398        s.entrada.as_mut().unwrap().host = "*.".into();
15399        let err = s.validate().unwrap_err();
15400        assert!(
15401            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15402                if reason.contains("wildcard")),
15403            "got {err:?}"
15404        );
15405    }
15406
15407    #[test]
15408    fn rejects_entrada_host_with_whitespace() {
15409        let mut s = three_member_spec();
15410        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15411        let err = s.validate().unwrap_err();
15412        assert!(
15413            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15414                if reason.contains("whitespace")),
15415            "got {err:?}"
15416        );
15417    }
15418
15419    #[test]
15420    fn rejects_entrada_host_space_names_offending_byte() {
15421        // Embedded space in the `:entrada :host` axis surfaces the
15422        // byte-naming diagnostic through the lifted
15423        // `find_ascii_whitespace_byte` predicate. Peer with the
15424        // sibling `parse_rejects_leading_whitespace` pins on
15425        // `supervisor::duration_codec` (a7ae622) — same "the
15426        // diagnostic carries the offending byte's `0x{b:02x}` shape"
15427        // discipline extended from the shared duration codec to the
15428        // Gateway API v1 Hostname axis.
15429        let mut s = three_member_spec();
15430        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15431        let err = s.validate().unwrap_err();
15432        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15433            panic!("expected EntradaHostInvalid, got {err:?}");
15434        };
15435        assert!(
15436            reason.contains("ASCII whitespace byte"),
15437            "expected byte-naming diagnostic, got {reason:?}"
15438        );
15439        assert!(
15440            reason.contains("0x20"),
15441            "expected offending space byte 0x20, got {reason:?}"
15442        );
15443    }
15444
15445    #[test]
15446    fn rejects_entrada_host_tab_names_offending_byte() {
15447        // Embedded tab byte in the `:entrada :host` axis — the
15448        // canonical paste-from-YAML-block-scalar / paste-from-
15449        // indented-doc footgun. Pins that the lifted predicate covers
15450        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
15451        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
15452        // not just the leading-space case the pre-lift `.bytes().any`
15453        // arm's opaque "must not contain whitespace" reason already
15454        // covered. Peer with `parse_rejects_tab_byte` on
15455        // `supervisor::duration_codec` (a7ae622).
15456        let mut s = three_member_spec();
15457        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
15458        let err = s.validate().unwrap_err();
15459        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15460            panic!("expected EntradaHostInvalid, got {err:?}");
15461        };
15462        assert!(
15463            reason.contains("ASCII whitespace byte"),
15464            "expected byte-naming diagnostic, got {reason:?}"
15465        );
15466        assert!(
15467            reason.contains("0x09"),
15468            "expected offending tab byte 0x09, got {reason:?}"
15469        );
15470    }
15471
15472    #[test]
15473    fn rejects_entrada_host_lf_names_offending_byte() {
15474        // Embedded LF byte in the `:entrada :host` axis — the
15475        // canonical paste-from-shell-heredoc / paste-from-multiline-
15476        // doc footgun the caixa-mesh YAML emitter would silently
15477        // reinterpret at the Gateway API v1 HTTPRoute admission
15478        // layer (an embedded LF byte in a YAML plain scalar either
15479        // truncates the value at the emitter or crashes the parser
15480        // on the k8s-apiserver side). Pins the third representative
15481        // of the full ASCII-whitespace set through the shared
15482        // predicate.
15483        let mut s = three_member_spec();
15484        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
15485        let err = s.validate().unwrap_err();
15486        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15487            panic!("expected EntradaHostInvalid, got {err:?}");
15488        };
15489        assert!(
15490            reason.contains("ASCII whitespace byte"),
15491            "expected byte-naming diagnostic, got {reason:?}"
15492        );
15493        assert!(
15494            reason.contains("0x0a"),
15495            "expected offending LF byte 0x0a, got {reason:?}"
15496        );
15497    }
15498
15499    #[test]
15500    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
15501        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
15502        // axis — the canonical paste-from-typography /
15503        // paste-from-word-processor footgun. Before the non-ASCII
15504        // Unicode `White_Space` scan lifted through the shared
15505        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
15506        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
15507        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
15508        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
15509        // with the far-from-source `label "…" must start and end
15510        // with an alphanumeric` diagnostic — burying the
15511        // paste-from-typography origin under a label-shape leak.
15512        // Peer with the sibling non-ASCII-whitespace pins at
15513        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
15514        // — 1b75b38), `limits::parse_duration`,
15515        // `limits::parse_millicores`, and the shared duration codec
15516        // — same "the diagnostic carries the offending Unicode
15517        // codepoint's `U+XXXX` shape" discipline extended from every
15518        // typed-magnitude codec to the Gateway API v1 Hostname axis.
15519        let mut s = three_member_spec();
15520        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
15521        let err = s.validate().unwrap_err();
15522        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15523            panic!("expected EntradaHostInvalid, got {err:?}");
15524        };
15525        assert!(
15526            reason.contains("non-ASCII Unicode whitespace character"),
15527            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15528        );
15529        assert!(
15530            reason.contains("U+00A0"),
15531            "expected offending NBSP codepoint U+00A0, got {reason:?}"
15532        );
15533    }
15534
15535    #[test]
15536    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
15537        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
15538        // `:entrada :host` axis — the canonical paste-from-web-doc /
15539        // paste-from-published-HTML footgun. `char::is_whitespace`
15540        // returns true for `U+2028` per the Unicode `White_Space`
15541        // property, so `str::trim` at any downstream site would
15542        // silently strip it — same drift class as NBSP but on a
15543        // different codepoint region. Pins the second representative
15544        // (non-Latin-1 `char::is_whitespace` member) through the
15545        // shared predicate. Peer with
15546        // `parse_byte_size_rejects_internal_line_separator` on
15547        // `limits::parse_byte_size` (1b75b38).
15548        let mut s = three_member_spec();
15549        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
15550        let err = s.validate().unwrap_err();
15551        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15552            panic!("expected EntradaHostInvalid, got {err:?}");
15553        };
15554        assert!(
15555            reason.contains("non-ASCII Unicode whitespace character"),
15556            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15557        );
15558        assert!(
15559            reason.contains("U+2028"),
15560            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
15561        );
15562    }
15563
15564    #[test]
15565    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
15566        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
15567        // labels in the `:entrada :host` axis — the canonical
15568        // paste-from-CJK-typography footgun (CJK IMEs default to
15569        // full-width whitespace when the space bar is pressed in
15570        // Japanese / Chinese input modes). Pins the third
15571        // representative of the non-ASCII Unicode `White_Space` set
15572        // through the shared predicate: the CJK block, distinct from
15573        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
15574        // SEPARATOR `U+2028` — covering the same axis breadth the
15575        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
15576        // (1b75b38) pins on `limits::parse_byte_size`.
15577        let mut s = three_member_spec();
15578        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
15579        let err = s.validate().unwrap_err();
15580        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15581            panic!("expected EntradaHostInvalid, got {err:?}");
15582        };
15583        assert!(
15584            reason.contains("non-ASCII Unicode whitespace character"),
15585            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15586        );
15587        assert!(
15588            reason.contains("U+3000"),
15589            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
15590        );
15591    }
15592
15593    #[test]
15594    fn rejects_entrada_host_too_long() {
15595        // Total length cap = 253; build a 254-byte host out of two
15596        // 63-byte labels + one 62-byte label + dots.
15597        let mut s = three_member_spec();
15598        let big = format!(
15599            "{}.{}.{}.{}",
15600            "a".repeat(63),
15601            "b".repeat(63),
15602            "c".repeat(63),
15603            "d".repeat(254 - 63 * 3 - 3)
15604        );
15605        assert_eq!(big.len(), 254);
15606        s.entrada.as_mut().unwrap().host = big;
15607        let err = s.validate().unwrap_err();
15608        assert!(
15609            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15610                if reason.contains("max length of 253")),
15611            "got {err:?}"
15612        );
15613    }
15614
15615    #[test]
15616    fn rejects_entrada_host_label_too_long() {
15617        let mut s = three_member_spec();
15618        // 64-byte label — one over the per-label cap.
15619        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
15620        let err = s.validate().unwrap_err();
15621        assert!(
15622            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15623                if reason.contains("label max length of 63")),
15624            "got {err:?}"
15625        );
15626    }
15627
15628    #[test]
15629    fn entrada_host_diagnostic_carries_offending_host() {
15630        // Diagnostic-shape pin — the offending host + a non-empty
15631        // reason flow through verbatim so the author can grep their
15632        // caixa.lisp for `:host "<host>"` and fix it in one edit.
15633        let mut s = three_member_spec();
15634        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
15635        let err = s.validate().unwrap_err();
15636        match err {
15637            AplicacaoError::EntradaHostInvalid { host, reason } => {
15638                assert_eq!(host, "checkout.quero.cloud:8080");
15639                assert!(!reason.is_empty(), "reason field must be non-empty");
15640            }
15641            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15642        }
15643    }
15644
15645    #[test]
15646    fn entrada_host_empty_takes_precedence_over_invalid() {
15647        // Ordering pin: `EmptyEntradaHost` is the more self-locating
15648        // diagnostic on `""` and must lead — `validate_entrada_host`
15649        // is only reached after the empty-check fires at the call
15650        // site. (The predicate itself defends against direct
15651        // invocation by returning the same error on `""`.)
15652        let mut s = three_member_spec();
15653        s.entrada.as_mut().unwrap().host = String::new();
15654        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
15655    }
15656
15657    #[test]
15658    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
15659        // Ordering pin: a missing :para member is the more
15660        // self-locating diagnostic and fires before the host gate.
15661        let mut s = three_member_spec();
15662        let e = s.entrada.as_mut().unwrap();
15663        e.para = "ghost".into();
15664        e.host = "BAD HOST".into();
15665        let err = s.validate().unwrap_err();
15666        assert!(
15667            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
15668            "got {err:?}"
15669        );
15670    }
15671
15672    #[test]
15673    fn entrada_host_invalid_fires_before_port_zero() {
15674        // Ordering pin: the host gate fires before the port gate so
15675        // a malformed host is named even when the port is also wrong.
15676        let mut s = three_member_spec();
15677        let e = s.entrada.as_mut().unwrap();
15678        e.host = "Checkout.quero.cloud".into();
15679        e.port = 0;
15680        let err = s.validate().unwrap_err();
15681        assert!(
15682            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15683                if host == "Checkout.quero.cloud"),
15684            "got {err:?}"
15685        );
15686    }
15687
15688    #[test]
15689    fn entrada_accepts_canonical_hosts() {
15690        // Positive-control sweep — every form the Gateway API
15691        // apiserver accepts must round-trip through validate. Covers
15692        // a plain DNS subdomain, a leading wildcard, a single-label
15693        // host (cluster-internal), a max-length-edge label, a
15694        // hyphen-bearing label, and a Punycode IDN label.
15695        for host in [
15696            "checkout.quero.cloud",
15697            "*.quero.cloud",
15698            "checkout",
15699            // 63-byte label — exactly the per-label cap.
15700            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
15701            "foo-bar.quero.cloud",
15702            // Punycode IDN — valid because the author pre-encoded.
15703            "xn--bcher-kva.example.com",
15704        ] {
15705            let mut s = three_member_spec();
15706            s.entrada.as_mut().unwrap().host = host.into();
15707            s.validate()
15708                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
15709        }
15710    }
15711
15712    #[test]
15713    fn entrada_host_max_length_validates() {
15714        // 253-byte host is the cap exactly — must validate. Build a
15715        // 253-byte host out of three 63-byte labels + one 61-byte
15716        // label + 3 dots = 252 bytes, then pad one byte to 253.
15717        let mut s = three_member_spec();
15718        let host = format!(
15719            "{}.{}.{}.{}",
15720            "a".repeat(63),
15721            "b".repeat(63),
15722            "c".repeat(63),
15723            "d".repeat(253 - 63 * 3 - 3)
15724        );
15725        assert_eq!(host.len(), 253);
15726        s.entrada.as_mut().unwrap().host = host;
15727        s.validate().unwrap();
15728    }
15729
15730    #[test]
15731    fn entrada_host_total_length_cap_threads_lifted_render_const() {
15732        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
15733        // total-length gate now reads the K8s Gateway API v1 Hostname
15734        // `maxLength: 253` cap from the lifted
15735        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
15736        // of truth — the same constant every future Gateway-API-Hostname
15737        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
15738        // materializer's per-host validator, the future per-`Certificate`
15739        // SAN emitter for cert-manager, the multi-`:entrada`
15740        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
15741        // from. Before the lift, the aplicacao-side reader consumed a
15742        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
15743        // 253-byte value as the peer render-side canonical bounds
15744        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
15745        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
15746        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
15747        // module boundary — a future 253-byte drift on either side would
15748        // silently split into two axes' worth of admission-schema mismatch
15749        // without a build-time signal. Pin the cap through a fresh 254-
15750        // byte host that hits the total-length arm, then read the reason
15751        // for the exact byte count the shared constant carries: any future
15752        // regression on the lift (a private alias reintroduced, a hard-
15753        // coded literal at the arm, a mismatch between the aplicacao-side
15754        // and render-side canonicals) surfaces as this pin's diagnostic
15755        // failing to match, not as a per-cluster admission rejection far
15756        // from the caixa.lisp source line.
15757        let mut s = three_member_spec();
15758        let over_cap = format!(
15759            "{}.{}.{}.{}",
15760            "a".repeat(63),
15761            "b".repeat(63),
15762            "c".repeat(63),
15763            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
15764        );
15765        assert_eq!(
15766            over_cap.len(),
15767            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
15768        );
15769        s.entrada.as_mut().unwrap().host = over_cap;
15770        let err = s.validate().unwrap_err();
15771        match err {
15772            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15773                let needle = format!(
15774                    "max length of {} bytes",
15775                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
15776                );
15777                assert!(
15778                    reason.contains(&needle),
15779                    "diagnostic must name the lifted \
15780                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
15781                );
15782            }
15783            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15784        }
15785    }
15786
15787    #[test]
15788    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
15789        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
15790        // on the per-label-cap axis. Before the lift, the aplicacao-side
15791        // per-label arm consumed a private const alias
15792        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
15793        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
15794        // split from it at the module boundary — every `.`-separated
15795        // label in a Gateway API v1 Hostname is a DNS-1123 label under
15796        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
15797        // so the private alias's 63 and the canonical const's 63 were
15798        // pinning the same underlying rule twice. Pin the cap through a
15799        // 64-byte label that hits the per-label arm, then read the reason
15800        // for the exact byte count the shared constant carries: any
15801        // future drift on either side (a private alias reintroduced, a
15802        // hard-coded literal at the arm, a mismatch between the two
15803        // 63-byte pins) surfaces at this pin's diagnostic rather than at
15804        // a per-cluster admission rejection whose "field is invalid"
15805        // opacity misframes the root cause.
15806        let mut s = three_member_spec();
15807        let over_cap_label = format!(
15808            "{}.quero.cloud",
15809            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
15810        );
15811        s.entrada.as_mut().unwrap().host = over_cap_label;
15812        let err = s.validate().unwrap_err();
15813        match err {
15814            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15815                let needle = format!(
15816                    "label max length of {} bytes",
15817                    crate::render::DNS_1123_LABEL_MAX_LEN,
15818                );
15819                assert!(
15820                    reason.contains(&needle),
15821                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
15822                     cap verbatim on the per-label arm, got: {reason:?}",
15823                );
15824            }
15825            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15826        }
15827    }
15828
15829    #[test]
15830    fn entrada_with_empty_paths_validates() {
15831        // Empty `:paths` is the documented "match every path" form;
15832        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
15833        let mut s = three_member_spec();
15834        s.entrada.as_mut().unwrap().paths = vec![];
15835        s.validate().unwrap();
15836    }
15837
15838    #[test]
15839    fn entrada_root_path_validates() {
15840        // The author-supplied bare-root `:entrada :paths` entry is the
15841        // same byte-shape the peer emit-side catch-all constant
15842        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
15843        // the author's `:paths` list is empty — sweeping the test-side
15844        // probe literal onto the lifted const closes the two-axis pin
15845        // (author-side admit + emit-side canonical fallback) around
15846        // one `&'static str`, so a future rebrand of the catch-all
15847        // reaches both consumers by construction. Peer to
15848        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
15849        // on the canonical-literal pin surface.
15850        let mut s = three_member_spec();
15851        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
15852        s.validate().unwrap();
15853    }
15854
15855    #[test]
15856    fn placement_strategy_variants_round_trip() {
15857        for s in [
15858            PlacementStrategy::SingleNode,
15859            PlacementStrategy::Replicated,
15860            PlacementStrategy::Sharded,
15861        ] {
15862            let p = Placement {
15863                estrategia: s,
15864                clusters: vec!["rio".into()],
15865                affinity: None,
15866                // Route the paired `:shard-key` fixture-builder through the
15867                // typed cross-slot invariant predicate
15868                // [`PlacementStrategy::requires_shard_key`] rather than the
15869                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
15870                // arm-identity predicate — the two answer the same
15871                // question under today's closed accept-set but a future
15872                // arm addition that consumed `:shard-key` under a
15873                // non-`Sharded` name would silently mis-attach the
15874                // fixture's `:shard-key` if the builder read through the
15875                // arm-identity predicate. The cross-slot-invariant
15876                // predicate migrates through one caixa-core edit on any
15877                // future arm addition; the fixture keeps producing a
15878                // `validate()`-passing round-trip by construction.
15879                shard_key: if s.requires_shard_key() {
15880                    Some("$key".into())
15881                } else {
15882                    None
15883                },
15884            };
15885            let json = serde_json::to_string(&p).unwrap();
15886            let back: Placement = serde_json::from_str(&json).unwrap();
15887            assert_eq!(back, p);
15888        }
15889    }
15890
15891    #[test]
15892    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
15893        // The fail-before-pass-after pin: pre-lift there was no
15894        // single-source binding between the [`PlacementStrategy`]
15895        // variant name the `Serialize` derive emits and the byte-
15896        // string every downstream cluster-side dispatcher (the
15897        // `lareira-fleet-programs` aggregator's per-entry strategy
15898        // branch, the future `app-operator` reconciler, the M3
15899        // Adaptive compression pass's per-strategy weighting) probes
15900        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
15901        // future `#[serde(rename_all = "kebab-case")]` attribute on
15902        // the enum — or a variant rename in the source — would
15903        // silently rebrand the emitted scalar under one spelling
15904        // while every downstream dispatcher still probed the other,
15905        // with the failure surfacing at the aggregator's dispatch
15906        // step or the operator's reconcile posture (workloads coming
15907        // up under the `default()` `Replicated` arm rather than the
15908        // typed slot's declared strategy) far from the source
15909        // rebrand commit and with no field naming the drift. Pinning
15910        // the two paths (the `Serialize` derive's serialized string
15911        // AND the [`PlacementStrategy::as_str`] helper) to the same
15912        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
15913        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15914        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
15915        // makes any future drift on either endpoint fail here at
15916        // caixa-core build time.
15917        for (variant, expected) in [
15918            (
15919                PlacementStrategy::SingleNode,
15920                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15921            ),
15922            (
15923                PlacementStrategy::Replicated,
15924                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15925            ),
15926            (
15927                PlacementStrategy::Sharded,
15928                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15929            ),
15930        ] {
15931            let json = serde_json::to_string(&variant).unwrap();
15932            assert_eq!(
15933                json,
15934                format!("\"{expected}\""),
15935                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
15936            );
15937            assert_eq!(
15938                variant.as_str(),
15939                expected,
15940                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
15941                 M3_PLACEMENT_ESTRATEGIA_* constant"
15942            );
15943        }
15944    }
15945
15946    #[test]
15947    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
15948        // Cross-arm drift-detection pin on the M3
15949        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
15950        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15951        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
15952        // scalar-value pentad: a future collapse of two canonical
15953        // variant byte-strings onto the same value (an accidental
15954        // copy-paste flip of
15955        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
15956        // read `"SingleNode"`, a per-arm rebrand that lands one const
15957        // without touching its paired peer) would silently reroute
15958        // every downstream operator's per-strategy dispatch onto the
15959        // sibling arm's reconcile branch and pass every
15960        // propagation-probe test that expected only the stale arm's
15961        // value — a `Replicated`-declared Aplicacao would come up
15962        // under the `SingleNode` primary-and-standby reconcile
15963        // posture, so every-cluster active-active workload would
15964        // silently collapse onto one-cluster-runs-at-a-time takeover
15965        // semantics against its declared strategy, with no field
15966        // naming the strategy-value drift root cause. Peer of the
15967        // sibling
15968        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
15969        // (09ffb2d) /
15970        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
15971        // (ccdf955) /
15972        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
15973        // (d739850) distinctness pins on the sibling OTP-shape /
15974        // caixa-kind closed-set typed-enum discriminator axes — the
15975        // fourth (and structurally the M3 mesh-primitive-defining)
15976        // closed-set typed-enum axis to converge on the same
15977        // "pairwise-distinct-by-construction" discipline.
15978        //
15979        // Fail-before-pass-after locally verified by mutating
15980        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
15981        // also read `"SingleNode"` — this pin fires as expected;
15982        // restoring passes.
15983        let all = [
15984            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15985            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15986            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15987        ];
15988        for (i, a) in all.iter().enumerate() {
15989            for (j, b) in all.iter().enumerate() {
15990                if i != j {
15991                    assert_ne!(
15992                        a, b,
15993                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
15994                         distinct — got duplicate {a:?} at indices {i} and {j}",
15995                    );
15996                }
15997            }
15998        }
15999    }
16000
16001    #[test]
16002    fn placement_strategy_display_routes_through_as_str_helper() {
16003        // The fail-before-pass-after pin: pre-lift the sibling
16004        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
16005        // / [`crate::supervisor::RestartPolicy`] both carried a stable
16006        // [`std::fmt::Display`] surface via their
16007        // `#[discriminant(also_display)]` gen-platform derive, but
16008        // [`PlacementStrategy`] did not — every consumer reaching for
16009        // a strategy byte-string past the wire format had to pick
16010        // between three paths ([`PlacementStrategy::as_str`], the
16011        // `Serialize` derive's serialized string, or `format!("{v:?}")`
16012        // on the `Debug` derive), any two of which a future variant
16013        // rename or `#[serde(rename_all = "kebab-case")]` attribute
16014        // would silently desynchronize. Wiring [`std::fmt::Display`]
16015        // through [`PlacementStrategy::as_str`] closes the third path:
16016        // every `format!("{v}")` call reaches the same lifted
16017        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
16018        // and the [`PlacementStrategy::as_str`] helper already route
16019        // through, so a future variant rename lands at exactly one
16020        // place. Pin the routing here so a future
16021        // `impl std::fmt::Display for PlacementStrategy` reimplementation
16022        // that hand-rolls the arms instead of delegating to
16023        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
16024        for variant in [
16025            PlacementStrategy::SingleNode,
16026            PlacementStrategy::Replicated,
16027            PlacementStrategy::Sharded,
16028        ] {
16029            assert_eq!(
16030                variant.to_string(),
16031                variant.as_str(),
16032                "PlacementStrategy::{variant:?} Display must route through \
16033                 PlacementStrategy::as_str (single source of truth: the lifted \
16034                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
16035            );
16036        }
16037    }
16038
16039    #[test]
16040    fn placement_strategy_display_matches_serialized_wire_byte_string() {
16041        // The fail-before-pass-after pin on the second half of the
16042        // three-path convergence: `Display` (user-facing text) agrees
16043        // byte-for-byte with the `Serialize` derive's wire format
16044        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
16045        // scalar) on every variant. Pre-lift the two paths were
16046        // structurally independent — a future
16047        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
16048        // would silently rebrand the emitted wire scalar
16049        // (`single-node`, `replicated`, `sharded`) while every consumer
16050        // that pretty-prints the strategy (the M3 diagnostic templates,
16051        // the future `feira app graph` per-Aplicacao strategy line,
16052        // the future M4 CR materializer's admission-webhook rejection
16053        // body) would still emit the TitleCase form the `as_str` /
16054        // `Display` route returns, with the mismatch surfacing at
16055        // consumer parse time / operator dispatch time far from the
16056        // source rebrand commit. Pin the two paths byte-for-byte here
16057        // so any future serde-attribute or variant-rename drift is a
16058        // caixa-core-build-time test failure at this call, not a
16059        // silent per-consumer dispatch miss.
16060        for variant in [
16061            PlacementStrategy::SingleNode,
16062            PlacementStrategy::Replicated,
16063            PlacementStrategy::Sharded,
16064        ] {
16065            let wire = serde_json::to_string(&variant).unwrap();
16066            // Strip the outer `"…"` the JSON string form carries — the
16067            // wire scalar the K8s / YAML apiserver consumes is the
16068            // enclosed byte-string, not the quote wrapper.
16069            let unquoted = wire
16070                .strip_prefix('"')
16071                .and_then(|s| s.strip_suffix('"'))
16072                .expect("serialized PlacementStrategy is a JSON string");
16073            assert_eq!(
16074                variant.to_string(),
16075                unquoted,
16076                "PlacementStrategy::{variant:?} Display byte-string must match the \
16077                 Serialize derive's wire byte-string (three-path convergence: \
16078                 Display + as_str + Serialize all resolve to the same \
16079                 M3_PLACEMENT_ESTRATEGIA_* const)"
16080            );
16081        }
16082    }
16083
16084    #[test]
16085    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
16086        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
16087        // derive on [`PlacementStrategy`]: for each of the three variants
16088        // exactly one of the generated `is_single_node` / `is_replicated`
16089        // / `is_sharded` predicates returns `true` and the other two
16090        // return `false`. Prior to this derive the three per-arm
16091        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
16092        // (the `placement_strategy_variants_round_trip` fixture, the
16093        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
16094        // fixture, and the
16095        // `validate_placement_reads_through_lifted_estrategia_accessor`
16096        // fixture) each open-coded a per-arm PartialEq compare against
16097        // the enum variant — three sites that expressed no compile-time
16098        // link back to the closed-set typed dispatch a future fourth
16099        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
16100        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
16101        // would have to thread through in lockstep or one fixture would
16102        // silently disagree with the others on which arms consume the
16103        // `:shard-key` axis. Peer of the sibling
16104        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
16105        // / [`crate::supervisor::RestartPolicy`] /
16106        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
16107        // the sibling closed-set typed-enum discriminator axes — extends
16108        // the same one-typed-dispatch-per-variant discipline onto the
16109        // fifth (and only remaining) closed-set typed-enum discriminator
16110        // on the caixa surface, closing the axis on the M3 mesh-slot
16111        // family.
16112        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
16113            (PlacementStrategy::SingleNode, [true, false, false]),
16114            (PlacementStrategy::Replicated, [false, true, false]),
16115            (PlacementStrategy::Sharded, [false, false, true]),
16116        ];
16117        for (variant, expected) in rows {
16118            let observed = [
16119                variant.is_single_node(),
16120                variant.is_replicated(),
16121                variant.is_sharded(),
16122            ];
16123            assert_eq!(
16124                observed, expected,
16125                "PlacementStrategy::{variant:?} is_* predicates must partition \
16126                 the arm set (single_node, replicated, sharded); got {observed:?}"
16127            );
16128        }
16129    }
16130
16131    #[test]
16132    fn placement_strategy_is_variant_predicates_are_const_fn() {
16133        // The [`gen_platform::IsVariant`] derive emits `const fn`
16134        // predicates on the peer [`crate::CaixaKind`] +
16135        // [`crate::upgrade::UpgradeInstruction`] +
16136        // [`crate::supervisor::RestartStrategy`] +
16137        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
16138        // pin the same posture on [`PlacementStrategy`] so a future
16139        // accidental downgrade to non-`const` (an added runtime helper
16140        // reachable only from a non-`const` context, a manual hand-rolled
16141        // `impl` that shadows the derive-generated method) trips at
16142        // caixa-core build time rather than surfacing as a downstream
16143        // `const`-context regression far from the derive declaration.
16144        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
16145        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
16146        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
16147        assert!(IS_SINGLE_NODE);
16148        assert!(IS_REPLICATED);
16149        assert!(IS_SHARDED);
16150    }
16151
16152    #[test]
16153    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
16154        // Fail-before-pass-after pin on the substrate-lifted
16155        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
16156        // per-arm predicate: for each variant in the closed accept-set the
16157        // predicate returns `true` iff the variant consumes the paired
16158        // [`Placement::shard_key`] axis under
16159        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
16160        // partition. Today the accept-set is the singleton `{Sharded}` —
16161        // `Sharded` is the Akka-style hash-keyed distribution arm
16162        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
16163        // §II.1) and `Replicated` (active-active) refuse the axis through
16164        // [`AplicacaoError::ShardKeyOnNonSharded`].
16165        //
16166        // Pins the per-arm truth-table so a future arm addition (an
16167        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
16168        // roadmap names, a `WeightedShard` promotion the future M5
16169        // adaptive-placement engine acknowledges) that landed a variant
16170        // without extending this predicate's arm-set would surface as a
16171        // caixa-core build-time exhaustiveness error at the
16172        // `match self { … }` arm-fan below rather than a silent per-consumer
16173        // mis-classification at renderer emit time. The paired
16174        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
16175        // predicate stays a distinct question — arm-identity (which the
16176        // sibling
16177        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
16178        // pin already locks) is not cross-slot-invariant consumption; today
16179        // they trip on the same singleton but the pair migrates through
16180        // one caixa-core edit on any future arm addition.
16181        //
16182        // Peer of the sibling per-arm classifier pins
16183        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
16184        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
16185        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
16186        // derived paired predicate on the post-projection typed-view axis
16187        // — same "per-arm semantic-classification predicate paired with
16188        // the arm-identity predicate the derive already emits" discipline
16189        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
16190        // `:placement :shard-key` cross-slot-invariant axis.
16191        let rows: [(PlacementStrategy, bool); 3] = [
16192            (PlacementStrategy::SingleNode, false),
16193            (PlacementStrategy::Replicated, false),
16194            (PlacementStrategy::Sharded, true),
16195        ];
16196        for (variant, expected) in rows {
16197            assert_eq!(
16198                variant.requires_shard_key(),
16199                expected,
16200                "PlacementStrategy::{variant:?}.requires_shard_key() must \
16201                 be {expected} (the substrate-canonical cross-slot invariant \
16202                 on the :placement :shard-key axis; today `Sharded` is the \
16203                 singleton consuming arm — MESH-COMPOSITION §II.4)",
16204            );
16205        }
16206    }
16207
16208    #[test]
16209    fn placement_strategy_requires_shard_key_is_const_fn() {
16210        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
16211        // invariant per-arm predicate is declared `#[must_use] pub const
16212        // fn` — pin the `const`-eval posture here so a future accidental
16213        // downgrade to non-`const` (an added runtime helper reachable
16214        // only from a non-`const` context, a manual hand-rolled `impl`
16215        // that shadows the current three-arm `match self { … }` dispatch)
16216        // trips at caixa-core build time rather than surfacing as a
16217        // downstream `const`-context regression far from the declaration.
16218        // Same shape as the sibling
16219        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
16220        // the peer [`gen_platform::IsVariant`]-derived arm-identity
16221        // predicate axis, but here the load-bearing assertions live in
16222        // module-scope `const _: () = assert!(…)` items so a violation
16223        // fails at compile time (const-eval trip) rather than test time —
16224        // strictly stronger than the runtime `assert!(CONST)` pattern the
16225        // sibling pin uses, and side-steps the
16226        // `clippy::assertions_on_constants` lint the runtime pattern
16227        // otherwise accumulates on the module baseline.
16228        //
16229        // The test body simply witnesses that the module-scope items
16230        // compiled and the runtime dispatch agrees with the const-eval
16231        // dispatch on every arm — the runtime read gives the test a
16232        // failure surface (rather than an empty test body clippy would
16233        // flag as a no-op).
16234        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
16235        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
16236        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
16237        assert_eq!(
16238            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
16239            [
16240                PlacementStrategy::SingleNode.requires_shard_key(),
16241                PlacementStrategy::Replicated.requires_shard_key(),
16242                PlacementStrategy::Sharded.requires_shard_key(),
16243            ],
16244            "runtime and const-eval dispatch on \
16245             PlacementStrategy::requires_shard_key must agree on every arm",
16246        );
16247    }
16248
16249    #[test]
16250    fn placement_estrategia_accessor_is_const_fn() {
16251        // The [`Placement::estrategia`] per-`:placement` distribution-
16252        // strategy `Copy`-return scalar accessor is declared
16253        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
16254        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
16255        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
16256        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
16257        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
16258        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
16259        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
16260        // [`RateLimit`], every one a `pub const fn`). Pin the
16261        // `const`-eval posture here so a future accidental downgrade to
16262        // non-`const` (an added runtime helper reachable only from a
16263        // non-`const` context, a slot promotion to a non-`Copy` return
16264        // that would silently drop the `const` qualifier, a manual
16265        // hand-rolled shadow) trips at caixa-core build time rather
16266        // than surfacing as a downstream `const`-context regression far
16267        // from the declaration.
16268        //
16269        // Same shape as the sibling
16270        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
16271        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
16272        // predicate axis — the load-bearing witness lives in the
16273        // module-scope `const fn` wrapper `estrategia_via_const_fn`
16274        // below: a body that calls [`Placement::estrategia`] under a
16275        // `const fn` signature is well-formed only when the callee is
16276        // itself `const fn`, so any future accidental downgrade of
16277        // [`Placement::estrategia`] to non-`const` fails at caixa-core
16278        // build time (const-eval E0015 / E0658 depending on the arm),
16279        // strictly stronger than a runtime `assert!(CONST)` and
16280        // side-stepping the destructor-in-const restriction that
16281        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
16282        // items on `Placement`'s `Vec<String>` / `Option<String>`
16283        // carriers.
16284        //
16285        // The runtime body witnesses that the const-eval-shaped
16286        // wrapper agrees with a direct call on every closed-set arm.
16287        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
16288            p.estrategia()
16289        }
16290        for estrategia in [
16291            PlacementStrategy::SingleNode,
16292            PlacementStrategy::Replicated,
16293            PlacementStrategy::Sharded,
16294        ] {
16295            let placement = Placement {
16296                estrategia,
16297                clusters: Vec::new(),
16298                affinity: None,
16299                shard_key: None,
16300            };
16301            assert_eq!(
16302                estrategia_via_const_fn(&placement),
16303                placement.estrategia(),
16304                "const-fn-wrapped and direct dispatch on \
16305                 Placement::estrategia must agree for {estrategia:?}",
16306            );
16307        }
16308    }
16309
16310    #[test]
16311    fn entrada_port_accessor_is_const_fn() {
16312        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
16313        // scalar accessor is declared `#[must_use] pub const fn` —
16314        // matching the peer M3 mesh-slot `Copy`-return accessor family
16315        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
16316        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
16317        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
16318        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
16319        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
16320        // [`RateLimit::window`] on the sibling [`RateLimit`], the
16321        // sibling per-`:placement` [`Placement::estrategia`] pinned by
16322        // [`placement_estrategia_accessor_is_const_fn`] above — every
16323        // one a `pub const fn`). Pin the `const`-eval posture here so
16324        // a future accidental downgrade to non-`const` (an added
16325        // runtime helper reachable only from a non-`const` context, an
16326        // `Option<u16>`-shape migration once the substrate grows
16327        // per-`:membros` heterogeneous listener ports that would
16328        // silently drop the `const` qualifier, a manual hand-rolled
16329        // shadow) trips at caixa-core build time rather than surfacing
16330        // as a downstream `const`-context regression far from the
16331        // declaration.
16332        //
16333        // Same shape as the sibling
16334        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
16335        // load-bearing witness lives in the module-scope `const fn`
16336        // wrapper `port_via_const_fn`: a body that calls
16337        // [`Entrada::port`] under a `const fn` signature is well-formed
16338        // only when the callee is itself `const fn`, side-stepping the
16339        // destructor-in-const restriction that would otherwise block a
16340        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
16341        // `String` / `Vec<String>` carriers.
16342        //
16343        // The runtime body sweeps a representative port set spanning
16344        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
16345        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
16346        // ceiling — the const-fn-wrapped call must agree with a direct
16347        // call on every fixture (a violation trips the test) and every
16348        // returned scalar must byte-equal the input `port` (a violation
16349        // means the accessor stopped being a raw field-return copy).
16350        const fn port_via_const_fn(e: &Entrada) -> u16 {
16351            e.port()
16352        }
16353        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
16354            let entrada = Entrada {
16355                host: String::new(),
16356                para: String::new(),
16357                port,
16358                paths: Vec::new(),
16359            };
16360            assert_eq!(
16361                port_via_const_fn(&entrada),
16362                entrada.port(),
16363                "const-fn-wrapped and direct dispatch on Entrada::port \
16364                 must agree for port={port}",
16365            );
16366            assert_eq!(
16367                entrada.port(),
16368                port,
16369                "Entrada::port must return the storage-side u16 verbatim \
16370                 for port={port}",
16371            );
16372        }
16373    }
16374
16375    #[test]
16376    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
16377        // Load-bearing cross-slot-partition pin closing the loop between
16378        // the substrate-lifted
16379        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
16380        // the closed-set typed enum and the actual
16381        // [`AplicacaoSpec::validate_placement`] runtime behavior across
16382        // the paired `:placement :shard-key` axis: every validated
16383        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
16384        // satisfies `placement.shard_key().is_some() ==
16385        // placement.estrategia().requires_shard_key()`. The four-cell
16386        // shape witness sweeps every combination of (variant in the
16387        // closed accept-set, `:shard-key` Some/None) and pins:
16388        //
16389        //   * variant.requires_shard_key() && shard_key.is_some() →
16390        //     validate() passes; the paired shape is the sole
16391        //     `requires_shard_key` arm-family accepted shape.
16392        //   * variant.requires_shard_key() && shard_key.is_none() →
16393        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
16394        //     the paired shape is the refused missing-key shape on
16395        //     Sharded-family arms.
16396        //   * !variant.requires_shard_key() && shard_key.is_some() →
16397        //     validate() fails with
16398        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
16399        //     is the refused declared-but-inert shape on non-Sharded-
16400        //     family arms.
16401        //   * !variant.requires_shard_key() && shard_key.is_none() →
16402        //     validate() passes; the paired shape is the sole
16403        //     non-`requires_shard_key` arm-family accepted shape.
16404        //
16405        // The compile-time-exhaustive `match p.estrategia()` dispatch at
16406        // [`AplicacaoSpec::validate_placement`] preserves its structural
16407        // arm-fan (a future arm addition still surfaces a build-time
16408        // exhaustiveness error there); this pin closes the semantic loop
16409        // between the arm-fan's shape-gate cascades and the substrate-
16410        // canonical predicate every downstream consumer of the paired
16411        // shape reads through. Fail-before-pass-after locally verified by
16412        // mutating the predicate's `Sharded => true` arm to `false` — the
16413        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
16414        // `validate() must pass` assertion; restoring passes. Same "close
16415        // the loop between the typed predicate and the runtime behavior"
16416        // discipline as the sibling
16417        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
16418        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
16419        // per-arm classifier axis.
16420        for variant in [
16421            PlacementStrategy::SingleNode,
16422            PlacementStrategy::Replicated,
16423            PlacementStrategy::Sharded,
16424        ] {
16425            for present in [false, true] {
16426                let mut spec = three_member_spec();
16427                spec.placement.estrategia = variant;
16428                spec.placement.shard_key = present.then(|| "tenantId".into());
16429                let expects_ok = variant.requires_shard_key() == present;
16430                let result = spec.validate();
16431                match (expects_ok, &result) {
16432                    (true, Ok(())) => {}
16433                    (false, Err(err)) => {
16434                        // Cross-check the refusal diagnostic names the
16435                        // right cell of the four-cell shape witness — the
16436                        // `requires_shard_key && !present` cell must trip
16437                        // [`AplicacaoError::ShardedWithoutKey`]; the
16438                        // `!requires_shard_key && present` cell must trip
16439                        // [`AplicacaoError::ShardKeyOnNonSharded`].
16440                        match (variant.requires_shard_key(), present, err) {
16441                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
16442                            (
16443                                false,
16444                                true,
16445                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
16446                            ) => {
16447                                assert_eq!(
16448                                    *e, variant,
16449                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
16450                                     the paired PlacementStrategy",
16451                                );
16452                            }
16453                            _ => panic!(
16454                                "unexpected refusal for estrategia={variant:?} \
16455                                 present={present}: {err:?}"
16456                            ),
16457                        }
16458                    }
16459                    (true, Err(err)) => panic!(
16460                        "validate() must pass for estrategia={variant:?} \
16461                         present={present} (requires_shard_key={} == present={present}), \
16462                         got {err:?}",
16463                        variant.requires_shard_key(),
16464                    ),
16465                    (false, Ok(())) => panic!(
16466                        "validate() must fail for estrategia={variant:?} \
16467                         present={present} (requires_shard_key={} != present={present})",
16468                        variant.requires_shard_key(),
16469                    ),
16470                }
16471            }
16472        }
16473    }
16474
16475    #[test]
16476    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
16477        // Pin the M3 diagnostic template routes through the typed
16478        // [`PlacementStrategy`] Display byte-string (rebound from the
16479        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
16480        // routes emitted identical bytes (the `Debug` derive on a
16481        // unit variant emits the variant name verbatim, exactly what
16482        // `as_str` returns), but the two paths were structurally
16483        // independent — a future `#[serde(rename_all = "…")]`
16484        // attribute or variant rename would coordinate the wire /
16485        // `Display` / `as_str` triple through the lifted const but
16486        // leave the `Debug` route on the compiler-derived variant name,
16487        // silently desynchronizing the diagnostic byte-string from the
16488        // wire byte-string. Rebinding the template onto `Display`
16489        // ties the diagnostic to the same lifted
16490        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
16491        // emits — drift becomes structurally impossible. Pin the
16492        // byte-string here so a future edit that reverts the template
16493        // to `{estrategia:?}` is caught at caixa-core test time, not
16494        // at consumer dispatch time.
16495        for (variant, expected_scalar) in [
16496            (
16497                PlacementStrategy::SingleNode,
16498                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16499            ),
16500            (
16501                PlacementStrategy::Replicated,
16502                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16503            ),
16504            (
16505                PlacementStrategy::Sharded,
16506                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16507            ),
16508        ] {
16509            let err = AplicacaoError::PlacementWithoutClusters {
16510                estrategia: variant,
16511            };
16512            let msg = err.to_string();
16513            assert!(
16514                msg.starts_with(&format!(":placement {expected_scalar} requires")),
16515                "PlacementWithoutClusters diagnostic for {variant:?} must open \
16516                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16517            );
16518        }
16519    }
16520
16521    #[test]
16522    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
16523        // Peer of
16524        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
16525        // on the second M3 diagnostic that carries the typed
16526        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
16527        // diagnostics now route the strategy scalar through the same
16528        // [`std::fmt::Display`] surface, tying the diagnostic
16529        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
16530        // const set the wire format also emits. The two non-Sharded
16531        // arms are exercised here (the diagnostic exists to flag a
16532        // `:shard-key` slot the current strategy will never consume);
16533        // the peer `Sharded` arm never reaches this diagnostic (the
16534        // `Sharded` strategy consumes `:shard-key` — the
16535        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
16536        // slot instead).
16537        for (variant, expected_scalar) in [
16538            (
16539                PlacementStrategy::SingleNode,
16540                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16541            ),
16542            (
16543                PlacementStrategy::Replicated,
16544                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16545            ),
16546        ] {
16547            let err = AplicacaoError::ShardKeyOnNonSharded {
16548                estrategia: variant,
16549                shard_key: "$tenantId".into(),
16550            };
16551            let msg = err.to_string();
16552            assert!(
16553                msg.starts_with(&format!(":placement {expected_scalar} carries")),
16554                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
16555                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16556            );
16557        }
16558    }
16559
16560    #[test]
16561    fn placement_strategy_all_enumerates_every_variant_once() {
16562        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
16563        // exhaustive-iteration surface: every variant appears exactly
16564        // once, and the slice length matches the arm count of the
16565        // closed set. Every consumer that walks the accepted-strategy
16566        // set (a future `feira app placement --list` CLI-side surfacing,
16567        // a future M4 admission-webhook's rejection body naming the
16568        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
16569        // reverse-projection consumers that iterate the accept-set for
16570        // a "did you mean" hint) reads through this slice, so a future
16571        // variant addition (an `Anycast` mesh-anycast arm the
16572        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
16573        // grows the enum but forgets to grow [`Self::ALL`] silently
16574        // truncates every downstream consumer's accept-set at the same
16575        // pre-addition boundary — this pin fails at caixa-core build
16576        // time on the pairwise-distinct + arm-count invariants.
16577        //
16578        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
16579        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
16580        // pins on the peer closed-set typed-enum axes.
16581        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
16582        assert_eq!(
16583            all.len(),
16584            3,
16585            "PlacementStrategy::ALL must enumerate every variant of the \
16586             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
16587        );
16588        for (i, a) in all.iter().enumerate() {
16589            for (j, b) in all.iter().enumerate() {
16590                if i != j {
16591                    assert_ne!(
16592                        a, b,
16593                        "PlacementStrategy::ALL must carry every variant exactly \
16594                         once — got duplicate {a:?} at indices {i} and {j}"
16595                    );
16596                }
16597            }
16598        }
16599        for variant in [
16600            PlacementStrategy::SingleNode,
16601            PlacementStrategy::Replicated,
16602            PlacementStrategy::Sharded,
16603        ] {
16604            assert!(
16605                all.contains(&variant),
16606                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
16607                 addition that grows the enum but forgets to grow the ALL slice \
16608                 silently truncates every downstream consumer's accept-set at the \
16609                 pre-addition boundary"
16610            );
16611        }
16612    }
16613
16614    #[test]
16615    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
16616        // Fail-before-pass-after pin on the forward accept-set of the
16617        // [`PlacementStrategy::from_wire`] reverse projection: every
16618        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
16619        // constant the [`PlacementStrategy::as_str`] emitter walks
16620        // parses back to its paired variant. Any future arm addition
16621        // that grows the emitter's `as_str` match but forgets to grow
16622        // the parser's `from_str` match silently splits the two halves
16623        // of the round-trip — the wire byte-string one non-serde
16624        // consumer parses from the one the emitter wrote — with the
16625        // failure surfacing at parse time far from the rebrand commit.
16626        // Pinning the three-arm accept-set here catches the drift at
16627        // caixa-core build time.
16628        //
16629        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
16630        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
16631        // closed-set typed-enum `str → Self` axes.
16632        for (wire, expected) in [
16633            (
16634                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16635                PlacementStrategy::SingleNode,
16636            ),
16637            (
16638                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16639                PlacementStrategy::Replicated,
16640            ),
16641            (
16642                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16643                PlacementStrategy::Sharded,
16644            ),
16645        ] {
16646            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16647                panic!(
16648                    "PlacementStrategy::from_wire({wire:?}) must accept every \
16649                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
16650                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
16651                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
16652                )
16653            });
16654            assert_eq!(
16655                parsed, expected,
16656                "PlacementStrategy::from_wire({wire:?}) must return \
16657                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
16658            );
16659        }
16660    }
16661
16662    #[test]
16663    fn placement_strategy_from_wire_round_trips_through_as_str() {
16664        // Fail-before-pass-after pin on the closed round-trip between
16665        // the forward [`PlacementStrategy::as_str`] emitter and the
16666        // reverse [`PlacementStrategy::from_wire`] parser: for every
16667        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
16668        // output must return exactly the same variant. Any per-arm
16669        // divergence — a future arm added to `as_str` but not
16670        // `from_str`, an accidental copy-paste flip in one but not the
16671        // other — silently splits the emit and parse halves and the
16672        // failure surfaces at consumer parse time far from the drift
16673        // site. The `ALL`-iterating shape means a future variant
16674        // addition picks up the coverage by construction.
16675        //
16676        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
16677        // [`crate::CaixaKind::from_wire`] and the
16678        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
16679        // sibling round-trip pin on [`RateLimitUnit`].
16680        for &variant in PlacementStrategy::ALL {
16681            let wire = variant.as_str();
16682            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16683                panic!(
16684                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16685                     must be Some({variant:?}) — the two halves of the round-trip \
16686                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
16687                     got None on wire byte-string {wire:?}"
16688                )
16689            });
16690            assert_eq!(
16691                parsed, variant,
16692                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16693                 must round-trip to the same variant; got {parsed:?}"
16694            );
16695        }
16696    }
16697
16698    #[test]
16699    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
16700        // Fail-before-pass-after pin on the closed-set refusal
16701        // discipline of [`PlacementStrategy::from_wire`]: every
16702        // byte-string outside the three-arm accept-set returns `None`
16703        // rather than silently collapsing onto the [`Default`]
16704        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
16705        // exercised here sweeps the load-bearing drift shapes: the
16706        // empty string (a stripped serde-attribute drift), an all-
16707        // whitespace string (the canonical text-editor accidental
16708        // padding shape), the lowercased kebab-case forms a future
16709        // `#[serde(rename_all = "kebab-case")]` attribute would emit
16710        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
16711        // coincidentally match the accepted canonical scalars, so only
16712        // `"single-node"` fires as a refusal, but pinning the case-
16713        // sensitivity of the accepted arms via the peer [`SingleNode`]
16714        // assertion in the round-trip pin makes the discipline
16715        // structurally clear), the lowercased single-word forms
16716        // (`"singlenode"`), the padded canonical scalar
16717        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
16718        // (`"Sharded\n"`), and a pointer-different `&'static str` that
16719        // happens to alias a canonical byte-string by content but not
16720        // by identity (validated implicitly by the emitter's routing
16721        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
16722        // identity a paired [`crate::assert_str_reexport_identity`] pin
16723        // in caixa-core's per-const declaration surface would catch).
16724        //
16725        // Peer of the sibling
16726        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
16727        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
16728        for bad in [
16729            "",
16730            " ",
16731            "\n",
16732            "\t",
16733            "single-node",
16734            "singlenode",
16735            "SingleNodes",
16736            "single_node",
16737            "single node",
16738            "SINGLENODE",
16739            "SingleNode ",
16740            " SingleNode",
16741            " Sharded ",
16742            "Sharded\n",
16743            "replicated ",
16744            "sharded",
16745            "REPLICATED",
16746            "Anycast",
16747            "Global",
16748            "?",
16749        ] {
16750            assert!(
16751                PlacementStrategy::from_wire(bad).is_none(),
16752                "PlacementStrategy::from_wire({bad:?}) must return None — the \
16753                 parser's accept-set is exactly the three PlacementStrategy::as_str \
16754                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
16755                 is outside that closed set"
16756            );
16757        }
16758    }
16759
16760    #[test]
16761    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
16762        // Fail-before-pass-after pin on the third path of the four-path
16763        // convergence: `from_str` (the reverse projection) inverts the
16764        // `Serialize` derive's wire byte-string on every variant.
16765        // Together with the pre-existing three-path convergence
16766        // (`Display` + `as_str` + `Serialize` all resolve to the same
16767        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
16768        // the peer
16769        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
16770        // this closes the round-trip: the wire byte-string the
16771        // `Serialize` derive emits parses back to the same variant
16772        // through `from_str`, so any future serde-attribute or variant-
16773        // rename drift on the emit half now surfaces as a matched drift
16774        // on the parse half at caixa-core build time — the two halves
16775        // migrate as a unit through the lifted consts on any future
16776        // rename, and the round-trip cannot silently split.
16777        //
16778        // Peer of the sibling
16779        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
16780        // wire-format pin — extends the three-path convergence
16781        // (`Display` + `as_str` + `Serialize`) onto the fourth path
16782        // (`from_str`), closing the `str ↔ Self` round-trip on the
16783        // M3 `:placement :estrategia` closed-set axis.
16784        for &variant in PlacementStrategy::ALL {
16785            let wire = serde_json::to_string(&variant).unwrap();
16786            let unquoted = wire
16787                .strip_prefix('"')
16788                .and_then(|s| s.strip_suffix('"'))
16789                .expect("serialized PlacementStrategy is a JSON string");
16790            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
16791                panic!(
16792                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
16793                     Serialize derive's wire byte-string for \
16794                     PlacementStrategy::{variant:?} — the four-path convergence \
16795                     (Display + as_str + Serialize + from_str) resolves through \
16796                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
16797                )
16798            });
16799            assert_eq!(
16800                parsed, variant,
16801                "PlacementStrategy::from_wire of the Serialize derive's wire \
16802                 byte-string for PlacementStrategy::{variant:?} must round-trip \
16803                 to the same variant; got {parsed:?}"
16804            );
16805        }
16806    }
16807
16808    #[test]
16809    fn rejects_zero_policy_timeout() {
16810        let mut s = three_member_spec();
16811        s.politicas.timeout = Some(Duration::ZERO);
16812        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
16813    }
16814
16815    #[test]
16816    fn rejects_zero_policy_retries() {
16817        let mut s = three_member_spec();
16818        s.politicas.retries = Some(0);
16819        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
16820    }
16821
16822    #[test]
16823    fn rejects_policy_retries_above_cap() {
16824        // The fail-before-pass-after pin: `Some(11)` is structurally
16825        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
16826        // passed validate on every pre-gate codebase because the
16827        // typed slot's only check was the zero-floor arm. The
16828        // thundering-herd amplification vector only surfaced at the
16829        // runtime substrate (Envoy / Cilium L7 retry overlay)
16830        // far from the source caixa.lisp with no field naming the
16831        // offending policy.
16832        let mut s = three_member_spec();
16833        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
16834        assert_eq!(
16835            s.validate().unwrap_err(),
16836            AplicacaoError::PolicyRetriesExceedsCap {
16837                retries: POLICY_RETRIES_MAX + 1
16838            }
16839        );
16840    }
16841
16842    #[test]
16843    fn rejects_policy_retries_far_above_cap() {
16844        // The `u32::MAX` worst case — the four-billion-retry policy
16845        // a typo (`(:retries 4294967295)`) or struct-literal
16846        // copy-paste lands in the slot. Pin the cap arm's coverage
16847        // explicitly across the full `u32` overflow so a future
16848        // relaxation that drops the upper bound surfaces here.
16849        let mut s = three_member_spec();
16850        s.politicas.retries = Some(u32::MAX);
16851        assert_eq!(
16852            s.validate().unwrap_err(),
16853            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
16854        );
16855    }
16856
16857    #[test]
16858    fn accepts_policy_retries_at_cap() {
16859        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
16860        // must validate. The cap is inclusive on the top edge,
16861        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16862        // discipline on the sibling [`crate::LimitsSpec::memory`]
16863        // axis. Pin the boundary explicitly so a future off-by-one
16864        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
16865        // surfaces here as a test failure rather than a silent
16866        // contract narrowing.
16867        let mut s = three_member_spec();
16868        s.politicas.retries = Some(POLICY_RETRIES_MAX);
16869        s.validate()
16870            .expect("retries == POLICY_RETRIES_MAX must validate");
16871    }
16872
16873    #[test]
16874    fn accepts_policy_retries_typical_values() {
16875        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
16876        // every value in the validated set must pass. The
16877        // Envoy / Istio production-playbook recommendation band
16878        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
16879        // (`maxRetries ≤ 10`) both lie within this set.
16880        for r in 1..=POLICY_RETRIES_MAX {
16881            let mut s = three_member_spec();
16882            s.politicas.retries = Some(r);
16883            s.validate()
16884                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
16885        }
16886    }
16887
16888    #[test]
16889    fn policy_retries_zero_takes_precedence_over_cap() {
16890        // The cross-arm ordering pin: `Some(0)` is structurally
16891        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
16892        // (cap), but the zero-floor diagnostic is the more
16893        // self-locating one (it directly names the omit-axis
16894        // remediation), so the validate gate must fire on zero
16895        // first. Pin the order so a future refactor that reorders
16896        // the arms surfaces here as a test failure rather than a
16897        // silent diagnostic regression. Same shape every other
16898        // zero-then-shape ordering on this surface uses
16899        // ([`AplicacaoError::PolicyTimeoutZero`] then
16900        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
16901        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
16902        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
16903        let mut s = three_member_spec();
16904        s.politicas.retries = Some(0);
16905        assert_eq!(
16906            s.validate().unwrap_err(),
16907            AplicacaoError::PolicyRetriesZero,
16908            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
16909        );
16910    }
16911
16912    #[test]
16913    fn policy_retries_cap_diagnostic_carries_offending_value() {
16914        // The diagnostic-shape pin: the offending `u32` is carried
16915        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
16916        // variant so the surfaced error message names the value the
16917        // author wrote (`":politicas :retries (47) exceeds the
16918        // mesh-policy ceiling …"`), not just the cap. Same
16919        // self-locating diagnostic shape every other typed-cap arm
16920        // on this surface carries
16921        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16922        // offending byte count verbatim).
16923        let mut s = three_member_spec();
16924        s.politicas.retries = Some(47);
16925        let err = s.validate().unwrap_err();
16926        assert!(
16927            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
16928            "got {err:?}"
16929        );
16930        let msg = err.to_string();
16931        assert!(
16932            msg.contains("47"),
16933            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
16934        );
16935    }
16936
16937    #[test]
16938    fn policy_retries_cap_is_aws_app_mesh_aligned() {
16939        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
16940        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
16941        // schema cap — the only upstream mesh-policy schema that
16942        // documents an explicit hard cap. Pinning the literal value
16943        // here surfaces a future drift (a relaxation to 20, a
16944        // tightening to 5) as a deliberate test edit, not a silent
16945        // contract narrowing.
16946        assert_eq!(POLICY_RETRIES_MAX, 10);
16947    }
16948
16949    #[test]
16950    fn rejects_circuit_breaker_zero_max_failures() {
16951        let mut s = three_member_spec();
16952        s.politicas.circuit_breaker = Some(CircuitBreaker {
16953            max_failures: 0,
16954            window: Duration::from_secs(60),
16955        });
16956        assert_eq!(
16957            s.validate().unwrap_err(),
16958            AplicacaoError::PolicyBreakerZeroFailures
16959        );
16960    }
16961
16962    #[test]
16963    fn rejects_circuit_breaker_max_failures_above_cap() {
16964        // The fail-before-pass-after pin: `1001` is structurally one
16965        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
16966        // silently passed validate on every pre-gate codebase
16967        // because the typed slot's only check was the zero-floor
16968        // arm. The breaker-no-op vector only surfaced at the runtime
16969        // substrate (Envoy / Cilium L7 outlier-detection overlay)
16970        // far from the source caixa.lisp with no field naming the
16971        // offending policy.
16972        let mut s = three_member_spec();
16973        s.politicas.circuit_breaker = Some(CircuitBreaker {
16974            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16975            window: Duration::from_secs(60),
16976        });
16977        assert_eq!(
16978            s.validate().unwrap_err(),
16979            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16980                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16981            }
16982        );
16983    }
16984
16985    #[test]
16986    fn rejects_circuit_breaker_max_failures_far_above_cap() {
16987        // The `u32::MAX` worst case — the four-billion-failure
16988        // threshold a typo (`(:max-failures 4294967295)`) or a
16989        // struct-literal copy-paste lands in the slot. Pin the cap
16990        // arm's coverage explicitly across the full `u32` overflow
16991        // so a future relaxation that drops the upper bound surfaces
16992        // here.
16993        let mut s = three_member_spec();
16994        s.politicas.circuit_breaker = Some(CircuitBreaker {
16995            max_failures: u32::MAX,
16996            window: Duration::from_secs(60),
16997        });
16998        assert_eq!(
16999            s.validate().unwrap_err(),
17000            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17001                max_failures: u32::MAX,
17002            }
17003        );
17004    }
17005
17006    #[test]
17007    fn accepts_circuit_breaker_max_failures_at_cap() {
17008        // The boundary value — exactly
17009        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
17010        // cap is inclusive on the top edge, matching the
17011        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
17012        // discipline on the sibling capped axes. Pin the boundary
17013        // explicitly so a future off-by-one tightening
17014        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
17015        // surfaces here as a test failure rather than a silent
17016        // contract narrowing.
17017        let mut s = three_member_spec();
17018        s.politicas.circuit_breaker = Some(CircuitBreaker {
17019            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
17020            window: Duration::from_secs(60),
17021        });
17022        s.validate()
17023            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
17024    }
17025
17026    #[test]
17027    fn accepts_circuit_breaker_max_failures_typical_values() {
17028        // The documented production-playbook band positive-control
17029        // sweep — every value Hystrix / Istio / Envoy / Polly /
17030        // Resilience4j recommend (5..=50) must pass, plus a sweep
17031        // through the hyperscale band (100, 500, 1000) the cap
17032        // accepts. Pin the inclusive validated set explicitly so a
17033        // future tightening of the ceiling surfaces here.
17034        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
17035            let mut s = three_member_spec();
17036            s.politicas.circuit_breaker = Some(CircuitBreaker {
17037                max_failures: n,
17038                window: Duration::from_secs(60),
17039            });
17040            s.validate()
17041                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
17042        }
17043    }
17044
17045    #[test]
17046    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
17047        // The cross-arm ordering pin: `0` is structurally outside
17048        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
17049        // (cap), but the zero-floor diagnostic is the more
17050        // self-locating one (it directly names the omit-axis
17051        // remediation), so the validate gate must fire on zero
17052        // first. Same shape every other zero-then-shape ordering on
17053        // this surface uses
17054        // ([`AplicacaoError::PolicyRetriesZero`] then
17055        // [`AplicacaoError::PolicyRetriesExceedsCap`];
17056        // [`AplicacaoError::PolicyTimeoutZero`] then
17057        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
17058        let mut s = three_member_spec();
17059        s.politicas.circuit_breaker = Some(CircuitBreaker {
17060            max_failures: 0,
17061            window: Duration::from_secs(60),
17062        });
17063        assert_eq!(
17064            s.validate().unwrap_err(),
17065            AplicacaoError::PolicyBreakerZeroFailures,
17066            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
17067        );
17068    }
17069
17070    #[test]
17071    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
17072        // The cross-arm ordering pin between the cap and the
17073        // sibling `:window` gates (zero-window, canonical-window).
17074        // A breaker carrying both an over-cap `max_failures` AND a
17075        // structurally invalid window (zero, sub-ms) must surface
17076        // the cap diagnostic first — the cap arm is wired
17077        // immediately after the zero-failure arm and strictly
17078        // before the window arms, so the offending value the
17079        // diagnostic names matches the order the author would
17080        // discover the gates by reading top-to-bottom through
17081        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
17082        // future refactor that reorders the arms surfaces here as a
17083        // test failure rather than a silent diagnostic regression.
17084        let mut s = three_member_spec();
17085        s.politicas.circuit_breaker = Some(CircuitBreaker {
17086            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17087            window: Duration::ZERO,
17088        });
17089        assert_eq!(
17090            s.validate().unwrap_err(),
17091            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17092                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17093            },
17094            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
17095        );
17096    }
17097
17098    #[test]
17099    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
17100        // The diagnostic-shape pin: the offending `u32` is carried
17101        // verbatim into the
17102        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
17103        // variant so the surfaced error message names the value the
17104        // author wrote (`":politicas :circuit-breaker :max-failures
17105        // (50000) exceeds the mesh-policy ceiling …"`), not just
17106        // the cap. Same self-locating diagnostic shape every other
17107        // typed-cap arm on this surface carries
17108        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
17109        // offending retry count verbatim,
17110        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
17111        // offending byte count verbatim).
17112        let mut s = three_member_spec();
17113        s.politicas.circuit_breaker = Some(CircuitBreaker {
17114            max_failures: 50_000,
17115            window: Duration::from_secs(60),
17116        });
17117        let err = s.validate().unwrap_err();
17118        assert!(
17119            matches!(
17120                err,
17121                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17122                    max_failures: 50_000
17123                }
17124            ),
17125            "got {err:?}"
17126        );
17127        let msg = err.to_string();
17128        assert!(
17129            msg.contains("50000"),
17130            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
17131        );
17132    }
17133
17134    #[test]
17135    fn policy_breaker_max_failures_cap_pins_canonical_value() {
17136        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
17137        // value at 1000 — an order of magnitude above every
17138        // documented production-playbook recommendation band
17139        // (Hystrix `requestVolumeThreshold` default 20, Istio
17140        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
17141        // `outlier_detection.consecutive_5xx` default 5, Polly /
17142        // Resilience4j typical 5..=50) and below the
17143        // clearly-pathological "effectively no protection" floor
17144        // (10_000, 100_000, u32::MAX). Pinning the literal value
17145        // here surfaces a future drift (a relaxation to 10_000, a
17146        // tightening to 100) as a deliberate test edit, not a
17147        // silent contract narrowing.
17148        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
17149    }
17150
17151    #[test]
17152    fn rejects_circuit_breaker_zero_window() {
17153        let mut s = three_member_spec();
17154        s.politicas.circuit_breaker = Some(CircuitBreaker {
17155            max_failures: 5,
17156            window: Duration::ZERO,
17157        });
17158        assert_eq!(
17159            s.validate().unwrap_err(),
17160            AplicacaoError::PolicyBreakerZeroWindow
17161        );
17162    }
17163
17164    #[test]
17165    fn rejects_zero_rate_limit() {
17166        let mut s = three_member_spec();
17167        s.politicas.rate_limit = Some(RateLimit {
17168            rate: 0,
17169            window: Duration::from_secs(1),
17170        });
17171        assert_eq!(
17172            s.validate().unwrap_err(),
17173            AplicacaoError::PolicyRateLimitZero
17174        );
17175    }
17176
17177    #[test]
17178    fn rejects_rate_limit_zero_window() {
17179        // `RateLimit { rate: 100, window: Duration::ZERO }` is
17180        // constructible programmatically (the typed `Duration` field
17181        // imposes no nonzero invariant) but renders through
17182        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
17183        // codec's `parse` rejects as `unknown rate-limit window unit
17184        // "0s"`. Until this validate-time gate landed the typed slot
17185        // accepted the value silently and the round-trip break only
17186        // surfaced at deserialize time (potentially in a downstream
17187        // consumer that never re-validates). Pin the rejection at
17188        // `AplicacaoSpec::validate` so the typed slot's valid set
17189        // matches the codec's round-trippable set structurally.
17190        let mut s = three_member_spec();
17191        s.politicas.rate_limit = Some(RateLimit {
17192            rate: 100,
17193            window: Duration::ZERO,
17194        });
17195        assert_eq!(
17196            s.validate().unwrap_err(),
17197            AplicacaoError::PolicyRateLimitWindowNotCanonical {
17198                window: Duration::ZERO
17199            }
17200        );
17201    }
17202
17203    #[test]
17204    fn rejects_rate_limit_arbitrary_seconds_window() {
17205        // 45 seconds is a valid `Duration` but not one of the three
17206        // canonical rate-limit windows the codec round-trips
17207        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
17208        // refuses on round-trip — same round-trip-break shape the
17209        // zero-window arm above pins, with a non-zero magnitude to
17210        // guard against a future "reject only zero" half-measure.
17211        let mut s = three_member_spec();
17212        let window = Duration::from_secs(45);
17213        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
17214        assert_eq!(
17215            s.validate().unwrap_err(),
17216            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17217        );
17218    }
17219
17220    #[test]
17221    fn rejects_rate_limit_two_minute_window() {
17222        // 120 seconds = 2 minutes is a "looks-canonical" but
17223        // not-canonical window: it's a clean integer multiple of the
17224        // minute unit, but the codec only round-trips the
17225        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
17226        // A `Duration::from_secs(120)` window renders as `"100/120s"`
17227        // which the parser rejects. Pinning this case rules out a
17228        // future "accept any clean multiple of s/m/h" relaxation
17229        // that would silently break the codec contract.
17230        let mut s = three_member_spec();
17231        let window = Duration::from_secs(120);
17232        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
17233        assert_eq!(
17234            s.validate().unwrap_err(),
17235            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17236        );
17237    }
17238
17239    #[test]
17240    fn rejects_rate_limit_subsecond_window() {
17241        // A sub-second window (e.g. 500ms) is a valid `Duration` but
17242        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
17243        // Pin the rejection so a future relaxation can't silently
17244        // admit fractional-second windows that the codec can't
17245        // round-trip.
17246        let mut s = three_member_spec();
17247        let window = Duration::from_millis(500);
17248        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
17249        assert_eq!(
17250            s.validate().unwrap_err(),
17251            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17252        );
17253    }
17254
17255    #[test]
17256    fn rejects_policy_rate_limit_above_cap() {
17257        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
17258        // is structurally one past the cap and silently passed
17259        // validate on every pre-gate codebase because the typed slot's
17260        // only `rate` check was the zero-floor arm. The no-op-limiter
17261        // shape only surfaced at the runtime substrate (Envoy's
17262        // `local_rate_limit.token_bucket.max_tokens`, the future
17263        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
17264        // with no field naming the offending policy.
17265        let mut s = three_member_spec();
17266        s.politicas.rate_limit = Some(RateLimit {
17267            rate: POLICY_RATE_LIMIT_MAX + 1,
17268            window: Duration::from_secs(1),
17269        });
17270        assert_eq!(
17271            s.validate().unwrap_err(),
17272            AplicacaoError::PolicyRateLimitExceedsCap {
17273                rate: POLICY_RATE_LIMIT_MAX + 1
17274            }
17275        );
17276    }
17277
17278    #[test]
17279    fn rejects_policy_rate_limit_far_above_cap() {
17280        // The `u32::MAX` worst case — the four-billion-token rate-limit
17281        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
17282        // copy-paste lands in the slot. Pin the cap arm's coverage
17283        // explicitly across the full `u32` overflow so a future
17284        // relaxation that drops the upper bound surfaces here. Peer to
17285        // `rejects_policy_retries_far_above_cap` on the sibling
17286        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
17287        // on the sibling `:max-failures` axis.
17288        let mut s = three_member_spec();
17289        s.politicas.rate_limit = Some(RateLimit {
17290            rate: u32::MAX,
17291            window: Duration::from_secs(1),
17292        });
17293        assert_eq!(
17294            s.validate().unwrap_err(),
17295            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
17296        );
17297    }
17298
17299    #[test]
17300    fn accepts_policy_rate_limit_at_cap() {
17301        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
17302        // must validate. The cap is inclusive on the top edge, matching
17303        // every other typed upper bound in this crate
17304        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
17305        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
17306        // across all three canonical windows so a future off-by-one
17307        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
17308        // window-conditional cap surfaces here as a test failure rather
17309        // than a silent contract narrowing.
17310        for secs in [1u64, 60, 3600] {
17311            let mut s = three_member_spec();
17312            s.politicas.rate_limit = Some(RateLimit {
17313                rate: POLICY_RATE_LIMIT_MAX,
17314                window: Duration::from_secs(secs),
17315            });
17316            s.validate().unwrap_or_else(|e| {
17317                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
17318            });
17319        }
17320    }
17321
17322    #[test]
17323    fn accepts_policy_rate_limit_typical_values() {
17324        // The documented production-playbook recommendation band —
17325        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
17326        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
17327        // Enterprise ~1M per-hour. Every value in the validated set
17328        // must pass; pin the band explicitly so a future tightening
17329        // surfaces here.
17330        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
17331            for secs in [1u64, 60, 3600] {
17332                let mut s = three_member_spec();
17333                s.politicas.rate_limit = Some(RateLimit {
17334                    rate,
17335                    window: Duration::from_secs(secs),
17336                });
17337                s.validate().unwrap_or_else(|e| {
17338                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
17339                });
17340            }
17341        }
17342    }
17343
17344    #[test]
17345    fn policy_rate_limit_zero_takes_precedence_over_cap() {
17346        // The cross-arm ordering pin: `rate == 0` is structurally
17347        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
17348        // (cap), but the zero-floor diagnostic is the more
17349        // self-locating one (it directly names the omit-axis
17350        // remediation). Pin the order so a future refactor that
17351        // reorders the arms surfaces here as a test failure rather
17352        // than a silent diagnostic regression. Same shape every other
17353        // zero-then-cap ordering on this surface uses
17354        // ([`AplicacaoError::PolicyRetriesZero`] then
17355        // [`AplicacaoError::PolicyRetriesExceedsCap`];
17356        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17357        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17358        let mut s = three_member_spec();
17359        s.politicas.rate_limit = Some(RateLimit {
17360            rate: 0,
17361            window: Duration::from_secs(1),
17362        });
17363        assert_eq!(
17364            s.validate().unwrap_err(),
17365            AplicacaoError::PolicyRateLimitZero,
17366            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
17367        );
17368    }
17369
17370    #[test]
17371    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
17372        // Two-axis-bad pin: rate above cap *and* window non-canonical.
17373        // The validate gate must fire on the rate cap first — the
17374        // amplification-shape (no-op limiter) diagnostic is the more
17375        // fundamental one; the window-canonical diagnostic is the
17376        // narrower codec-round-trip shape. Pin the ordering so a future
17377        // refactor that reorders the rate-then-window check arms
17378        // surfaces here as a test failure rather than a silent
17379        // diagnostic regression.
17380        let mut s = three_member_spec();
17381        s.politicas.rate_limit = Some(RateLimit {
17382            rate: POLICY_RATE_LIMIT_MAX + 1,
17383            window: Duration::from_secs(45),
17384        });
17385        assert_eq!(
17386            s.validate().unwrap_err(),
17387            AplicacaoError::PolicyRateLimitExceedsCap {
17388                rate: POLICY_RATE_LIMIT_MAX + 1
17389            },
17390            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
17391        );
17392    }
17393
17394    #[test]
17395    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
17396        // The diagnostic-shape pin: the offending `u32` is carried
17397        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
17398        // variant so the surfaced error message names the value the
17399        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
17400        // the mesh-policy ceiling …"`), not just the cap. Same
17401        // self-locating diagnostic shape every other typed-cap arm on
17402        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
17403        // carries the offending retries count verbatim,
17404        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
17405        // the offending failure count verbatim).
17406        let mut s = three_member_spec();
17407        s.politicas.rate_limit = Some(RateLimit {
17408            rate: 5_000_000,
17409            window: Duration::from_secs(1),
17410        });
17411        let err = s.validate().unwrap_err();
17412        assert!(
17413            matches!(
17414                err,
17415                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
17416            ),
17417            "got {err:?}"
17418        );
17419        let msg = err.to_string();
17420        assert!(
17421            msg.contains("5000000"),
17422            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
17423        );
17424    }
17425
17426    #[test]
17427    fn policy_rate_limit_cap_pins_canonical_value() {
17428        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
17429        // 1_000_000 — two-to-three orders of magnitude above every
17430        // documented production-playbook recommendation band (Envoy /
17431        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
17432        // Gateway 10_000..=100_000 per-minute) and below the
17433        // clearly-pathological "paste-from-binary blob" floor
17434        // (100_000_000, u32::MAX). Pinning the literal value here
17435        // surfaces a future drift (a relaxation to 10_000_000, a
17436        // tightening to 100_000) as a deliberate test edit, not a
17437        // silent contract narrowing.
17438        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
17439    }
17440
17441    #[test]
17442    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
17443        // Both axes are invalid here: rate == 0 *and* window is
17444        // non-canonical. The validate gate must fire on rate first
17445        // (matching the existing `rejects_zero_rate_limit` ordering),
17446        // so the existing diagnostic continues to lead with the
17447        // simpler "zero rate" framing. Pinning the order of checks
17448        // so a future refactor that reorders the arms surfaces here
17449        // as a test failure rather than a silent diagnostic
17450        // regression.
17451        let mut s = three_member_spec();
17452        s.politicas.rate_limit = Some(RateLimit {
17453            rate: 0,
17454            window: Duration::from_secs(45),
17455        });
17456        assert_eq!(
17457            s.validate().unwrap_err(),
17458            AplicacaoError::PolicyRateLimitZero
17459        );
17460    }
17461
17462    #[test]
17463    fn rate_limit_canonical_windows_validate() {
17464        // The three canonical windows the codec round-trips
17465        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
17466        // unchanged. Pin the full canonical set as a positive case
17467        // (the existing `rate_limit_round_trip_seconds` /
17468        // `rate_limit_round_trip_minutes` tests pin the
17469        // serialize-then-deserialize property at the codec layer; this
17470        // test pins the validate-side complement so a future tightening
17471        // of the canonical set — e.g. dropping `:hour` — surfaces here
17472        // as a test failure rather than a silent contract narrowing).
17473        for secs in [1u64, 60, 3600] {
17474            let mut s = three_member_spec();
17475            s.politicas.rate_limit = Some(RateLimit {
17476                rate: 100,
17477                window: Duration::from_secs(secs),
17478            });
17479            s.validate().expect("canonical window must validate");
17480        }
17481    }
17482
17483    #[test]
17484    fn rate_limit_validated_value_round_trips_through_codec() {
17485        // The structural property the validate gate enforces:
17486        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
17487        // losslessly through the `rate_limit_codec` (serialize → string
17488        // → deserialize → equal value). Pin this end-to-end so a future
17489        // change to either side (the validate gate's accepted window
17490        // set, the codec's parse/render unit set) that breaks the
17491        // alignment surfaces here. The previous-state shape (typed
17492        // slot accepts arbitrary `Duration`, codec only round-trips
17493        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
17494        // window — the validate gate now forecloses that.
17495        for secs in [1u64, 60, 3600] {
17496            let mut s = three_member_spec();
17497            s.politicas.rate_limit = Some(RateLimit {
17498                rate: 250,
17499                window: Duration::from_secs(secs),
17500            });
17501            s.validate().unwrap();
17502            let json = serde_json::to_string(&s.politicas).unwrap();
17503            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17504            assert_eq!(
17505                back.rate_limit, s.politicas.rate_limit,
17506                "every validated :rate-limit must round-trip losslessly through the codec"
17507            );
17508        }
17509    }
17510
17511    #[test]
17512    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
17513        // The hour-window canonical form (`"<n>/h"`) was missing from
17514        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
17515        // pair. Now that the validate gate pins 3600s as part of the
17516        // canonical set, pin its serialize-side render shape too so
17517        // the third leg of the s/m/h tripod is explicitly tested.
17518        let policy = MeshPolicy {
17519            rate_limit: Some(RateLimit {
17520                rate: 10000,
17521                window: Duration::from_secs(3600),
17522            }),
17523            ..Default::default()
17524        };
17525        let json = serde_json::to_string(&policy).unwrap();
17526        assert!(
17527            json.contains("\"10000/h\""),
17528            "hour-window canonical form must render with `h` suffix (got: {json})"
17529        );
17530        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17531        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
17532    }
17533
17534    #[test]
17535    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
17536        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
17537        // typed accessor's accepted-window set against the codec's
17538        // accepted set explicitly. A future addition to the codec
17539        // (e.g. accepting `:day`/`:week` as authoring units) must be
17540        // accompanied by a parallel addition here, and a regression
17541        // that drops one of the three canonical units from either
17542        // side surfaces as a test failure. The accessor is the
17543        // single source of truth for the canonical-window set —
17544        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
17545        // gate and [`rate_limit_codec::render`]'s canonical arm both
17546        // read through it — this test enshrines that its
17547        // `Duration → Option<RateLimitUnit>` projection matches the
17548        // codec's parse / render arms' accepted-window set exactly.
17549        //
17550        // Predecessor: this pin previously read the module-private
17551        // free helper `is_canonical_rate_limit_window` — a delegate
17552        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
17553        // — but the helper had no production consumers left after the
17554        // validate-gate migration onto [`RateLimit::canonical_unit`]
17555        // and was deleted; the closed-set arm-window bijection now
17556        // lives on exactly one typed dispatch on the substrate
17557        // primitive.
17558        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
17559            RateLimit { rate: 1, window }.canonical_unit()
17560        };
17561        assert!(canonical_unit(Duration::from_secs(1)).is_some());
17562        assert!(canonical_unit(Duration::from_secs(60)).is_some());
17563        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
17564        // Non-canonical windows the accessor rejects.
17565        assert!(canonical_unit(Duration::ZERO).is_none());
17566        assert!(canonical_unit(Duration::from_secs(2)).is_none());
17567        assert!(canonical_unit(Duration::from_secs(30)).is_none());
17568        assert!(canonical_unit(Duration::from_secs(120)).is_none());
17569        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
17570        // Sub-second windows: even `Duration::from_millis(1000)` is
17571        // exactly 1s and accepted; `Duration::from_millis(500)` is
17572        // sub-second and rejected.
17573        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
17574        assert!(canonical_unit(Duration::from_millis(500)).is_none());
17575        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
17576    }
17577
17578    #[test]
17579    fn rate_limit_unit_table_projections_are_mutual_inverses() {
17580        // Bidirection pin against the closed-set typed enum
17581        // [`RateLimitUnit`] arm-table (the canonical
17582        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
17583        // of the rate-limit unit surface reads from). The two
17584        // projection directions [`RateLimitUnit::from_suffix`] /
17585        // [`RateLimitUnit::window`] (str → Duration, exposed as one
17586        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
17587        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
17588        // (Duration → str, exposed as one typed dispatch through
17589        // [`RateLimit::canonical_unit`] composed with
17590        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
17591        // codec's parse arm ([`rate_limit_codec::parse`] via
17592        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
17593        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
17594        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
17595        // via [`RateLimit::canonical_unit`]) all key off. A future
17596        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
17597        // sub-second window) is one variant + one arm per method on the
17598        // closed-set enum; the compiler-enforced exhaustiveness on
17599        // every consumer's `match self` arms picks it up by
17600        // construction. This pin enshrines that both projection
17601        // directions agree on every canonical arm row and neither
17602        // leaks a spurious entry the other doesn't recognize.
17603        //
17604        // Predecessor: this test previously read the two vestigial
17605        // module-private free helpers `rate_limit_window_unit` and
17606        // `rate_limit_window_from_unit` on the `Duration → &str` and
17607        // `&str → Duration` axes; the former was deleted after its
17608        // sole production consumer ([`rate_limit_codec::render`])
17609        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
17610        // the latter is folded here into the substrate primitive
17611        // [`RateLimitUnit::window_from_suffix`] so both projection
17612        // directions live on the closed-set enum's arm-table.
17613        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
17614            let window = super::RateLimitUnit::window_from_suffix(unit)
17615                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
17616            assert_eq!(
17617                window,
17618                Duration::from_secs(secs),
17619                "unit {unit:?} must resolve to {secs}s"
17620            );
17621            let projected_suffix = RateLimit { rate: 1, window }
17622                .canonical_unit()
17623                .map(super::RateLimitUnit::as_suffix);
17624            assert_eq!(
17625                projected_suffix,
17626                Some(unit),
17627                "Duration({secs}s) must render as {unit:?} \
17628                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
17629            );
17630        }
17631        // Non-table units yield None on the `unit → Duration`
17632        // projection — a future `"d"` addition to the table would
17633        // flip this arm; today it pins the current three-row table's
17634        // rejection semantics.
17635        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
17636        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
17637        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
17638        // Non-table Durations yield None on the `Duration → unit`
17639        // projection — pins that the two projections agree on the
17640        // "not in the table" semantic too, so a drift where the
17641        // parse-side accepts a value the render-side can't emit is
17642        // a build error at the two-arm pair, not a silent codec
17643        // round-trip break.
17644        let projected_suffix = |window: Duration| -> Option<&'static str> {
17645            RateLimit { rate: 1, window }
17646                .canonical_unit()
17647                .map(super::RateLimitUnit::as_suffix)
17648        };
17649        assert!(projected_suffix(Duration::from_secs(2)).is_none());
17650        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
17651        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
17652    }
17653
17654    #[test]
17655    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
17656        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
17657        // substrate-primitive `&str → Duration` associated method the
17658        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
17659        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
17660        // to the same [`Duration`] the two-step composition
17661        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
17662        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
17663        // `"MIN"`) must project to [`None`] on both paths. A future
17664        // implementation of `window_from_suffix` that took a shortcut
17665        // through a per-suffix `match` table (bypassing the arm-table's
17666        // `Self::from_suffix` scan and the arm-table's `Self::window`
17667        // dispatch) would silently split the accept-set — the parse
17668        // arm would accept a suffix the enum's arm-table doesn't know,
17669        // or reject a suffix the enum's arm-table does; this pin
17670        // surfaces that drift at caixa-core build time rather than at a
17671        // downstream serde round-trip audit on a live `MeshPolicy`.
17672        //
17673        // Same byte-parity discipline the sibling
17674        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
17675        // pin carries on the peer `Duration → RateLimitUnit` axis via
17676        // [`RateLimit::canonical_unit`], and the peer
17677        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17678        // carries on the bidirectional arm-table axis — extended here
17679        // onto the fifth (and last unlifted) projection axis on the
17680        // closed-set enum's arm-table.
17681        let composition = |suffix: &str| -> Option<Duration> {
17682            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
17683        };
17684        for suffix in ["s", "m", "h"] {
17685            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17686            let via_composition = composition(suffix);
17687            assert_eq!(
17688                via_method, via_composition,
17689                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17690                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
17691                 method must delegate to the arm-table's two typed dispatches, \
17692                 not shortcut through a per-suffix match table"
17693            );
17694            assert!(
17695                via_method.is_some(),
17696                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
17697                 RateLimitUnit::window_from_suffix"
17698            );
17699        }
17700        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
17701            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17702            let via_composition = composition(suffix);
17703            assert_eq!(
17704                via_method, via_composition,
17705                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17706                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
17707                 axis too"
17708            );
17709            assert!(
17710                via_method.is_none(),
17711                "non-arm suffix {suffix:?} must project to None via \
17712                 RateLimitUnit::window_from_suffix — a future extension that \
17713                 accepted this suffix without a corresponding arm on the enum \
17714                 would split the codec's parse-accepted set from the enum's \
17715                 arm-table"
17716            );
17717        }
17718        // And the codec's parse arm now reads through this method: a
17719        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
17720        // the same `Duration` the method returns for its unit, closing
17721        // the two-consumer drift surface (the codec's parse arm and the
17722        // enum's arm-table) with one typed dispatch on the substrate
17723        // primitive.
17724        for suffix in ["s", "m", "h"] {
17725            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
17726            let mp: MeshPolicy = serde_json::from_str(&wire)
17727                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
17728            let parsed = mp.rate_limit().expect("rate_limit payload present");
17729            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
17730                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
17731            assert_eq!(
17732                parsed.window(),
17733                via_method,
17734                "codec parse arm on {wire:?} must resolve the window through \
17735                 RateLimitUnit::window_from_suffix, not a divergent path"
17736            );
17737        }
17738    }
17739
17740    #[test]
17741    fn rate_limit_unit_all_enumerates_every_arm_once() {
17742        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
17743        // enumerate every arm of the closed-set enum exactly once, in
17744        // the canonical shortest-to-longest window order (Second before
17745        // Minute before Hour) — the same order the sibling
17746        // [`crate::supervisor::RestartStrategy`] /
17747        // [`crate::supervisor::RestartPolicy`] /
17748        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
17749        // typed enums carry (the arm declared first is the arm listed
17750        // first). A future variant addition that extends the enum
17751        // without appending to [`RateLimitUnit::ALL`] leaves the
17752        // exhaustive iteration surface silently short one arm — the
17753        // codec's parse arm would then reject the new suffix even
17754        // though the enum knows it. This pin closes the drift.
17755        assert_eq!(
17756            super::RateLimitUnit::ALL,
17757            &[
17758                super::RateLimitUnit::Second,
17759                super::RateLimitUnit::Minute,
17760                super::RateLimitUnit::Hour,
17761            ],
17762            "RateLimitUnit::ALL must enumerate every arm exactly once, \
17763             in canonical shortest-to-longest window order"
17764        );
17765    }
17766
17767    #[test]
17768    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
17769        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
17770        // every arm's [`RateLimitUnit::as_suffix`] output must parse
17771        // back through [`RateLimitUnit::from_suffix`] to the same
17772        // variant. A future arm addition that lands `as_suffix` but
17773        // forgets `from_suffix` (`from_suffix` iterates
17774        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
17775        // is the load-bearing carrier of the round-trip; the sibling
17776        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
17777        // the `ALL` half) trips here at caixa-core build time rather
17778        // than surfacing as a codec round-trip miss (a `render` emit
17779        // that lands a suffix the paired `parse` cannot decode).
17780        for unit in super::RateLimitUnit::ALL {
17781            let suffix = unit.as_suffix();
17782            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
17783                panic!(
17784                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
17785                     RateLimitUnit::as_suffix output — got None for {unit:?}"
17786                )
17787            });
17788            assert_eq!(
17789                parsed, *unit,
17790                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
17791                 must return RateLimitUnit::{unit:?}"
17792            );
17793        }
17794    }
17795
17796    #[test]
17797    fn rate_limit_unit_from_window_and_window_round_trip() {
17798        // Total round-trip pin on the `(from_window, window)` pair:
17799        // every arm's [`RateLimitUnit::window`] output must parse back
17800        // through [`RateLimitUnit::from_window`] to the same variant.
17801        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
17802        // on the peer `Duration` axis — the two round-trip pins
17803        // together enshrine that both projections of the typed
17804        // canonical-unit bijection are total on the arm-set.
17805        for unit in super::RateLimitUnit::ALL {
17806            let window = unit.window();
17807            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
17808                panic!(
17809                    "RateLimitUnit::from_window({window:?}) must accept every \
17810                     RateLimitUnit::window output — got None for {unit:?}"
17811                )
17812            });
17813            assert_eq!(
17814                parsed, *unit,
17815                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17816                 must return RateLimitUnit::{unit:?}"
17817            );
17818        }
17819    }
17820
17821    #[test]
17822    fn rate_limit_unit_from_window_accessor_is_const_fn() {
17823        // Fail-before-pass-after pin: witnesses the
17824        // [`RateLimitUnit::from_window`] `const`-eval posture via a
17825        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
17826        // -> Option<RateLimitUnit>` whose body calls
17827        // `RateLimitUnit::from_window(window)`, well-formed only when
17828        // the callee is itself `const fn` (any future downgrade to
17829        // non-`const` fails at caixa-core build time with E0015 `cannot
17830        // call non-const function`, strictly stronger than a runtime
17831        // `assert!`, side-stepping the destructor-in-const restriction
17832        // that blocks direct `const _: Option<RateLimitUnit> =
17833        // RateLimitUnit::from_window(...)` items on `Duration`'s
17834        // carrier). The runtime body sweeps every closed-set
17835        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
17836        // rejection sample (`Duration::from_millis(500)` sub-second
17837        // residue) and asserts the wrapped and direct dispatches agree
17838        // — a violation means the wrapper stopped compiling under a
17839        // future `const`-posture downgrade, or the reverse resolver's
17840        // arm-set silently split from the peer `Self::window` emitter's
17841        // arm-set. Peer of the sibling
17842        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
17843        // (152c868) /
17844        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
17845        // (152c868) /
17846        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
17847        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
17848        // `const`-eval-surface pins on the peer M2 / M3 substrate-
17849        // primitive `Copy`-return accessor axes, extended onto the
17850        // reverse `Duration → RateLimitUnit` projection axis on the
17851        // M3 mesh-slot rate-limit closed-set typed enum.
17852        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
17853            super::RateLimitUnit::from_window(window)
17854        }
17855        for unit in super::RateLimitUnit::ALL {
17856            let window = unit.window();
17857            let via_wrapper = from_window_via_const_fn(window);
17858            let direct = super::RateLimitUnit::from_window(window);
17859            assert_eq!(
17860                via_wrapper, direct,
17861                "RateLimitUnit::from_window({window:?}) via const fn \
17862                 wrapper must agree with direct dispatch for {unit:?}"
17863            );
17864            assert_eq!(
17865                via_wrapper,
17866                Some(*unit),
17867                "RateLimitUnit::from_window({window:?}) via const fn \
17868                 wrapper must return Some({unit:?}) for the peer \
17869                 window() output"
17870            );
17871        }
17872        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
17873        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
17874    }
17875
17876    #[test]
17877    fn rate_limit_unit_from_window_composes_through_window_accessor() {
17878        // Composition-witness pin on the routing-through-peer discipline:
17879        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
17880        // through the peer `pub const fn` [`RateLimitUnit::window`]
17881        // canonical-`Duration` projection rather than a hand-authored
17882        // per-arm second-magnitude literal — a future arm-magnitude edit
17883        // on the sibling `window()` accessor (a `Second → 2s` typo, a
17884        // `Hour → 3599s` off-by-one) must therefore reach this reverse
17885        // resolver by construction. A pin that hard-coded the three
17886        // second-magnitudes here would silently split from the peer
17887        // emitter on any such edit; instead, this pin asserts the
17888        // composition invariant `from_window(u.window()) == Some(u)`
17889        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
17890        // arm — a violation means either the peer `Self::window`
17891        // accessor drifted (breaking every downstream consumer that
17892        // reads through it), or the reverse resolver stopped routing
17893        // through the peer (introducing a hand-authored literal that
17894        // silently disagrees with the emitter). Either failure is a
17895        // caixa-core-build-time surface, not a downstream renderer
17896        // round-trip regression.
17897        //
17898        // Peer of the sibling
17899        // [`crate::render::assert_str_reexport_identity`] discipline on
17900        // the substrate-primitive `&'static str` re-export axis and the
17901        // [`rate_limit_unit_from_window_and_window_round_trip`]
17902        // round-trip pin on the peer projection direction; extends the
17903        // one-canonical-dispatch-per-projection discipline onto the
17904        // reverse-resolver's per-arm probe axis.
17905        for unit in super::RateLimitUnit::ALL {
17906            let window_via_peer = unit.window();
17907            let resolved = super::RateLimitUnit::from_window(window_via_peer);
17908            assert_eq!(
17909                resolved,
17910                Some(*unit),
17911                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17912                 must return Some({unit:?}) — the reverse resolver's per-arm \
17913                 probes must route through the peer `Self::window` accessor \
17914                 so any future arm-magnitude edit reaches both projection \
17915                 directions by construction"
17916            );
17917        }
17918    }
17919
17920    #[test]
17921    fn rate_limit_canonical_unit_accessor_is_const_fn() {
17922        // Fail-before-pass-after pin: witnesses the
17923        // [`RateLimit::canonical_unit`] `const`-eval posture via a
17924        // `const fn` wrapper
17925        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
17926        // whose body calls `rl.canonical_unit()`, well-formed only when
17927        // the callee is itself `const fn` (any future downgrade to
17928        // non-`const` fails at caixa-core build time with E0015 `cannot
17929        // call non-const method`). The runtime body sweeps every
17930        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
17931        // constructs a typed [`RateLimit`] with the peer `Self::window`
17932        // canonical `Duration`, then asserts both the wrapper and the
17933        // direct dispatch agree and both return `Some(unit)`. Composes
17934        // with the sibling
17935        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
17936        // typed [`RateLimit`] projection layer's `const`-posture is
17937        // load-bearing on the reverse resolver's `const`-posture, and
17938        // both must migrate together (a downgrade of either surface
17939        // splits the paired `const`-eval-surface pass on the M3
17940        // mesh-slot rate-limit `Duration ↔ Self` bijection).
17941        const fn canonical_unit_via_const_fn(
17942            rl: &super::RateLimit,
17943        ) -> Option<super::RateLimitUnit> {
17944            rl.canonical_unit()
17945        }
17946        for unit in super::RateLimitUnit::ALL {
17947            let rl = super::RateLimit {
17948                rate: 1,
17949                window: unit.window(),
17950            };
17951            let via_wrapper = canonical_unit_via_const_fn(&rl);
17952            let direct = rl.canonical_unit();
17953            assert_eq!(
17954                via_wrapper, direct,
17955                "RateLimit::canonical_unit() via const fn wrapper must \
17956                 agree with direct dispatch for {unit:?}"
17957            );
17958            assert_eq!(
17959                via_wrapper,
17960                Some(*unit),
17961                "RateLimit::canonical_unit() via const fn wrapper must \
17962                 return Some({unit:?}) for a RateLimit whose window is \
17963                 the peer RateLimitUnit::{unit:?}.window() output"
17964            );
17965        }
17966    }
17967
17968    #[test]
17969    fn rate_limit_unit_projections_are_pairwise_distinct() {
17970        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
17971        // [`RateLimitUnit::window`] outputs must be pairwise distinct
17972        // across every arm — an accidental copy-paste flip that
17973        // reroutes one arm's suffix or window to also match another
17974        // silently collapses two arms onto one, so
17975        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
17976        // (both using `find` on `Self::ALL`) would return whichever
17977        // arm the linear scan lands on first — a match-arm-ordering-
17978        // dependent outcome the closed-set typed-enum shape is meant
17979        // to rule out structurally. Peer of the sibling
17980        // `caixa_kind_wire_consts_are_pairwise_distinct` /
17981        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
17982        // other closed-set typed-enum discriminator axes.
17983        let all = super::RateLimitUnit::ALL;
17984        for (i, a) in all.iter().enumerate() {
17985            for (j, b) in all.iter().enumerate() {
17986                if i != j {
17987                    assert_ne!(
17988                        a.as_suffix(),
17989                        b.as_suffix(),
17990                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
17991                         must be distinct — a collision silently collapses two \
17992                         arms onto one under from_suffix's linear scan"
17993                    );
17994                    assert_ne!(
17995                        a.window(),
17996                        b.window(),
17997                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
17998                         must be distinct — a collision silently collapses two \
17999                         arms onto one under from_window's linear scan"
18000                    );
18001                }
18002            }
18003        }
18004    }
18005
18006    #[test]
18007    fn rate_limit_unit_display_routes_through_as_suffix() {
18008        // Route pin: [`std::fmt::Display`] must byte-equal
18009        // [`RateLimitUnit::as_suffix`] on every arm — the single
18010        // source of truth for the canonical suffix. A future
18011        // reimplementation that hand-rolls the arms instead of
18012        // delegating to [`RateLimitUnit::as_suffix`] would silently
18013        // desynchronize `format!("{u}")` from the codec's parse arm
18014        // (which uses `as_suffix` to compare suffixes). Peer of the
18015        // sibling `caixa_kind_display_routes_through_as_str_helper` /
18016        // `placement_strategy_display_routes_through_as_str_helper`
18017        // pins on the peer closed-set typed-enum Display axes.
18018        for unit in super::RateLimitUnit::ALL {
18019            assert_eq!(
18020                unit.to_string(),
18021                unit.as_suffix(),
18022                "RateLimitUnit::{unit:?} Display must route through \
18023                 as_suffix (single source of truth: the canonical suffix \
18024                 the codec parses and renders)"
18025            );
18026        }
18027    }
18028
18029    #[test]
18030    fn rate_limit_unit_from_window_rejects_non_canonical() {
18031        // Rejection pin on the parser's accept-set: any Duration
18032        // outside the three-arm [`RateLimitUnit::window`] output set
18033        // (sub-second residue, or a second-magnitude outside `{1, 60,
18034        // 3600}`) must return `None`. A future accidental widening of
18035        // the accept-set (rounding down sub-second residue to the
18036        // nearest arm, admitting `Duration::from_secs(30)` as a
18037        // half-minute unit) would silently drift the parser's accept-
18038        // set from the emitter's — a validated slot with a
18039        // non-canonical window would then round-trip through the
18040        // codec to a canonical form the author never wrote.
18041        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
18042        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
18043        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
18044        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
18045        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
18046        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
18047        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
18048    }
18049
18050    #[test]
18051    fn rate_limit_unit_from_suffix_rejects_unknown() {
18052        // Rejection pin on the suffix parser's accept-set: any string
18053        // outside the three-arm [`RateLimitUnit::as_suffix`] output
18054        // set must return `None`. Peer of the sibling
18055        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
18056        // the [`crate::CaixaKind`] `from_wire` accept-set.
18057        for bad in [
18058            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
18059            " s",
18060        ] {
18061            assert!(
18062                super::RateLimitUnit::from_suffix(bad).is_none(),
18063                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
18064                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
18065                 outputs"
18066            );
18067        }
18068    }
18069
18070    #[test]
18071    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
18072        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
18073        // every canonical `:window` magnitude the validate gate
18074        // accepts must map to the paired [`RateLimitUnit`] arm through
18075        // this accessor. A future validate-gate rebrand that widened
18076        // the accepted-window set without extending [`RateLimitUnit`]
18077        // would silently split the accessor's `Some`-return set from
18078        // the validate gate's accept-set — a slot that satisfies
18079        // validate would land at the accessor with `None`, so a
18080        // consumer past validate that pattern-matches on the returned
18081        // `Some` would silently miss the newly-accepted magnitude.
18082        for (window_secs, expected) in [
18083            (1u64, super::RateLimitUnit::Second),
18084            (60, super::RateLimitUnit::Minute),
18085            (3600, super::RateLimitUnit::Hour),
18086        ] {
18087            let rl = RateLimit {
18088                rate: 100,
18089                window: Duration::from_secs(window_secs),
18090            };
18091            assert_eq!(
18092                rl.canonical_unit(),
18093                Some(expected),
18094                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
18095                 must return Some({expected:?})"
18096            );
18097        }
18098        // Non-canonical windows the validate gate rejects also return
18099        // None here — the accessor is the typed-enum projection of
18100        // the sibling `is_canonical_rate_limit_window` predicate.
18101        let bad = RateLimit {
18102            rate: 100,
18103            window: Duration::from_secs(30),
18104        };
18105        assert!(
18106            bad.canonical_unit().is_none(),
18107            "RateLimit with a non-canonical window must return None from \
18108             canonical_unit — the validate gate rejects the same set"
18109        );
18110    }
18111
18112    #[test]
18113    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
18114        // Fail-before-pass-after byte-parity pin: for every canonical
18115        // window the [`rate_limit_codec::render`] arm's emitted string
18116        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
18117        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
18118        // the vestigial free helper [`rate_limit_window_unit`] (a
18119        // `find_map`-walked `Duration → &'static str` delegate) onto the
18120        // substrate primitive [`RateLimit::canonical_unit`] typed method
18121        // (a closed-set `match self.window` arm on
18122        // [`RateLimitUnit::from_window`], projected through
18123        // [`RateLimitUnit::as_suffix`] via the enum's
18124        // [`std::fmt::Display`] impl). A future re-routing of the render
18125        // arm through a differently-computed unit projection would break
18126        // this pin at build time rather than as a silent per-consumer
18127        // codec round-trip drift far from the substrate primitive edit.
18128        //
18129        // Sibling to the peer
18130        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
18131        // on the free-helper axis: that pin locks the two projections
18132        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
18133        // on the closed-set arm table; this pin locks the codec's render
18134        // arm reads through the typed accessor rather than the free
18135        // helper. Two production consumers of the canonical-unit axis
18136        // now key off one typed dispatch on the substrate primitive.
18137        for (window_secs, unit) in [
18138            (1u64, super::RateLimitUnit::Second),
18139            (60, super::RateLimitUnit::Minute),
18140            (3600, super::RateLimitUnit::Hour),
18141        ] {
18142            let rl = RateLimit {
18143                rate: 42,
18144                window: Duration::from_secs(window_secs),
18145            };
18146            let policy = MeshPolicy {
18147                rate_limit: Some(rl),
18148                ..Default::default()
18149            };
18150            let json = serde_json::to_string(&policy).unwrap();
18151            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
18152            assert!(
18153                json.contains(&expected),
18154                "rate_limit_codec::render must emit {expected} (via \
18155                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
18156                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
18157            );
18158            // And the accessor route resolves to the same typed unit
18159            // the render arm's Display formatting is asked to produce —
18160            // so a future edit that split the two paths (one through
18161            // the accessor, one through a re-introduced free helper)
18162            // trips this pin.
18163            assert_eq!(
18164                rl.canonical_unit(),
18165                Some(unit),
18166                "RateLimit::canonical_unit must return Some({unit:?}) for a \
18167                 {window_secs}s window; the codec render arm reads the same \
18168                 typed unit through this accessor"
18169            );
18170        }
18171    }
18172
18173    #[test]
18174    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
18175        // Fail-before-pass-after byte-parity pin on the validate gate's
18176        // canonical-window shape probe: every non-canonical `:window`
18177        // the free-helper predicate [`is_canonical_rate_limit_window`]
18178        // rejects is also rejected by the substrate primitive
18179        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
18180        // gate now reads through, and vice versa on the accepted set
18181        // (the three canonical windows). Locks the migration from the
18182        // free helper onto the substrate primitive: a future re-routing
18183        // of one of the two paths through a differently-computed unit
18184        // projection would silently split the codec's accepted set from
18185        // the validate gate's accepted set — a two-consumer drift the
18186        // codec-round-trip pin
18187        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
18188        // above closes on the render arm and this pin closes on the
18189        // validate arm.
18190        for canonical_window_secs in [1u64, 60, 3600] {
18191            let mut s = three_member_spec();
18192            let rl = RateLimit {
18193                rate: 100,
18194                window: Duration::from_secs(canonical_window_secs),
18195            };
18196            s.politicas.rate_limit = Some(rl);
18197            assert!(
18198                s.validate().is_ok(),
18199                "canonical {canonical_window_secs}s window must pass \
18200                 validate_politicas — the validate gate now reads \
18201                 RateLimit::canonical_unit().is_none() and the accessor \
18202                 returns Some on every canonical arm"
18203            );
18204            assert!(
18205                rl.canonical_unit().is_some(),
18206                "canonical {canonical_window_secs}s window must resolve to \
18207                 Some on RateLimit::canonical_unit — the validate gate reads \
18208                 this accessor directly"
18209            );
18210        }
18211        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
18212            let mut s = three_member_spec();
18213            let rl = RateLimit {
18214                rate: 100,
18215                window: Duration::from_secs(non_canonical_window_secs),
18216            };
18217            s.politicas.rate_limit = Some(rl);
18218            assert_eq!(
18219                s.validate().unwrap_err(),
18220                AplicacaoError::PolicyRateLimitWindowNotCanonical {
18221                    window: rl.window(),
18222                },
18223                "non-canonical {non_canonical_window_secs}s window must be \
18224                 rejected by validate_politicas — the validate gate now \
18225                 keys off RateLimit::canonical_unit().is_none()"
18226            );
18227            assert!(
18228                rl.canonical_unit().is_none(),
18229                "non-canonical {non_canonical_window_secs}s window must \
18230                 resolve to None on RateLimit::canonical_unit — the two \
18231                 paths (the free helper the validate gate previously read \
18232                 and the substrate primitive the validate gate now reads) \
18233                 must agree on the same rejected set"
18234            );
18235        }
18236        // And the substrate-primitive [`RateLimit::canonical_unit`]
18237        // accessor's accepted-window set matches the codec's parse arm's
18238        // accepted-suffix set on every canonical / non-canonical shape,
18239        // so a future silent drift between the codec's accepted set and
18240        // the validate gate's accepted set is a build error at test time
18241        // (both consumers key off the same closed-set enum's `match self`
18242        // arms). The predecessor free helper `is_canonical_rate_limit_window`
18243        // — a delegate that composed [`RateLimitUnit::from_window`] with
18244        // `.is_some()` — was deleted after this migration; the
18245        // canonical-window set now lives on exactly one typed dispatch
18246        // on the substrate primitive.
18247        for (secs, expected) in [
18248            (1u64, true),
18249            (60, true),
18250            (3600, true),
18251            (2, false),
18252            (30, false),
18253            (86_400, false),
18254        ] {
18255            let window = Duration::from_secs(secs);
18256            let rl = RateLimit { rate: 1, window };
18257            assert_eq!(
18258                rl.canonical_unit().is_some(),
18259                expected,
18260                "RateLimit::canonical_unit().is_some() must agree with the \
18261                 codec-accepted canonical-window set on {secs}s"
18262            );
18263            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
18264                1 => "s",
18265                60 => "m",
18266                3600 => "h",
18267                _ => return,
18268            })
18269            .is_some_and(|d| d == window);
18270            if expected {
18271                assert!(
18272                    suffix_from_axis,
18273                    "the codec's `&str → Duration` axis \
18274                     ({secs}s) must round-trip to the same Duration the \
18275                     substrate primitive's accessor returns Some on"
18276                );
18277            }
18278        }
18279    }
18280
18281    #[test]
18282    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
18283        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
18284        // derive: for each of the three variants, exactly one of the
18285        // generated `is_second` / `is_minute` / `is_hour` predicates
18286        // returns `true` and the other two return `false`. Peer of
18287        // the sibling
18288        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
18289        // sibling `IsVariant`-derived closed-set typed-enum pins.
18290        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
18291            (super::RateLimitUnit::Second, [true, false, false]),
18292            (super::RateLimitUnit::Minute, [false, true, false]),
18293            (super::RateLimitUnit::Hour, [false, false, true]),
18294        ];
18295        for (variant, expected) in rows {
18296            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
18297            assert_eq!(
18298                observed, expected,
18299                "RateLimitUnit::{variant:?} is_* predicates must partition \
18300                 the arm set (second, minute, hour); got {observed:?}"
18301            );
18302        }
18303    }
18304
18305    #[test]
18306    fn rejects_policy_timeout_sub_millisecond() {
18307        // A purely sub-millisecond `Duration` (`from_micros(500)` =
18308        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
18309        // arm passes — but `as_millis() == 0`, so the shared codec's
18310        // `render` arm returns the literal `"0s"`, which the
18311        // codec's `parse` arm then deserializes as `Duration::ZERO`
18312        // and the `PolicyTimeoutZero` zero-floor gate would reject
18313        // on re-validate. Pin the rejection at the typed slot's
18314        // canonical-floor gate so the round-trip break surfaces at
18315        // validate time, naming the offending `Duration`, rather
18316        // than at the next serialize → deserialize round-trip far
18317        // from the source `caixa.lisp`.
18318        let mut s = three_member_spec();
18319        let timeout = Duration::from_micros(500);
18320        s.politicas.timeout = Some(timeout);
18321        assert_eq!(
18322            s.validate().unwrap_err(),
18323            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
18324        );
18325    }
18326
18327    #[test]
18328    fn rejects_policy_timeout_non_integer_millisecond() {
18329        // A `Duration` with non-integer-millisecond residue
18330        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
18331        // through the shared codec's `render` arm as `"1ms"` (the
18332        // `as_millis()` floor truncates), which the codec's `parse`
18333        // arm then deserializes as `Duration::from_millis(1)` =
18334        // 1_000_000 ns — silently *different* from the original.
18335        // Pin the rejection so this round-trip break surfaces at
18336        // validate time, where the offending `Duration` is named,
18337        // rather than as a silent value-laundered round-trip on the
18338        // next codec round-trip.
18339        let mut s = three_member_spec();
18340        let timeout = Duration::from_micros(1500);
18341        s.politicas.timeout = Some(timeout);
18342        assert_eq!(
18343            s.validate().unwrap_err(),
18344            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
18345        );
18346    }
18347
18348    #[test]
18349    fn accepts_policy_timeout_integer_millisecond_forms() {
18350        // The codec's accepted set — integer multiples of 1ms — is
18351        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
18352        // `1h` all pass the canonical gate. Pin the canonical-forms
18353        // sweep so a future tightening of the codec's grammar (e.g.
18354        // dropping `:ms`) surfaces here as a test failure rather
18355        // than a silent contract narrowing on the typed slot.
18356        for timeout in [
18357            Duration::from_millis(1),
18358            Duration::from_millis(500),
18359            Duration::from_millis(1500),
18360            Duration::from_secs(30),
18361            Duration::from_secs(120),
18362            Duration::from_secs(3600),
18363        ] {
18364            let mut s = three_member_spec();
18365            s.politicas.timeout = Some(timeout);
18366            s.validate()
18367                .expect("integer-millisecond :timeout must validate");
18368        }
18369    }
18370
18371    #[test]
18372    fn policy_timeout_zero_takes_precedence_over_canonical() {
18373        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
18374        // pass the canonical-millisecond gate; the more self-locating
18375        // `PolicyTimeoutZero` arm (which names the omit-axis
18376        // remediation directly) must fire first. Pin the ordering so
18377        // a future refactor that reorders the arms surfaces here as a
18378        // test failure rather than a silent diagnostic regression.
18379        let mut s = three_member_spec();
18380        s.politicas.timeout = Some(Duration::ZERO);
18381        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
18382    }
18383
18384    #[test]
18385    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
18386        // The diagnostic envelope carries the offending `Duration`
18387        // verbatim so the author can grep their `caixa.lisp` for
18388        // `:timeout "<value>"` and fix it in one edit. Same
18389        // diagnostic shape every other typed-slot canonical-form
18390        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
18391        // peer `:rate-limit :window` axis.
18392        let mut s = three_member_spec();
18393        let timeout = Duration::from_nanos(1_000_001);
18394        s.politicas.timeout = Some(timeout);
18395        match s.validate().unwrap_err() {
18396            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
18397                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
18398            }
18399            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
18400        }
18401    }
18402
18403    #[test]
18404    fn rejects_policy_timeout_above_cap() {
18405        // The fail-before-pass-after pin: 3601s = 1h + 1s is
18406        // structurally one canonical-tick past the
18407        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
18408        // integer-millisecond magnitude the canonical-form arm above
18409        // accepts cleanly, that the codec round-trips losslessly as
18410        // `"3601s"`, and that silently passed validate on every
18411        // pre-gate codebase because the typed slot's only checks were
18412        // the zero-floor and canonical-form arms. The mesh-level
18413        // deadline degenerates only at the runtime substrate (Envoy
18414        // / Cilium L7 timeout overlay) far from the source
18415        // `caixa.lisp` with no field naming the offending policy.
18416        let mut s = three_member_spec();
18417        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
18418        s.politicas.timeout = Some(timeout);
18419        assert_eq!(
18420            s.validate().unwrap_err(),
18421            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18422        );
18423    }
18424
18425    #[test]
18426    fn rejects_policy_timeout_one_millisecond_above_cap() {
18427        // Boundary case: exactly 1ms past the cap (the granularity
18428        // the canonical-form gate enforces). Catches a future
18429        // "strictly less than" half-measure and pins the diagnostic
18430        // to name the offending `Duration` verbatim. Peer of
18431        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
18432        // boundary pin on the sibling `:limits :memory` top edge.
18433        let mut s = three_member_spec();
18434        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
18435        s.politicas.timeout = Some(timeout);
18436        assert_eq!(
18437            s.validate().unwrap_err(),
18438            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18439        );
18440    }
18441
18442    #[test]
18443    fn rejects_policy_timeout_far_above_cap() {
18444        // The "obvious authoring footgun" case: a `(:timeout "24h")`
18445        // or `(:timeout "86400s")` — values the canonical-form arm
18446        // accepts as integer-millisecond magnitudes, the codec
18447        // round-trips losslessly through serde, but the mesh-level
18448        // policy cannot honor (a 24-hour synchronous-`:contratos`
18449        // deadline is operationally indistinguishable from
18450        // omit-the-axis). Until this gate landed validate accepted
18451        // it. Pin both common above-cap values (24h, 7d) so a future
18452        // relaxation that drops the upper bound surfaces here.
18453        for timeout in [
18454            Duration::from_secs(86_400),    // 24h
18455            Duration::from_secs(604_800),   // 7d
18456            Duration::from_secs(1_000_000), // ~11.5 days
18457        ] {
18458            let mut s = three_member_spec();
18459            s.politicas.timeout = Some(timeout);
18460            assert_eq!(
18461                s.validate().unwrap_err(),
18462                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18463            );
18464        }
18465    }
18466
18467    #[test]
18468    fn accepts_policy_timeout_at_cap() {
18469        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
18470        // must validate. The cap is inclusive on the top edge,
18471        // matching the [`POLICY_RETRIES_MAX`] /
18472        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
18473        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18474        // sibling capped axes. Pin the boundary explicitly so a
18475        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
18476        // instead of `>`) surfaces here as a test failure rather
18477        // than a silent contract narrowing.
18478        let mut s = three_member_spec();
18479        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
18480        s.validate()
18481            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
18482    }
18483
18484    #[test]
18485    fn accepts_policy_timeout_typical_values() {
18486        // The documented production-playbook band positive-control
18487        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
18488        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
18489        // plus a sweep through the long-running-workflow band
18490        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
18491        // validated set explicitly so a future tightening of the
18492        // ceiling surfaces here as a deliberate test edit, not a
18493        // silent contract narrowing.
18494        for timeout in [
18495            Duration::from_millis(1),
18496            Duration::from_millis(500),
18497            Duration::from_secs(1),
18498            Duration::from_secs(10),
18499            Duration::from_secs(15), // Envoy default
18500            Duration::from_secs(30),
18501            Duration::from_secs(60), // AWS App Mesh typical
18502            Duration::from_secs(300),
18503            Duration::from_secs(900),
18504            Duration::from_secs(1800),
18505            Duration::from_secs(3600), // exactly 1h, the cap
18506        ] {
18507            let mut s = three_member_spec();
18508            s.politicas.timeout = Some(timeout);
18509            s.validate()
18510                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
18511        }
18512    }
18513
18514    #[test]
18515    fn policy_timeout_zero_takes_precedence_over_cap() {
18516        // The cross-arm ordering pin: `Duration::ZERO` is
18517        // structurally outside both `>= 1ms` (zero-floor) and
18518        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
18519        // diagnostic is the more self-locating one (it directly
18520        // names the omit-axis remediation), so the validate gate
18521        // must fire on zero first. Same shape every other
18522        // zero-then-shape ordering on this surface uses
18523        // ([`AplicacaoError::PolicyRetriesZero`] then
18524        // [`AplicacaoError::PolicyRetriesExceedsCap`];
18525        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18526        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18527        let mut s = three_member_spec();
18528        s.politicas.timeout = Some(Duration::ZERO);
18529        assert_eq!(
18530            s.validate().unwrap_err(),
18531            AplicacaoError::PolicyTimeoutZero,
18532            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18533        );
18534    }
18535
18536    #[test]
18537    fn policy_timeout_canonical_takes_precedence_over_cap() {
18538        // The cross-arm ordering pin: a `Duration` that is *both*
18539        // sub-millisecond (non-canonical-form) and structurally
18540        // above the cap surfaces the canonical-form diagnostic
18541        // first, because the round-trip-shape break is the more
18542        // fundamental issue (the value can't even round-trip
18543        // through the codec, so the cap diagnostic naming
18544        // `1ms..=1h` would be misleading — there's no integer-ms
18545        // form of the offending value). Pin the order so a future
18546        // refactor that reorders the arms surfaces here as a test
18547        // failure rather than a silent diagnostic regression.
18548        let mut s = three_member_spec();
18549        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
18550        // *and* total magnitude above the 1h cap.
18551        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
18552        s.politicas.timeout = Some(timeout);
18553        assert_eq!(
18554            s.validate().unwrap_err(),
18555            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
18556            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18557        );
18558    }
18559
18560    #[test]
18561    fn policy_timeout_cap_diagnostic_carries_offending_value() {
18562        // The diagnostic-shape pin: the offending `Duration` is
18563        // carried verbatim into the
18564        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
18565        // surfaced error message names the value the author wrote
18566        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
18567        // exceeds the mesh-policy ceiling …"`), not just the cap.
18568        // Same self-locating diagnostic shape every other typed-cap
18569        // arm on this surface carries
18570        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
18571        // offending retry count verbatim).
18572        let mut s = three_member_spec();
18573        let timeout = Duration::from_secs(7200); // 2h
18574        s.politicas.timeout = Some(timeout);
18575        let err = s.validate().unwrap_err();
18576        assert!(
18577            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
18578            "got {err:?}"
18579        );
18580        let msg = err.to_string();
18581        assert!(
18582            msg.contains("7200"),
18583            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
18584        );
18585    }
18586
18587    #[test]
18588    fn policy_timeout_cap_pins_canonical_value() {
18589        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
18590        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
18591        // the shared duration codec emits as a clean canonical
18592        // string (`"<n>h"`). Pinning the literal value here surfaces
18593        // a future drift (a relaxation to 24h, a tightening to 5m)
18594        // as a deliberate test edit, not a silent contract
18595        // narrowing. Same shape every other typed-cap value pin on
18596        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
18597        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
18598        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
18599    }
18600
18601    #[test]
18602    fn policy_timeout_cap_value_round_trips_through_codec() {
18603        // The codec round-trip property the cap arm preserves: the
18604        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
18605        // the shared duration codec — every value at the cap renders
18606        // to a clean canonical string (`"1h"`) and parses back to
18607        // the same `Duration`. Pin this so a future drift between
18608        // the cap constant and the codec's largest emitted unit
18609        // surfaces here. Same shape every other typed boundary pin
18610        // on this surface uses
18611        // (`wasm32_memory_cap_matches_parsed_4_gib`).
18612        let policy = MeshPolicy {
18613            timeout: Some(POLICY_TIMEOUT_MAX),
18614            ..Default::default()
18615        };
18616        let json = serde_json::to_string(&policy).unwrap();
18617        // The codec emits `"1h"` for the canonical 1-hour magnitude.
18618        assert!(
18619            json.contains("\"1h\""),
18620            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
18621        );
18622        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18623        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
18624    }
18625
18626    #[test]
18627    fn rejects_circuit_breaker_window_sub_millisecond() {
18628        // Peer of the `:timeout` sub-millisecond arm on the second
18629        // typed-`Duration` `:politicas` axis: a purely sub-ms
18630        // `Duration` (`from_micros(500)`) renders through the shared
18631        // codec as `"0s"`, which the codec parses back to
18632        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
18633        // zero-floor gate then rejects on re-validate.
18634        let mut s = three_member_spec();
18635        let window = Duration::from_micros(500);
18636        s.politicas.circuit_breaker = Some(CircuitBreaker {
18637            max_failures: 5,
18638            window,
18639        });
18640        assert_eq!(
18641            s.validate().unwrap_err(),
18642            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18643        );
18644    }
18645
18646    #[test]
18647    fn rejects_circuit_breaker_window_non_integer_millisecond() {
18648        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
18649        // with non-integer-millisecond residue renders through the
18650        // shared codec as the truncated `"<n>ms"` form, parsing back
18651        // to a *different* `Duration` on the next round-trip.
18652        let mut s = three_member_spec();
18653        let window = Duration::from_micros(1500);
18654        s.politicas.circuit_breaker = Some(CircuitBreaker {
18655            max_failures: 5,
18656            window,
18657        });
18658        assert_eq!(
18659            s.validate().unwrap_err(),
18660            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18661        );
18662    }
18663
18664    #[test]
18665    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
18666        // The canonical-forms sweep on the breaker axis: every
18667        // integer-ms multiple the codec round-trips losslessly
18668        // passes the canonical gate.
18669        for window in [
18670            Duration::from_millis(1),
18671            Duration::from_millis(500),
18672            Duration::from_millis(1500),
18673            Duration::from_secs(30),
18674            Duration::from_secs(60),
18675            Duration::from_secs(3600),
18676        ] {
18677            let mut s = three_member_spec();
18678            s.politicas.circuit_breaker = Some(CircuitBreaker {
18679                max_failures: 5,
18680                window,
18681            });
18682            s.validate()
18683                .expect("integer-millisecond :circuit-breaker :window must validate");
18684        }
18685    }
18686
18687    #[test]
18688    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
18689        // `Duration::ZERO` would pass the canonical-ms gate (the
18690        // sub-ns residue is zero) but must surface the narrower
18691        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
18692        // remediation.
18693        let mut s = three_member_spec();
18694        s.politicas.circuit_breaker = Some(CircuitBreaker {
18695            max_failures: 5,
18696            window: Duration::ZERO,
18697        });
18698        assert_eq!(
18699            s.validate().unwrap_err(),
18700            AplicacaoError::PolicyBreakerZeroWindow
18701        );
18702    }
18703
18704    #[test]
18705    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
18706        // Both axes invalid: max_failures == 0 *and* window is
18707        // sub-ms. The validate gate must fire on max_failures first
18708        // (matching the existing ordering pin
18709        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
18710        // the existing diagnostic continues to lead with the simpler
18711        // "zero threshold" framing.
18712        let mut s = three_member_spec();
18713        s.politicas.circuit_breaker = Some(CircuitBreaker {
18714            max_failures: 0,
18715            window: Duration::from_micros(500),
18716        });
18717        assert_eq!(
18718            s.validate().unwrap_err(),
18719            AplicacaoError::PolicyBreakerZeroFailures
18720        );
18721    }
18722
18723    #[test]
18724    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
18725        let mut s = three_member_spec();
18726        let window = Duration::from_nanos(60_000_000_001);
18727        s.politicas.circuit_breaker = Some(CircuitBreaker {
18728            max_failures: 5,
18729            window,
18730        });
18731        match s.validate().unwrap_err() {
18732            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
18733                assert_eq!(w, window, "diagnostic must carry the offending Duration");
18734            }
18735            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
18736        }
18737    }
18738
18739    #[test]
18740    fn rejects_circuit_breaker_window_above_cap() {
18741        // The fail-before-pass-after pin: 3601s = 1h + 1s is
18742        // structurally one canonical-tick past the
18743        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
18744        // integer-millisecond magnitude the canonical-form arm above
18745        // accepts cleanly, that the codec round-trips losslessly as
18746        // `"3601s"`, and that silently passed validate on every
18747        // pre-gate codebase because the typed slot's only checks were
18748        // the zero-floor and canonical-form arms. The
18749        // rolling-window-to-lifetime-counter degeneration surfaces
18750        // only at the runtime substrate (Envoy's outlier_detection
18751        // interval, the future CiliumClusterwideEnvoyConfig overlay)
18752        // far from the source `caixa.lisp` with no field naming the
18753        // offending policy.
18754        let mut s = three_member_spec();
18755        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18756        s.politicas.circuit_breaker = Some(CircuitBreaker {
18757            max_failures: 5,
18758            window,
18759        });
18760        assert_eq!(
18761            s.validate().unwrap_err(),
18762            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18763        );
18764    }
18765
18766    #[test]
18767    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
18768        // Boundary case: exactly 1ms past the cap (the granularity the
18769        // canonical-form gate enforces). Catches a future "strictly
18770        // less than" half-measure and pins the diagnostic to name the
18771        // offending `Duration` verbatim. Peer of
18772        // `rejects_policy_timeout_one_millisecond_above_cap` on the
18773        // sibling duration-typed `:politicas :timeout` top edge.
18774        let mut s = three_member_spec();
18775        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
18776        s.politicas.circuit_breaker = Some(CircuitBreaker {
18777            max_failures: 5,
18778            window,
18779        });
18780        assert_eq!(
18781            s.validate().unwrap_err(),
18782            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18783        );
18784    }
18785
18786    #[test]
18787    fn rejects_circuit_breaker_window_far_above_cap() {
18788        // The "obvious authoring footgun" case: a `(:window "24h")` or
18789        // `(:window "86400s")` — values the canonical-form arm
18790        // accepts as integer-millisecond magnitudes, the codec
18791        // round-trips losslessly through serde, but the
18792        // rolling-window breaker contract cannot honor (a 24-hour
18793        // rolling failure window is operationally a lifetime counter).
18794        // Until this gate landed validate accepted it. Pin both common
18795        // above-cap values (24h, 7d) so a future relaxation that
18796        // drops the upper bound surfaces here.
18797        for window in [
18798            Duration::from_secs(86_400),    // 24h
18799            Duration::from_secs(604_800),   // 7d
18800            Duration::from_secs(1_000_000), // ~11.5 days
18801        ] {
18802            let mut s = three_member_spec();
18803            s.politicas.circuit_breaker = Some(CircuitBreaker {
18804                max_failures: 5,
18805                window,
18806            });
18807            assert_eq!(
18808                s.validate().unwrap_err(),
18809                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18810            );
18811        }
18812    }
18813
18814    #[test]
18815    fn accepts_circuit_breaker_window_at_cap() {
18816        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
18817        // (1h) — must validate. The cap is inclusive on the top edge,
18818        // matching the [`POLICY_TIMEOUT_MAX`] /
18819        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
18820        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18821        // sibling capped axes. Pin the boundary explicitly so a
18822        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
18823        // instead of `>`) surfaces here as a test failure rather than
18824        // a silent contract narrowing.
18825        let mut s = three_member_spec();
18826        s.politicas.circuit_breaker = Some(CircuitBreaker {
18827            max_failures: 5,
18828            window: POLICY_BREAKER_WINDOW_MAX,
18829        });
18830        s.validate()
18831            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
18832    }
18833
18834    #[test]
18835    fn accepts_circuit_breaker_window_typical_values() {
18836        // The documented production-playbook band positive-control
18837        // sweep — every value Hystrix / resilience4j / Istio / Envoy
18838        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
18839        // through the long-tail failure-detection band (15m, 30m, 1h)
18840        // the cap accepts. Pin the inclusive validated set explicitly
18841        // so a future tightening of the ceiling surfaces here as a
18842        // deliberate test edit, not a silent contract narrowing.
18843        for window in [
18844            Duration::from_millis(1),
18845            Duration::from_millis(500),
18846            Duration::from_secs(1),
18847            Duration::from_secs(10), // Hystrix / Istio / Envoy default
18848            Duration::from_secs(30),
18849            Duration::from_secs(60),  // resilience4j typical
18850            Duration::from_secs(300), // AWS App Mesh typical
18851            Duration::from_secs(900),
18852            Duration::from_secs(1800),
18853            Duration::from_secs(3600), // exactly 1h, the cap
18854        ] {
18855            let mut s = three_member_spec();
18856            s.politicas.circuit_breaker = Some(CircuitBreaker {
18857                max_failures: 5,
18858                window,
18859            });
18860            s.validate()
18861                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
18862        }
18863    }
18864
18865    #[test]
18866    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
18867        // The cross-arm ordering pin: `Duration::ZERO` is structurally
18868        // outside both `>= 1ms` (zero-floor) and
18869        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
18870        // diagnostic is the more self-locating one (it directly names
18871        // the omit-axis remediation), so the validate gate must fire
18872        // on zero first. Same shape every other zero-then-cap
18873        // ordering on this surface uses
18874        // ([`AplicacaoError::PolicyTimeoutZero`] then
18875        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
18876        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18877        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18878        let mut s = three_member_spec();
18879        s.politicas.circuit_breaker = Some(CircuitBreaker {
18880            max_failures: 5,
18881            window: Duration::ZERO,
18882        });
18883        assert_eq!(
18884            s.validate().unwrap_err(),
18885            AplicacaoError::PolicyBreakerZeroWindow,
18886            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18887        );
18888    }
18889
18890    #[test]
18891    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
18892        // The cross-arm ordering pin: a `Duration` that is *both*
18893        // sub-millisecond (non-canonical-form) and structurally above
18894        // the cap surfaces the canonical-form diagnostic first,
18895        // because the round-trip-shape break is the more fundamental
18896        // issue (the value can't even round-trip through the codec, so
18897        // the cap diagnostic naming `1ms..=1h` would be misleading —
18898        // there's no integer-ms form of the offending value). Pin the
18899        // order so a future refactor that reorders the arms surfaces
18900        // here as a test failure rather than a silent diagnostic
18901        // regression. Peer of
18902        // `policy_timeout_canonical_takes_precedence_over_cap` on the
18903        // sibling duration-typed `:politicas :timeout` axis.
18904        let mut s = three_member_spec();
18905        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
18906        s.politicas.circuit_breaker = Some(CircuitBreaker {
18907            max_failures: 5,
18908            window,
18909        });
18910        assert_eq!(
18911            s.validate().unwrap_err(),
18912            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
18913            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18914        );
18915    }
18916
18917    #[test]
18918    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
18919        // The cross-arm ordering pin between the two breaker axes: a
18920        // `CircuitBreaker` whose *both* `max_failures` is above its
18921        // cap *and* `window` is above its cap surfaces the
18922        // max-failures cap diagnostic first, because the validate
18923        // gate visits the failures arm before the window arm. Pin the
18924        // order so a future refactor that reorders the breaker arms
18925        // surfaces here.
18926        let mut s = three_member_spec();
18927        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18928        s.politicas.circuit_breaker = Some(CircuitBreaker {
18929            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18930            window,
18931        });
18932        assert_eq!(
18933            s.validate().unwrap_err(),
18934            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18935                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
18936            },
18937            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
18938        );
18939    }
18940
18941    #[test]
18942    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
18943        // The diagnostic-shape pin: the offending `Duration` is
18944        // carried verbatim into the
18945        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
18946        // the surfaced error message names the value the author wrote
18947        // (`":politicas :circuit-breaker :window (Duration { secs:
18948        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
18949        // just the cap. Same self-locating diagnostic shape every
18950        // other typed-cap arm on this surface carries
18951        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
18952        // offending `Duration` verbatim).
18953        let mut s = three_member_spec();
18954        let window = Duration::from_secs(7200); // 2h
18955        s.politicas.circuit_breaker = Some(CircuitBreaker {
18956            max_failures: 5,
18957            window,
18958        });
18959        let err = s.validate().unwrap_err();
18960        assert!(
18961            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
18962            "got {err:?}"
18963        );
18964        let msg = err.to_string();
18965        assert!(
18966            msg.contains("7200"),
18967            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
18968        );
18969    }
18970
18971    #[test]
18972    fn circuit_breaker_window_cap_pins_canonical_value() {
18973        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
18974        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
18975        // shared duration codec emits as a clean canonical string
18976        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
18977        // the sibling duration-typed `:politicas :timeout` axis (the
18978        // two duration-typed `:politicas` axes share a uniform top
18979        // edge). Pinning the literal value here surfaces a future
18980        // drift (a relaxation to 24h, a tightening to 5m) as a
18981        // deliberate test edit, not a silent contract narrowing. Same
18982        // shape every other typed-cap value pin on this surface uses
18983        // (`policy_timeout_cap_pins_canonical_value`).
18984        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
18985        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
18986        assert_eq!(
18987            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
18988            "the two duration-typed `:politicas` caps share the same top edge"
18989        );
18990    }
18991
18992    #[test]
18993    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
18994        // The codec round-trip property the cap arm preserves: the
18995        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
18996        // through the shared duration codec — every value at the cap
18997        // renders to a clean canonical string (`"1h"`) and parses back
18998        // to the same `Duration`. Pin this so a future drift between
18999        // the cap constant and the codec's largest emitted unit
19000        // surfaces here. Same shape every other typed boundary pin on
19001        // this surface uses
19002        // (`policy_timeout_cap_value_round_trips_through_codec`).
19003        let policy = MeshPolicy {
19004            circuit_breaker: Some(CircuitBreaker {
19005                max_failures: 5,
19006                window: POLICY_BREAKER_WINDOW_MAX,
19007            }),
19008            ..Default::default()
19009        };
19010        let json = serde_json::to_string(&policy).unwrap();
19011        // The codec emits `"1h"` for the canonical 1-hour magnitude.
19012        assert!(
19013            json.contains("\"1h\""),
19014            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
19015        );
19016        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19017        assert_eq!(
19018            back.circuit_breaker.unwrap().window,
19019            POLICY_BREAKER_WINDOW_MAX
19020        );
19021    }
19022
19023    #[test]
19024    fn is_integer_millisecond_duration_predicate_tracks_codec() {
19025        // Pin the predicate's accepted set against the codec's
19026        // accepted set explicitly. The codec parses
19027        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
19028        // accepted value is an integer-millisecond multiple — so the
19029        // predicate must accept exactly that set. Same shape every
19030        // other predicate-on-the-typed-slot helper carries
19031        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
19032        // Read directly from the codec-owned predicate — the crate's
19033        // single source of truth every typed-`Duration` axis now routes
19034        // through via
19035        // [`crate::render::require_positive_canonical_bounded_duration`].
19036        use super::supervisor::duration_codec::is_integer_millisecond_duration;
19037        assert!(is_integer_millisecond_duration(Duration::ZERO));
19038        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
19039        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
19040        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
19041        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
19042        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
19043        // Non-integer-millisecond residue: rejected.
19044        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
19045        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
19046        assert!(!is_integer_millisecond_duration(Duration::from_micros(
19047            1500
19048        )));
19049        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
19050        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
19051            999_999
19052        )));
19053        // The 1-ns-past-1ms boundary: rejected (no longer a clean
19054        // integer-millisecond multiple).
19055        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
19056            1_000_001
19057        )));
19058    }
19059
19060    #[test]
19061    fn policy_timeout_validated_value_round_trips_through_codec() {
19062        // The structural property the canonical-ms gate enforces:
19063        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
19064        // round-trips losslessly through the shared `duration_codec`
19065        // (serialize → string → deserialize → equal value). Pin this
19066        // end-to-end so a future change to either side (the validate
19067        // gate's accepted granularity, the codec's parse/render unit
19068        // set) that breaks the alignment surfaces here. The
19069        // previous-state shape (typed slot accepts arbitrary
19070        // `Duration`, codec only round-trips integer-ms) would fail
19071        // this test for any `Duration::from_micros(1500)` timeout —
19072        // the validate gate now forecloses that.
19073        for timeout in [
19074            Duration::from_millis(1),
19075            Duration::from_millis(1500),
19076            Duration::from_secs(30),
19077            Duration::from_secs(3600),
19078        ] {
19079            let mut s = three_member_spec();
19080            s.politicas.timeout = Some(timeout);
19081            s.validate().unwrap();
19082            let json = serde_json::to_string(&s.politicas).unwrap();
19083            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19084            assert_eq!(
19085                back.timeout, s.politicas.timeout,
19086                "every validated :timeout must round-trip losslessly through the codec"
19087            );
19088        }
19089    }
19090
19091    #[test]
19092    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
19093        // Peer of the `:timeout` round-trip property on the breaker
19094        // axis.
19095        for window in [
19096            Duration::from_millis(1),
19097            Duration::from_millis(1500),
19098            Duration::from_secs(30),
19099            Duration::from_secs(3600),
19100        ] {
19101            let mut s = three_member_spec();
19102            s.politicas.circuit_breaker = Some(CircuitBreaker {
19103                max_failures: 5,
19104                window,
19105            });
19106            s.validate().unwrap();
19107            let json = serde_json::to_string(&s.politicas).unwrap();
19108            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19109            assert_eq!(
19110                back.circuit_breaker.unwrap().window,
19111                window,
19112                "every validated :circuit-breaker :window must round-trip losslessly"
19113            );
19114        }
19115    }
19116
19117    #[test]
19118    fn empty_politicas_validates() {
19119        // Omitting every policy axis is fine — defaults express "no
19120        // policy on this axis", not "policy = 0". The fixture's typical
19121        // values continue to validate; this test pins that
19122        // MeshPolicy::default() is a clean pass through validate().
19123        let mut s = three_member_spec();
19124        s.politicas = MeshPolicy::default();
19125        s.validate().unwrap();
19126    }
19127
19128    #[test]
19129    fn typical_politicas_validates_with_every_axis_set() {
19130        // The full §III.1 example block (timeout + retries + breaker +
19131        // mtls + rate-limit) — every axis nonzero — must remain a
19132        // clean pass.
19133        let mut s = three_member_spec();
19134        s.politicas = MeshPolicy {
19135            timeout: Some(Duration::from_secs(30)),
19136            retries: Some(3),
19137            circuit_breaker: Some(CircuitBreaker {
19138                max_failures: 5,
19139                window: Duration::from_secs(60),
19140            }),
19141            mtls_required: Some(true),
19142            rate_limit: Some(RateLimit {
19143                rate: 100,
19144                window: Duration::from_secs(1),
19145            }),
19146        };
19147        s.validate().unwrap();
19148    }
19149
19150    #[test]
19151    fn rejects_empty_cluster_name() {
19152        let mut s = three_member_spec();
19153        s.placement.clusters = vec!["rio".into(), "".into()];
19154        assert_eq!(
19155            s.validate().unwrap_err(),
19156            AplicacaoError::PlacementClusterEmpty
19157        );
19158    }
19159
19160    #[test]
19161    fn rejects_duplicate_cluster_names() {
19162        let mut s = three_member_spec();
19163        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
19164        let err = s.validate().unwrap_err();
19165        assert!(
19166            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
19167            "got {err:?}"
19168        );
19169    }
19170
19171    #[test]
19172    fn rejects_placement_cluster_with_uppercase() {
19173        // The canonical "I copied the cluster's display name verbatim"
19174        // typo — K8s context names are lowercase per DNS-1123 label
19175        // rule, but org docs often round-trip a TitleCase identifier
19176        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
19177        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
19178        // on the peer name axis.
19179        let mut s = three_member_spec();
19180        s.placement.clusters = vec!["Rio".into(), "mar".into()];
19181        let err = s.validate().unwrap_err();
19182        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19183            panic!("expected PlacementClusterInvalid, got other variant");
19184        };
19185        assert_eq!(cluster, "Rio");
19186        assert!(
19187            reason.contains("uppercase"),
19188            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19189        );
19190        assert!(
19191            reason.contains("\"rio\""),
19192            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19193        );
19194    }
19195
19196    #[test]
19197    fn rejects_placement_cluster_with_underscore() {
19198        // The canonical "I'm thinking of an env var / hostname slug"
19199        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
19200        // schema. K8s context filtering on `my_cluster` silently misses
19201        // the cluster the author intended; the gate moves it to caixa-
19202        // build time. Same shape as `rejects_membro_caixa_with_underscore`
19203        // (3f9d7a0).
19204        let mut s = three_member_spec();
19205        s.placement.clusters = vec!["my_cluster".into()];
19206        let err = s.validate().unwrap_err();
19207        assert!(
19208            matches!(
19209                err,
19210                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19211                    if cluster == "my_cluster" && reason.contains('_')
19212            ),
19213            "got {err:?}"
19214        );
19215    }
19216
19217    #[test]
19218    fn rejects_placement_cluster_with_dot() {
19219        // A `:placement :clusters` entry is a single DNS-1123 *label*,
19220        // not a subdomain — even though K8s context names sometimes
19221        // carry a dotted form via kubeconfig conventions, the strictest
19222        // floor among the use sites (DNS-1035 cluster.x-k8s.io
19223        // `metadata.name`, Cilium identity label values) wins. The "I
19224        // want to namespace my cluster names with `.`" intent is
19225        // expressed via `-` (`mar-east`).
19226        let mut s = three_member_spec();
19227        s.placement.clusters = vec!["team.rio".into()];
19228        let err = s.validate().unwrap_err();
19229        assert!(
19230            matches!(
19231                err,
19232                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19233                    if cluster == "team.rio" && reason.contains('.')
19234            ),
19235            "got {err:?}"
19236        );
19237    }
19238
19239    #[test]
19240    fn rejects_placement_cluster_with_leading_hyphen() {
19241        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
19242        // with an alphanumeric. The K8s apiserver rejects `-rio`
19243        // outright; the rendered fan-out would emit a `metadata.name:
19244        // "-rio"` that fails admission far from the source caixa.lisp.
19245        let mut s = three_member_spec();
19246        s.placement.clusters = vec!["-rio".into()];
19247        let err = s.validate().unwrap_err();
19248        assert!(
19249            matches!(
19250                err,
19251                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19252                    if cluster == "-rio" && reason.contains("start and end")
19253            ),
19254            "got {err:?}"
19255        );
19256    }
19257
19258    #[test]
19259    fn rejects_placement_cluster_with_trailing_hyphen() {
19260        // The symmetric arm of the boundary rule. Pin separately so
19261        // both ends are covered against a future relaxation that only
19262        // checks one boundary (parallel to
19263        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
19264        let mut s = three_member_spec();
19265        s.placement.clusters = vec!["rio-".into()];
19266        let err = s.validate().unwrap_err();
19267        assert!(
19268            matches!(
19269                err,
19270                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19271                    if cluster == "rio-"
19272            ),
19273            "got {err:?}"
19274        );
19275    }
19276
19277    #[test]
19278    fn rejects_placement_cluster_with_unicode() {
19279        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19280        // before it reaches K8s. The byte-by-byte ASCII validity check
19281        // rejects multi-byte UTF-8 sequences by the first byte that
19282        // fails `[a-z0-9-]`.
19283        let mut s = three_member_spec();
19284        s.placement.clusters = vec!["rió".into()];
19285        let err = s.validate().unwrap_err();
19286        assert!(
19287            matches!(
19288                err,
19289                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19290                    if cluster == "rió"
19291            ),
19292            "got {err:?}"
19293        );
19294    }
19295
19296    #[test]
19297    fn rejects_placement_cluster_with_whitespace() {
19298        // Whitespace is the canonical "I pasted from a sketch / doc"
19299        // footgun. The apiserver rejects every cluster `metadata.name`
19300        // value carrying whitespace.
19301        let mut s = three_member_spec();
19302        s.placement.clusters = vec!["rio cluster".into()];
19303        let err = s.validate().unwrap_err();
19304        assert!(
19305            matches!(
19306                err,
19307                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19308                    if cluster == "rio cluster"
19309            ),
19310            "got {err:?}"
19311        );
19312    }
19313
19314    #[test]
19315    fn rejects_placement_cluster_too_long() {
19316        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
19317        // pin. The diagnostic names both the cap (63) and the actual
19318        // length so the author can shorten in one edit. Mirrors
19319        // `rejects_membro_caixa_too_long` (3f9d7a0).
19320        let mut s = three_member_spec();
19321        let too_long = "a".repeat(64);
19322        s.placement.clusters = vec![too_long.clone()];
19323        let err = s.validate().unwrap_err();
19324        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19325            panic!("expected PlacementClusterInvalid");
19326        };
19327        assert_eq!(cluster, too_long);
19328        assert!(
19329            reason.contains("63") && reason.contains("64"),
19330            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19331        );
19332    }
19333
19334    #[test]
19335    fn placement_cluster_max_length_validates() {
19336        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
19337        // future tightening (e.g. dropping to 62) surfaces here as a
19338        // regression, mirroring `membro_caixa_max_length_validates`
19339        // (3f9d7a0).
19340        let mut s = three_member_spec();
19341        s.placement.clusters = vec!["a".repeat(63)];
19342        s.validate().unwrap();
19343    }
19344
19345    #[test]
19346    fn accepts_canonical_placement_cluster_forms() {
19347        // The DNS-1123 label shapes a caixa author is realistically
19348        // going to write for cluster names: single-word lowercase
19349        // (`rio`), regional hyphen-joined (`mar-east`), single
19350        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
19351        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
19352        // Pin every leg so a future tightening that bans (e.g.) digit-
19353        // start identifiers surfaces here.
19354        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
19355            let mut s = three_member_spec();
19356            s.placement.clusters = vec![form.into()];
19357            s.validate().unwrap_or_else(|e| {
19358                panic!("canonical cluster form {form:?} must validate, got {e:?}")
19359            });
19360        }
19361    }
19362
19363    #[test]
19364    fn placement_cluster_empty_takes_precedence_over_invalid() {
19365        // Order pin: the existing `PlacementClusterEmpty` diagnostic
19366        // (which doesn't try to parse) fires before the new
19367        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
19368        // `:clusters` entry keeps its narrower error message — the new
19369        // gate would also reject `""`, but the empty-string arm is the
19370        // more self-locating diagnostic. Mirrors the
19371        // `membro_caixa_empty_takes_precedence_over_invalid` pin
19372        // (3f9d7a0).
19373        let mut s = three_member_spec();
19374        s.placement.clusters = vec!["rio".into(), "".into()];
19375        let err = s.validate().unwrap_err();
19376        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
19377    }
19378
19379    #[test]
19380    fn placement_cluster_invalid_fires_before_duplicate_check() {
19381        // Order pin: a malformed-shape `:clusters` entry surfaces *its
19382        // own* diagnostic, even when a later entry would otherwise
19383        // collapse onto a duplicate name. The per-entry shape gate runs
19384        // inline before the duplicate-key insert, parallel to
19385        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
19386        let mut s = three_member_spec();
19387        s.placement.clusters = vec!["Rio".into(), "rio".into()];
19388        let err = s.validate().unwrap_err();
19389        assert!(
19390            matches!(
19391                err,
19392                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
19393            ),
19394            "got {err:?}"
19395        );
19396    }
19397
19398    #[test]
19399    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
19400        // The diagnostic-shape pin: the error names the offending
19401        // `:clusters` value verbatim so the author can grep their
19402        // caixa.lisp without re-running the build, and carries a
19403        // non-empty `reason` naming the specific violation. Same shape
19404        // every typed-shape gate enshrines
19405        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
19406        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
19407        let mut s = three_member_spec();
19408        s.placement.clusters = vec!["BAD_CLUSTER".into()];
19409        let err = s.validate().unwrap_err();
19410        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19411            panic!("expected PlacementClusterInvalid");
19412        };
19413        assert_eq!(cluster, "BAD_CLUSTER");
19414        assert!(
19415            !reason.is_empty(),
19416            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
19417        );
19418    }
19419
19420    #[test]
19421    fn rejects_sharded_with_empty_clusters() {
19422        // §III.1: Sharded uses :clusters as the shard pool. An empty
19423        // pool means "shard across no clusters" — meaningless, same as
19424        // Replicated with no hosts.
19425        let mut s = three_member_spec();
19426        s.placement.estrategia = PlacementStrategy::Sharded;
19427        s.placement.shard_key = Some("$tenantId".into());
19428        s.placement.clusters = vec![];
19429        assert!(matches!(
19430            s.validate().unwrap_err(),
19431            AplicacaoError::PlacementWithoutClusters {
19432                estrategia: PlacementStrategy::Sharded
19433            }
19434        ));
19435    }
19436
19437    #[test]
19438    fn rejects_sharded_with_empty_shard_key() {
19439        let mut s = three_member_spec();
19440        s.placement.estrategia = PlacementStrategy::Sharded;
19441        s.placement.shard_key = Some("".into());
19442        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
19443    }
19444
19445    #[test]
19446    fn rejects_shard_key_under_replicated_strategy() {
19447        // The fail-before-pass-after pin: a `:placement (:estrategia
19448        // Replicated :shard-key "tenantId")` manifest carries the
19449        // hash-keyed-distribution slot on a strategy that never consumes
19450        // it. Before the gate the typed slot's value silently vanished
19451        // at the renderer layer (caixa-mesh emits `placement.shardKey`
19452        // verbatim regardless of strategy; the Akka-style cluster-
19453        // sharding reconciler keys off `estrategia == Sharded` and
19454        // ignores the slot otherwise), with no diagnostic. Lifting the
19455        // rejection to a build-time gate makes the
19456        // `shard_key.is_some() == matches!(estrategia, Sharded)`
19457        // partition a structural property of every validated
19458        // [`Placement`].
19459        let mut s = three_member_spec();
19460        // The fixture already uses Replicated; just add a shard-key.
19461        s.placement.shard_key = Some("$tenantId".into());
19462        let err = s.validate().unwrap_err();
19463        let AplicacaoError::ShardKeyOnNonSharded {
19464            estrategia,
19465            shard_key,
19466        } = err
19467        else {
19468            panic!("expected ShardKeyOnNonSharded, got {err:?}");
19469        };
19470        assert_eq!(estrategia, PlacementStrategy::Replicated);
19471        assert_eq!(shard_key, "$tenantId");
19472    }
19473
19474    #[test]
19475    fn rejects_shard_key_under_singlenode_strategy() {
19476        // Peer of the Replicated case above on the SingleNode arm: OTP
19477        // distributed-app takeover (one cluster runs at a time) has no
19478        // hash-keyed routing axis to consume `:shard-key` either, so
19479        // the rejection fires on both non-Sharded arms uniformly.
19480        let mut s = three_member_spec();
19481        s.placement.estrategia = PlacementStrategy::SingleNode;
19482        s.placement.shard_key = Some("$tenantId".into());
19483        let err = s.validate().unwrap_err();
19484        let AplicacaoError::ShardKeyOnNonSharded {
19485            estrategia,
19486            shard_key,
19487        } = err
19488        else {
19489            panic!("expected ShardKeyOnNonSharded, got {err:?}");
19490        };
19491        assert_eq!(estrategia, PlacementStrategy::SingleNode);
19492        assert_eq!(shard_key, "$tenantId");
19493    }
19494
19495    #[test]
19496    fn rejects_empty_shard_key_under_replicated_strategy() {
19497        // The `Some("")` case under non-Sharded is rejected by
19498        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
19499        // fires before the empty-value gate), not
19500        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
19501        // the `Sharded` arm). Pin the partition so a future reorder of
19502        // the validate_placement match arms doesn't silently swap which
19503        // diagnostic the author sees — both are author errors, but
19504        // ShardKeyOnNonSharded names which strategy is the actual fix
19505        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
19506        // only says "pick a non-empty key".
19507        let mut s = three_member_spec();
19508        s.placement.shard_key = Some(String::new());
19509        let err = s.validate().unwrap_err();
19510        assert!(
19511            matches!(
19512                err,
19513                AplicacaoError::ShardKeyOnNonSharded {
19514                    estrategia: PlacementStrategy::Replicated,
19515                    ref shard_key,
19516                } if shard_key.is_empty()
19517            ),
19518            "got {err:?}"
19519        );
19520    }
19521
19522    #[test]
19523    fn replicated_without_shard_key_validates() {
19524        // The complement of the rejection: `:placement :estrategia
19525        // Replicated` with `:shard-key None` is the canonical happy
19526        // path on every existing fixture. Pin the no-shard-key case so
19527        // the new gate doesn't accidentally fire on `None`.
19528        let mut s = three_member_spec();
19529        assert!(matches!(
19530            s.placement.estrategia,
19531            PlacementStrategy::Replicated
19532        ));
19533        s.placement.shard_key = None;
19534        s.validate().unwrap();
19535    }
19536
19537    #[test]
19538    fn singlenode_without_shard_key_validates() {
19539        // Peer of the Replicated no-shard-key case on the SingleNode
19540        // arm — both non-Sharded strategies must validate cleanly when
19541        // the slot is omitted.
19542        let mut s = three_member_spec();
19543        s.placement.estrategia = PlacementStrategy::SingleNode;
19544        s.placement.shard_key = None;
19545        s.validate().unwrap();
19546    }
19547
19548    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
19549        // Fixture builder for the `:placement :shard-key` shape gate
19550        // tests: a three-member Aplicacao on the `Sharded` strategy
19551        // with the supplied `:shard-key` slot. Co-locates the
19552        // arm-construction so every test below carries one line of
19553        // setup (the offending `:shard-key` value) and the assertion.
19554        let mut s = three_member_spec();
19555        s.placement.estrategia = PlacementStrategy::Sharded;
19556        s.placement.shard_key = Some(key.into());
19557        s
19558    }
19559
19560    #[test]
19561    fn rejects_shard_key_with_embedded_space() {
19562        // The canonical paste-from-aligned-doc footgun:
19563        // `:shard-key "$tenant Id"` — the Akka-style entity-id
19564        // extractor reads the slot as a single-token reference, and an
19565        // embedded space breaks the token boundary at the runtime
19566        // hash-extractor pass with no diagnostic naming the offending
19567        // entry.
19568        let s = sharded_spec_with_key("$tenant Id");
19569        let err = s.validate().unwrap_err();
19570        assert!(
19571            matches!(
19572                err,
19573                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19574                    if shard_key == "$tenant Id" && reason.contains("space")
19575            ),
19576            "got {err:?}"
19577        );
19578    }
19579
19580    #[test]
19581    fn rejects_shard_key_with_leading_space() {
19582        // Leading-space arm of the embedded-whitespace footgun — the
19583        // paste-from-aligned-doc / paste-from-CSV-cell variant where
19584        // the leading column-padding leaked into the slot.
19585        let s = sharded_spec_with_key(" $tenantId");
19586        let err = s.validate().unwrap_err();
19587        assert!(
19588            matches!(
19589                err,
19590                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
19591                    if shard_key == " $tenantId"
19592            ),
19593            "got {err:?}"
19594        );
19595    }
19596
19597    #[test]
19598    fn rejects_shard_key_with_trailing_newline() {
19599        // The canonical paste-from-shell-heredoc footgun — every
19600        // `<<EOF` heredoc terminator paste leaves a trailing newline
19601        // the YAML emitter then folds away inconsistently across
19602        // emitter implementations.
19603        let s = sharded_spec_with_key("$tenantId\n");
19604        let err = s.validate().unwrap_err();
19605        assert!(
19606            matches!(
19607                err,
19608                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19609                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
19610            ),
19611            "got {err:?}"
19612        );
19613    }
19614
19615    #[test]
19616    fn rejects_shard_key_with_embedded_tab() {
19617        // The paste-from-aligned-doc tab-stop variant — tabs land
19618        // alongside spaces in copy-paste from formatted columns.
19619        let s = sharded_spec_with_key("$tenant\tId");
19620        let err = s.validate().unwrap_err();
19621        assert!(
19622            matches!(
19623                err,
19624                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19625                    if shard_key == "$tenant\tId" && reason.contains("tab")
19626            ),
19627            "got {err:?}"
19628        );
19629    }
19630
19631    #[test]
19632    fn rejects_shard_key_with_control_character() {
19633        // The paste-from-binary / paste-from-screen-cleared-terminal
19634        // footgun — an embedded `\x01` (SOH) byte that some YAML
19635        // emitters silently strip and others escape as ``,
19636        // breaking round-trip across emitter implementations.
19637        let s = sharded_spec_with_key("$tenant\u{0001}Id");
19638        let err = s.validate().unwrap_err();
19639        assert!(
19640            matches!(
19641                err,
19642                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19643                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
19644            ),
19645            "got {err:?}"
19646        );
19647    }
19648
19649    #[test]
19650    fn rejects_shard_key_with_non_ascii() {
19651        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
19652        // footgun — non-ASCII bytes normalize differently between the
19653        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
19654        // YAML parser, the same entity ID can silently map to two
19655        // distinct shards on a re-render.
19656        let s = sharded_spec_with_key("$tenàntId");
19657        let err = s.validate().unwrap_err();
19658        assert!(
19659            matches!(
19660                err,
19661                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19662                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
19663            ),
19664            "got {err:?}"
19665        );
19666    }
19667
19668    #[test]
19669    fn rejects_shard_key_too_long() {
19670        // Length cap pin: 64 bytes — one byte over the
19671        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
19672        // here is a paste-from-doc multi-line blob landing in
19673        // `:shard-key` instead of a single-token extractor expression.
19674        let too_long = "a".repeat(64);
19675        let s = sharded_spec_with_key(&too_long);
19676        let err = s.validate().unwrap_err();
19677        let AplicacaoError::ShardKeyInvalid {
19678            ref shard_key,
19679            ref reason,
19680        } = err
19681        else {
19682            panic!("expected ShardKeyInvalid, got {err:?}");
19683        };
19684        assert_eq!(shard_key, &too_long);
19685        assert!(
19686            reason.contains("63") && reason.contains("64"),
19687            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19688        );
19689    }
19690
19691    #[test]
19692    fn shard_key_max_length_validates() {
19693        // Boundary pin: 63 bytes exactly — the
19694        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
19695        // dropping to 62) surfaces here as a regression, mirroring
19696        // `placement_cluster_max_length_validates` /
19697        // `placement_affinity_max_length_validates` on the peer
19698        // identifier-shaped slots.
19699        let s = sharded_spec_with_key(&"a".repeat(63));
19700        s.validate().unwrap();
19701    }
19702
19703    #[test]
19704    fn accepts_canonical_shard_key_forms() {
19705        // The Akka-style entity-id extractor shapes a caixa author is
19706        // realistically going to write — pin every leg so a future
19707        // tightening that bans (e.g.) the `${...}` interpolation
19708        // variant or the `metadata.<field>` JSONPath form surfaces
19709        // here as a regression. The canonical forms span:
19710        //
19711        //   - bare property name (`tenantId`, `customerId`)
19712        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
19713        //   - JSONPath-style nested reference (`metadata.tenantId`,
19714        //     `$.user.id`)
19715        //   - interpolation-style template (`${tenant}`)
19716        //   - snake_case property name (`customer_id`)
19717        //   - kebab-case property name (`customer-id` — accepted
19718        //     because the slot is a printable-ASCII single-token
19719        //     reference, not a DNS-1123 label like
19720        //     `:placement :affinity` / `:clusters`)
19721        //   - single character (`a`, `$` — boundary)
19722        for form in [
19723            "tenantId",
19724            "customerId",
19725            "$tenantId",
19726            "metadata.tenantId",
19727            "$.user.id",
19728            "${tenant}",
19729            "customer_id",
19730            "customer-id",
19731            "a",
19732            "$",
19733        ] {
19734            let s = sharded_spec_with_key(form);
19735            s.validate().unwrap_or_else(|e| {
19736                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
19737            });
19738        }
19739    }
19740
19741    #[test]
19742    fn shard_key_empty_takes_precedence_over_invalid() {
19743        // Order pin: the existing `ShardedKeyEmpty` diagnostic
19744        // (reserved for the `Sharded` `Some("")` arm) fires before the
19745        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
19746        // `:shard-key` keeps its narrower error message — the new gate
19747        // would also reject `""` defensively, but the empty-string arm
19748        // is the more self-locating diagnostic. Mirrors the
19749        // `placement_cluster_empty_takes_precedence_over_invalid` pin
19750        // on the peer identifier-shaped slot.
19751        let s = sharded_spec_with_key("");
19752        let err = s.validate().unwrap_err();
19753        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
19754    }
19755
19756    #[test]
19757    fn shard_key_invalid_diagnostic_carries_offending_value() {
19758        // The diagnostic-shape pin: the error names the offending
19759        // `:shard-key` value verbatim so the author can grep their
19760        // caixa.lisp without re-running the build, and carries a
19761        // parser-shaped `reason:` naming the specific violation —
19762        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19763        // on the peer identifier-shaped slot.
19764        let s = sharded_spec_with_key("$tenant Id");
19765        let err = s.validate().unwrap_err();
19766        let AplicacaoError::ShardKeyInvalid {
19767            ref shard_key,
19768            ref reason,
19769        } = err
19770        else {
19771            panic!("expected ShardKeyInvalid, got {err:?}");
19772        };
19773        assert_eq!(shard_key, "$tenant Id");
19774        assert!(
19775            !reason.is_empty(),
19776            "reason must name the specific violation, got empty string"
19777        );
19778    }
19779
19780    #[test]
19781    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
19782        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
19783        // `:shard-key` carried on non-Sharded strategies) fires before
19784        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
19785        // a `Replicated` strategy surfaces the more self-locating
19786        // strategy-mismatch diagnostic (naming the actual fix — drop
19787        // the slot, or switch to Sharded) rather than the shape
19788        // diagnostic. The strategy-mismatch arm is the more actionable
19789        // diagnostic: a malformed shard-key on Replicated is "you
19790        // shouldn't have a :shard-key here at all", not "your
19791        // :shard-key value is malformed".
19792        let mut s = three_member_spec();
19793        // Replicated is the default fixture strategy.
19794        s.placement.shard_key = Some("$tenant Id".into());
19795        let err = s.validate().unwrap_err();
19796        assert!(
19797            matches!(
19798                err,
19799                AplicacaoError::ShardKeyOnNonSharded {
19800                    estrategia: PlacementStrategy::Replicated,
19801                    ..
19802                }
19803            ),
19804            "got {err:?}"
19805        );
19806    }
19807
19808    #[test]
19809    fn rejects_empty_affinity_hint() {
19810        let mut s = three_member_spec();
19811        s.placement.affinity = Some("".into());
19812        assert_eq!(
19813            s.validate().unwrap_err(),
19814            AplicacaoError::PlacementAffinityEmpty
19815        );
19816    }
19817
19818    #[test]
19819    fn placement_without_affinity_validates() {
19820        // Omitting :affinity is fine — the placement engine falls back
19821        // to the default heuristic. Pin the no-hint case so the
19822        // affinity-empty rejection doesn't accidentally fire on `None`.
19823        let mut s = three_member_spec();
19824        s.placement.affinity = None;
19825        s.validate().unwrap();
19826    }
19827
19828    #[test]
19829    fn rejects_placement_affinity_with_uppercase() {
19830        // The canonical "I copied the ADR's display name verbatim" typo
19831        // — placement hints land verbatim in K8s label-selector
19832        // territory, where the apiserver enforces the DNS-1123 label
19833        // rule (lowercase-only) on every identity-keyed admission axis.
19834        // Mirrors `rejects_placement_cluster_with_uppercase` on the
19835        // sibling slot.
19836        let mut s = three_member_spec();
19837        s.placement.affinity = Some("DataLocality".into());
19838        let err = s.validate().unwrap_err();
19839        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19840            panic!("expected PlacementAffinityInvalid, got other variant");
19841        };
19842        assert_eq!(affinity, "DataLocality");
19843        assert!(
19844            reason.contains("uppercase"),
19845            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19846        );
19847        assert!(
19848            reason.contains("\"datalocality\""),
19849            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19850        );
19851    }
19852
19853    #[test]
19854    fn rejects_placement_affinity_with_underscore() {
19855        // The canonical "I'm thinking of an env var / Python identifier"
19856        // leak — `_` is forbidden by every DNS-1123 label schema. Same
19857        // shape as `rejects_placement_cluster_with_underscore` on the
19858        // sibling slot.
19859        let mut s = three_member_spec();
19860        s.placement.affinity = Some("data_locality".into());
19861        let err = s.validate().unwrap_err();
19862        assert!(
19863            matches!(
19864                err,
19865                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19866                    if affinity == "data_locality" && reason.contains('_')
19867            ),
19868            "got {err:?}"
19869        );
19870    }
19871
19872    #[test]
19873    fn rejects_placement_affinity_with_dot() {
19874        // A `:placement :affinity` value is a single DNS-1123 *label*
19875        // (it lands as a K8s label value selector key), not a subdomain.
19876        // The "I want to namespace my hint with `.`" intent is expressed
19877        // via `-` (`data-locality-east`).
19878        let mut s = three_member_spec();
19879        s.placement.affinity = Some("data.locality".into());
19880        let err = s.validate().unwrap_err();
19881        assert!(
19882            matches!(
19883                err,
19884                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19885                    if affinity == "data.locality" && reason.contains('.')
19886            ),
19887            "got {err:?}"
19888        );
19889    }
19890
19891    #[test]
19892    fn rejects_placement_affinity_with_unicode() {
19893        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19894        // before it reaches K8s. The byte-by-byte ASCII validity check
19895        // rejects multi-byte UTF-8 sequences by the first byte that
19896        // fails `[a-z0-9-]`.
19897        let mut s = three_member_spec();
19898        s.placement.affinity = Some("data-localité".into());
19899        let err = s.validate().unwrap_err();
19900        assert!(
19901            matches!(
19902                err,
19903                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19904                    if affinity == "data-localité"
19905            ),
19906            "got {err:?}"
19907        );
19908    }
19909
19910    #[test]
19911    fn rejects_placement_affinity_with_leading_hyphen() {
19912        // DNS-1123 boundary rule: labels must start with an
19913        // alphanumeric. Pin separately from the trailing-hyphen arm so
19914        // a future relaxation that only checks one boundary surfaces
19915        // here as a regression (parallel to
19916        // `rejects_placement_cluster_with_leading_hyphen`).
19917        let mut s = three_member_spec();
19918        s.placement.affinity = Some("-data-locality".into());
19919        let err = s.validate().unwrap_err();
19920        assert!(
19921            matches!(
19922                err,
19923                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19924                    if affinity == "-data-locality" && reason.contains("start and end")
19925            ),
19926            "got {err:?}"
19927        );
19928    }
19929
19930    #[test]
19931    fn rejects_placement_affinity_with_trailing_hyphen() {
19932        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
19933        // ends are covered against a future relaxation.
19934        let mut s = three_member_spec();
19935        s.placement.affinity = Some("data-locality-".into());
19936        let err = s.validate().unwrap_err();
19937        assert!(
19938            matches!(
19939                err,
19940                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19941                    if affinity == "data-locality-"
19942            ),
19943            "got {err:?}"
19944        );
19945    }
19946
19947    #[test]
19948    fn rejects_placement_affinity_with_whitespace() {
19949        // Whitespace is the canonical "I pasted from a sketch / doc"
19950        // footgun. The apiserver rejects every label-selector value
19951        // carrying whitespace.
19952        let mut s = three_member_spec();
19953        s.placement.affinity = Some("data locality".into());
19954        let err = s.validate().unwrap_err();
19955        assert!(
19956            matches!(
19957                err,
19958                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19959                    if affinity == "data locality"
19960            ),
19961            "got {err:?}"
19962        );
19963    }
19964
19965    #[test]
19966    fn rejects_placement_affinity_too_long() {
19967        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
19968        // pin. The diagnostic names both the cap (63) and the actual
19969        // length so the author can shorten in one edit. Mirrors
19970        // `rejects_placement_cluster_too_long`.
19971        let mut s = three_member_spec();
19972        let too_long = "a".repeat(64);
19973        s.placement.affinity = Some(too_long.clone());
19974        let err = s.validate().unwrap_err();
19975        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19976            panic!("expected PlacementAffinityInvalid");
19977        };
19978        assert_eq!(affinity, too_long);
19979        assert!(
19980            reason.contains("63") && reason.contains("64"),
19981            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19982        );
19983    }
19984
19985    #[test]
19986    fn placement_affinity_max_length_validates() {
19987        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
19988        // future tightening (e.g. dropping to 62) surfaces here as a
19989        // regression, mirroring `placement_cluster_max_length_validates`.
19990        let mut s = three_member_spec();
19991        s.placement.affinity = Some("a".repeat(63));
19992        s.validate().unwrap();
19993    }
19994
19995    #[test]
19996    fn accepts_canonical_placement_affinity_forms() {
19997        // The DNS-1123 label shapes a caixa author is realistically
19998        // going to write for placement hints: the M3 canonical examples
19999        // (`data-locality`, `low-latency`, `anti-affinity`), the
20000        // single-token form (`affinity`), the single-character boundary
20001        // (`a`), the digit-start (DNS-1123 allows this, unlike
20002        // DNS-1035), and a regional-suffixed form. Pin every leg so a
20003        // future tightening that bans (e.g.) digit-start identifiers
20004        // surfaces here.
20005        for form in [
20006            "data-locality",
20007            "low-latency",
20008            "anti-affinity",
20009            "affinity",
20010            "a",
20011            "3-tier",
20012            "locality-east",
20013        ] {
20014            let mut s = three_member_spec();
20015            s.placement.affinity = Some(form.into());
20016            s.validate().unwrap_or_else(|e| {
20017                panic!("canonical affinity form {form:?} must validate, got {e:?}")
20018            });
20019        }
20020    }
20021
20022    #[test]
20023    fn placement_affinity_empty_takes_precedence_over_invalid() {
20024        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
20025        // (which doesn't try to parse) fires before the new
20026        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
20027        // `:affinity` keeps its narrower error message — the new gate
20028        // would also reject `""`, but the empty-string arm is the more
20029        // self-locating diagnostic. Mirrors the
20030        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
20031        let mut s = three_member_spec();
20032        s.placement.affinity = Some(String::new());
20033        let err = s.validate().unwrap_err();
20034        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
20035    }
20036
20037    #[test]
20038    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
20039        // The diagnostic shape pin: every rejection carries the offending
20040        // `affinity:` verbatim plus a parser-shaped `reason:` so the
20041        // author can grep their caixa.lisp for `:affinity "<hint>"` and
20042        // fix it in one edit. Mirrors the
20043        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
20044        // pin on the sibling slot.
20045        let mut s = three_member_spec();
20046        s.placement.affinity = Some("Data_Locality".into());
20047        let err = s.validate().unwrap_err();
20048        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
20049            panic!("expected PlacementAffinityInvalid");
20050        };
20051        assert_eq!(affinity, "Data_Locality");
20052        assert!(
20053            !reason.is_empty(),
20054            "diagnostic reason must not be empty (got: {reason:?})"
20055        );
20056    }
20057
20058    #[test]
20059    fn singlenode_with_takeover_candidates_validates() {
20060        // OTP distributed-application convention (MESH-COMPOSITION
20061        // §II.1): SingleNode runs on one cluster at a time but the
20062        // :clusters list enumerates the takeover candidates. Multiple
20063        // entries are not a contradiction — they are the failover pool.
20064        let mut s = three_member_spec();
20065        s.placement.estrategia = PlacementStrategy::SingleNode;
20066        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
20067        s.validate().unwrap();
20068    }
20069
20070    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
20071
20072    #[test]
20073    fn mesh_policy_default_is_empty() {
20074        // The Default impl carries None on every axis — the typed
20075        // analog of an unset `:politicas (())` slot. Renderers that
20076        // overlay the policy onto a cluster artifact key off this
20077        // predicate to skip the slot entirely; pinning so a future
20078        // axis added to MeshPolicy can't silently break the contract
20079        // (a new field whose Default is non-None would flip is_empty
20080        // to false on every existing caixa, surfacing here).
20081        assert!(MeshPolicy::default().is_empty());
20082    }
20083
20084    #[test]
20085    fn mesh_policy_with_only_timeout_is_not_empty() {
20086        let p = MeshPolicy {
20087            timeout: Some(Duration::from_secs(30)),
20088            ..Default::default()
20089        };
20090        assert!(!p.is_empty());
20091    }
20092
20093    #[test]
20094    fn mesh_policy_with_only_retries_is_not_empty() {
20095        let p = MeshPolicy {
20096            retries: Some(3),
20097            ..Default::default()
20098        };
20099        assert!(!p.is_empty());
20100    }
20101
20102    #[test]
20103    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
20104        let p = MeshPolicy {
20105            circuit_breaker: Some(CircuitBreaker {
20106                max_failures: 5,
20107                window: Duration::from_secs(60),
20108            }),
20109            ..Default::default()
20110        };
20111        assert!(!p.is_empty());
20112    }
20113
20114    #[test]
20115    fn mesh_policy_with_only_mtls_required_is_not_empty() {
20116        // Even `mtls_required: Some(false)` (an explicit opt-out) is
20117        // not empty — the author *named* the axis, the renderer needs
20118        // to honor that vs. fall back to the cluster default.
20119        let p = MeshPolicy {
20120            mtls_required: Some(false),
20121            ..Default::default()
20122        };
20123        assert!(!p.is_empty());
20124    }
20125
20126    #[test]
20127    fn mesh_policy_with_only_rate_limit_is_not_empty() {
20128        let p = MeshPolicy {
20129            rate_limit: Some(RateLimit {
20130                rate: 100,
20131                window: Duration::from_secs(1),
20132            }),
20133            ..Default::default()
20134        };
20135        assert!(!p.is_empty());
20136    }
20137
20138    #[test]
20139    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
20140        // The three-member happy-path fixture sets timeout + retries +
20141        // mtls_required — every populated axis must read non-empty.
20142        // Pin the round-trip so the M3.x per-:politicas emitter (the
20143        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
20144        // on is_empty() to decide whether to emit at all without
20145        // re-deriving the contract from inline field probes.
20146        assert!(!three_member_spec().politicas.is_empty());
20147    }
20148
20149    // ── shared duration codec: cross-slot integer-magnitude gate ──
20150    //
20151    // The integer-magnitude discipline applied to
20152    // `supervisor::duration_codec::parse` lifts onto every typed slot
20153    // that routes through the shared codec — `MeshPolicy::timeout`
20154    // (`:politicas :timeout`) and `CircuitBreaker::window`
20155    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
20156    // These cross-slot tests pin that the gate fires at the serde
20157    // layer for both typed slots, not just for the supervisor side.
20158
20159    #[test]
20160    fn policy_timeout_serde_rejects_fractional_seconds() {
20161        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
20162        // so the shared codec's integer-magnitude gate applies on
20163        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
20164        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
20165        // deserialize with the canonical-form diagnostic naming the
20166        // offending `"1.5"` and the remediation `"1500ms"`.
20167        let payload = r#"{"timeout":"1.5s"}"#;
20168        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20169        let msg = err.to_string();
20170        assert!(
20171            msg.contains("not a non-negative integer"),
20172            "expected integer-magnitude diagnostic in {msg:?}"
20173        );
20174        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
20175        assert!(
20176            msg.contains("\"1500ms\""),
20177            "missing canonical-form remediation in {msg:?}"
20178        );
20179    }
20180
20181    #[test]
20182    fn policy_timeout_serde_rejects_leading_plus_sign() {
20183        // Pin the leading-`+` arm cross-slot — the prior f64 parser
20184        // accepted `"+30s"` silently and round-tripped to `"30s"`.
20185        let payload = r#"{"timeout":"+30s"}"#;
20186        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20187        let msg = err.to_string();
20188        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
20189    }
20190
20191    #[test]
20192    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
20193        // `CircuitBreaker::window` uses `with =
20194        // "supervisor::duration_codec_required"` (the required-Duration
20195        // variant that delegates to the same shared parser). `"0.5m"`
20196        // parsed to 30s and round-tripped to `"30s"` on next emit —
20197        // DRIFT closed.
20198        let payload = format!(
20199            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
20200            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
20201            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
20202        );
20203        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
20204        let msg = err.to_string();
20205        assert!(
20206            msg.contains("not a non-negative integer"),
20207            "expected integer-magnitude diagnostic in {msg:?}"
20208        );
20209        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
20210        assert!(
20211            msg.contains("\"30s\""),
20212            "missing canonical-form remediation in {msg:?}"
20213        );
20214    }
20215
20216    #[test]
20217    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
20218        // Pin the happy-path on the cross-slot side: every canonical
20219        // author shape `render` ever emits parses cleanly through the
20220        // shared codec on the `CircuitBreaker` slot. The
20221        // codec's accepted set (post-gate) is exactly its emitted set
20222        // for the integer-magnitude class.
20223        for window_lit in ["30s", "500ms", "2m", "1h"] {
20224            let payload = format!(
20225                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
20226                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
20227                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
20228            );
20229            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
20230                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
20231            });
20232            assert_eq!(cb.max_failures, 5);
20233        }
20234    }
20235
20236    // ── rate_limit_codec: integer-magnitude gate ──
20237    //
20238    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
20239    // / 737a676 / d53c922 trajectory landed on every typed-duration /
20240    // typed-byte-size codec in caixa-core lifts onto the fifth typed
20241    // codec — `rate_limit_codec` — through the digit-only magnitude
20242    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
20243    // These tests pin the gate at the serde layer for `:politicas
20244    // :rate-limit` (the only typed slot the codec backs), and at the
20245    // codec-internal `parse` layer for the canonical positive cases.
20246
20247    #[test]
20248    fn rate_limit_serde_rejects_fractional_rate() {
20249        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
20250        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
20251        // wording, which didn't name the canonical-form remediation or
20252        // the round-trip drift the next emit would produce. Now refused
20253        // at deserialize with the canonical-form diagnostic naming the
20254        // offending `"1.5"` magnitude and the round-trip drift wording.
20255        let payload = r#"{"rateLimit":"1.5/s"}"#;
20256        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20257        let msg = err.to_string();
20258        assert!(
20259            msg.contains("not a non-negative integer"),
20260            "expected integer-magnitude diagnostic in {msg:?}"
20261        );
20262        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
20263        assert!(
20264            msg.contains("THEORY.md"),
20265            "missing render-determinism contract citation in {msg:?}"
20266        );
20267    }
20268
20269    #[test]
20270    fn rate_limit_serde_rejects_leading_plus_sign() {
20271        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
20272        // permissive-`+` parse), so `"+100/s"` silently parsed to
20273        // `RateLimit { 100, 1s }` and round-tripped through `render` to
20274        // `"100/s"` — a *different* canonical string on the next emit,
20275        // breaking the THEORY.md Part V render-determinism contract
20276        // exactly the way the peer duration codecs' `"+30s"` case did.
20277        // This is the load-bearing class the digit-only gate closes
20278        // beyond what `u32::from_str`'s strictness covers on its own.
20279        let payload = r#"{"rateLimit":"+100/s"}"#;
20280        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20281        let msg = err.to_string();
20282        assert!(
20283            msg.contains("not a non-negative integer"),
20284            "expected integer-magnitude diagnostic in {msg:?}"
20285        );
20286        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
20287    }
20288
20289    #[test]
20290    fn rate_limit_serde_rejects_leading_minus_sign() {
20291        // The signed-negative arm: `"-1/s"` lands on the
20292        // non-canonical-but-numeric branch via the `i64` fallback (the
20293        // `f64` parse also succeeds), surfacing the canonical-form
20294        // diagnostic. Replaces the prior value-laundered "not a u32"
20295        // wording with the unified diagnostic across signs.
20296        let payload = r#"{"rateLimit":"-1/s"}"#;
20297        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20298        let msg = err.to_string();
20299        assert!(
20300            msg.contains("not a non-negative integer"),
20301            "expected integer-magnitude diagnostic in {msg:?}"
20302        );
20303        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
20304    }
20305
20306    #[test]
20307    fn rate_limit_serde_rejects_decimal_shaped_integer() {
20308        // `"100.0/s"` is integer-valued numerically but not in the
20309        // codec's accepted set — `render` emits `"100/s"`, so the
20310        // round-trip would drift. Lifted to the canonical-form
20311        // diagnostic peer with the duration codec's `"1.0s"` case
20312        // (1c55a2a).
20313        let payload = r#"{"rateLimit":"100.0/s"}"#;
20314        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20315        let msg = err.to_string();
20316        assert!(
20317            msg.contains("not a non-negative integer"),
20318            "expected integer-magnitude diagnostic in {msg:?}"
20319        );
20320        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
20321    }
20322
20323    #[test]
20324    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
20325        // Non-numeric, non-digit-only input lands on the existing
20326        // narrower `"not a u32"` arm (preserved for diagnostic-shape
20327        // stability on the parser-shape footgun case). Pin this so a
20328        // future relaxation of the numeric-fallback predicate doesn't
20329        // silently collapse garbage onto the canonical-form arm — same
20330        // partition the peer duration codecs draw between
20331        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
20332        let payload = r#"{"rateLimit":"abc/s"}"#;
20333        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20334        let msg = err.to_string();
20335        assert!(
20336            msg.contains("not a u32"),
20337            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
20338        );
20339        assert!(
20340            !msg.contains("not a non-negative integer"),
20341            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
20342        );
20343    }
20344
20345    #[test]
20346    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
20347        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
20348        // u32's range. The digit-only gate passes; `u32::from_str`
20349        // fails on overflow. Surface that with the overflow-shaped
20350        // diagnostic naming the offending magnitude verbatim, peer
20351        // with `supervisor::duration_codec`'s overflow arm. Pinning
20352        // the wording so a future refactor doesn't silently collapse
20353        // overflow onto the canonical-form arm.
20354        let payload = r#"{"rateLimit":"4294967296/s"}"#;
20355        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20356        let msg = err.to_string();
20357        assert!(
20358            msg.contains("overflows u32"),
20359            "expected overflow diagnostic in {msg:?}"
20360        );
20361        assert!(
20362            msg.contains("\"4294967296\""),
20363            "missing offending magnitude in {msg:?}"
20364        );
20365    }
20366
20367    #[test]
20368    fn rate_limit_serde_rejects_leading_zero_magnitude() {
20369        // `"0100/s"` is digit-only, so the existing
20370        // non-digit-only / sign / fractional arm doesn't catch it —
20371        // `u32::from_str("0100")` returns `Ok(100)`, so before this
20372        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
20373        // round-tripped through `render` to `"100/s"` — a *different*
20374        // canonical string on the next emit, breaking the THEORY.md
20375        // Part V render-determinism contract exactly the way the
20376        // peer `"+100/s"` case did before the leading-`+` arm landed.
20377        // This is the load-bearing class the leading-zero gate closes
20378        // beyond what the existing digit-only / sign / fractional
20379        // gates cover, and the peer arm to the leading-`+` test
20380        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
20381        // canonical-form-drift axis.
20382        let payload = r#"{"rateLimit":"0100/s"}"#;
20383        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20384        let msg = err.to_string();
20385        assert!(
20386            msg.contains("non-canonical leading zero"),
20387            "expected leading-zero diagnostic in {msg:?}"
20388        );
20389        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
20390        assert!(
20391            msg.contains("THEORY.md"),
20392            "missing render-determinism contract citation in {msg:?}"
20393        );
20394    }
20395
20396    #[test]
20397    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
20398        // `"00/s"` is the degenerate leading-zero case — every byte
20399        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
20400        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
20401        // a *different* canonical string, same render-determinism
20402        // violation. The single-byte `"0/s"` itself is in the
20403        // accepted set (round-trips losslessly through `render`,
20404        // refused downstream by `PolicyRateLimitZero`); the
20405        // multi-byte `"00/s"` is not. Pins the boundary between the
20406        // accepted single-`0` and the rejected leading-zero class.
20407        let payload = r#"{"rateLimit":"00/s"}"#;
20408        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20409        let msg = err.to_string();
20410        assert!(
20411            msg.contains("non-canonical leading zero"),
20412            "expected leading-zero diagnostic in {msg:?}"
20413        );
20414        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
20415    }
20416
20417    #[test]
20418    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
20419        // Cross-window pin — the gate is window-agnostic; the
20420        // leading-zero class is a property of the magnitude, not the
20421        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
20422        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
20423        // single-window coverage extended across the three canonical
20424        // windows the codec accepts.
20425        let payload = r#"{"rateLimit":"007/h"}"#;
20426        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20427        let msg = err.to_string();
20428        assert!(
20429            msg.contains("non-canonical leading zero"),
20430            "expected leading-zero diagnostic in {msg:?}"
20431        );
20432        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
20433    }
20434
20435    #[test]
20436    fn rate_limit_serde_rejects_leading_whitespace() {
20437        // `" 100/s"` — the canonical paste-from-aligned-doc /
20438        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
20439        // the top-level `s.trim()` silently ate the leading space and
20440        // parsed the value to `RateLimit { 100, 1s }`, which then
20441        // round-tripped through `render` to `"100/s"` (a *different*
20442        // canonical string on the next emit) — the exact
20443        // canonical-form-drift class the leading-`+` / leading-zero
20444        // arms already close, extended to the whitespace byte class.
20445        let payload = r#"{"rateLimit":" 100/s"}"#;
20446        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20447        let msg = err.to_string();
20448        assert!(
20449            msg.contains("contains whitespace byte"),
20450            "expected whitespace diagnostic in {msg:?}"
20451        );
20452        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20453        assert!(
20454            msg.contains("THEORY.md"),
20455            "missing render-determinism contract citation in {msg:?}"
20456        );
20457    }
20458
20459    #[test]
20460    fn rate_limit_serde_rejects_trailing_whitespace() {
20461        // `"100/s "` — the canonical shell-history / trailing-space
20462        // paste footgun. Before this gate the top-level `s.trim()`
20463        // silently ate the trailing space and parsed to
20464        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
20465        // next emit — same canonical-form drift as the leading-space
20466        // sibling, closed on the same whitespace-byte arm.
20467        let payload = r#"{"rateLimit":"100/s "}"#;
20468        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20469        let msg = err.to_string();
20470        assert!(
20471            msg.contains("contains whitespace byte"),
20472            "expected whitespace diagnostic in {msg:?}"
20473        );
20474        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20475    }
20476
20477    #[test]
20478    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
20479        // `"100 / s"` — the canonical typographically-spaced author
20480        // shape (the same idiom every prose reference to a rate limit
20481        // renders as, mistakenly retained when the value is pasted
20482        // into a codec-shaped slot). Before this gate the per-part
20483        // `rate_str.trim()` / `unit.trim()` calls silently ate both
20484        // spaces on either side of `/` and parsed to
20485        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
20486        // codec's *internal* whitespace-tolerance vector, orthogonal
20487        // to the leading / trailing surface but the same canonical-
20488        // form-drift class. Pins the arm as strictly stronger than the
20489        // pre-existing top-level `s.trim()` behavior: it fires on
20490        // whitespace anywhere in the value, not just at the string
20491        // boundary.
20492        let payload = r#"{"rateLimit":"100 / s"}"#;
20493        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20494        let msg = err.to_string();
20495        assert!(
20496            msg.contains("contains whitespace byte"),
20497            "expected whitespace diagnostic in {msg:?}"
20498        );
20499        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20500    }
20501
20502    #[test]
20503    fn rate_limit_serde_rejects_tab_byte() {
20504        // `"\t100/s"` — the canonical paste-from-indented-doc /
20505        // paste-from-YAML-block-scalar footgun where a tab byte leads
20506        // the magnitude. Pins that the gate covers tab (`0x09`) as
20507        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
20508        // members and both would be silently swallowed by `s.trim()`
20509        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
20510        // space alone to the full ASCII-whitespace set (space `0x20`,
20511        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
20512        // the tab arm as a representative of the non-space members.
20513        let payload = r#"{"rateLimit":"\t100/s"}"#;
20514        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20515        let msg = err.to_string();
20516        assert!(
20517            msg.contains("contains whitespace byte"),
20518            "expected whitespace diagnostic in {msg:?}"
20519        );
20520        assert!(
20521            msg.contains("0x09"),
20522            "missing offending tab byte in {msg:?}"
20523        );
20524    }
20525
20526    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
20527    //
20528    // Successor to the ASCII-whitespace arm (1ad7755) on
20529    // `rate_limit_codec` — closes the strictly-complementary class the
20530    // byte-scan cannot see, through the lifted
20531    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
20532
20533    #[test]
20534    fn rate_limit_serde_rejects_leading_nbsp() {
20535        // NBSP prefix — paste-from-typography footgun. Byte-scan
20536        // misses, `str::trim` silently strips it, value drifts to
20537        // `"100/s"` on next serialize.
20538        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
20539        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20540        let msg = err.to_string();
20541        assert!(
20542            msg.contains("non-ASCII Unicode whitespace character"),
20543            "expected non-ASCII whitespace diagnostic in {msg:?}"
20544        );
20545        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
20546    }
20547
20548    #[test]
20549    fn rate_limit_serde_rejects_internal_em_space() {
20550        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
20551        // paste-from-typography footgun on the `<integer>/<unit>`
20552        // shape.
20553        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
20554        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20555        let msg = err.to_string();
20556        assert!(
20557            msg.contains("non-ASCII Unicode whitespace character"),
20558            "expected non-ASCII whitespace diagnostic in {msg:?}"
20559        );
20560        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
20561    }
20562
20563    #[test]
20564    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
20565        // Positive-control pin: every ASCII-only canonical form the
20566        // renderer emits stays accepted through the new arm.
20567        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
20568            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
20569            let p: MeshPolicy = serde_json::from_str(&payload)
20570                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
20571            assert!(p.rate_limit.is_some());
20572        }
20573    }
20574
20575    #[test]
20576    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
20577        // The boundary case — `"0/s"` is the canonical form
20578        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
20579        // it at the parse layer; the downstream
20580        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
20581        // `rate == 0` at the typed-validate layer above. Pins the
20582        // partition: the leading-zero gate at the codec layer does
20583        // not poach the rate-zero semantic-validation arm at the
20584        // typed-validate layer above (a future stricter codec must
20585        // not reject `"0/s"` here, or it'd collapse the diagnostic
20586        // partitioning that lets `PolicyRateLimitZero` name the
20587        // offending typed slot).
20588        let payload = r#"{"rateLimit":"0/s"}"#;
20589        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
20590            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
20591        });
20592        let rl = policy.rate_limit.expect("rate_limit must be Some");
20593        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
20594        assert_eq!(
20595            rl.window,
20596            Duration::from_secs(1),
20597            "single-`0` magnitude with `s` unit must parse to window=1s"
20598        );
20599    }
20600
20601    #[test]
20602    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
20603        // The complementary boundary pin — every magnitude
20604        // `render` emits starts with `[1-9]` (or is the single byte
20605        // `"0"`), so the canonical-form predicate is `(len == 1) ||
20606        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
20607        // '1'` case explicitly so a future tightening of the gate
20608        // (e.g. an over-eager "no leading digit < 5" rule, or a
20609        // mistakenly anchored start-of-magnitude byte check) lands
20610        // here before the canonical-forms-iterating test would catch
20611        // it.
20612        let payload = r#"{"rateLimit":"100/s"}"#;
20613        let policy: MeshPolicy = serde_json::from_str(payload)
20614            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
20615        let rl = policy.rate_limit.expect("rate_limit must be Some");
20616        assert_eq!(
20617            rl.rate, 100,
20618            "canonical-100 magnitude must parse to rate=100"
20619        );
20620    }
20621
20622    #[test]
20623    fn rate_limit_serde_accepts_integer_canonical_forms() {
20624        // Pin the happy-path: every canonical author shape `render`
20625        // ever emits parses cleanly through the codec post-gate. The
20626        // codec's accepted set (post-gate) is exactly its emitted set
20627        // for the integer-magnitude class — same property
20628        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
20629        // gates guarantee on the peer codecs. Iterating across rate
20630        // magnitudes (including `"0"`, which the codec accepts even
20631        // though `validate_politicas` rejects `rate == 0` at the typed
20632        // layer above) closes the codec contract at the parse layer
20633        // independently of the validate layer.
20634        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
20635            for unit_lit in ["s", "m", "h"] {
20636                let lit = format!("{rate_lit}/{unit_lit}");
20637                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
20638                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
20639                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
20640                });
20641                let rl = policy.rate_limit.expect("rate_limit must be Some");
20642                assert_eq!(
20643                    rl.rate,
20644                    rate_lit.parse::<u32>().unwrap(),
20645                    "rate mismatch for {lit:?}"
20646                );
20647            }
20648        }
20649    }
20650
20651    #[test]
20652    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
20653        // The structural property the gate enforces: serialize ∘
20654        // deserialize is the identity on every canonical author shape.
20655        // Peer of `parse_byte_size`'s and `parse_duration`'s
20656        // `_round_trips_through_render_for_every_canonical_form` tests
20657        // on the rate-limit axis. Before the gate, `"+100/s"` violated
20658        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
20659        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
20660        for rate in [1u32, 100, 5000, 1_000_000] {
20661            for (window, unit) in [
20662                (Duration::from_secs(1), "s"),
20663                (Duration::from_secs(60), "m"),
20664                (Duration::from_secs(3600), "h"),
20665            ] {
20666                let policy = MeshPolicy {
20667                    rate_limit: Some(RateLimit { rate, window }),
20668                    ..Default::default()
20669                };
20670                let json = serde_json::to_string(&policy).unwrap();
20671                let expected = format!("\"{rate}/{unit}\"");
20672                assert!(
20673                    json.contains(&expected),
20674                    "expected {expected:?} in {json:?}"
20675                );
20676                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20677                assert_eq!(
20678                    back.rate_limit, policy.rate_limit,
20679                    "round-trip for {json:?}"
20680                );
20681            }
20682        }
20683    }
20684
20685    // ── self-membership cross-slot gate ──────────────────────────────
20686
20687    #[test]
20688    fn validate_no_self_membership_rejects_self_named_membro() {
20689        // An Aplicacao whose `:membros` lists its own `:nome` is a
20690        // one-node lacre-closure recursion — rejected, naming the parent.
20691        let membros = vec![
20692            membro("catalog", "^0.1"),
20693            membro("checkout", "^0.1"),
20694            membro("cart", "^0.1"),
20695        ];
20696        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
20697        assert!(
20698            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
20699            "got {err:?}"
20700        );
20701    }
20702
20703    #[test]
20704    fn validate_no_self_membership_accepts_distinct_membros() {
20705        // Positive control: distinct member names (including a member
20706        // that is itself an Aplicacao — recursive composition is valid,
20707        // MESH-COMPOSITION §V) pass the gate.
20708        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
20709        validate_no_self_membership(&membros, "checkout").unwrap();
20710    }
20711
20712    #[test]
20713    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
20714        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
20715        // `NoMembros` arm (the more-fundamental "graph must have nodes"
20716        // gate), not by this cross-slot self-edge gate. Keeping the
20717        // self-membership predicate vacuously-ok on the empty input
20718        // matches its supervisor-axis peer
20719        // (`validate_no_self_supervision_empty_children_is_ok`) and
20720        // makes the gate composable from any future call site (an M4
20721        // CR materializer's per-membros validator) without re-checking
20722        // emptiness.
20723        validate_no_self_membership(&[], "checkout").unwrap();
20724    }
20725
20726    #[test]
20727    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
20728        // Pinning the Display: the self-membership diagnostic must name
20729        // the offending caixa verbatim + the "lists itself" framing the
20730        // author can grep for, so the cluster-far failure surfaces at
20731        // build time with one-line remediation. Same diagnostic shape
20732        // as the supervisor-axis `ChildSupervisesSelf` peer.
20733        let membros = vec![membro("orquestra", "^0.1")];
20734        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
20735        let msg = err.to_string();
20736        assert!(
20737            msg.contains("orquestra"),
20738            "diagnostic must name the offending caixa nome (got: {msg:?})"
20739        );
20740        assert!(
20741            msg.contains("lists itself"),
20742            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
20743        );
20744    }
20745
20746    #[test]
20747    fn default_servico_port_constant_pins_canonical_8080_literal() {
20748        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
20749        // at the verbatim `8080` literal both consumers (the
20750        // `Entrada::port` serde default via [`default_port`] and the
20751        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
20752        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
20753        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
20754        // discipline (a085b26) on the per-renderer canonical-K8s-axis
20755        // string-constant axis: a future refactor that drifts the
20756        // constant out from under either consumer surfaces here ahead
20757        // of every per-renderer's first emission. The literal value
20758        // matches the well-known HTTP-alt port the `pleme-computeunit`
20759        // library chart already emits as its `trigger.service.port`
20760        // default — by construction the same value the substrate
20761        // assumes about every Servico's in-cluster L4 listener.
20762        assert_eq!(
20763            DEFAULT_SERVICO_PORT, 8080,
20764            "canonical Servico port literal must remain `8080` verbatim — \
20765             this is the value both the `Entrada::port` serde default and the \
20766             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
20767        );
20768    }
20769
20770    #[test]
20771    fn default_port_helper_returns_canonical_servico_port_constant() {
20772        // The bridge-arm — pins that the [`default_port`] helper
20773        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
20774        // attribute hooks routes through the lifted
20775        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
20776        // literal. A future refactor that re-introduces the `8080`
20777        // literal at the helper's return site (silently re-opening
20778        // the drift footgun this lift closed) surfaces here ahead of
20779        // every author-side `(:entrada (:host … :para …))` slot
20780        // without an explicit `:port`. Peer with the
20781        // `default_namespace_re_export_points_at_caixa_core_canonical`
20782        // pin on the caixa-mesh-side re-export axis.
20783        assert_eq!(
20784            default_port(),
20785            DEFAULT_SERVICO_PORT,
20786            "the serde-default helper must route through the lifted constant"
20787        );
20788    }
20789
20790    #[test]
20791    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
20792        // The end-to-end pin — an author-surface `(:entrada (:host …
20793        // :para …))` without an explicit `:port` slot deserializes to
20794        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
20795        // verbatim. Routes the canonical lifted constant through both
20796        // the serde-default machinery (the `#[serde(default =
20797        // "default_port")]` attribute) and the typed-value-shape
20798        // contract (the resulting [`Entrada::port`] value). A future
20799        // refactor that drifts either axis — replacing the serde
20800        // hook's helper, changing the typed slot's wire shape — would
20801        // surface here before any per-renderer's CNP / Gateway /
20802        // HTTPRoute emission consumed the drifted default.
20803        let entrada: Entrada =
20804            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
20805        assert_eq!(
20806            entrada.port, DEFAULT_SERVICO_PORT,
20807            "the serde default must materialize as the lifted canonical Servico port"
20808        );
20809    }
20810
20811    #[test]
20812    fn servico_port_min_pins_canonical_accept_set_floor() {
20813        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
20814        // verbatim `1` literal every typed `:entrada :port` acceptance
20815        // gate keys off. Peer with the
20816        // [`default_servico_port_constant_pins_canonical_8080_literal`]
20817        // discipline on the canonical-Servico-port-constant axis: a
20818        // future refactor that drifts the accept-set floor out from
20819        // under the sole consumer at [`AplicacaoSpec::validate`]'s
20820        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
20821        // every per-`:entrada` `EntradaPortZero` diagnostic. The
20822        // literal value matches the IANA-registered TCP/UDP port
20823        // space floor (`1..=65535` — port `0` is the "any ephemeral"
20824        // sentinel, not a well-defined destination the substrate's
20825        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
20826        // axis can honor).
20827        assert_eq!(
20828            SERVICO_PORT_MIN, 1,
20829            "canonical Servico port accept-set floor must remain `1` verbatim — \
20830             this is the value the `AplicacaoSpec::validate` gate at \
20831             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
20832        );
20833    }
20834
20835    #[test]
20836    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
20837        // The cross-const invariant pin — the substrate's canonical
20838        // default port must satisfy its own accept-set floor by
20839        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
20840        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
20841        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
20842        // override the operator pins through a future
20843        // `:placement :default-port` slot that lands out-of-range, a
20844        // per-edition Servico-port migration that lifted the floor
20845        // above the previous default without coordinating the pair —
20846        // would silently invalidate the serde-default emission at
20847        // every author-side `(:entrada (:host … :para …))` slot
20848        // without an explicit `:port`: the default port would fall
20849        // below the accept-set floor, the `AplicacaoSpec::validate`
20850        // gate would reject every default-carrying Aplicacao as
20851        // `EntradaPortZero`, and the substrate's typed
20852        // `(defcaixa … :kind Aplicacao)` surface would fail validate
20853        // on every Aplicacao whose author omitted `:entrada :port`
20854        // for the substrate's chosen default — a class of authoring-
20855        // surface footguns the compile-time pin structurally closes.
20856        // Peer with the
20857        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
20858        // (27f9b34) cross-const invariant pin discipline on the peer
20859        // canonical-Helm-per-values-block child-chart-enablement-toggle
20860        // axis pair.
20861        assert!(
20862            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
20863            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
20864             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
20865             every default-carrying `(:entrada (:host … :para …))` slot without an \
20866             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
20867             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
20868        );
20869    }
20870
20871    #[test]
20872    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
20873        // The gate-site pin — asserts the `AplicacaoSpec::validate`
20874        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
20875        // `EntradaPortZero` diagnostic on the below-floor input
20876        // `port: 0` (the only below-floor value the `u16` field can
20877        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
20878        // is the singleton `{0}`). A future refactor that drifts the
20879        // gate off the lifted const (silently re-introducing an
20880        // inline `if e.port == 0` byte-check) surfaces here — the
20881        // pin cannot distinguish `< 1` from `== 0` on the current
20882        // floor, but it *does* pin that the diagnostic fires on `0`
20883        // through whichever gate is wired, so any future accept-set
20884        // floor migration (a hypothetical unprivileged-only
20885        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
20886        // update this test alongside the const declaration —
20887        // structurally guaranteeing the gate + accept-set + pin
20888        // trio move together. Peer with the
20889        // [`rejects_zero_entrada_port`] behavioral pin on the same
20890        // per-`:entrada :port` axis — that pin asserts the pre-lift
20891        // behavioral contract (`port: 0` → `EntradaPortZero`); this
20892        // pin adds the structural link to the lifted floor const.
20893        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
20894        let mut s = three_member_spec();
20895        s.entrada.as_mut().unwrap().port = 0;
20896        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
20897    }
20898
20899    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
20900
20901    #[test]
20902    fn membro_serde_keys_match_lifted_membro_key_consts() {
20903        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
20904        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
20905        // name the exact camelCase JSON keys the
20906        // `#[serde(rename_all = "camelCase")]` attribute on
20907        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
20908        // that each canonical byte-sequence appears verbatim in the
20909        // JSON — a future accidental `rename_all = "snake_case"` /
20910        // `"kebab-case"` / verbatim-field-name flip at the derive
20911        // attribute (any of which would silently break every downstream
20912        // JSON consumer that reaches for one of the two consts via
20913        // `Value::get(...)`) surfaces here as a build-time test failure
20914        // at `aplicacao.rs`, not as an apply-time
20915        // `.get(<stale-canonical-const>)` returning `None` far from the
20916        // derive-attr drift's commit. Peer with the sibling
20917        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
20918        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
20919        // same discipline the SupervisorSpec top-level lift established,
20920        // extended here to the M3 [`Membro`] per-`:membros` axis.
20921        let m = Membro {
20922            caixa: "catalog".into(),
20923            versao: "^0.1".into(),
20924        };
20925        let json = serde_json::to_string(&m).unwrap();
20926        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
20927            let quoted = format!("\"{key}\"");
20928            assert!(
20929                json.contains(&quoted),
20930                "serialized Membro must carry the lifted MEMBRO_KEY_* \
20931                 byte-sequence {quoted} verbatim in the JSON emission \
20932                 (got: {json})",
20933            );
20934        }
20935    }
20936
20937    #[test]
20938    fn membro_key_consts_are_pairwise_distinct() {
20939        // Cross-axis drift-detection pin: a future collapse of the two
20940        // canonical [`Membro`] per-entry byte-strings onto the same
20941        // value (e.g. an accidental copy-paste flip of
20942        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
20943        // silently reroute every downstream probe on one axis onto the
20944        // sibling axis's overlay entry and pass every propagation-probe
20945        // test that expected only the stale axis's value. Peer of the
20946        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
20947        // (40cc4e5).
20948        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
20949        for (i, a) in all.iter().enumerate() {
20950            for b in all.iter().skip(i + 1) {
20951                assert_ne!(
20952                    a, b,
20953                    "MEMBRO_KEY_* consts must be pairwise-distinct \
20954                     canonical byte-sequences — got `{a}` == `{b}`",
20955                );
20956            }
20957        }
20958    }
20959
20960    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
20961    //    URL-path fallback resolver every HTTPRoute-aware renderer
20962    //    reaching for a per-rule path-list resolution routes through.
20963    //    The four pin tests below fix the four-way accept-set the
20964    //    resolver must always honor: (:paths-non-empty-verbatim,
20965    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
20966    //    :paths-preserves-order-across-multiple-entries) — drift on any
20967    //    arm surfaces at caixa-core build time rather than at cluster-
20968    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
20969    //    sibling `:politicas` typed-primitive dispatch axis.
20970
20971    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
20972        Entrada {
20973            host: "example.com".into(),
20974            para: "cart".into(),
20975            paths: paths.into_iter().map(String::from).collect(),
20976            port: DEFAULT_SERVICO_PORT,
20977        }
20978    }
20979
20980    #[test]
20981    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
20982        // The typed `:entrada :paths` slot carries an author-declared
20983        // list — the resolver returns each entry verbatim, no
20984        // catch-all substitution. The canonical "author declared
20985        // paths, honor them verbatim" arm of the path-list dispatch.
20986        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
20987        assert_eq!(
20988            e.resolved_paths(),
20989            vec!["/api/cart", "/api/products"],
20990            "resolved_paths must return each `:entrada :paths` entry \
20991             verbatim when the typed slot is non-empty (got {:?})",
20992            e.resolved_paths(),
20993        );
20994    }
20995
20996    #[test]
20997    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
20998        // Empty `:entrada :paths` slot — the resolver substitutes the
20999        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
21000        // catch-all fallback verbatim. Pins the empty-arm of the
21001        // resolver's four-way accept-set against a future silent
21002        // detour that returned an empty Vec (which would emit an
21003        // HTTPRoute with zero rules — silently dropping every
21004        // external `:entrada` flow at admission time), routed to a
21005        // different fallback shape, or dropped the catch-all
21006        // altogether.
21007        let e = entrada_with_paths(vec![]);
21008        assert_eq!(
21009            e.resolved_paths(),
21010            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
21011            "resolved_paths on empty `:entrada :paths` must fall back \
21012             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
21013             all — got {:?}",
21014            e.resolved_paths(),
21015        );
21016    }
21017
21018    #[test]
21019    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
21020        // Single-entry `:entrada :paths` — the resolver returns the
21021        // single declared path verbatim, NOT the catch-all fallback
21022        // (author declared a path, honor it — the empty-arm and the
21023        // len-1 arm are semantically distinct axes of the resolver's
21024        // accept-set). Pins that the resolver treats "author declared
21025        // one path" as authored input, not as the empty case.
21026        let e = entrada_with_paths(vec!["/api/only"]);
21027        assert_eq!(
21028            e.resolved_paths(),
21029            vec!["/api/only"],
21030            "resolved_paths on single-entry `:entrada :paths` must \
21031             return the declared path verbatim, NOT the catch-all \
21032             fallback (got {:?})",
21033            e.resolved_paths(),
21034        );
21035    }
21036
21037    #[test]
21038    fn resolved_paths_preserves_author_declared_order() {
21039        // The `:entrada :paths` list is author-ordered — the resolver
21040        // preserves the author's declaration order verbatim, since
21041        // per-rule dispatch order at the K8s Gateway API HTTPRoute
21042        // consumer is significant (first-match-wins under the
21043        // path-prefix matcher). Pins against a future silent
21044        // re-sort / dedup / normalize detour that reordered author
21045        // input.
21046        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
21047        assert_eq!(
21048            e.resolved_paths(),
21049            vec!["/z/last", "/a/first", "/m/mid"],
21050            "resolved_paths must preserve author-declared `:entrada \
21051             :paths` order verbatim — got {:?}",
21052            e.resolved_paths(),
21053        );
21054    }
21055
21056    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
21057    //    slot `&[String]` slice accessor every per-`:entrada` consumer
21058    //    that must see the author's declaration verbatim (not the
21059    //    fallback-applied projection the sibling `resolved_paths`
21060    //    returns) routes through. The three pin tests below fix the
21061    //    accept-set the accessor must honor: (:non-empty-byte-equal,
21062    //    :empty-projects-empty-slice, :preserves-author-declared-order)
21063    //    — drift on any arm surfaces at caixa-core build time rather
21064    //    than at cluster-apply time. Peer discipline with the sibling
21065    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
21066    //    peer M3 mesh-slot `Vec<String>`-carry axis.
21067
21068    #[test]
21069    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
21070        // Byte-equal pin: [`Entrada::paths`] must project the raw
21071        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
21072        // slice borrowed from the typed slot's own [`Vec<String>`]
21073        // storage — no re-ordering, no dedup, no per-entry normalization,
21074        // no fallback substitution (the fallback-applying projection is
21075        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
21076        // a future silent detour that re-normalized the list, dropped
21077        // duplicates the [`AplicacaoSpec::validate`]
21078        // `EntradaPathDuplicate` refusal already rejects at build time,
21079        // or (most severe) accidentally routed through the fallback-
21080        // applying sibling and returned the substrate catch-all when
21081        // the author declared an empty list — collapsing the raw-slot
21082        // and fallback-applied axes into one and breaking the
21083        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
21084        //
21085        // Peer of the sibling
21086        // [`Placement::clusters`]-shape byte-equal pin
21087        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
21088        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
21089        let fixtures: Vec<Vec<String>> = vec![
21090            Vec::new(),
21091            vec!["/api/cart".into()],
21092            vec!["/api/cart".into(), "/api/products".into()],
21093            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
21094        ];
21095        for paths in fixtures {
21096            let e = Entrada {
21097                host: "example.com".into(),
21098                para: "cart".into(),
21099                paths: paths.clone(),
21100                port: DEFAULT_SERVICO_PORT,
21101            };
21102            assert_eq!(
21103                e.paths(),
21104                paths.as_slice(),
21105                "Entrada::paths must return :entrada :paths verbatim \
21106                 (got {:?}, expected {:?})",
21107                e.paths(),
21108                paths.as_slice(),
21109            );
21110            assert_eq!(
21111                e.paths(),
21112                e.paths.as_slice(),
21113                "Entrada::paths accessor and .paths.as_slice() field \
21114                 access must byte-equal — the accessor is the substrate-\
21115                 primitive typed dispatch every downstream per-`:entrada` \
21116                 raw-slot path-list consumer must route through",
21117            );
21118            assert_eq!(
21119                e.paths().len(),
21120                e.paths.len(),
21121                "Entrada::paths().len() must byte-equal self.paths.len() \
21122                 — a length drift would silently split the paired \
21123                 pre-flight cascade-head `.is_empty()` probe input in \
21124                 the sibling [`Entrada::resolved_paths`] resolver from \
21125                 the per-entry validate loop's traversal input in \
21126                 [`AplicacaoSpec::validate`]",
21127            );
21128        }
21129    }
21130
21131    #[test]
21132    fn resolved_paths_reads_through_lifted_paths_accessor() {
21133        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
21134        // pre-flight `.paths().is_empty()` cascade-head probe (which
21135        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
21136        // catch-all fallback arm when the accessor projects the empty
21137        // slice) and the per-entry `.paths().iter().map(String::as_str)`
21138        // projection (which must reach every entry in the same order
21139        // the accessor projects, so the sibling
21140        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
21141        // per-entry projection stay in lockstep by construction) must
21142        // both key off the lifted accessor. Pins the two-site coherence
21143        // by exercising each production consumer end-to-end: (1) the
21144        // catch-all-fallback arm under the empty slice, (2) the
21145        // author-declared-verbatim arm under a two-entry cohort whose
21146        // per-entry projection must byte-equal the input's per-entry
21147        // author-declared paths in the author's declared order.
21148        //
21149        // Peer of the sibling M3
21150        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
21151        // `validate_placement_reads_through_lifted_clusters_accessor`
21152        // on the sibling `Placement::clusters` reader-site convergence.
21153        let empty = entrada_with_paths(vec![]);
21154        assert_eq!(
21155            empty.resolved_paths(),
21156            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
21157            "resolved_paths on empty :entrada :paths must trip the \
21158             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
21159             catch-all fallback — routing through the lifted paths() \
21160             accessor must not silently drop the fallback arm",
21161        );
21162
21163        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
21164        assert_eq!(
21165            declared.resolved_paths(),
21166            vec!["/api/cart", "/api/products"],
21167            "resolved_paths on non-empty :entrada :paths must return each \
21168             entry verbatim in the author's declared order — routing \
21169             through the lifted paths() accessor must not silently \
21170             reorder or drop entries",
21171        );
21172        // Byte-equal pin against the raw-slot accessor to keep the
21173        // fallback-applying resolver's per-entry projection input in
21174        // lockstep with the raw-slot accessor's projection.
21175        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
21176        assert_eq!(
21177            declared.resolved_paths(),
21178            raw_projected,
21179            "resolved_paths non-empty projection must byte-equal the \
21180             lifted paths() accessor's per-entry String::as_str projection \
21181             — the two projections share the same input slice by \
21182             construction, so any drift here would surface a silent \
21183             re-ordering / dedup / normalization detour in the resolver",
21184        );
21185    }
21186
21187    #[test]
21188    fn validate_reads_through_lifted_entrada_paths_accessor() {
21189        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
21190        // per-entry value-shape gate's `for p in e.paths()` traversal
21191        // (which must reach every entry in the same order the accessor
21192        // projects, so both the per-entry `EntradaPathEmpty` /
21193        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
21194        // the duplicate-detection HashSet insert that trips
21195        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
21196        // projection) must route through the lifted accessor. Pins the
21197        // coherence by exercising each production consumer end-to-end:
21198        // (1) the `EntradaPathEmpty` refusal fires on the second entry
21199        // of a two-entry cohort whose head is valid but tail is empty
21200        // (which requires the loop to reach the second entry through
21201        // the accessor), and (2) the `EntradaPathDuplicate` refusal
21202        // fires on the second entry of a two-entry cohort that shares
21203        // a path (which requires the loop to reach both entries — a
21204        // first-entry-only projection would silently pass since the
21205        // dedup HashSet has room for the first insert).
21206        //
21207        // Peer of the sibling
21208        // `validate_placement_reads_through_lifted_clusters_accessor`
21209        // on the sibling `Placement::clusters` reader-site convergence.
21210        let base = crate::AplicacaoSpec {
21211            membros: vec![crate::Membro {
21212                caixa: "cart".into(),
21213                versao: "^0.1".into(),
21214            }],
21215            contratos: Vec::new(),
21216            politicas: crate::MeshPolicy::default(),
21217            placement: crate::Placement {
21218                estrategia: crate::PlacementStrategy::SingleNode,
21219                clusters: vec!["rio".into()],
21220                shard_key: None,
21221                affinity: None,
21222            },
21223            entrada: Some(Entrada {
21224                host: "example.com".into(),
21225                para: "cart".into(),
21226                paths: vec!["/api/cart".into(), String::new()],
21227                port: DEFAULT_SERVICO_PORT,
21228            }),
21229        };
21230        assert_eq!(
21231            base.validate(),
21232            Err(crate::AplicacaoError::EntradaPathEmpty),
21233            "validate must trip EntradaPathEmpty on the second entry of \
21234             a two-entry cohort — routing through the lifted paths() \
21235             accessor must not silently short-circuit the loop at the \
21236             valid head entry",
21237        );
21238
21239        let mut dup = base;
21240        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
21241        assert_eq!(
21242            dup.validate(),
21243            Err(crate::AplicacaoError::EntradaPathDuplicate {
21244                path: "/api/cart".into(),
21245            }),
21246            "validate must trip EntradaPathDuplicate on the second entry \
21247             of a two-entry cohort that shares a path — routing through \
21248             the lifted paths() accessor must not silently short-circuit \
21249             the dedup HashSet insert at the first entry",
21250        );
21251    }
21252
21253    // ── Entrada::hostname / Entrada::hostnames — the substrate-
21254    //    canonical per-`:entrada` DNS-hostname resolver pair every
21255    //    Gateway-API-aware renderer reaching for a per-listener
21256    //    singular `hostname:` filter (Gateway) or a per-route plural
21257    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
21258    //    The three pin tests below fix the two-way accept-set the pair
21259    //    must always honor: (:singular-byte-equal-to-host,
21260    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
21261    //    on any arm surfaces at caixa-core build time rather than at
21262    //    cluster-apply time when the API server refuses the HTTPRoute
21263    //    for non-intersecting hostname filters. Peer discipline with
21264    //    the sibling `resolved_paths` accept-set pin block above on the
21265    //    per-`:entrada` path-list resolver axis.
21266
21267    fn entrada_with_host(host: &str) -> Entrada {
21268        Entrada {
21269            host: host.into(),
21270            para: "cart".into(),
21271            paths: Vec::new(),
21272            port: DEFAULT_SERVICO_PORT,
21273        }
21274    }
21275
21276    #[test]
21277    fn hostname_returns_entrada_host_byte_equal() {
21278        // The canonical singular-axis pin: [`Entrada::hostname`] must
21279        // return the `:entrada :host` field byte-for-byte, borrowed
21280        // from the typed slot's own [`String`] storage. Pins against a
21281        // future silent detour that re-normalized the host (an
21282        // accidental `.to_lowercase()` — validate_entrada_host already
21283        // enforces lowercase, so any re-normalization is redundant + a
21284        // drift surface between the validator and the accessor), a
21285        // trailing-`.` fully-qualified DNS shape substitution, or a
21286        // Punycode round-trip that lowered a Unicode host through IDNA.
21287        let e = entrada_with_host("checkout.quero.cloud");
21288        assert_eq!(
21289            e.hostname(),
21290            "checkout.quero.cloud",
21291            "Entrada::hostname must return :entrada :host verbatim \
21292             (got {:?})",
21293            e.hostname(),
21294        );
21295        assert_eq!(
21296            e.hostname(),
21297            e.host.as_str(),
21298            "Entrada::hostname must byte-equal the .host field access",
21299        );
21300    }
21301
21302    #[test]
21303    fn hostnames_returns_singleton_of_hostname_accessor() {
21304        // The pair-invariant pin: [`Entrada::hostnames`] must always
21305        // return exactly `vec![hostname()]` — the singleton list whose
21306        // sole entry is the substrate's canonical per-`:entrada`
21307        // singular hostname. Pins the two-consumer coherence axis: the
21308        // Gateway listener's singular `hostname:` filter and the
21309        // HTTPRoute's plural `spec.hostnames[]` filter list must
21310        // agree, else the Gateway API v1.x conformance layer rejects
21311        // the HTTPRoute at attach time with
21312        // `Accepted:False/NoMatchingParent` (the parent Gateway's
21313        // listener hostname doesn't intersect the route's hostname
21314        // filter list) — a divergence whose apply-time symptom is far
21315        // from any single-site commit and never surfaces in the
21316        // emitted YAML. Pinning the pair-invariant here makes any
21317        // future accidental split (an accidental `.to_string() + "."`
21318        // trailing-`.` on the plural side that didn't land on the
21319        // singular side, an accidental prefix stripping on one axis,
21320        // an accidental wildcard prepend the SNI fan-out overlay
21321        // authors on the plural side without a paired singular
21322        // migration) trip at caixa-core build time.
21323        let e = entrada_with_host("checkout.quero.cloud");
21324        assert_eq!(
21325            e.hostnames(),
21326            vec![e.hostname()],
21327            "Entrada::hostnames must return `vec![hostname()]` under \
21328             the pair-invariant — got {:?} vs. singleton {:?}",
21329            e.hostnames(),
21330            vec![e.hostname()],
21331        );
21332    }
21333
21334    #[test]
21335    fn hostnames_is_singleton_under_single_host_author_surface() {
21336        // The singleton-shape pin: under today's single-hostname-per-
21337        // `:entrada` author surface (the `:host` slot is a single
21338        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
21339        // must always return a list of length exactly one. Pins
21340        // against a future silent detour that returned an empty list
21341        // (which would emit an HTTPRoute with `spec.hostnames: []` —
21342        // matching every incoming Host header regardless of the
21343        // Aplicacao's declared ingress apex, silently over-matching
21344        // every foreign VirtualHost the parent Gateway also fronts) or
21345        // a duplicated entry (which the Gateway API v1.x parser
21346        // accepts as a `[]-length-2 list of equal hostnames]` but
21347        // whose semantics differ from the intended singleton). The
21348        // author-surface extension point ("a future `:entrada
21349        // :alt-hosts` list overlay" the docstring names) is the sole
21350        // future axis that flips this pin — that migration will re-
21351        // author this test to pin the new plural cardinality.
21352        let e = entrada_with_host("checkout.quero.cloud");
21353        assert_eq!(
21354            e.hostnames().len(),
21355            1,
21356            "Entrada::hostnames must be a singleton under today's \
21357             single-hostname-per-`:entrada` author surface — got \
21358             length {}: {:?}",
21359            e.hostnames().len(),
21360            e.hostnames(),
21361        );
21362    }
21363
21364    // ── Entrada::destination — the substrate-canonical per-`:entrada`
21365    //    destination-Servico scalar accessor every Gateway-API
21366    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
21367    //    discriminator arg (HTTPRoute name composer) or a per-rule
21368    //    `backendRefs[0].name` axis routes through. The two pin tests
21369    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
21370    //    either arm surfaces at caixa-core build time rather than at
21371    //    cluster-apply time when an HTTPRoute's `metadata.name` and
21372    //    `backendRefs[]` silently disagree on which destination Servico
21373    //    the ingress fronts. Peer discipline with the sibling
21374    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
21375    //    blocks above on the per-`:entrada` path-list / DNS-hostname
21376    //    resolver axes.
21377
21378    #[test]
21379    fn destination_returns_entrada_para_byte_equal() {
21380        // The canonical destination-scalar pin: [`Entrada::destination`]
21381        // must return the `:entrada :para` field byte-for-byte, borrowed
21382        // from the typed slot's own [`String`] storage. Pins against a
21383        // future silent detour that re-normalized the destination (an
21384        // accidental `.to_lowercase()` — the destination Servico is
21385        // already validated as a DNS-1123 label upstream, so any
21386        // re-normalization is redundant + a drift surface between the
21387        // validator and the accessor), a namespace-prefix rewrite (an
21388        // accidental `format!("{namespace}/{para}")` per-CR fully-
21389        // qualified rewrite that didn't land on the peer axis), or a
21390        // per-cluster suffix stamp the operator authors on one
21391        // consumer without the other.
21392        for para in ["cart", "checkout", "catalog", "orders-v2"] {
21393            let e = Entrada {
21394                host: "checkout.quero.cloud".into(),
21395                para: para.into(),
21396                paths: Vec::new(),
21397                port: DEFAULT_SERVICO_PORT,
21398            };
21399            assert_eq!(
21400                e.destination(),
21401                para,
21402                "Entrada::destination must return :entrada :para verbatim \
21403                 (got {:?}, expected {para:?})",
21404                e.destination(),
21405            );
21406            assert_eq!(
21407                e.destination(),
21408                e.para.as_str(),
21409                "Entrada::destination must byte-equal the .para field access",
21410            );
21411        }
21412    }
21413
21414    #[test]
21415    fn destination_borrows_from_entrada_para_storage() {
21416        // The borrow-not-copy pin: [`Entrada::destination`] must
21417        // return a `&str` slice that borrows from the typed slot's
21418        // own [`String`] storage — same-address invariant with
21419        // `entrada.para.as_str()`. Pins against a future silent detour
21420        // that allocated a fresh `String` (`self.para.clone()` in the
21421        // body would type-check but silently drop the borrow, and
21422        // every downstream consumer that assumed the returned slice
21423        // outlives `&self` would break on a stale-reference use-after-
21424        // free). Peer with the sibling `hostname_returns_entrada_
21425        // host_byte_equal` on the singular-DNS-hostname axis.
21426        let e = entrada_with_host("checkout.quero.cloud");
21427        let dest = e.destination();
21428        let para_slice = e.para.as_str();
21429        assert_eq!(
21430            dest.as_ptr(),
21431            para_slice.as_ptr(),
21432            "Entrada::destination must borrow from the .para String's \
21433             backing storage — a fresh allocation here means the \
21434             accessor no longer names the substrate-primitive typed \
21435             dispatch and every downstream consumer would silently \
21436             carry a detached copy",
21437        );
21438        assert_eq!(
21439            dest.len(),
21440            para_slice.len(),
21441            "Entrada::destination and .para.as_str() must byte-equal in \
21442             length as well as in address",
21443        );
21444    }
21445
21446    #[test]
21447    fn port_returns_entrada_port_verbatim_across_permutations() {
21448        // The canonical L4-port-scalar pin: [`Entrada::port`] must
21449        // return the `:entrada :port` field verbatim as a `u16` across
21450        // every author-declared value in the validated accept-set
21451        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
21452        // silent detour that clamped the port (an accidental
21453        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
21454        // land on the peer [`AplicacaoSpec::port_for_destination`]
21455        // resolver), rewrote it through a per-cluster port-remap table
21456        // the operator authors on one consumer without the other, or
21457        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
21458        // serde-default value (which would silently collapse the
21459        // distinction between "author explicitly declared `:port 8080`"
21460        // and "author omitted the slot and inherited the default" the
21461        // future per-cluster override slot depends on). Peer with the
21462        // sibling `destination_returns_entrada_para_byte_equal` +
21463        // `hostname_returns_entrada_host_byte_equal` pins on the
21464        // per-`:entrada` `&str` scalar axes.
21465        for port in [
21466            SERVICO_PORT_MIN,
21467            DEFAULT_SERVICO_PORT,
21468            8443u16,
21469            9090u16,
21470            u16::MAX,
21471        ] {
21472            let e = Entrada {
21473                host: "checkout.quero.cloud".into(),
21474                para: "cart".into(),
21475                paths: Vec::new(),
21476                port,
21477            };
21478            assert_eq!(
21479                e.port(),
21480                port,
21481                "Entrada::port must return :entrada :port verbatim \
21482                 (got {}, expected {port})",
21483                e.port(),
21484            );
21485            assert_eq!(
21486                e.port(),
21487                e.port,
21488                "Entrada::port accessor and .port field access must \
21489                 byte-equal — the accessor is the substrate-primitive \
21490                 typed dispatch every downstream L4-port consumer must \
21491                 route through",
21492            );
21493        }
21494    }
21495
21496    #[test]
21497    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
21498        // Two-consumer coherence pin: the
21499        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
21500        // (which reads through [`Entrada::port`] to compare against
21501        // [`SERVICO_PORT_MIN`]) and the
21502        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
21503        // through [`Entrada::port`] to emit the per-destination
21504        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
21505        // lifted accessor, so any future rebrand on the typed slot's
21506        // reader shape lands at exactly one place. Pins the two-site
21507        // coherence by exercising a below-floor port through validate
21508        // (which must reject) and a validated in-accept-set port through
21509        // port_for_destination (which must emit the same value the
21510        // accessor returns).
21511        let mut spec = three_member_spec();
21512        if let Some(e) = spec.entrada.as_mut() {
21513            e.port = 0;
21514        }
21515        assert_eq!(
21516            spec.validate().unwrap_err(),
21517            AplicacaoError::EntradaPortZero,
21518            "validate must reject `:entrada :port 0` through the lifted \
21519             Entrada::port accessor — port zero lies below \
21520             SERVICO_PORT_MIN and the validator routes through port() \
21521             to name the floor",
21522        );
21523
21524        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
21525            let mut spec = three_member_spec();
21526            if let Some(e) = spec.entrada.as_mut() {
21527                e.port = port;
21528            }
21529            spec.validate().expect(
21530                "entrada with in-accept-set :port must validate — the \
21531                 structural-floor gate reads through Entrada::port",
21532            );
21533            let entrada_ref = spec.entrada().expect(":entrada present");
21534            assert_eq!(
21535                spec.port_for_destination(entrada_ref.destination()),
21536                entrada_ref.port(),
21537                "port_for_destination(entrada.destination()) must equal \
21538                 entrada.port() — the two consumers of the per-:entrada \
21539                 L4-port axis (validator, per-destination resolver) both \
21540                 route through Entrada::port",
21541            );
21542        }
21543    }
21544
21545    #[test]
21546    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
21547        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
21548        // must return the `:contratos :de` field byte-for-byte, borrowed
21549        // from the typed slot's own [`String`] storage. Peer of the
21550        // sibling `destination_returns_entrada_para_byte_equal` pin on
21551        // the per-`:entrada` axis — same "the substrate-primitive
21552        // accessor must byte-equal the raw field access verbatim across
21553        // every author-declared value" discipline extended to the
21554        // per-`:contratos` caller arm. Pins against a future silent
21555        // detour that re-normalized the caller (an accidental
21556        // `.to_lowercase()` — every `:contratos :de` is validated as a
21557        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
21558        // re-normalization is redundant + a drift surface between the
21559        // validator and the accessor), a namespace-prefix rewrite (an
21560        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
21561        // rewrite that didn't land on the peer axis), or a per-cluster
21562        // suffix stamp the operator authors on one consumer without the
21563        // other.
21564        for de in ["cart", "checkout", "catalog", "orders-v2"] {
21565            let c = WitContract {
21566                de: de.into(),
21567                para: "downstream".into(),
21568                wit: "wasi:http/proxy".into(),
21569                endpoint: Some("/lookup".into()),
21570                subject: None,
21571                slot: None,
21572            };
21573            assert_eq!(
21574                c.source(),
21575                de,
21576                "WitContract::source must return :contratos :de verbatim \
21577                 (got {:?}, expected {de:?})",
21578                c.source(),
21579            );
21580            assert_eq!(
21581                c.source(),
21582                c.de.as_str(),
21583                "WitContract::source must byte-equal the .de field access",
21584            );
21585        }
21586    }
21587
21588    #[test]
21589    fn wit_contract_source_borrows_from_de_storage() {
21590        // The borrow-not-copy pin: [`WitContract::source`] must return a
21591        // `&str` slice that borrows from the typed slot's own [`String`]
21592        // storage — same-address invariant with `c.de.as_str()`. Pins
21593        // against a future silent detour that allocated a fresh `String`
21594        // (`self.de.clone()` in the body would type-check but silently
21595        // drop the borrow, and every downstream consumer that assumed
21596        // the returned slice outlives `&self` would break on a stale-
21597        // reference use-after-free). Peer of the sibling
21598        // `destination_borrows_from_entrada_para_storage` on the
21599        // per-`:entrada` axis.
21600        let c = WitContract {
21601            de: "cart".into(),
21602            para: "catalog".into(),
21603            wit: "wasi:http/proxy".into(),
21604            endpoint: Some("/lookup".into()),
21605            subject: None,
21606            slot: None,
21607        };
21608        let src = c.source();
21609        let de_slice = c.de.as_str();
21610        assert_eq!(
21611            src.as_ptr(),
21612            de_slice.as_ptr(),
21613            "WitContract::source must borrow from the .de String's \
21614             backing storage — a fresh allocation here means the \
21615             accessor no longer names the substrate-primitive typed \
21616             dispatch and every downstream consumer would silently \
21617             carry a detached copy",
21618        );
21619        assert_eq!(
21620            src.len(),
21621            de_slice.len(),
21622            "WitContract::source and .de.as_str() must byte-equal in \
21623             length as well as in address",
21624        );
21625    }
21626
21627    #[test]
21628    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
21629        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
21630        // must return the `:contratos :para` field byte-for-byte,
21631        // borrowed from the typed slot's own [`String`] storage. Peer of
21632        // the sibling `destination_returns_entrada_para_byte_equal` on
21633        // the per-`:entrada` axis — both accessors name "the destination-
21634        // Servico byte-string" concept on their respective mesh-slot
21635        // atoms (per-ingress apex vs. per-typed-edge callee) and both
21636        // must project the underlying `.para` field verbatim so every
21637        // downstream renderer that composes them with peer accessors
21638        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
21639        // per-edge L4 port emit site) reads the same byte-string the
21640        // author declared.
21641        for para in ["catalog", "payment", "orders", "inventory-v3"] {
21642            let c = WitContract {
21643                de: "cart".into(),
21644                para: para.into(),
21645                wit: "wasi:http/proxy".into(),
21646                endpoint: Some("/lookup".into()),
21647                subject: None,
21648                slot: None,
21649            };
21650            assert_eq!(
21651                c.destination(),
21652                para,
21653                "WitContract::destination must return :contratos :para \
21654                 verbatim (got {:?}, expected {para:?})",
21655                c.destination(),
21656            );
21657            assert_eq!(
21658                c.destination(),
21659                c.para.as_str(),
21660                "WitContract::destination must byte-equal the .para \
21661                 field access",
21662            );
21663        }
21664    }
21665
21666    #[test]
21667    fn wit_contract_destination_borrows_from_para_storage() {
21668        // The borrow-not-copy pin: [`WitContract::destination`] must
21669        // return a `&str` slice that borrows from the typed slot's own
21670        // [`String`] storage — same-address invariant with
21671        // `c.para.as_str()`. Peer of the sibling
21672        // `destination_borrows_from_entrada_para_storage` on the
21673        // per-`:entrada` axis.
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 dest = c.destination();
21683        let para_slice = c.para.as_str();
21684        assert_eq!(
21685            dest.as_ptr(),
21686            para_slice.as_ptr(),
21687            "WitContract::destination must borrow from the .para \
21688             String's backing storage — a fresh allocation here means \
21689             the accessor no longer names the substrate-primitive typed \
21690             dispatch and every downstream consumer would silently \
21691             carry a detached copy",
21692        );
21693        assert_eq!(
21694            dest.len(),
21695            para_slice.len(),
21696            "WitContract::destination and .para.as_str() must byte-equal \
21697             in length as well as in address",
21698        );
21699    }
21700
21701    #[test]
21702    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
21703        // The canonical per-`:contratos` WIT-world-reference scalar pin:
21704        // [`WitContract::world_ref`] must return the `:contratos :wit`
21705        // field byte-for-byte, borrowed from the typed slot's own
21706        // [`String`] storage. Sibling of the peer per-`:contratos`
21707        // [`WitContract::source`] / [`WitContract::destination`]
21708        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
21709        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
21710        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
21711        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
21712        // "the substrate-primitive accessor must byte-equal the raw
21713        // field access verbatim across every author-declared value"
21714        // discipline extended to the per-`:contratos` WIT-world arm.
21715        // Pins against a future silent detour that re-canonicalized the
21716        // WIT world reference (an accidental `.to_lowercase()` pass that
21717        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
21718        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
21719        // gate is already lowercase-prefixed so any re-normalization is
21720        // redundant + a drift surface between the validator and the
21721        // accessor), an M4-promotion-shape rewrite that formatted a
21722        // typed WIT-world enum through [`Display`] and silently drifted
21723        // the printer output from the source `caixa.lisp`, or a per-
21724        // cluster WIT-alias rewrite that didn't land on the peer field-
21725        // access sites. Five values sweep the shape-dispatch accept-set
21726        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
21727        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
21728        // `wasi:keyvalue/`).
21729        for (wit, endpoint, subject, slot) in [
21730            ("wasi:http/proxy", Some("/lookup"), None, None),
21731            ("http:proxy", Some("/health"), None, None),
21732            ("nats:pub-sub", None, Some("orders.paid"), None),
21733            ("kafka:events", None, Some("checkout-events"), None),
21734            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
21735        ] {
21736            let c = WitContract {
21737                de: "cart".into(),
21738                para: "downstream".into(),
21739                wit: wit.into(),
21740                endpoint: endpoint.map(str::to_string),
21741                subject: subject.map(str::to_string),
21742                slot: slot.map(str::to_string),
21743            };
21744            assert_eq!(
21745                c.world_ref(),
21746                wit,
21747                "WitContract::world_ref must return :contratos :wit \
21748                 verbatim (got {:?}, expected {wit:?})",
21749                c.world_ref(),
21750            );
21751            assert_eq!(
21752                c.world_ref(),
21753                c.wit.as_str(),
21754                "WitContract::world_ref must byte-equal the .wit field \
21755                 access",
21756            );
21757        }
21758    }
21759
21760    #[test]
21761    fn wit_contract_world_ref_borrows_from_wit_storage() {
21762        // The borrow-not-copy pin: [`WitContract::world_ref`] must
21763        // return a `&str` slice that borrows from the typed slot's own
21764        // [`String`] storage — same-address invariant with
21765        // `c.wit.as_str()`. Pins against a future silent detour that
21766        // allocated a fresh `String` (`self.wit.clone()` in the body
21767        // would type-check but silently drop the borrow, and every
21768        // downstream consumer that assumed the returned slice outlives
21769        // `&self` would break on a stale-reference use-after-free — the
21770        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
21771        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
21772        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
21773        // / [`is_pubsub`][WitContract::is_pubsub] /
21774        // [`is_store`][WitContract::is_store] methods route through —
21775        // each borrow from the WitContract's own storage and each would
21776        // silently misbehave if this accessor produced a detached copy).
21777        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
21778        // [`WitContract::destination`] and per-`:entrada`
21779        // [`Entrada::destination`] / [`Entrada::hostname`] and
21780        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
21781        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
21782        let c = WitContract {
21783            de: "cart".into(),
21784            para: "catalog".into(),
21785            wit: "wasi:http/proxy".into(),
21786            endpoint: Some("/lookup".into()),
21787            subject: None,
21788            slot: None,
21789        };
21790        let world = c.world_ref();
21791        let wit_slice = c.wit.as_str();
21792        assert_eq!(
21793            world.as_ptr(),
21794            wit_slice.as_ptr(),
21795            "WitContract::world_ref must borrow from the .wit String's \
21796             backing storage — a fresh allocation here means the \
21797             accessor no longer names the substrate-primitive typed \
21798             dispatch and every downstream consumer would silently carry \
21799             a detached copy",
21800        );
21801        assert_eq!(
21802            world.len(),
21803            wit_slice.len(),
21804            "WitContract::world_ref and .wit.as_str() must byte-equal in \
21805             length as well as in address",
21806        );
21807    }
21808
21809    #[test]
21810    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
21811        // Sibling-triple invariant pin composing all three per-`:contratos`
21812        // substrate-primitive typed dispatches — [`WitContract::source`]
21813        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
21814        // [`WitContract::world_ref`] — at the joint
21815        // `(source(), destination(), world_ref())` call shape every
21816        // renderer that fans on per-edge caller-callee-shape identity
21817        // keys off. The invariant, evaluated per-contract:
21818        //
21819        //   (c.source(), c.destination(), c.world_ref())
21820        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
21821        //
21822        // Closes the last unlifted per-`:contratos` scalar axis — every
21823        // downstream consumer that reads the triple now routes through
21824        // exactly three typed dispatches on the substrate primitive,
21825        // not two typed + one open-coded field access. A future refactor
21826        // that silently split any one accessor's projection (an
21827        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
21828        // canonicalization that didn't reach the peer `source`/
21829        // `destination` arms, an accidental `source()` per-cluster
21830        // caller-alias rewrite that didn't land on the `world_ref` peer)
21831        // surfaces at caixa-core build time. Peer of the sibling per-
21832        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
21833        // per-`:entrada` `(hostname(), destination())` (6db982c /
21834        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
21835        // axes, extended to the per-`:contratos` triple.
21836        for (de, para, wit, endpoint, subject, slot) in [
21837            (
21838                "cart",
21839                "catalog",
21840                "wasi:http/proxy",
21841                Some("/lookup"),
21842                None,
21843                None,
21844            ),
21845            (
21846                "checkout",
21847                "orders",
21848                "nats:pub-sub",
21849                None,
21850                Some("orders.paid"),
21851                None,
21852            ),
21853            (
21854                "cart",
21855                "kv",
21856                "wasi:keyvalue/store",
21857                None,
21858                None,
21859                Some("carts/{cart_id}"),
21860            ),
21861            (
21862                "orders-v2",
21863                "inventory-v3",
21864                "http:proxy",
21865                Some("/reserve"),
21866                None,
21867                None,
21868            ),
21869        ] {
21870            let c = WitContract {
21871                de: de.into(),
21872                para: para.into(),
21873                wit: wit.into(),
21874                endpoint: endpoint.map(str::to_string),
21875                subject: subject.map(str::to_string),
21876                slot: slot.map(str::to_string),
21877            };
21878            assert_eq!(
21879                (c.source(), c.destination(), c.world_ref()),
21880                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
21881                "(WitContract::source, ::destination, ::world_ref) must \
21882                 project (.de, .para, .wit) verbatim across every author-\
21883                 declared triple (got ({:?}, {:?}, {:?}), expected \
21884                 ({de:?}, {para:?}, {wit:?}))",
21885                c.source(),
21886                c.destination(),
21887                c.world_ref(),
21888            );
21889        }
21890    }
21891
21892    #[test]
21893    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
21894        // The canonical per-`:contratos` owned-form caller-callee-pair
21895        // pin: [`WitContract::edge_pair`] must return the
21896        // `(source(), destination())` tuple in owned form byte-for-byte,
21897        // projected through the lifted [`WitContract::source`] /
21898        // [`WitContract::destination`] scalar accessors. Pins the
21899        // composite-projection invariant on the per-`:contratos`
21900        // mesh-slot atom — every author-declared `(de, para)` pair must
21901        // round-trip verbatim through the substrate primitive's typed
21902        // dispatch, so the nine [`AplicacaoError`] diagnostic-
21903        // construction sites the accessor now feeds
21904        // ([`AplicacaoError::EmptyWit`],
21905        // [`AplicacaoError::ContratoEndpointEmpty`],
21906        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
21907        // [`AplicacaoError::ContratoEndpointInvalid`],
21908        // [`AplicacaoError::ContratoSubjectEmpty`],
21909        // [`AplicacaoError::ContratoSubjectInvalid`],
21910        // [`AplicacaoError::ContratoSlotEmpty`],
21911        // [`AplicacaoError::ContratoSlotInvalid`],
21912        // [`AplicacaoError::ContratoDuplicate`]) all read the same
21913        // `(de, para)` label pair every author sees at the source
21914        // `caixa.lisp`. Pins against a future silent detour that swapped
21915        // the `.0` / `.1` arms (an accidental `(destination(),
21916        // source())` re-order in the body would silently invert every
21917        // downstream diagnostic's `de:` / `para:` label pair, silently
21918        // reversing the direction of every operator-facing typed error
21919        // arrow), a fresh-allocation shape drift (an accidental
21920        // `.to_string()` on one arm but not the other would leave the
21921        // owned/borrowed pair mismatched vs. the sibling `source()` /
21922        // `destination()` returns), or an M4 per-cluster caller/callee-
21923        // alias rewrite that landed on `source()` without reaching
21924        // `destination()` (or vice versa). Peer of the sibling per-
21925        // `:contratos` `(source, destination, world_ref)` triple
21926        // pin above on the mesh-slot-atom scalar-value axes, extended
21927        // to the owned-form pair-projection axis.
21928        for (de, para, wit, endpoint, subject, slot) in [
21929            (
21930                "cart",
21931                "catalog",
21932                "wasi:http/proxy",
21933                Some("/lookup"),
21934                None,
21935                None,
21936            ),
21937            (
21938                "checkout",
21939                "orders",
21940                "nats:pub-sub",
21941                None,
21942                Some("orders.paid"),
21943                None,
21944            ),
21945            (
21946                "cart",
21947                "kv",
21948                "wasi:keyvalue/store",
21949                None,
21950                None,
21951                Some("carts/{cart_id}"),
21952            ),
21953            (
21954                "orders-v2",
21955                "inventory-v3",
21956                "http:proxy",
21957                Some("/reserve"),
21958                None,
21959                None,
21960            ),
21961        ] {
21962            let c = WitContract {
21963                de: de.into(),
21964                para: para.into(),
21965                wit: wit.into(),
21966                endpoint: endpoint.map(str::to_string),
21967                subject: subject.map(str::to_string),
21968                slot: slot.map(str::to_string),
21969            };
21970            assert_eq!(
21971                c.edge_pair(),
21972                (de.to_string(), para.to_string()),
21973                "WitContract::edge_pair must return (:contratos :de, \
21974                 :contratos :para) as an owned tuple verbatim (got {:?}, \
21975                 expected ({de:?}, {para:?}))",
21976                c.edge_pair(),
21977            );
21978        }
21979    }
21980
21981    #[test]
21982    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
21983        // The composition pin: [`WitContract::edge_pair`] must return
21984        // exactly `(source().to_string(), destination().to_string())` —
21985        // the owned form of the sibling accessor pair — so any future
21986        // refactor that silently re-authored the caller-arm / callee-arm
21987        // projection to bypass the lifted scalar accessors (an accidental
21988        // `(self.de.clone(), self.para.clone())` regression back to the
21989        // raw field-access shape, an M4-typed-caller-enum `Display`
21990        // re-canonicalization on `source()` that didn't reach
21991        // `edge_pair()`, a per-cluster alias rewrite the operator lands
21992        // on `destination()` without reaching this composite projection)
21993        // trips at caixa-core build time. Pins the "typed dispatch
21994        // composes with typed dispatch, not with raw field access"
21995        // discipline every downstream diagnostic-construction site now
21996        // routes through — a `de:` / `para:` label pair whose
21997        // projection silently drifted off the substrate primitive's
21998        // scalar accessors would silently split the diagnostic's self-
21999        // locating signal from the source `caixa.lisp` author's view.
22000        // Peer of the sibling per-`:politicas` `is_empty` /
22001        // `validate_politicas` accessor-routing-pin family on the M3
22002        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
22003        let c = WitContract {
22004            de: "cart".into(),
22005            para: "catalog".into(),
22006            wit: "wasi:http/proxy".into(),
22007            endpoint: Some("/lookup".into()),
22008            subject: None,
22009            slot: None,
22010        };
22011        assert_eq!(
22012            c.edge_pair(),
22013            (c.source().to_string(), c.destination().to_string()),
22014            "WitContract::edge_pair must compose exactly \
22015             (source().to_string(), destination().to_string()) — a \
22016             bypass of either sibling accessor here would silently \
22017             decouple the composite-projection axis from the \
22018             substrate-primitive scalar accessors every downstream \
22019             consumer routes through",
22020        );
22021    }
22022
22023    #[test]
22024    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
22025     {
22026        // The canonical per-`:contratos` owned-form
22027        // caller-callee-world-ref-triple pin:
22028        // [`WitContract::edge_triple`] must return the
22029        // `(source(), destination(), world_ref())` tuple in owned form
22030        // byte-for-byte, projected through the lifted
22031        // [`WitContract::source`] / [`WitContract::destination`] /
22032        // [`WitContract::world_ref`] scalar accessors. Pins the
22033        // composite-projection invariant on the per-`:contratos`
22034        // mesh-slot atom — every author-declared `(de, para, wit)`
22035        // triple must round-trip verbatim through the substrate
22036        // primitive's typed dispatch, so the nine
22037        // [`AplicacaoError`] diagnostic-construction sites the
22038        // accessor now feeds (the [`WitTarget`]-dispatch's eight
22039        // wrong-target / missing-target / invalid-wit / capability-
22040        // with-payload arms in [`WitContract::target`], plus the
22041        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
22042        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
22043        // read the same `(de, para, wit)` triple every author sees at
22044        // the source `caixa.lisp`. Pins against a future silent
22045        // detour that swapped any two arms (an accidental `(destination(),
22046        // source(), world_ref())` re-order in the body would silently
22047        // invert every downstream diagnostic's `de:` / `para:` label
22048        // pair, silently reversing the direction of every operator-
22049        // facing typed error arrow), a fresh-allocation shape drift
22050        // (an accidental `.to_string()` skipped on one arm would leave
22051        // the owned/borrowed triple mismatched vs. the sibling
22052        // `source()` / `destination()` / `world_ref()` returns), or an
22053        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
22054        // canonicalization pass that landed on one accessor without
22055        // reaching the peers. Peer of the sibling per-`:contratos`
22056        // caller-callee-pair
22057        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
22058        // pin on the mesh-slot-atom composite-projection axis,
22059        // extended to the triple-projection axis.
22060        for (de, para, wit, endpoint, subject, slot) in [
22061            (
22062                "cart",
22063                "catalog",
22064                "wasi:http/proxy",
22065                Some("/lookup"),
22066                None,
22067                None,
22068            ),
22069            (
22070                "checkout",
22071                "orders",
22072                "nats:pub-sub",
22073                None,
22074                Some("orders.paid"),
22075                None,
22076            ),
22077            (
22078                "cart",
22079                "kv",
22080                "wasi:keyvalue/store",
22081                None,
22082                None,
22083                Some("carts/{cart_id}"),
22084            ),
22085            (
22086                "orders-v2",
22087                "inventory-v3",
22088                "http:proxy",
22089                Some("/reserve"),
22090                None,
22091                None,
22092            ),
22093        ] {
22094            let c = WitContract {
22095                de: de.into(),
22096                para: para.into(),
22097                wit: wit.into(),
22098                endpoint: endpoint.map(str::to_string),
22099                subject: subject.map(str::to_string),
22100                slot: slot.map(str::to_string),
22101            };
22102            assert_eq!(
22103                c.edge_triple(),
22104                (de.to_string(), para.to_string(), wit.to_string()),
22105                "WitContract::edge_triple must return (:contratos :de, \
22106                 :contratos :para, :contratos :wit) as an owned triple \
22107                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
22108                c.edge_triple(),
22109            );
22110        }
22111    }
22112
22113    #[test]
22114    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
22115        // The composition pin: [`WitContract::edge_triple`] must return
22116        // exactly `(source().to_string(), destination().to_string(),
22117        // world_ref().to_string())` — the owned form of the sibling
22118        // scalar-accessor triple — so any future refactor that silently
22119        // re-authored one arm's projection to bypass the lifted scalar
22120        // accessors (an accidental `(self.de.clone(), self.para.clone(),
22121        // self.wit.clone())` regression back to the raw field-access
22122        // shape the internal `edge` closure and the ContratoDuplicate
22123        // diagnostic both carried before this lift landed, an
22124        // M4-typed-caller-enum `Display` re-canonicalization on
22125        // `source()` that didn't reach `edge_triple()`, a per-cluster
22126        // alias rewrite the operator lands on `destination()` /
22127        // `world_ref()` without reaching this composite projection)
22128        // trips at caixa-core build time. Pins the "typed dispatch
22129        // composes with typed dispatch, not with raw field access"
22130        // discipline every downstream diagnostic-construction site now
22131        // routes through — a `de:` / `para:` / `wit:` triple whose
22132        // projection silently drifted off the substrate primitive's
22133        // scalar accessors would silently split the diagnostic's self-
22134        // locating signal from the source `caixa.lisp` author's view.
22135        // Peer of the sibling per-`:contratos` edge_pair composition-
22136        // pin above on the mesh-slot-atom composite-projection axis.
22137        let c = WitContract {
22138            de: "cart".into(),
22139            para: "catalog".into(),
22140            wit: "wasi:http/proxy".into(),
22141            endpoint: Some("/lookup".into()),
22142            subject: None,
22143            slot: None,
22144        };
22145        assert_eq!(
22146            c.edge_triple(),
22147            (
22148                c.source().to_string(),
22149                c.destination().to_string(),
22150                c.world_ref().to_string(),
22151            ),
22152            "WitContract::edge_triple must compose exactly \
22153             (source().to_string(), destination().to_string(), \
22154             world_ref().to_string()) — a bypass of any sibling accessor \
22155             here would silently decouple the composite-projection axis \
22156             from the substrate-primitive scalar accessors every \
22157             downstream consumer routes through",
22158        );
22159    }
22160
22161    #[test]
22162    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
22163        // The canonical semantics-pin: [`WitContract::edge_triple`] must
22164        // project the full `(de, para, wit)` identity of a `:contratos`
22165        // edge — the sub-triple every triple-carrying
22166        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
22167        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
22168        // missing-target, capability-with-payload, invalid-wit, and the
22169        // duplicate-gate). Rejects a drift in shape (an accidental
22170        // silent detour that returned a `(de, para)` pair or added an
22171        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
22172        // would trip here because the return type would no longer
22173        // pattern-match the eight `let (de, para, wit) = edge();`
22174        // destructures the [`WitContract::target`] dispatch feeds off
22175        // + the paired duplicate-gate `let (de, para, wit) =
22176        // c.edge_triple();` destructure in
22177        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
22178        // `:contratos` caller-callee-pair pin above extended to the
22179        // triple projection surface: closes the "one composite
22180        // accessor per typed diagnostic-construction sub-tuple"
22181        // discipline on the per-`:contratos` mesh-slot-atom axis.
22182        let c = WitContract {
22183            de: "checkout".into(),
22184            para: "orders".into(),
22185            wit: "nats:pub-sub".into(),
22186            endpoint: None,
22187            subject: Some("orders.paid".into()),
22188            slot: None,
22189        };
22190        let (de, para, wit) = c.edge_triple();
22191        assert_eq!(de, "checkout");
22192        assert_eq!(para, "orders");
22193        assert_eq!(wit, "nats:pub-sub");
22194    }
22195
22196    #[test]
22197    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
22198     {
22199        // The composition pin: [`WitContract::identity`] must return
22200        // exactly `(source(), destination(), world_ref(), endpoint(),
22201        // subject(), slot())` — the borrowed form of the six-scalar-
22202        // accessor identity axis. Any future refactor that silently
22203        // re-authored one arm's projection to bypass a scalar accessor
22204        // (a `self.de.as_str()` regression back to raw field access on
22205        // any of the three required arms, a `self.endpoint.as_deref()`
22206        // regression on any of the three optional arms, an M4 per-
22207        // cluster caller/callee-alias rewrite the operator lands on
22208        // `source()` / `destination()` without reaching this composite
22209        // projection) trips at caixa-core build time. Sweeps four
22210        // permutations of the WIT-shape × payload lattice — HTTP with
22211        // endpoint, pub-sub with subject, store with slot, payload-less
22212        // capability — so every payload arm is exercised. Peer of the
22213        // sibling per-`:contratos`
22214        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
22215        // composition pin on the mesh-slot-atom composite-projection
22216        // axis; extends the discipline from the (de, para, wit) prefix
22217        // onto the full-identity axis carrying the three payload arms.
22218        for (de, para, wit, endpoint, subject, slot) in [
22219            (
22220                "cart",
22221                "catalog",
22222                "wasi:http/proxy",
22223                Some("/lookup"),
22224                None,
22225                None,
22226            ),
22227            (
22228                "checkout",
22229                "orders",
22230                "nats:pub-sub",
22231                None,
22232                Some("orders.paid"),
22233                None,
22234            ),
22235            (
22236                "cart",
22237                "kv",
22238                "wasi:keyvalue/store",
22239                None,
22240                None,
22241                Some("carts/{cart_id}"),
22242            ),
22243            ("audit", "sink", "wasi:logging", None, None, None),
22244        ] {
22245            let c = WitContract {
22246                de: de.into(),
22247                para: para.into(),
22248                wit: wit.into(),
22249                endpoint: endpoint.map(str::to_owned),
22250                subject: subject.map(str::to_owned),
22251                slot: slot.map(str::to_owned),
22252            };
22253            assert_eq!(
22254                c.identity(),
22255                (
22256                    c.source(),
22257                    c.destination(),
22258                    c.world_ref(),
22259                    c.endpoint(),
22260                    c.subject(),
22261                    c.slot(),
22262                ),
22263                "WitContract::identity must compose exactly \
22264                 (source(), destination(), world_ref(), endpoint(), \
22265                 subject(), slot()) — a bypass of any sibling accessor \
22266                 here would silently decouple the identity-projection \
22267                 axis from the substrate-primitive scalar accessors \
22268                 every dedup-key consumer routes through",
22269            );
22270        }
22271    }
22272
22273    #[test]
22274    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
22275        // The canonical semantics-pin: [`WitContract::identity`] must
22276        // project the six-axis (de, para, wit, endpoint, subject, slot)
22277        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22278        // gate keys off — two `WitContract`s that agree on all six axes
22279        // are the same typed edge declared twice, the graph-edge
22280        // analogue of duplicate `:membros` / `:placement :clusters` /
22281        // `:entrada :paths` entries. Rejects a shape drift (an
22282        // accidental silent detour that returned a prefix tuple or
22283        // added an extra field) by pattern-matching the six-arm shape.
22284        // Peer of the sibling per-`:contratos`
22285        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
22286        // pin extended from the (de, para, wit) prefix onto the full
22287        // six-axis identity that the dedup key rides.
22288        let c = WitContract {
22289            de: "cart".into(),
22290            para: "catalog".into(),
22291            wit: "wasi:http/proxy".into(),
22292            endpoint: Some("/products/:id".into()),
22293            subject: None,
22294            slot: None,
22295        };
22296        let (de, para, wit, endpoint, subject, slot) = c.identity();
22297        assert_eq!(de, "cart");
22298        assert_eq!(para, "catalog");
22299        assert_eq!(wit, "wasi:http/proxy");
22300        assert_eq!(endpoint, Some("/products/:id"));
22301        assert_eq!(subject, None);
22302        assert_eq!(slot, None);
22303
22304        // Two byte-identical contracts must produce equal identities —
22305        // the dedup key's foundational invariant.
22306        let c2 = c.clone();
22307        assert_eq!(c.identity(), c2.identity());
22308
22309        // Any change on any of the six axes must break the identity —
22310        // sweeps by mutating one axis at a time.
22311        let mut mutated = c.clone();
22312        mutated.de = "search".into();
22313        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
22314        let mut mutated = c.clone();
22315        mutated.para = "warehouse".into();
22316        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
22317        let mut mutated = c.clone();
22318        mutated.wit = "http:legacy".into();
22319        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
22320        let mut mutated = c.clone();
22321        mutated.endpoint = Some("/search".into());
22322        assert_ne!(
22323            c.identity(),
22324            mutated.identity(),
22325            "endpoint axis must partition"
22326        );
22327        let mut mutated = c.clone();
22328        mutated.subject = Some("orders.paid".into());
22329        assert_ne!(
22330            c.identity(),
22331            mutated.identity(),
22332            "subject axis must partition"
22333        );
22334        let mut mutated = c;
22335        mutated.slot = Some("carts/{id}".into());
22336        assert_ne!(mutated.identity().5, None, "slot axis must partition");
22337    }
22338
22339    #[test]
22340    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
22341        // The canonical per-`:contratos` structural-self-edge pin:
22342        // [`WitContract::is_self_loop`] must return `true` when the
22343        // `:de` and `:para` fields agree byte-for-byte, across every
22344        // WIT-shape variant the per-edge shape family carries. Pins
22345        // the shape-agnostic identity-space partition the
22346        // [`AplicacaoSpec::validate`] self-edge gate at
22347        // caixa-core/src/aplicacao.rs:5559 fires against — all four
22348        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
22349        // under the same one predicate. Four permutations sweep the
22350        // accept-set: HTTP with endpoint, pub-sub with subject, KV
22351        // store with slot, and payload-less capability.
22352        for (nome, wit, endpoint, subject, slot) in [
22353            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
22354            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
22355            (
22356                "kv",
22357                "wasi:keyvalue/store",
22358                None,
22359                None,
22360                Some("carts/{cart_id}"),
22361            ),
22362            ("audit", "wasi:logging", None, None, None),
22363        ] {
22364            let c = WitContract {
22365                de: nome.into(),
22366                para: nome.into(),
22367                wit: wit.into(),
22368                endpoint: endpoint.map(str::to_string),
22369                subject: subject.map(str::to_string),
22370                slot: slot.map(str::to_string),
22371            };
22372            assert!(
22373                c.is_self_loop(),
22374                "WitContract::is_self_loop must return true when \
22375                 :contratos :de == :contratos :para (got false on \
22376                 {nome:?} under {wit:?})",
22377            );
22378        }
22379    }
22380
22381    #[test]
22382    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
22383        // The complement pin: [`WitContract::is_self_loop`] must return
22384        // `false` on every well-shaped inter-Servico contract (the
22385        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
22386        // names — "Servico A calls Servico B" between two distinct
22387        // graph nodes). Pins against a future silent detour that
22388        // inverted the predicate (an accidental `!= ` swap for `==`
22389        // would silently reject every legitimate inter-Servico edge
22390        // and admit every self-edge — the exact inversion of the
22391        // author-intended shape). Four permutations sweep the same
22392        // WIT-shape accept-set the sibling positive-arm test carries.
22393        for (de, para, wit, endpoint, subject, slot) in [
22394            (
22395                "cart",
22396                "catalog",
22397                "wasi:http/proxy",
22398                Some("/lookup"),
22399                None,
22400                None,
22401            ),
22402            (
22403                "checkout",
22404                "orders",
22405                "nats:pub-sub",
22406                None,
22407                Some("orders.paid"),
22408                None,
22409            ),
22410            (
22411                "cart",
22412                "kv",
22413                "wasi:keyvalue/store",
22414                None,
22415                None,
22416                Some("carts/{cart_id}"),
22417            ),
22418            ("audit", "sink", "wasi:logging", None, None, None),
22419        ] {
22420            let c = WitContract {
22421                de: de.into(),
22422                para: para.into(),
22423                wit: wit.into(),
22424                endpoint: endpoint.map(str::to_string),
22425                subject: subject.map(str::to_string),
22426                slot: slot.map(str::to_string),
22427            };
22428            assert!(
22429                !c.is_self_loop(),
22430                "WitContract::is_self_loop must return false when \
22431                 :contratos :de differs from :contratos :para (got true \
22432                 on {de:?} → {para:?} under {wit:?})",
22433            );
22434        }
22435    }
22436
22437    #[test]
22438    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
22439        // The composition pin: [`WitContract::is_self_loop`] must
22440        // resolve to exactly `self.source() == self.destination()` —
22441        // the equality probe of the sibling scalar-accessor pair — so
22442        // any future refactor that silently re-authored the predicate
22443        // to bypass the lifted scalar accessors (an accidental
22444        // `self.de == self.para` regression back to the raw field-
22445        // access shape, an M4-typed-caller-enum identity-comparison
22446        // rule that landed on `source()` without reaching
22447        // `destination()`, a per-cluster alias rewrite the operator
22448        // pins on `destination()` without reaching this predicate)
22449        // trips at caixa-core build time. Pins the "typed dispatch
22450        // composes with typed dispatch, not with raw field access"
22451        // discipline the sibling [`WitContract::edge_pair`] /
22452        // [`WitContract::edge_triple`] composite-projection accessors
22453        // already carry, extended onto the per-edge endpoint-equality
22454        // predicate axis. Positive and complement arms both fire.
22455        let self_edge = WitContract {
22456            de: "cart".into(),
22457            para: "cart".into(),
22458            wit: "wasi:http/proxy".into(),
22459            endpoint: Some("/lookup".into()),
22460            subject: None,
22461            slot: None,
22462        };
22463        assert_eq!(
22464            self_edge.is_self_loop(),
22465            self_edge.source() == self_edge.destination(),
22466            "WitContract::is_self_loop must compose exactly \
22467             `source() == destination()` — a bypass of either sibling \
22468             accessor here would silently decouple the endpoint-\
22469             equality predicate from the substrate-primitive scalar \
22470             accessors every downstream consumer routes through",
22471        );
22472        let inter_edge = WitContract {
22473            de: "cart".into(),
22474            para: "catalog".into(),
22475            wit: "wasi:http/proxy".into(),
22476            endpoint: Some("/lookup".into()),
22477            subject: None,
22478            slot: None,
22479        };
22480        assert_eq!(
22481            inter_edge.is_self_loop(),
22482            inter_edge.source() == inter_edge.destination(),
22483            "WitContract::is_self_loop must compose exactly \
22484             `source() == destination()` on the complement arm too",
22485        );
22486    }
22487
22488    #[test]
22489    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
22490        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
22491        // pin: [`WitContract::endpoint`] must return the `:contratos
22492        // :endpoint` field byte-for-byte, borrowed from the typed slot's
22493        // own `Option<String>` storage. Peer of the sibling
22494        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
22495        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
22496        // mesh-slot `Option<String>` optional-scalar axes — same "the
22497        // substrate-primitive accessor must byte-equal the raw field
22498        // access verbatim across every author-declared value" discipline
22499        // extended to the per-`:contratos` HTTP-payload-carrier arm.
22500        // Pins against a future silent detour that re-canonicalized the
22501        // endpoint (an accidental percent-encoding pass that didn't
22502        // reach the peer field-access site at the dedup key, a per-CR
22503        // fully-qualified prefix rewrite the operator authors on one
22504        // consumer without the other, or an M4 typed-path-template
22505        // `Display` re-canonicalization that silently drifted the
22506        // printer output from the source `caixa.lisp`). Four values
22507        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
22508        // gate upstream admits (short root-path, dashed, param-shaped,
22509        // deep-hierarchy).
22510        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
22511            let c = WitContract {
22512                de: "cart".into(),
22513                para: "catalog".into(),
22514                wit: "wasi:http/proxy".into(),
22515                endpoint: Some(endpoint.into()),
22516                subject: None,
22517                slot: None,
22518            };
22519            assert_eq!(
22520                c.endpoint(),
22521                Some(endpoint),
22522                "WitContract::endpoint must return :contratos :endpoint \
22523                 verbatim (got {:?}, expected Some({endpoint:?}))",
22524                c.endpoint(),
22525            );
22526            assert_eq!(
22527                c.endpoint(),
22528                c.endpoint.as_deref(),
22529                "WitContract::endpoint must byte-equal the .endpoint \
22530                 field's `.as_deref()` projection",
22531            );
22532        }
22533    }
22534
22535    #[test]
22536    fn wit_contract_endpoint_none_when_field_is_none() {
22537        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
22538        // payload-carrier accessor pin: when the typed slot is absent —
22539        // the canonical shape under a non-HTTP `:wit` world per the
22540        // [`WitContract::target`]-enforced shape ↔ target partition
22541        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
22542        // carries `:slot`, [`WitTarget::Capability`] carries none) —
22543        // [`WitContract::endpoint`] must return `None`. Pins against a
22544        // future silent detour that projected the absent slot to a
22545        // `Some("")` empty-string default (the canonical `Option<String>`
22546        // → `String` collapse footgun the sibling M2
22547        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22548        // emptiness predicates already guard on the peer M2 typed-slot
22549        // surfaces), a `Some("None")` stringified-None round-trip, or a
22550        // `Some` arm whose contents were derived from a sibling slot (an
22551        // accidental fallback to the `:subject` / `:slot` payload that
22552        // read the pub-sub / store payload into the endpoint axis).
22553        // Three contracts sweep the accept-set every non-HTTP `:wit`
22554        // world lands on — pub-sub NATS, key/value, and payload-less
22555        // capability.
22556        for (wit, subject, slot) in [
22557            ("nats:pub-sub", Some("orders.paid"), None),
22558            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22559            ("wasi:cli/environment", None, None),
22560        ] {
22561            let c = WitContract {
22562                de: "cart".into(),
22563                para: "downstream".into(),
22564                wit: wit.into(),
22565                endpoint: None,
22566                subject: subject.map(str::to_string),
22567                slot: slot.map(str::to_string),
22568            };
22569            assert!(
22570                c.endpoint().is_none(),
22571                "WitContract::endpoint must return None when the typed \
22572                 slot is absent under :wit {wit:?} (got {:?})",
22573                c.endpoint(),
22574            );
22575            assert_eq!(
22576                c.endpoint(),
22577                c.endpoint.as_deref(),
22578                "WitContract::endpoint must byte-equal the .endpoint \
22579                 field's `.as_deref()` projection in the absent arm",
22580            );
22581        }
22582    }
22583
22584    #[test]
22585    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
22586        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
22587        // an `Option<&str>` whose `Some` arm borrows from the typed
22588        // slot's own [`String`] storage — same-address invariant with
22589        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
22590        // detour that allocated a fresh `String`
22591        // (`self.endpoint.clone().map(...)` in the body would type-check
22592        // but silently drop the borrow, and every downstream consumer
22593        // that assumed the returned slice outlives `&self` would break
22594        // on a stale-reference use-after-free — the [`WitContract::target`]
22595        // Http-arm payload extraction rebinds the returned `Option<&str>`
22596        // through `.ok_or_else(...)` and threads the `&str` payload into
22597        // [`WitTarget::Http { endpoint: &'a str }`], the
22598        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
22599        // [`ContratoIdentity`] dedup key threads the returned
22600        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
22601        // from the WitContract's own storage and each would silently
22602        // misbehave if this accessor produced a detached copy). Peer of
22603        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
22604        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22605        // shaped optional-scalar axes — first extension of the
22606        // `Option<&str>` borrow-not-copy discipline onto the
22607        // per-`:contratos` HTTP-shaped payload-carrier axis.
22608        let c = WitContract {
22609            de: "cart".into(),
22610            para: "catalog".into(),
22611            wit: "wasi:http/proxy".into(),
22612            endpoint: Some("/lookup".into()),
22613            subject: None,
22614            slot: None,
22615        };
22616        let ep = c.endpoint().expect("Some arm");
22617        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
22618        assert_eq!(
22619            ep.as_ptr(),
22620            storage_slice.as_ptr(),
22621            "WitContract::endpoint must borrow from the .endpoint \
22622             String's backing storage — a fresh allocation here means \
22623             the accessor no longer names the substrate-primitive typed \
22624             dispatch and every downstream consumer would silently \
22625             carry a detached copy",
22626        );
22627        assert_eq!(
22628            ep.len(),
22629            storage_slice.len(),
22630            "WitContract::endpoint and .endpoint.as_deref() must byte-\
22631             equal in length as well as in address",
22632        );
22633    }
22634
22635    #[test]
22636    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
22637        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
22638        // pin: [`WitContract::subject`] must return the `:contratos
22639        // :subject` field byte-for-byte, borrowed from the typed slot's
22640        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
22641        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
22642        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22643        // optional-scalar axis — same "the substrate-primitive accessor
22644        // must byte-equal the raw field access verbatim across every
22645        // author-declared value" discipline extended to the pub-sub arm.
22646        // Pins against a future silent detour that re-canonicalized the
22647        // subject (an accidental `.to_lowercase()` normalization that
22648        // didn't reach the peer field-access site at the dedup key, a
22649        // per-CR fully-qualified prefix rewrite the operator authors on
22650        // one consumer without the other, or an M4 typed-subject-template
22651        // `Display` re-canonicalization that silently drifted the printer
22652        // output from the source `caixa.lisp`). Four values sweep the
22653        // NATS accept-set every pub-sub author-declared subject lands on
22654        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
22655        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
22656            let c = WitContract {
22657                de: "cart".into(),
22658                para: "notifier".into(),
22659                wit: "nats:pub-sub".into(),
22660                endpoint: None,
22661                subject: Some(subject.into()),
22662                slot: None,
22663            };
22664            assert_eq!(
22665                c.subject(),
22666                Some(subject),
22667                "WitContract::subject must return :contratos :subject \
22668                 verbatim (got {:?}, expected Some({subject:?}))",
22669                c.subject(),
22670            );
22671            assert_eq!(
22672                c.subject(),
22673                c.subject.as_deref(),
22674                "WitContract::subject must byte-equal the .subject \
22675                 field's `.as_deref()` projection",
22676            );
22677        }
22678    }
22679
22680    #[test]
22681    fn wit_contract_subject_none_when_field_is_none() {
22682        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
22683        // shaped payload-carrier accessor pin: when the typed slot is
22684        // absent — the canonical shape under a non-pub-sub `:wit` world
22685        // per the [`WitContract::target`]-enforced shape ↔ target
22686        // partition ([`WitTarget::Http`] carries `:endpoint`,
22687        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
22688        // carries none) — [`WitContract::subject`] must return `None`.
22689        // Pins against a future silent detour that projected the absent
22690        // slot to a `Some("")` empty-string default (the canonical
22691        // `Option<String>` → `String` collapse footgun the sibling M2
22692        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22693        // emptiness predicates already guard on the peer M2 typed-slot
22694        // surfaces), a `Some("None")` stringified-None round-trip, or a
22695        // `Some` arm whose contents were derived from a sibling slot (an
22696        // accidental fallback to the `:endpoint` / `:slot` payload that
22697        // read the HTTP / store payload into the subject axis). Three
22698        // contracts sweep the accept-set every non-pub-sub `:wit` world
22699        // lands on — HTTP proxy, key/value store, and payload-less
22700        // capability.
22701        for (wit, endpoint, slot) in [
22702            ("wasi:http/proxy", Some("/lookup"), None),
22703            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22704            ("wasi:cli/environment", None, None),
22705        ] {
22706            let c = WitContract {
22707                de: "cart".into(),
22708                para: "downstream".into(),
22709                wit: wit.into(),
22710                endpoint: endpoint.map(str::to_string),
22711                subject: None,
22712                slot: slot.map(str::to_string),
22713            };
22714            assert!(
22715                c.subject().is_none(),
22716                "WitContract::subject must return None when the typed \
22717                 slot is absent under :wit {wit:?} (got {:?})",
22718                c.subject(),
22719            );
22720            assert_eq!(
22721                c.subject(),
22722                c.subject.as_deref(),
22723                "WitContract::subject must byte-equal the .subject \
22724                 field's `.as_deref()` projection in the absent arm",
22725            );
22726        }
22727    }
22728
22729    #[test]
22730    fn wit_contract_subject_borrows_from_subject_storage() {
22731        // The borrow-not-copy pin: [`WitContract::subject`] must return
22732        // an `Option<&str>` whose `Some` arm borrows from the typed
22733        // slot's own [`String`] storage — same-address invariant with
22734        // `c.subject.as_deref().unwrap()`. Pins against a future silent
22735        // detour that allocated a fresh `String`
22736        // (`self.subject.clone().map(...)` in the body would type-check
22737        // but silently drop the borrow, and every downstream consumer
22738        // that assumed the returned slice outlives `&self` would break
22739        // on a stale-reference use-after-free — the [`WitContract::target`]
22740        // PubSub-arm payload extraction rebinds the returned
22741        // `Option<&str>` through `.ok_or_else(...)` and threads the
22742        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
22743        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22744        // [`ContratoIdentity`] dedup key threads the returned
22745        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
22746        // from the WitContract's own storage and each would silently
22747        // misbehave if this accessor produced a detached copy). Peer of
22748        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
22749        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22750        // shaped optional-scalar axis — second extension of the
22751        // `Option<&str>` borrow-not-copy discipline onto the
22752        // per-`:contratos` payload-carrier family, this time on the
22753        // pub-sub arm.
22754        let c = WitContract {
22755            de: "cart".into(),
22756            para: "notifier".into(),
22757            wit: "nats:pub-sub".into(),
22758            endpoint: None,
22759            subject: Some("orders.paid".into()),
22760            slot: None,
22761        };
22762        let sub = c.subject().expect("Some arm");
22763        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
22764        assert_eq!(
22765            sub.as_ptr(),
22766            storage_slice.as_ptr(),
22767            "WitContract::subject must borrow from the .subject \
22768             String's backing storage — a fresh allocation here means \
22769             the accessor no longer names the substrate-primitive typed \
22770             dispatch and every downstream consumer would silently \
22771             carry a detached copy",
22772        );
22773        assert_eq!(
22774            sub.len(),
22775            storage_slice.len(),
22776            "WitContract::subject and .subject.as_deref() must byte-\
22777             equal in length as well as in address",
22778        );
22779    }
22780
22781    #[test]
22782    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
22783        // The canonical per-`:contratos` key/value-store-shaped
22784        // `:slot`-scalar pin: [`WitContract::slot`] must return the
22785        // `:contratos :slot` field byte-for-byte, borrowed from the
22786        // typed slot's own `Option<String>` storage. Peer of the
22787        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
22788        // [`WitContract::subject`] (90de675) accessor pins on the M3
22789        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22790        // optional-scalar axis — same "the substrate-primitive
22791        // accessor must byte-equal the raw field access verbatim
22792        // across every author-declared value" discipline extended to
22793        // the store arm. Pins against a future silent detour that
22794        // re-canonicalized the slot template (an accidental
22795        // `.to_lowercase()` bucket-prefix normalization that didn't
22796        // reach the peer field-access site at the dedup key, a per-CR
22797        // fully-qualified prefix rewrite the operator authors on one
22798        // consumer without the other, or an M4 typed-key-template
22799        // `Display` re-canonicalization that silently drifted the
22800        // printer output from the source `caixa.lisp`). Four values
22801        // sweep the wasi:keyvalue accept-set every store-shaped
22802        // author-declared slot lands on (flat bucket, single-param
22803        // template, multi-param template, nested-hierarchy template).
22804        for slot in [
22805            "sessions",
22806            "carts/{cart_id}",
22807            "orders/{tenant}/{order_id}",
22808            "cache/tenant-a/orders/{id}",
22809        ] {
22810            let c = WitContract {
22811                de: "cart".into(),
22812                para: "kv".into(),
22813                wit: "wasi:keyvalue/store".into(),
22814                endpoint: None,
22815                subject: None,
22816                slot: Some(slot.into()),
22817            };
22818            assert_eq!(
22819                c.slot(),
22820                Some(slot),
22821                "WitContract::slot must return :contratos :slot \
22822                 verbatim (got {:?}, expected Some({slot:?}))",
22823                c.slot(),
22824            );
22825            assert_eq!(
22826                c.slot(),
22827                c.slot.as_deref(),
22828                "WitContract::slot must byte-equal the .slot field's \
22829                 `.as_deref()` projection",
22830            );
22831        }
22832    }
22833
22834    #[test]
22835    fn wit_contract_slot_none_when_field_is_none() {
22836        // The absent-`:slot` arm of the per-`:contratos` store-shaped
22837        // payload-carrier accessor pin: when the typed slot is absent —
22838        // the canonical shape under a non-store `:wit` world per the
22839        // [`WitContract::target`]-enforced shape ↔ target partition
22840        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
22841        // carries `:subject`, [`WitTarget::Capability`] carries none) —
22842        // [`WitContract::slot`] must return `None`. Pins against a
22843        // future silent detour that projected the absent slot to a
22844        // `Some("")` empty-string default (the canonical
22845        // `Option<String>` → `String` collapse footgun the sibling M2
22846        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22847        // emptiness predicates already guard on the peer M2 typed-slot
22848        // surfaces), a `Some("None")` stringified-None round-trip, or
22849        // a `Some` arm whose contents were derived from a sibling
22850        // slot (an accidental fallback to the `:endpoint` / `:subject`
22851        // payload that read the HTTP / pub-sub payload into the store
22852        // axis). Three contracts sweep the accept-set every non-store
22853        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
22854        // payload-less capability.
22855        for (wit, endpoint, subject) in [
22856            ("wasi:http/proxy", Some("/lookup"), None),
22857            ("nats:pub-sub", None, Some("orders.paid")),
22858            ("wasi:cli/environment", None, None),
22859        ] {
22860            let c = WitContract {
22861                de: "cart".into(),
22862                para: "downstream".into(),
22863                wit: wit.into(),
22864                endpoint: endpoint.map(str::to_string),
22865                subject: subject.map(str::to_string),
22866                slot: None,
22867            };
22868            assert!(
22869                c.slot().is_none(),
22870                "WitContract::slot must return None when the typed \
22871                 slot is absent under :wit {wit:?} (got {:?})",
22872                c.slot(),
22873            );
22874            assert_eq!(
22875                c.slot(),
22876                c.slot.as_deref(),
22877                "WitContract::slot must byte-equal the .slot field's \
22878                 `.as_deref()` projection in the absent arm",
22879            );
22880        }
22881    }
22882
22883    #[test]
22884    fn wit_contract_slot_borrows_from_slot_storage() {
22885        // The borrow-not-copy pin: [`WitContract::slot`] must return
22886        // an `Option<&str>` whose `Some` arm borrows from the typed
22887        // slot's own [`String`] storage — same-address invariant with
22888        // `c.slot.as_deref().unwrap()`. Pins against a future silent
22889        // detour that allocated a fresh `String`
22890        // (`self.slot.clone().map(...)` in the body would type-check
22891        // but silently drop the borrow, and every downstream consumer
22892        // that assumed the returned slice outlives `&self` would
22893        // break on a stale-reference use-after-free — the
22894        // [`WitContract::target`] Store-arm payload extraction rebinds
22895        // the returned `Option<&str>` through `.ok_or_else(...)` and
22896        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
22897        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22898        // [`ContratoIdentity`] dedup key threads the returned
22899        // `Option<&str>` into the six-tuple's store arm — each borrow
22900        // from the WitContract's own storage and each would silently
22901        // misbehave if this accessor produced a detached copy). Peer
22902        // of the sibling per-`:contratos` [`WitContract::endpoint`]
22903        // (7020470) / [`WitContract::subject`] (90de675)
22904        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
22905        // shaped optional-scalar axis — third and final extension of
22906        // the `Option<&str>` borrow-not-copy discipline onto the
22907        // per-`:contratos` payload-carrier family, this time on the
22908        // store arm.
22909        let c = WitContract {
22910            de: "cart".into(),
22911            para: "kv".into(),
22912            wit: "wasi:keyvalue/store".into(),
22913            endpoint: None,
22914            subject: None,
22915            slot: Some("carts/{cart_id}".into()),
22916        };
22917        let slot = c.slot().expect("Some arm");
22918        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
22919        assert_eq!(
22920            slot.as_ptr(),
22921            storage_slice.as_ptr(),
22922            "WitContract::slot must borrow from the .slot String's \
22923             backing storage — a fresh allocation here means the \
22924             accessor no longer names the substrate-primitive typed \
22925             dispatch and every downstream consumer would silently \
22926             carry a detached copy",
22927        );
22928        assert_eq!(
22929            slot.len(),
22930            storage_slice.len(),
22931            "WitContract::slot and .slot.as_deref() must byte-equal \
22932             in length as well as in address",
22933        );
22934    }
22935
22936    #[test]
22937    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
22938        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
22939        // [`Membro::nome`] must return the `:membros :caixa` field
22940        // byte-for-byte, borrowed from the typed slot's own [`String`]
22941        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
22942        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22943        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
22944        // slot-atom scalar-value axes — same "the substrate-primitive
22945        // accessor must byte-equal the raw field access verbatim across
22946        // every author-declared value" discipline extended to the
22947        // per-`:membros` member-identity arm. Pins against a future
22948        // silent detour that re-normalized the member identity (an
22949        // accidental `.to_lowercase()` — every `:membros :caixa` is
22950        // validated as a DNS-1123 label upstream via
22951        // [`validate_membro_caixa`], so any re-normalization is
22952        // redundant + a drift surface between the validator and the
22953        // accessor), a namespace-prefix rewrite (an accidental
22954        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
22955        // rewrite that didn't land on the peer axes), or a per-cluster
22956        // alias stamp the operator authors on one consumer without the
22957        // other. Four values sweep the accept-set the DNS-1123 gate
22958        // upstream admits (short single-word / dashed / v-suffixed
22959        // member names).
22960        for name in ["cart", "checkout", "catalog", "orders-v2"] {
22961            let m = Membro {
22962                caixa: name.into(),
22963                versao: "^0.1".into(),
22964            };
22965            assert_eq!(
22966                m.nome(),
22967                name,
22968                "Membro::nome must return :membros :caixa verbatim \
22969                 (got {:?}, expected {name:?})",
22970                m.nome(),
22971            );
22972            assert_eq!(
22973                m.nome(),
22974                m.caixa.as_str(),
22975                "Membro::nome must byte-equal the .caixa field access",
22976            );
22977        }
22978    }
22979
22980    #[test]
22981    fn membro_nome_borrows_from_caixa_storage() {
22982        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
22983        // slice that borrows from the typed slot's own [`String`]
22984        // storage — same-address invariant with `m.caixa.as_str()`. Pins
22985        // against a future silent detour that allocated a fresh `String`
22986        // (`self.caixa.clone()` in the body would type-check but
22987        // silently drop the borrow, and every downstream consumer that
22988        // assumed the returned slice outlives `&self` would break on a
22989        // stale-reference use-after-free — the `HashSet<&str>` collector
22990        // at [`AplicacaoSpec::validate`]'s `names` seed, the
22991        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
22992        // [`AplicacaoSpec::detect_sync_cycles`], the
22993        // [`crate::render::insert_first_seen`] dedup key at
22994        // [`AplicacaoSpec::validate_membros`] — each borrow from the
22995        // Membro's own storage and each would silently misbehave if
22996        // this accessor produced a detached copy). Peer of the sibling
22997        // per-`:contratos` [`WitContract::source`] /
22998        // [`WitContract::destination`] and per-`:entrada`
22999        // [`Entrada::destination`] borrow-invariant pins on the mesh-
23000        // slot-atom scalar-value axes.
23001        let m = Membro {
23002            caixa: "checkout".into(),
23003            versao: "^0.1".into(),
23004        };
23005        let name = m.nome();
23006        let caixa_slice = m.caixa.as_str();
23007        assert_eq!(
23008            name.as_ptr(),
23009            caixa_slice.as_ptr(),
23010            "Membro::nome must borrow from the .caixa String's backing \
23011             storage — a fresh allocation here means the accessor no \
23012             longer names the substrate-primitive typed dispatch and \
23013             every downstream consumer would silently carry a detached \
23014             copy",
23015        );
23016        assert_eq!(
23017            name.len(),
23018            caixa_slice.len(),
23019            "Membro::nome and .caixa.as_str() must byte-equal in length \
23020             as well as in address",
23021        );
23022    }
23023
23024    #[test]
23025    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
23026        // The canonical per-`:membros` member-`:versao`-scalar pin:
23027        // [`Membro::versao_requirement`] must return the
23028        // `:membros :versao` field byte-for-byte, borrowed from the typed
23029        // slot's own [`String`] storage. Sibling of the peer
23030        // `membro_nome_returns_caixa_byte_equal_across_permutations`
23031        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
23032        // — same "the substrate-primitive accessor must byte-equal the
23033        // raw field access verbatim across every author-declared value"
23034        // discipline extended to the per-`:membros` member-`:versao`
23035        // requirement-string arm. Pins against a future silent detour
23036        // that re-canonicalized the requirement (an accidental
23037        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
23038        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
23039        // drifted the printer output away from the source `caixa.lisp`,
23040        // an accidental whitespace trim on `"^ 0.1"` that no consumer
23041        // ever produced from the field-access side, an accidental
23042        // per-cluster lacre-projected concrete-version rewrite that
23043        // didn't land on the peer field-access sites). Five values sweep
23044        // the accept-set the shared
23045        // [`crate::render::require_valid_versao_requirement`] gate
23046        // admits (caret / tilde / exact / wildcard / bare-major).
23047        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
23048            let m = Membro {
23049                caixa: "cart".into(),
23050                versao: req.into(),
23051            };
23052            assert_eq!(
23053                m.versao_requirement(),
23054                req,
23055                "Membro::versao_requirement must return :membros :versao \
23056                 verbatim (got {:?}, expected {req:?})",
23057                m.versao_requirement(),
23058            );
23059            assert_eq!(
23060                m.versao_requirement(),
23061                m.versao.as_str(),
23062                "Membro::versao_requirement must byte-equal the .versao \
23063                 field access",
23064            );
23065        }
23066    }
23067
23068    #[test]
23069    fn membro_versao_requirement_borrows_from_versao_storage() {
23070        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
23071        // return a `&str` slice that borrows from the typed slot's own
23072        // [`String`] storage — same-address invariant with
23073        // `m.versao.as_str()`. Pins against a future silent detour that
23074        // allocated a fresh `String` (`self.versao.clone()` in the body
23075        // would type-check but silently drop the borrow, and every
23076        // downstream consumer that assumed the returned slice outlives
23077        // `&self` would break on a stale-reference use-after-free). Peer
23078        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
23079        // per-`:contratos` [`WitContract::source`] /
23080        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
23081        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
23082        // the mesh-slot-atom scalar-value axes.
23083        let m = Membro {
23084            caixa: "checkout".into(),
23085            versao: "^0.1".into(),
23086        };
23087        let req = m.versao_requirement();
23088        let versao_slice = m.versao.as_str();
23089        assert_eq!(
23090            req.as_ptr(),
23091            versao_slice.as_ptr(),
23092            "Membro::versao_requirement must borrow from the .versao \
23093             String's backing storage — a fresh allocation here means \
23094             the accessor no longer names the substrate-primitive typed \
23095             dispatch and every downstream consumer would silently carry \
23096             a detached copy",
23097        );
23098        assert_eq!(
23099            req.len(),
23100            versao_slice.len(),
23101            "Membro::versao_requirement and .versao.as_str() must byte-\
23102             equal in length as well as in address",
23103        );
23104    }
23105
23106    #[test]
23107    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
23108        // Sibling-pair invariant pin composing both per-`:membros`
23109        // substrate-primitive typed dispatches — [`Membro::nome`]
23110        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
23111        // `(nome(), versao_requirement())` call shape every renderer
23112        // that fans on per-member identity + version pin keys off. The
23113        // invariant, evaluated per-member:
23114        //
23115        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
23116        //
23117        // Closes the last unlifted per-`:membros` scalar axis — every
23118        // downstream consumer that reads the pair now routes through
23119        // exactly two typed dispatches on the substrate primitive, not
23120        // one typed + one open-coded field access. A future refactor
23121        // that silently split either accessor's projection (an
23122        // accidental `nome()` namespace-prefix rewrite that didn't
23123        // reach the peer, an accidental `versao_requirement()` lacre-
23124        // projected concrete-version rewrite that didn't land on the
23125        // `nome()` peer) surfaces at caixa-core build time. Peer of the
23126        // sibling per-`:entrada` `(hostname(), destination())` and
23127        // per-`:contratos` `(source(), destination())` pair invariants
23128        // on the mesh-slot-atom scalar-value axes.
23129        for (caixa, versao) in [
23130            ("cart", "^0.1"),
23131            ("checkout", "~0.1.2"),
23132            ("catalog", "0.1.0"),
23133            ("orders-v2", "*"),
23134        ] {
23135            let m = Membro {
23136                caixa: caixa.into(),
23137                versao: versao.into(),
23138            };
23139            assert_eq!(
23140                (m.nome(), m.versao_requirement()),
23141                (m.caixa.as_str(), m.versao.as_str()),
23142                "(Membro::nome, Membro::versao_requirement) must project \
23143                 (.caixa, .versao) verbatim across every author-declared \
23144                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
23145                m.nome(),
23146                m.versao_requirement(),
23147            );
23148        }
23149    }
23150
23151    #[test]
23152    fn validate_membros_empty_gate_routes_through_nome_accessor() {
23153        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
23154        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
23155        // not the raw `.caixa` field access. Structurally: setting
23156        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
23157        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
23158        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
23159        // (i.e. the empty string) — so the emptiness predicate the
23160        // refusal arm reaches under is the accessor-projected value,
23161        // not a peer field that would silently drift under a future
23162        // accessor-side rewrite.
23163        //
23164        // Pins against a future silent detour that (a) re-derived the
23165        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
23166        // instead of `self.nome().is_empty()`, silently disagreeing with
23167        // every peer consumer (the `validate_membro_caixa(m.nome())`
23168        // call one line below, the dedup-key `insert_first_seen(&mut
23169        // seen, m.nome(), …)` two lines below, the emit-side per-
23170        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
23171        // (b) accessor-side introduced a per-tenant alias arm the
23172        // caller was unaware of, silently rewriting an author-declared
23173        // `:caixa "checkout"` to `""` — the raw-field-access gate
23174        // would fail-open while the accessor-routed peer consumers
23175        // would fail-closed, splitting the diagnostic from the actual
23176        // failure surface.
23177        //
23178        // Peer of the sibling
23179        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
23180        // (c0110f1) composition pin — same "the shape-gate predicate
23181        // must route through the substrate-primitive typed dispatch"
23182        // discipline extended onto the per-`:membros` empty-`:caixa`
23183        // refusal-arm axis. Closes the last unlifted `.caixa` production-
23184        // code read site on `Membro` — after this converge every
23185        // caixa-core `.caixa` field access outside the accessor's own
23186        // body is either a test-side field-setter (in-module tests
23187        // constructing invalid-shape inputs) or a doc-comment reference.
23188        let mut s = three_member_spec();
23189        s.membros[1].caixa = String::new();
23190        assert!(
23191            s.membros[1].nome().is_empty(),
23192            "Membro::nome must byte-equal the .caixa field access — an \
23193             accessor-side detour that no longer projects the raw field \
23194             would silently split this drift-detection test from the \
23195             validate() refusal arm",
23196        );
23197        assert_eq!(
23198            s.membros[1].nome(),
23199            s.membros[1].caixa.as_str(),
23200            "Membro::nome and .caixa.as_str() must byte-equal on an \
23201             empty-`:caixa` entry — the emptiness gate keys off the \
23202             accessor by construction",
23203        );
23204        assert_eq!(
23205            s.validate().unwrap_err(),
23206            AplicacaoError::MembroCaixaEmpty,
23207            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
23208             on an entry whose accessor-projected `nome()` is empty",
23209        );
23210    }
23211
23212    #[test]
23213    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
23214        // The canonical per-`:placement` Akka-cluster-sharding
23215        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
23216        // the `:placement :shard-key` field byte-for-byte, borrowed
23217        // from the typed slot's own `Option<String>` storage. Peer of
23218        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
23219        // per-`:contratos` [`WitContract::source`] /
23220        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
23221        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
23222        // slot-atom scalar-value axes — same "the substrate-primitive
23223        // accessor must byte-equal the raw field access verbatim across
23224        // every author-declared value" discipline extended to the
23225        // per-`:placement` Akka-cluster-sharding key extractor arm.
23226        // Pins against a future silent detour that re-normalized the
23227        // key (an accidental `.to_lowercase()` — every non-empty
23228        // `:shard-key` is validated as a printable-ASCII single-token
23229        // reference upstream via [`validate_placement_shard_key`], so
23230        // any re-normalization is redundant + a drift surface between
23231        // the validator and the accessor), a per-cluster alias rewrite
23232        // the operator authors on one consumer without the other, or an
23233        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
23234        // that didn't land on the peer field-access sites. Four values
23235        // sweep the accept-set the shape gate admits — bare identifier,
23236        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
23237        // the four canonical Akka-style entity-id extractor shapes the
23238        // future M4 cluster-sharding reconciler hashes.
23239        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
23240            let p = Placement {
23241                estrategia: PlacementStrategy::Sharded,
23242                clusters: vec!["rio".into()],
23243                affinity: None,
23244                shard_key: Some(key.into()),
23245            };
23246            assert_eq!(
23247                p.shard_key(),
23248                Some(key),
23249                "Placement::shard_key must return :placement :shard-key \
23250                 verbatim (got {:?}, expected Some({key:?}))",
23251                p.shard_key(),
23252            );
23253            assert_eq!(
23254                p.shard_key(),
23255                p.shard_key.as_deref(),
23256                "Placement::shard_key must byte-equal the .shard_key \
23257                 field's `.as_deref()` projection",
23258            );
23259        }
23260    }
23261
23262    #[test]
23263    fn placement_shard_key_none_when_field_is_none() {
23264        // The absent-`:shard-key` arm of the per-`:placement`
23265        // Akka-cluster-sharding accessor pin: when the typed slot is
23266        // absent — the canonical shape under `:estrategia Replicated` /
23267        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
23268        // enforced `shard_key.is_some() == matches!(estrategia,
23269        // Sharded)` partition — [`Placement::shard_key`] must return
23270        // `None`. Pins against a future silent detour that projected
23271        // the absent slot to a `Some("")` empty-string default (the
23272        // canonical `Option<String>` → `String` collapse footgun the
23273        // sibling M2 [`crate::LimitsSpec::is_empty`] /
23274        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
23275        // already guard on the peer M2 typed-slot surfaces), a
23276        // `Some("None")` stringified-None round-trip, or a `Some` arm
23277        // whose contents were derived from a sibling slot (an
23278        // accidental fallback to `estrategia.as_str()` that read the
23279        // strategy discriminator into the key axis). Two placements
23280        // sweep the accept-set every `validate`-passing non-`Sharded`
23281        // shape lands on — `Replicated` (Erlang/OTP distributed-app
23282        // takeover) and `SingleNode` (single-node hosting).
23283        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
23284            let p = Placement {
23285                estrategia,
23286                clusters: vec!["rio".into()],
23287                affinity: None,
23288                shard_key: None,
23289            };
23290            assert!(
23291                p.shard_key().is_none(),
23292                "Placement::shard_key must return None when the typed \
23293                 slot is absent under :estrategia {estrategia:?} (got {:?})",
23294                p.shard_key(),
23295            );
23296            assert_eq!(
23297                p.shard_key(),
23298                p.shard_key.as_deref(),
23299                "Placement::shard_key must byte-equal the .shard_key \
23300                 field's `.as_deref()` projection in the absent arm",
23301            );
23302        }
23303    }
23304
23305    #[test]
23306    fn placement_shard_key_borrows_from_shard_key_storage() {
23307        // The borrow-not-copy pin: [`Placement::shard_key`] must return
23308        // an `Option<&str>` whose `Some` arm borrows from the typed
23309        // slot's own [`String`] storage — same-address invariant with
23310        // `p.shard_key.as_deref().unwrap()`. Pins against a future
23311        // silent detour that allocated a fresh `String`
23312        // (`self.shard_key.clone().map(...)` in the body would type-
23313        // check but silently drop the borrow, and every downstream
23314        // consumer that assumed the returned slice outlives `&self`
23315        // would break on a stale-reference use-after-free — the
23316        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
23317        // gate's `Some(k)`-bound match arm reads `k: &str` under the
23318        // accessor's return type and would silently misbehave if this
23319        // accessor produced a detached copy). Peer of the sibling
23320        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
23321        // [`WitContract::source`] / [`WitContract::destination`]
23322        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
23323        // (6db982c) borrow-invariant pins on the mesh-slot-atom
23324        // scalar-value axes — first extension of the discipline onto
23325        // an `Option<String>`-shaped optional-scalar axis.
23326        let p = Placement {
23327            estrategia: PlacementStrategy::Sharded,
23328            clusters: vec!["rio".into()],
23329            affinity: None,
23330            shard_key: Some("tenantId".into()),
23331        };
23332        let key = p.shard_key().expect("Some arm");
23333        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
23334        assert_eq!(
23335            key.as_ptr(),
23336            storage_slice.as_ptr(),
23337            "Placement::shard_key must borrow from the .shard_key \
23338             String's backing storage — a fresh allocation here means \
23339             the accessor no longer names the substrate-primitive typed \
23340             dispatch and every downstream consumer would silently \
23341             carry a detached copy",
23342        );
23343        assert_eq!(
23344            key.len(),
23345            storage_slice.len(),
23346            "Placement::shard_key and .shard_key.as_deref() must byte-\
23347             equal in length as well as in address",
23348        );
23349    }
23350
23351    #[test]
23352    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
23353        // The canonical per-`:placement` M3-Adaptive-compression-hint
23354        // scalar pin: [`Placement::affinity`] must return the
23355        // `:placement :affinity` field byte-for-byte, borrowed from the
23356        // typed slot's own `Option<String>` storage. Peer of the sibling
23357        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
23358        // pin on the sibling `Option<&str>` optional-scalar axis — same
23359        // "the substrate-primitive accessor must byte-equal the raw
23360        // field access verbatim across every author-declared value"
23361        // discipline extended to the peer per-`:placement` M3-Adaptive-
23362        // compression-hint arm. Pins against a future silent detour
23363        // that re-normalized the hint (an accidental `.to_lowercase()`
23364        // — every `:affinity` is already validated as a DNS-1123 label
23365        // upstream via [`validate_placement_affinity`], so any re-
23366        // normalization is redundant + a drift surface between the
23367        // validator and the accessor), a per-cluster alias rewrite the
23368        // operator authors on one consumer without the other, or an
23369        // accidental hint-family collapse (`low-latency` → `latency`
23370        // that dropped the qualifier prefix). Four values sweep the
23371        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
23372        // canonical adaptive-compression-weight biases the future M4
23373        // placement engine reads.
23374        for hint in [
23375            "data-locality",
23376            "low-latency",
23377            "high-throughput",
23378            "cost-optimized",
23379        ] {
23380            let p = Placement {
23381                estrategia: PlacementStrategy::Replicated,
23382                clusters: vec!["rio".into()],
23383                affinity: Some(hint.into()),
23384                shard_key: None,
23385            };
23386            assert_eq!(
23387                p.affinity(),
23388                Some(hint),
23389                "Placement::affinity must return :placement :affinity \
23390                 verbatim (got {:?}, expected Some({hint:?}))",
23391                p.affinity(),
23392            );
23393            assert_eq!(
23394                p.affinity(),
23395                p.affinity.as_deref(),
23396                "Placement::affinity must byte-equal the .affinity \
23397                 field's `.as_deref()` projection",
23398            );
23399        }
23400    }
23401
23402    #[test]
23403    fn placement_affinity_none_when_field_is_none() {
23404        // The absent-`:affinity` arm of the per-`:placement`
23405        // M3-Adaptive-compression-hint accessor pin: when the typed
23406        // slot is absent — the canonical shape of an Aplicacao that
23407        // leaves the compression weighting up to the placement engine's
23408        // cluster-default arm — [`Placement::affinity`] must return
23409        // `None`. Pins against a future silent detour that projected
23410        // the absent slot to a `Some("")` empty-string default (the
23411        // canonical `Option<String>` → `String` collapse footgun the
23412        // sibling M2 [`crate::LimitsSpec::is_empty`] /
23413        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
23414        // already guard on the peer M2 typed-slot surfaces), a
23415        // `Some("None")` stringified-None round-trip, a `Some` arm
23416        // whose contents were derived from a sibling slot (an
23417        // accidental fallback to `estrategia.as_str()` that read the
23418        // strategy discriminator into the hint axis), or a
23419        // `Some("default")` implicit-default that would silently biases
23420        // the routing without the author having written one. Three
23421        // placements sweep the accept-set every `validate`-passing
23422        // `:affinity None` shape lands on — one per PlacementStrategy
23423        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
23424        // with a shard-key), since `:affinity` is orthogonal to
23425        // `:estrategia` in the typed grammar.
23426        for (estrategia, shard_key) in [
23427            (PlacementStrategy::SingleNode, None),
23428            (PlacementStrategy::Replicated, None),
23429            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
23430        ] {
23431            let p = Placement {
23432                estrategia,
23433                clusters: vec!["rio".into()],
23434                affinity: None,
23435                shard_key,
23436            };
23437            assert!(
23438                p.affinity().is_none(),
23439                "Placement::affinity must return None when the typed \
23440                 slot is absent under :estrategia {estrategia:?} (got {:?})",
23441                p.affinity(),
23442            );
23443            assert_eq!(
23444                p.affinity(),
23445                p.affinity.as_deref(),
23446                "Placement::affinity must byte-equal the .affinity \
23447                 field's `.as_deref()` projection in the absent arm",
23448            );
23449        }
23450    }
23451
23452    #[test]
23453    fn placement_affinity_borrows_from_affinity_storage() {
23454        // The borrow-not-copy pin: [`Placement::affinity`] must return
23455        // an `Option<&str>` whose `Some` arm borrows from the typed
23456        // slot's own [`String`] storage — same-address invariant with
23457        // `p.affinity.as_deref().unwrap()`. Pins against a future
23458        // silent detour that allocated a fresh `String`
23459        // (`self.affinity.clone().map(...)` in the body would type-
23460        // check but silently drop the borrow, and every downstream
23461        // consumer that assumed the returned slice outlives `&self`
23462        // would break on a stale-reference use-after-free — the
23463        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
23464        // gate reads the accessor's `&str` return through the
23465        // [`validate_placement_affinity`] `&str` parameter and would
23466        // silently misbehave if this accessor produced a detached
23467        // copy). Peer of the sibling per-`:placement`
23468        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
23469        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
23470        // extends the discipline onto the sibling per-`:placement`
23471        // M3-Adaptive-compression-hint arm.
23472        let p = Placement {
23473            estrategia: PlacementStrategy::Replicated,
23474            clusters: vec!["rio".into()],
23475            affinity: Some("data-locality".into()),
23476            shard_key: None,
23477        };
23478        let hint = p.affinity().expect("Some arm");
23479        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
23480        assert_eq!(
23481            hint.as_ptr(),
23482            storage_slice.as_ptr(),
23483            "Placement::affinity must borrow from the .affinity \
23484             String's backing storage — a fresh allocation here means \
23485             the accessor no longer names the substrate-primitive typed \
23486             dispatch and every downstream consumer would silently \
23487             carry a detached copy",
23488        );
23489        assert_eq!(
23490            hint.len(),
23491            storage_slice.len(),
23492            "Placement::affinity and .affinity.as_deref() must byte-\
23493             equal in length as well as in address",
23494        );
23495    }
23496
23497    #[test]
23498    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
23499        // The canonical per-`:placement` distribution-strategy-scalar
23500        // pin: [`Placement::estrategia`] must return the `:placement
23501        // :estrategia` field verbatim as a [`PlacementStrategy`],
23502        // `Copy`-projected from the typed slot's own `PlacementStrategy`
23503        // storage across every variant in the closed accept-set
23504        // (`SingleNode` — Erlang/OTP distributed-app takeover;
23505        // `Replicated` — active-active across every named cluster;
23506        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
23507        // against a future silent detour that re-derived the strategy
23508        // from a peer axis (an accidental fallback to
23509        // `if shard_key.is_some() { Sharded } else { Replicated }`
23510        // collapse that read the shard-key axis into the strategy
23511        // discriminator), a variant remap the operator authors on one
23512        // consumer without the other, or a stale-derive detour that
23513        // substituted [`PlacementStrategy::default`] when the field
23514        // held any explicit variant (which would silently collapse the
23515        // distinction between "author explicitly declared `:estrategia
23516        // Replicated`" and "author omitted the slot and inherited the
23517        // default" the future per-cluster override slot depends on).
23518        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
23519        // pin on the `Copy`-return `u16` scalar axis — same "the
23520        // substrate-primitive accessor must byte-equal the raw field
23521        // access verbatim across every author-declared value" discipline
23522        // extended onto the per-`:placement` distribution-strategy
23523        // `Copy`-composite-enum scalar axis.
23524        for estrategia in [
23525            PlacementStrategy::SingleNode,
23526            PlacementStrategy::Replicated,
23527            PlacementStrategy::Sharded,
23528        ] {
23529            // Route the paired `:shard-key` fixture-builder through the
23530            // typed cross-slot invariant predicate
23531            // [`PlacementStrategy::requires_shard_key`] rather than the
23532            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
23533            // arm-identity predicate — same discipline the sibling
23534            // `placement_strategy_variants_round_trip` fixture builder now
23535            // reads through.
23536            let shard_key = estrategia
23537                .requires_shard_key()
23538                .then(|| "tenantId".to_string());
23539            let p = Placement {
23540                estrategia,
23541                clusters: vec!["rio".into()],
23542                affinity: None,
23543                shard_key,
23544            };
23545            assert_eq!(
23546                p.estrategia(),
23547                estrategia,
23548                "Placement::estrategia must return :placement :estrategia \
23549                 verbatim (got {:?}, expected {estrategia:?})",
23550                p.estrategia(),
23551            );
23552            assert_eq!(
23553                p.estrategia(),
23554                p.estrategia,
23555                "Placement::estrategia accessor and .estrategia field \
23556                 access must byte-equal — the accessor is the substrate-\
23557                 primitive typed dispatch every downstream distribution-\
23558                 strategy consumer must route through",
23559            );
23560        }
23561    }
23562
23563    #[test]
23564    fn validate_placement_reads_through_lifted_estrategia_accessor() {
23565        // Three-consumer coherence pin: the
23566        // [`AplicacaoSpec::validate_placement`]
23567        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
23568        // `estrategia:` field (which reads through
23569        // [`Placement::estrategia`] to name the strategy the empty
23570        // `:clusters` list was declared against), the same method's
23571        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
23572        // reads through [`Placement::estrategia`] to fan across the
23573        // shape-gate cascades), and the non-`Sharded`-arm
23574        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
23575        // `estrategia:` field (which reads through
23576        // [`Placement::estrategia`] to name the strategy the declared-
23577        // but-inert `:shard-key` was authored under) must all key off
23578        // the lifted accessor, so any future rebrand on the typed
23579        // slot's reader shape lands at exactly one place. Pins the
23580        // three-site coherence by exercising each error surface end-
23581        // to-end and asserting the surfaced `estrategia:` field byte-
23582        // equals the accessor's return. Peer of the sibling per-
23583        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
23584        // pin on the M3 mesh-slot `Copy`-return scalar axis.
23585
23586        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
23587        // whose `estrategia:` field must byte-equal the accessor's return
23588        // for every variant in the closed accept-set.
23589        for estrategia in [
23590            PlacementStrategy::SingleNode,
23591            PlacementStrategy::Replicated,
23592            PlacementStrategy::Sharded,
23593        ] {
23594            let mut spec = three_member_spec();
23595            spec.placement.estrategia = estrategia;
23596            spec.placement.clusters = Vec::new();
23597            // Route the paired `:shard-key` spec-mutator through the typed
23598            // cross-slot invariant predicate
23599            // [`PlacementStrategy::requires_shard_key`] rather than the
23600            // [`gen_platform::IsVariant`]-derived
23601            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
23602            // same discipline the sibling
23603            // `placement_strategy_variants_round_trip` and
23604            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
23605            // fixture builders now read through.
23606            spec.placement.shard_key = estrategia
23607                .requires_shard_key()
23608                .then(|| "tenantId".to_string());
23609            let err = spec.validate().unwrap_err();
23610            match err {
23611                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
23612                    assert_eq!(
23613                        e,
23614                        spec.placement.estrategia(),
23615                        "PlacementWithoutClusters.estrategia must byte-equal \
23616                         Placement::estrategia() — the error carrier reads \
23617                         through the lifted accessor",
23618                    );
23619                }
23620                other => panic!(
23621                    "expected PlacementWithoutClusters, got {other:?} for \
23622                     estrategia={estrategia:?}"
23623                ),
23624            }
23625        }
23626
23627        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
23628        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
23629        // must byte-equal the accessor's return for both non-`Sharded`
23630        // strategies.
23631        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
23632            let mut spec = three_member_spec();
23633            spec.placement.estrategia = estrategia;
23634            spec.placement.shard_key = Some("tenantId".into());
23635            let err = spec.validate().unwrap_err();
23636            match err {
23637                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
23638                    assert_eq!(
23639                        e,
23640                        spec.placement.estrategia(),
23641                        "ShardKeyOnNonSharded.estrategia must byte-equal \
23642                         Placement::estrategia() — the non-Sharded-arm \
23643                         refusal reads through the lifted accessor",
23644                    );
23645                }
23646                other => panic!(
23647                    "expected ShardKeyOnNonSharded, got {other:?} for \
23648                     estrategia={estrategia:?}"
23649                ),
23650            }
23651        }
23652    }
23653
23654    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
23655    //
23656    // The [`Placement::clusters`] accessor lift is the second slice-return
23657    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
23658    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
23659    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
23660    // below cover (1) the accessor's byte-equal projection against the raw
23661    // field access across the empty / singleton / cohort fixtures the
23662    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
23663    // and the per-cluster validate loop fan between, and (2) the two-
23664    // consumer coherence of the paired pre-flight refusal probe and the
23665    // per-cluster validate loop routing through the accessor on both arms.
23666
23667    #[test]
23668    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
23669        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
23670        // [`Placement::clusters`] must return the `:placement :clusters`
23671        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
23672        // the same backing buffer the raw `self.clusters.as_slice()`
23673        // field access borrows from, byte-equal across every
23674        // representative fixture in the accept-set — the empty slice
23675        // (the pre-validation sentinel every
23676        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
23677        // the singleton slice (the minimal `SingleNode`-shape cohort),
23678        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
23679        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
23680        //
23681        // Pins against a future silent detour that returned
23682        // `&Vec<String>` (which would type-check but leak the storage-
23683        // side `Vec`'s grow/push/reserve surface no consumer of the
23684        // typed view reaches for), a fresh-allocated `Vec<String>` copy
23685        // (which would type-check via a coercion but silently break
23686        // every downstream caller that relied on the slice sharing the
23687        // backing buffer's identity), or an out-of-order or length-
23688        // drifted projection (which would silently split the paired
23689        // pre-flight `.is_empty()` refusal probe's input from the per-
23690        // cluster validate loop's traversal input).
23691        //
23692        // Peer of the sibling M2
23693        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23694        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23695        // `:supervisor` static-child-list axis, extended onto the M3
23696        // per-`:placement` distribution-target-list `Vec`-carry axis.
23697        let fixtures: Vec<Vec<String>> = vec![
23698            Vec::new(),
23699            vec!["rio".into()],
23700            vec!["rio".into(), "mar".into()],
23701            vec!["rio".into(), "mar".into(), "plo".into()],
23702        ];
23703        for clusters in fixtures {
23704            let p = Placement {
23705                clusters: clusters.clone(),
23706                ..Placement::default()
23707            };
23708            assert_eq!(
23709                p.clusters(),
23710                clusters.as_slice(),
23711                "Placement::clusters must return :placement :clusters \
23712                 verbatim (got {:?}, expected {:?})",
23713                p.clusters(),
23714                clusters.as_slice(),
23715            );
23716            assert_eq!(
23717                p.clusters(),
23718                p.clusters.as_slice(),
23719                "Placement::clusters accessor and .clusters.as_slice() \
23720                 field access must byte-equal — the accessor is the \
23721                 substrate-primitive typed dispatch every downstream \
23722                 cluster-pool consumer must route through",
23723            );
23724            assert_eq!(
23725                p.clusters().len(),
23726                p.clusters.len(),
23727                "Placement::clusters().len() must byte-equal \
23728                 self.clusters.len() — a length-drift would silently \
23729                 split the paired pre-flight `.is_empty()` refusal \
23730                 probe input from the per-cluster validate loop's \
23731                 traversal input",
23732            );
23733        }
23734    }
23735
23736    #[test]
23737    fn validate_placement_reads_through_lifted_clusters_accessor() {
23738        // Two-consumer coherence pin: the
23739        // [`AplicacaoSpec::validate_placement`] pre-flight
23740        // `self.placement.clusters().is_empty()` refusal probe (which
23741        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
23742        // the accessor projects the empty slice) and the per-cluster
23743        // validate loop's `for c in self.placement.clusters()`
23744        // traversal (which must reach every entry in the same order
23745        // the accessor projects, so both the per-entry value-shape
23746        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
23747        // and the duplicate-detection HashSet insert that trips
23748        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
23749        // accessor's projection) must both key off the lifted
23750        // accessor, so any future rebrand on the typed slot's reader
23751        // shape lands at exactly one place. Pins the two-site
23752        // coherence by exercising each production consumer end-to-end:
23753        // (1) the `PlacementWithoutClusters` refusal under the empty
23754        // slice, (2) the `PlacementClusterInvalid` refusal fires on
23755        // the second entry of a two-cluster cohort whose head is
23756        // valid but tail is not (which requires the loop to reach the
23757        // second entry through the accessor), and (3) the
23758        // `PlacementClusterDuplicate` refusal fires on the second
23759        // entry of a two-cluster cohort that shares a name (which
23760        // requires the loop to reach both entries — a first-entry-only
23761        // projection would silently pass since the dedup HashSet has
23762        // room for the first insert).
23763        //
23764        // Peer of the sibling M2
23765        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23766        // (bc92bce) coherence pin on the per-`:supervisor` static-
23767        // child-list axis, extended onto the M3 per-`:placement`
23768        // distribution-target-list `Vec`-carry axis.
23769
23770        // (1) Pre-flight `.is_empty()` probe: the empty slice must
23771        // trip `PlacementWithoutClusters`.
23772        let mut spec = three_member_spec();
23773        spec.placement.clusters = Vec::new();
23774        match spec.validate().unwrap_err() {
23775            AplicacaoError::PlacementWithoutClusters { .. } => {}
23776            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
23777        }
23778        assert!(
23779            spec.placement.clusters().is_empty(),
23780            "the pre-flight refusal input must be the empty slice per \
23781             the accessor's projection",
23782        );
23783
23784        // (2) Per-cluster validate loop: a two-cluster cohort with an
23785        // invalid tail entry must trip `PlacementClusterInvalid` on
23786        // the tail — the loop must reach the second entry through
23787        // the accessor.
23788        let mut spec = three_member_spec();
23789        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
23790        match spec.validate().unwrap_err() {
23791            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
23792                assert_eq!(
23793                    cluster, "BAD_CLUSTER",
23794                    "PlacementClusterInvalid.cluster must carry the \
23795                     tail entry the loop reached through the accessor",
23796                );
23797            }
23798            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
23799        }
23800        assert_eq!(
23801            spec.placement.clusters().len(),
23802            2,
23803            "the per-cluster validate loop's traversal input must be \
23804             a two-element slice per the accessor's projection",
23805        );
23806
23807        // (3) Per-cluster validate loop: a two-cluster cohort that
23808        // shares a name must trip `PlacementClusterDuplicate` on the
23809        // second entry — the loop must reach both entries through the
23810        // accessor for the dedup HashSet's second insert to collide.
23811        let mut spec = three_member_spec();
23812        spec.placement.clusters = vec!["rio".into(), "rio".into()];
23813        match spec.validate().unwrap_err() {
23814            AplicacaoError::PlacementClusterDuplicate { cluster } => {
23815                assert_eq!(
23816                    cluster, "rio",
23817                    "PlacementClusterDuplicate.cluster must carry the \
23818                     shared cluster name verbatim",
23819                );
23820            }
23821            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
23822        }
23823        assert_eq!(
23824            spec.placement.clusters().len(),
23825            2,
23826            "the per-cluster validate loop's traversal input must be \
23827             a two-element slice per the accessor's projection",
23828        );
23829    }
23830
23831    #[test]
23832    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
23833        // The canonical per-`:membros` member-list-slice-shape pin:
23834        // [`AplicacaoSpec::membros`] must return the `:membros` typed
23835        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
23836        // same backing buffer the raw `self.membros.as_slice()` field
23837        // access borrows from, byte-equal across every representative
23838        // fixture in the accept-set — the empty slice (the pre-
23839        // validation sentinel every [`AplicacaoError::NoMembros`]
23840        // refusal keys off), the singleton slice (the minimal one-
23841        // Servico Aplicacao shape), and multi-entry cohorts (the peer
23842        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
23843        // load-bearing identity of the application graph).
23844        //
23845        // Pins against a future silent detour that returned
23846        // `&Vec<Membro>` (which would type-check but leak the storage-
23847        // side `Vec`'s grow/push/reserve surface no consumer of the
23848        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
23849        // (which would type-check via a coercion but silently break
23850        // every downstream caller that relied on the slice sharing the
23851        // backing buffer's identity), or an out-of-order or length-
23852        // drifted projection (which would silently split the paired
23853        // `HashSet<&str>` name-set seed's collect input from the
23854        // pre-flight `.is_empty()` refusal probe's input from the per-
23855        // member validate loop's traversal input from the
23856        // programs.yaml emitter's per-entry fan-out loop's input from
23857        // the `feira app graph` per-member print traversal's input).
23858        //
23859        // Peer of the sibling M2
23860        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23861        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23862        // `:supervisor` static-child-list axis and the sibling M3
23863        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
23864        // (a6e18d7) `&[String]` byte-equal pin on the per-
23865        // `:placement` distribution-target-list axis — extends the
23866        // slice-return-accessor byte-equal-projection discipline onto
23867        // the outermost M3 mesh-slot type's per-Aplicacao member-list
23868        // `Vec`-carry axis.
23869        let fixtures: Vec<Vec<Membro>> = vec![
23870            Vec::new(),
23871            vec![membro("catalog", "^0.1")],
23872            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23873            vec![
23874                membro("catalog", "^0.1"),
23875                membro("cart", "^0.1"),
23876                membro("payment", "^0.2"),
23877            ],
23878        ];
23879        for membros in fixtures {
23880            let s = AplicacaoSpec {
23881                membros: membros.clone(),
23882                contratos: Vec::new(),
23883                politicas: MeshPolicy::default(),
23884                placement: Placement::default(),
23885                entrada: None,
23886            };
23887            assert_eq!(
23888                s.membros(),
23889                membros.as_slice(),
23890                "AplicacaoSpec::membros must return :membros verbatim \
23891                 (got {:?}, expected {:?})",
23892                s.membros(),
23893                membros.as_slice(),
23894            );
23895            assert_eq!(
23896                s.membros(),
23897                s.membros.as_slice(),
23898                "AplicacaoSpec::membros accessor and .membros.as_slice() \
23899                 field access must byte-equal — the accessor is the \
23900                 substrate-primitive typed dispatch every downstream \
23901                 member-list consumer must route through",
23902            );
23903            assert_eq!(
23904                s.membros().len(),
23905                s.membros.len(),
23906                "AplicacaoSpec::membros().len() must byte-equal \
23907                 self.membros.len() — a length-drift would silently \
23908                 split the paired `HashSet<&str>` name-set seed's \
23909                 collect input from the pre-flight `.is_empty()` \
23910                 refusal probe input from the per-member validate \
23911                 loop's traversal input",
23912            );
23913        }
23914    }
23915
23916    #[test]
23917    fn validate_reads_through_lifted_membros_accessor() {
23918        // Three-consumer coherence pin: the
23919        // [`AplicacaoSpec::validate_membros`] pre-flight
23920        // `self.membros().is_empty()` refusal probe (which must trip
23921        // [`AplicacaoError::NoMembros`] when the accessor projects the
23922        // empty slice), the same method's per-member validate loop's
23923        // `for m in self.membros()` traversal (which must reach every
23924        // entry in the same order the accessor projects, so both the
23925        // per-entry empty-`:caixa` gate that trips
23926        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
23927        // detection `insert_first_seen` that trips
23928        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
23929        // projection), and the peer [`AplicacaoSpec::validate`]'s
23930        // `HashSet<&str>` name-set seed's
23931        // `self.membros().iter().map(Membro::nome).collect()` collect
23932        // input (which every `:contratos` `:de` / `:para` membership
23933        // lookup rejects an unknown name against) must all three key
23934        // off the lifted accessor, so any future rebrand on the typed
23935        // slot's reader shape lands at exactly one place. Pins the
23936        // three-site coherence by exercising each production consumer
23937        // end-to-end: (1) the `NoMembros` refusal under the empty
23938        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
23939        // second entry of a two-member cohort whose head is valid but
23940        // tail has an empty `:caixa` (which requires the loop to
23941        // reach the second entry through the accessor), and (3) the
23942        // `MembroDuplicate` refusal fires on the second entry of a
23943        // two-member cohort that shares a `:caixa` name (which
23944        // requires the loop to reach both entries through the
23945        // accessor for the dedup HashSet's second insert to collide).
23946        //
23947        // Peer of the sibling M2
23948        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23949        // (bc92bce) coherence pin on the per-`:supervisor` static-
23950        // child-list axis and the sibling M3
23951        // `validate_placement_reads_through_lifted_clusters_accessor`
23952        // (a6e18d7) coherence pin on the per-`:placement` distribution-
23953        // target-list axis — extends the slice-return-accessor
23954        // multi-consumer coherence discipline onto the outermost M3
23955        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
23956
23957        // (1) Pre-flight `.is_empty()` probe: the empty slice must
23958        // trip `NoMembros`.
23959        let mut spec = three_member_spec();
23960        spec.membros = Vec::new();
23961        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
23962        assert!(
23963            spec.membros().is_empty(),
23964            "the pre-flight refusal input must be the empty slice per \
23965             the accessor's projection",
23966        );
23967
23968        // (2) Per-member validate loop: a two-member cohort with an
23969        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
23970        // the tail — the loop must reach the second entry through
23971        // the accessor.
23972        let mut spec = three_member_spec();
23973        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
23974        assert_eq!(
23975            spec.validate().unwrap_err(),
23976            AplicacaoError::MembroCaixaEmpty,
23977        );
23978        assert_eq!(
23979            spec.membros().len(),
23980            2,
23981            "the per-member validate loop's traversal input must be \
23982             a two-element slice per the accessor's projection",
23983        );
23984
23985        // (3) Per-member validate loop: a two-member cohort that
23986        // shares a `:caixa` name must trip `MembroDuplicate` on the
23987        // second entry — the loop must reach both entries through the
23988        // accessor for the dedup HashSet's second insert to collide.
23989        let mut spec = three_member_spec();
23990        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
23991        match spec.validate().unwrap_err() {
23992            AplicacaoError::MembroDuplicate { caixa } => {
23993                assert_eq!(
23994                    caixa, "catalog",
23995                    "MembroDuplicate.caixa must carry the shared \
23996                     member name verbatim",
23997                );
23998            }
23999            other => panic!("expected MembroDuplicate, got {other:?}"),
24000        }
24001        assert_eq!(
24002            spec.membros().len(),
24003            2,
24004            "the per-member validate loop's traversal input must be \
24005             a two-element slice per the accessor's projection",
24006        );
24007    }
24008
24009    #[test]
24010    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
24011        // The canonical per-`:contratos` contract-list-slice-shape pin:
24012        // [`AplicacaoSpec::contratos`] must return the `:contratos`
24013        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
24014        // slice-view over the same backing buffer the raw
24015        // `self.contratos.as_slice()` field access borrows from, byte-
24016        // equal across every representative fixture in the accept-set —
24017        // the empty slice (the pre-validation "internal-only mesh" shape
24018        // an Aplicacao whose members exchange no typed edges renders
24019        // through), the singleton slice (the minimal one-edge Aplicacao
24020        // shape), and multi-entry cohorts (the peer multi-edge shapes
24021        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
24022        // of the application graph).
24023        //
24024        // Pins against a future silent detour that returned
24025        // `&Vec<WitContract>` (which would type-check but leak the
24026        // storage-side `Vec`'s grow/push/reserve surface no consumer of
24027        // the typed view reaches for), a fresh-allocated
24028        // `Vec<WitContract>` copy (which would type-check via a coercion
24029        // but silently break every downstream caller that relied on the
24030        // slice sharing the backing buffer's identity), or an out-of-
24031        // order or length-drifted projection (which would silently split
24032        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
24033        // seed's traversal input from the `detect_sync_cycles` per-edge
24034        // adjacency-list seed's traversal input from the
24035        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
24036        // BTreeMap grouping loop's traversal input from the
24037        // `feira app graph` per-contract print traversal's input).
24038        //
24039        // Peer of the immediately-adjacent sibling M3
24040        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
24041        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
24042        // node-list axis, the sibling M3
24043        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
24044        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
24045        // distribution-target-list axis, and the sibling M2
24046        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
24047        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
24048        // `:supervisor` static-child-list axis — extends the slice-
24049        // return-accessor byte-equal-projection discipline onto the
24050        // outermost M3 mesh-slot type's per-Aplicacao contract-list
24051        // `Vec`-carry axis, closing the last unlifted per-
24052        // `AplicacaoSpec` `Vec`-carry axis.
24053        let fixtures: Vec<Vec<WitContract>> = vec![
24054            Vec::new(),
24055            vec![contract_http("cart", "catalog", "/products/:id")],
24056            vec![
24057                contract_http("cart", "catalog", "/products/:id"),
24058                contract_http("cart", "payment", "/charge"),
24059            ],
24060            vec![
24061                contract_http("cart", "catalog", "/products/:id"),
24062                contract_http("cart", "payment", "/charge"),
24063                contract_http("payment", "catalog", "/audit"),
24064            ],
24065        ];
24066        for contratos in fixtures {
24067            let s = AplicacaoSpec {
24068                membros: vec![
24069                    membro("catalog", "^0.1"),
24070                    membro("cart", "^0.1"),
24071                    membro("payment", "^0.2"),
24072                ],
24073                contratos: contratos.clone(),
24074                politicas: MeshPolicy::default(),
24075                placement: Placement::default(),
24076                entrada: None,
24077            };
24078            assert_eq!(
24079                s.contratos(),
24080                contratos.as_slice(),
24081                "AplicacaoSpec::contratos must return :contratos verbatim \
24082                 (got {:?}, expected {:?})",
24083                s.contratos(),
24084                contratos.as_slice(),
24085            );
24086            assert_eq!(
24087                s.contratos(),
24088                s.contratos.as_slice(),
24089                "AplicacaoSpec::contratos accessor and \
24090                 .contratos.as_slice() field access must byte-equal — \
24091                 the accessor is the substrate-primitive typed dispatch \
24092                 every downstream contract-list consumer must route \
24093                 through",
24094            );
24095            assert_eq!(
24096                s.contratos().len(),
24097                s.contratos.len(),
24098                "AplicacaoSpec::contratos().len() must byte-equal \
24099                 self.contratos.len() — a length-drift would silently \
24100                 split the paired per-edge validate-loop's traversal \
24101                 input from the sync-cycle adjacency-list seed's \
24102                 traversal input from the cilium_network_policies \
24103                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
24104                 input from the `feira app graph` per-contract print \
24105                 traversal's input",
24106            );
24107        }
24108    }
24109
24110    #[test]
24111    fn validate_reads_through_lifted_contratos_accessor() {
24112        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
24113        // per-`:contratos` validate-loop's `for c in self.contratos()`
24114        // traversal (which must reach every entry in the same order the
24115        // accessor projects, so both the per-entry
24116        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
24117        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
24118        // dedup `HashSet` insert key off the accessor's projection),
24119        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
24120        // `for c in self.contratos()` adjacency-list seed (which drives
24121        // the sync-subgraph deadlock-detection gate via
24122        // [`AplicacaoError::SyncCycle`]), and the peer
24123        // [`caixa_mesh::cilium_network_policies`]'s
24124        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
24125        // grouping loop (which drives the per-CNP fan-out) must all
24126        // three key off the lifted accessor, so any future rebrand on
24127        // the typed slot's reader shape lands at exactly one place. Pins
24128        // the three-site coherence by exercising the two caixa-core
24129        // production consumers end-to-end: (1) the empty-`:contratos`
24130        // slice must validate without a per-edge diagnostic (the
24131        // per-edge loop is a no-op under the empty projection), (2) the
24132        // `ContratoMemberMissing` refusal fires on the second entry of a
24133        // two-edge cohort whose head references a valid member but tail
24134        // references a phantom name (which requires the loop to reach
24135        // the second entry through the accessor), and (3) the
24136        // `SyncCycle` refusal fires on a self-referential two-edge
24137        // cohort through the sync-cycle detector's peer projection
24138        // (which requires the detector to iterate the accessor's
24139        // projection to add the back-edge to its adjacency list).
24140        //
24141        // Peer of the sibling M3
24142        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24143        // three-consumer coherence pin on the per-`:membros` node-list
24144        // axis and the sibling M3
24145        // `validate_placement_reads_through_lifted_clusters_accessor`
24146        // (a6e18d7) coherence pin on the per-`:placement` distribution-
24147        // target-list axis — extends the slice-return-accessor multi-
24148        // consumer coherence discipline onto the outermost M3 mesh-slot
24149        // type's per-Aplicacao contract-list `Vec`-carry axis.
24150
24151        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
24152        // and no per-edge diagnostic surfaces. Validate succeeds on
24153        // the well-formed `:membros` head.
24154        let mut spec = three_member_spec();
24155        spec.contratos = Vec::new();
24156        assert!(
24157            spec.validate().is_ok(),
24158            "empty :contratos must validate — the per-edge loop is a \
24159             no-op under the accessor's empty projection",
24160        );
24161        assert!(
24162            spec.contratos().is_empty(),
24163            "the per-edge validate loop's traversal input must be the \
24164             empty slice per the accessor's projection",
24165        );
24166
24167        // (2) Per-edge validate loop: a two-edge cohort whose tail
24168        // references a phantom `:para` member must trip
24169        // `ContratoMemberMissing` on the tail — the loop must reach
24170        // the second entry through the accessor for the membership
24171        // lookup to fail on the phantom name.
24172        let mut spec = three_member_spec();
24173        spec.contratos = vec![
24174            contract_http("cart", "catalog", "/products/:id"),
24175            contract_http("cart", "phantom", "/x"),
24176        ];
24177        let err = spec.validate().unwrap_err();
24178        assert!(
24179            matches!(
24180                err,
24181                AplicacaoError::ContratoMemberMissing { ref caixa }
24182                    if caixa == "phantom"
24183            ),
24184            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
24185        );
24186        assert_eq!(
24187            spec.contratos().len(),
24188            2,
24189            "the per-edge validate loop's traversal input must be \
24190             a two-element slice per the accessor's projection",
24191        );
24192
24193        // (3) Sync-cycle detector: a two-edge synchronous cohort
24194        // whose second edge closes the sync-subgraph back onto the
24195        // first must trip [`AplicacaoError::ContratoCycle`] — the
24196        // detector must iterate the accessor's projection to add
24197        // both edges to its adjacency list, so a length-drift on
24198        // the accessor's projection would silently disagree with
24199        // the sync-cycle detector on which edge closes the loop.
24200        // Peer projection to the `validate` per-edge loop above:
24201        // the sync-cycle detector routes through the same lifted
24202        // accessor, so a rebrand of the reader shape lands at one
24203        // place. Uses a two-edge cohort (cart → catalog → cart)
24204        // because the per-edge `ContratoSelfLoop` gate fires before
24205        // the sync-cycle detector on a single self-referential edge
24206        // (`cart → cart`) — the cycle-detector's input must be a
24207        // multi-edge cohort for its per-edge traversal input to be
24208        // observably wider than the per-edge validate loop's input.
24209        let mut spec = three_member_spec();
24210        spec.contratos = vec![
24211            contract_http("cart", "catalog", "/products/:id"),
24212            contract_http("catalog", "cart", "/callback"),
24213        ];
24214        let err = spec.validate().unwrap_err();
24215        assert!(
24216            matches!(err, AplicacaoError::ContratoCycle { .. }),
24217            "expected ContratoCycle from the sync-cycle detector on a \
24218             two-edge back-edge cohort, got {err:?}",
24219        );
24220        assert_eq!(
24221            spec.contratos().len(),
24222            2,
24223            "the sync-cycle detector's traversal input must be a \
24224             two-element slice per the accessor's projection",
24225        );
24226    }
24227
24228    #[test]
24229    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
24230        // The canonical per-`:politicas` outer-composite-reference-shape
24231        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
24232        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
24233        // the same backing storage the raw `&self.politicas` field
24234        // access borrows from, byte-equal across every representative
24235        // fixture in the accept-set — the default `MeshPolicy` (the
24236        // author-empty "no policy on any axis" shape whose
24237        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
24238        // shapes carrying one axis at a time
24239        // (`{mtls_required, timeout, retries, circuit_breaker,
24240        // rate_limit}` — the minimal five-axis fan-out over the
24241        // per-axis lifted accessor family every downstream mesh-artifact
24242        // emitter dispatches on), and the multi-axis composite (the
24243        // canonical `three_member_spec` fixture's `{timeout, retries,
24244        // mtls_required}` triple — the load-bearing shape every
24245        // Aplicacao-scoped fixture in this suite constructs).
24246        //
24247        // Pins against a future silent detour that returned a fresh-
24248        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
24249        // impl but silently break every downstream caller that relied
24250        // on the reference sharing the composite's backing identity), a
24251        // reference to an operator-resolved overlay (the future
24252        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
24253        // acknowledges — its resolution must land at exactly this
24254        // accessor body, not silently divert the raw slot away from a
24255        // second consumer), or an axis-shuffled projection (a future
24256        // detour that swapped `timeout` and `retries` through the
24257        // accessor would silently split the paired `validate_politicas`
24258        // per-axis bracket-dispatch's traversal input from the peer
24259        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
24260        // emitter's fan-out input from the peer
24261        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
24262        // overlay emitter's fan-out input).
24263        //
24264        // Peer of the sibling M3
24265        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
24266        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
24267        // node-list `Vec`-carry axis and the sibling M3
24268        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
24269        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
24270        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
24271        // accessor byte-equal-projection discipline onto the outermost
24272        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
24273        // reference axis, the first `&Composite`-return accessor on the
24274        // outer [`AplicacaoSpec`] type.
24275        let fixtures: Vec<MeshPolicy> = vec![
24276            MeshPolicy::default(),
24277            MeshPolicy {
24278                mtls_required: Some(true),
24279                ..MeshPolicy::default()
24280            },
24281            MeshPolicy {
24282                mtls_required: Some(false),
24283                ..MeshPolicy::default()
24284            },
24285            MeshPolicy {
24286                timeout: Some(Duration::from_secs(30)),
24287                ..MeshPolicy::default()
24288            },
24289            MeshPolicy {
24290                retries: Some(3),
24291                ..MeshPolicy::default()
24292            },
24293            MeshPolicy {
24294                circuit_breaker: Some(CircuitBreaker {
24295                    max_failures: 5,
24296                    window: Duration::from_secs(30),
24297                }),
24298                ..MeshPolicy::default()
24299            },
24300            MeshPolicy {
24301                rate_limit: Some(RateLimit {
24302                    rate: 100,
24303                    window: Duration::from_secs(1),
24304                }),
24305                ..MeshPolicy::default()
24306            },
24307            MeshPolicy {
24308                timeout: Some(Duration::from_secs(30)),
24309                retries: Some(3),
24310                mtls_required: Some(true),
24311                ..MeshPolicy::default()
24312            },
24313        ];
24314        for politicas in fixtures {
24315            let s = AplicacaoSpec {
24316                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24317                contratos: Vec::new(),
24318                politicas: politicas.clone(),
24319                placement: Placement::default(),
24320                entrada: None,
24321            };
24322            assert_eq!(
24323                *s.politicas(),
24324                politicas,
24325                "AplicacaoSpec::politicas must return :politicas verbatim \
24326                 (got {:?}, expected {:?})",
24327                s.politicas(),
24328                politicas,
24329            );
24330            assert!(
24331                std::ptr::eq(s.politicas(), &s.politicas),
24332                "AplicacaoSpec::politicas accessor and &self.politicas \
24333                 field access must borrow the same backing storage — \
24334                 the accessor is the substrate-primitive typed dispatch \
24335                 every downstream mesh-policy composite consumer must \
24336                 route through, and a reference-identity split would \
24337                 silently break every consumer that relied on the \
24338                 borrow sharing the composite's storage",
24339            );
24340            assert_eq!(
24341                s.politicas().is_empty(),
24342                s.politicas.is_empty(),
24343                "AplicacaoSpec::politicas().is_empty() must byte-equal \
24344                 self.politicas.is_empty() — an emptiness-drift would \
24345                 silently split the paired `validate_politicas` \
24346                 per-axis bracket-dispatch's seed from the peer \
24347                 caixa-mesh CNP mTLS-overlay emitter's key from the \
24348                 peer caixa-mesh HTTPRoute timeout+retry overlay \
24349                 emitter's key",
24350            );
24351        }
24352    }
24353
24354    #[test]
24355    fn validate_politicas_reads_through_lifted_politicas_accessor() {
24356        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
24357        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
24358        // followed by the per-axis fan-out `p.timeout()` /
24359        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
24360        // the lifted axis-level accessor family) must key off the
24361        // lifted outer accessor, so any future rebrand on the typed
24362        // slot's outer-composite reader shape lands at exactly one
24363        // place. Pins the multi-axis coherence by exercising each
24364        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
24365        // a `Some(Duration::ZERO)` timeout under the outer accessor's
24366        // reference projection, (2) `PolicyRetriesZero` fires on a
24367        // `Some(0)` retries under the same projection, and (3) an
24368        // empty [`MeshPolicy::default`] passes `validate_politicas` —
24369        // the outer accessor's reference-projection reaches every
24370        // per-axis branch without silently short-circuiting any.
24371        //
24372        // Peer of the sibling M3
24373        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24374        // three-consumer coherence pin on the per-`:membros` node-list
24375        // axis and the sibling M3
24376        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24377        // three-consumer coherence pin on the per-`:contratos`
24378        // edge-list axis — extends the multi-consumer coherence
24379        // discipline onto the outermost M3 mesh-slot type's per-
24380        // Aplicacao mesh-policy composite-reference axis, the first
24381        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
24382        // type.
24383
24384        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
24385        // reference projection: a `Some(Duration::ZERO)` timeout must
24386        // trip the zero-floor gate. The bracket-dispatch's first arm
24387        // reads `p.timeout()` on the reference returned by the outer
24388        // accessor.
24389        let mut spec = three_member_spec();
24390        spec.politicas.timeout = Some(Duration::ZERO);
24391        spec.politicas.retries = None;
24392        spec.politicas.circuit_breaker = None;
24393        spec.politicas.rate_limit = None;
24394        assert_eq!(
24395            spec.validate().unwrap_err(),
24396            AplicacaoError::PolicyTimeoutZero,
24397        );
24398        assert!(
24399            std::ptr::eq(spec.politicas(), &spec.politicas),
24400            "the `validate_politicas` per-axis bracket-dispatch's \
24401             traversal input must be the same backing composite the \
24402             accessor's reference projection borrows from",
24403        );
24404
24405        // (2) `PolicyRetriesZero` refusal under the outer accessor's
24406        // reference projection: a `Some(0)` retries must trip the
24407        // zero-floor gate. The bracket-dispatch's second arm reads
24408        // `p.retries()` on the reference returned by the outer accessor.
24409        let mut spec = three_member_spec();
24410        spec.politicas.timeout = None;
24411        spec.politicas.retries = Some(0);
24412        spec.politicas.circuit_breaker = None;
24413        spec.politicas.rate_limit = None;
24414        assert_eq!(
24415            spec.validate().unwrap_err(),
24416            AplicacaoError::PolicyRetriesZero,
24417        );
24418
24419        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
24420        // — every per-axis arm short-circuits on `None`, so the outer
24421        // accessor's reference projection reaches the fall-through
24422        // `Ok(())` without any per-axis refusal firing.
24423        let mut spec = three_member_spec();
24424        spec.politicas = MeshPolicy::default();
24425        assert!(
24426            spec.validate().is_ok(),
24427            "an empty `MeshPolicy` must pass `validate_politicas` — \
24428             every per-axis arm short-circuits on `None` under the \
24429             outer accessor's reference projection",
24430        );
24431        assert!(
24432            spec.politicas().is_empty(),
24433            "the outer accessor's reference projection must be the \
24434             empty composite per the `MeshPolicy::default()` fixture",
24435        );
24436    }
24437
24438    #[test]
24439    #[allow(clippy::too_many_lines)]
24440    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
24441        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
24442        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
24443        // must both key off the lifted axis-level accessors
24444        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
24445        // the peer `:circuit-breaker` / `:rate-limit` arms already
24446        // routing through [`MeshPolicy::circuit_breaker`] /
24447        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
24448        // per axis on the substrate primitive" shape at the fan-out
24449        // (four axes, four accessors, no raw-field-access site
24450        // anywhere on the bracket-dispatch). Pins the per-axis
24451        // coherence at the accept-set boundaries the bracket carves:
24452        //   1. accessor byte-equal to raw field on every representative
24453        //      accept-set value (`None`, sub-cap, at-cap, past-cap
24454        //      sentinel) — a future accessor drift that no longer
24455        //      shipped the raw slot verbatim would surface here,
24456        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
24457        //      routed through the accessor's projection, proving the
24458        //      first arm reads through the accessor rather than a
24459        //      silent-detour peer-axis field access,
24460        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
24461        //      through the accessor's projection, proving the second
24462        //      arm reads through the accessor,
24463        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
24464        //      passes validate under the accessor projection (paired
24465        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
24466        //      sibling axis), pinning the upper-boundary accept-arm
24467        //      also routes through the accessor.
24468        //
24469        // Peer of the sibling M3
24470        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24471        // outer-composite-reference coherence pin (which asserts the
24472        // `let p = self.politicas()` seed); extends the discipline onto
24473        // the per-axis fan-out layer that consumes the seed's
24474        // reference. Same shape as
24475        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24476        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24477        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
24478        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
24479
24480        // (1) Accessor byte-equal to raw field on the `:timeout` axis
24481        // across the accept-set boundaries the bracket dispatch's
24482        // three-arm gate carves out
24483        // ([`crate::render::require_positive_canonical_bounded_duration`]
24484        // — zero-floor + canonical-form + upper-cap).
24485        for timeout in [
24486            None,
24487            Some(Duration::ZERO),
24488            Some(Duration::from_millis(1)),
24489            Some(POLICY_TIMEOUT_MAX),
24490        ] {
24491            let p = MeshPolicy {
24492                timeout,
24493                ..MeshPolicy::default()
24494            };
24495            assert_eq!(
24496                p.timeout(),
24497                p.timeout,
24498                "MeshPolicy::timeout accessor must byte-equal the raw \
24499                 .timeout field across every accept-set boundary the \
24500                 validate_politicas :timeout arm carves out — a drift \
24501                 here would silently split the validate bracket's arm \
24502                 from the peer caixa-mesh HTTPRoute timeout-overlay \
24503                 emitter's read",
24504            );
24505        }
24506
24507        // (2) Accessor byte-equal to raw field on the `:retries` axis
24508        // across the accept-set boundaries the bracket dispatch's
24509        // two-arm gate carves out
24510        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
24511        // + upper-cap).
24512        for retries in [
24513            None,
24514            Some(0u32),
24515            Some(1u32),
24516            Some(POLICY_RETRIES_MAX),
24517            Some(POLICY_RETRIES_MAX + 1),
24518            Some(u32::MAX),
24519        ] {
24520            let p = MeshPolicy {
24521                retries,
24522                ..MeshPolicy::default()
24523            };
24524            assert_eq!(
24525                p.retries(),
24526                p.retries,
24527                "MeshPolicy::retries accessor must byte-equal the raw \
24528                 .retries field across every accept-set boundary the \
24529                 validate_politicas :retries arm carves out — a drift \
24530                 here would silently split the validate bracket's arm \
24531                 from the peer caixa-mesh HTTPRoute retry-overlay \
24532                 emitter's read",
24533            );
24534        }
24535
24536        // (3) `PolicyTimeoutZero` fires on the accessor-projected
24537        // zero-floor boundary. A silent detour that no longer read
24538        // through `p.timeout()` (a peer-axis field read, an accidental
24539        // Option::and-then chain that collapsed the None arm to Some,
24540        // an accessor rebrand that clamped the return through the
24541        // upper cap) would fail to refuse here.
24542        let mut spec = three_member_spec();
24543        spec.politicas.timeout = Some(Duration::ZERO);
24544        spec.politicas.retries = None;
24545        spec.politicas.circuit_breaker = None;
24546        spec.politicas.rate_limit = None;
24547        assert_eq!(
24548            spec.politicas().timeout(),
24549            Some(Duration::ZERO),
24550            "the accessor projection must reflect the fixture's \
24551             `Some(Duration::ZERO)` :timeout verbatim",
24552        );
24553        assert_eq!(
24554            spec.validate().unwrap_err(),
24555            AplicacaoError::PolicyTimeoutZero,
24556            "the validate_politicas :timeout zero-floor arm must fire \
24557             through the lifted accessor's projection — a silent \
24558             detour to a peer-axis field would fail to refuse",
24559        );
24560
24561        // (4) `PolicyRetriesZero` fires on the accessor-projected
24562        // zero-floor boundary on the sibling `:retries` axis.
24563        let mut spec = three_member_spec();
24564        spec.politicas.timeout = None;
24565        spec.politicas.retries = Some(0);
24566        spec.politicas.circuit_breaker = None;
24567        spec.politicas.rate_limit = None;
24568        assert_eq!(
24569            spec.politicas().retries(),
24570            Some(0),
24571            "the accessor projection must reflect the fixture's \
24572             `Some(0)` :retries verbatim",
24573        );
24574        assert_eq!(
24575            spec.validate().unwrap_err(),
24576            AplicacaoError::PolicyRetriesZero,
24577            "the validate_politicas :retries zero-floor arm must fire \
24578             through the lifted accessor's projection — a silent \
24579             detour to a peer-axis field would fail to refuse",
24580        );
24581
24582        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
24583        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
24584        // must pass validate under the accessor projection — pins the
24585        // upper-boundary accept-arm also routes through the lifted
24586        // accessor (a drift that clamped or short-circuited at the
24587        // upper boundary would fail the whole-spec validate here).
24588        let mut spec = three_member_spec();
24589        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
24590        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
24591        spec.politicas.circuit_breaker = None;
24592        spec.politicas.rate_limit = None;
24593        assert_eq!(
24594            spec.politicas().timeout(),
24595            Some(POLICY_TIMEOUT_MAX),
24596            "the accessor projection must reflect the fixture's \
24597             at-cap :timeout verbatim",
24598        );
24599        assert_eq!(
24600            spec.politicas().retries(),
24601            Some(POLICY_RETRIES_MAX),
24602            "the accessor projection must reflect the fixture's \
24603             at-cap :retries verbatim",
24604        );
24605        assert!(
24606            spec.validate().is_ok(),
24607            "at-cap :timeout + :retries must pass validate under the \
24608             accessor projection — the upper-boundary accept-arm on \
24609             both axes routes through the lifted accessor",
24610        );
24611    }
24612
24613    #[test]
24614    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
24615        // The canonical per-`:placement` outer-composite-reference-shape
24616        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
24617        // typed `Placement` verbatim as a `&Placement` reference over the
24618        // same backing storage the raw `&self.placement` field access
24619        // borrows from, byte-equal across every representative fixture in
24620        // the accept-set — the default `Placement` (the substrate seed
24621        // shape whose [`PlacementStrategy::default`] evaluates to
24622        // `SingleNode` with an empty `:clusters` pool and both
24623        // optional-scalar axes `None`), and every canonical strategy /
24624        // cluster-pool / optional-scalar combination the
24625        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
24626        // three [`PlacementStrategy`] variants — `SingleNode`,
24627        // `Replicated`, `Sharded` — cross-projected with a non-empty
24628        // `:clusters` pool and, on the `Sharded` arm, a non-empty
24629        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
24630        // canonical `three_member_spec` `Replicated` fixture's
24631        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
24632        //
24633        // Pins against a future silent detour that returned a fresh-
24634        // cloned `Placement` copy (which would type-check via a `Clone`
24635        // impl but silently break every downstream caller that relied on
24636        // the reference sharing the composite's backing identity), a
24637        // reference to an operator-resolved overlay (the future per-
24638        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
24639        // acknowledges — its resolution must land at exactly this
24640        // accessor body, not silently divert the raw slot away from a
24641        // second consumer), or an axis-shuffled projection (a future
24642        // detour that swapped `clusters` and `affinity` through the
24643        // accessor would silently split the paired `validate_placement`
24644        // per-axis bracket-dispatch's traversal input from the peer
24645        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
24646        // programs.yaml distribution-annotation emitter's fan-out input
24647        // from the peer `feira app graph` per-Aplicacao print line's
24648        // input).
24649        //
24650        // Peer of the sibling M3
24651        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24652        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
24653        // outer mesh-policy composite-reference axis, and of the sibling
24654        // slice-return `aplicacao_spec_membros_returns_membros_slice_
24655        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
24656        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
24657        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
24658        // the outer-accessor byte-equal-projection discipline onto the
24659        // outermost M3 mesh-slot type's per-Aplicacao distribution
24660        // composite-reference axis, the second `&Composite`-return
24661        // accessor on the outer [`AplicacaoSpec`] type.
24662        let fixtures: Vec<Placement> = vec![
24663            Placement::default(),
24664            Placement {
24665                estrategia: PlacementStrategy::SingleNode,
24666                clusters: vec!["rio".into()],
24667                affinity: None,
24668                shard_key: None,
24669            },
24670            Placement {
24671                estrategia: PlacementStrategy::Replicated,
24672                clusters: vec!["rio".into(), "mar".into()],
24673                affinity: None,
24674                shard_key: None,
24675            },
24676            Placement {
24677                estrategia: PlacementStrategy::Replicated,
24678                clusters: vec!["rio".into(), "mar".into()],
24679                affinity: Some("data-locality".into()),
24680                shard_key: None,
24681            },
24682            Placement {
24683                estrategia: PlacementStrategy::Sharded,
24684                clusters: vec!["rio".into(), "mar".into()],
24685                affinity: None,
24686                shard_key: Some("tenantId".into()),
24687            },
24688            Placement {
24689                estrategia: PlacementStrategy::Sharded,
24690                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
24691                affinity: Some("low-latency".into()),
24692                shard_key: Some("metadata.tenantId".into()),
24693            },
24694        ];
24695        for placement in fixtures {
24696            let s = AplicacaoSpec {
24697                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24698                contratos: Vec::new(),
24699                politicas: MeshPolicy::default(),
24700                placement: placement.clone(),
24701                entrada: None,
24702            };
24703            assert_eq!(
24704                *s.placement(),
24705                placement,
24706                "AplicacaoSpec::placement must return :placement verbatim \
24707                 (got {:?}, expected {:?})",
24708                s.placement(),
24709                placement,
24710            );
24711            assert!(
24712                std::ptr::eq(s.placement(), &s.placement),
24713                "AplicacaoSpec::placement accessor and &self.placement \
24714                 field access must borrow the same backing storage — the \
24715                 accessor is the substrate-primitive typed dispatch every \
24716                 downstream distribution-composite consumer must route \
24717                 through, and a reference-identity split would silently \
24718                 break every consumer that relied on the borrow sharing \
24719                 the composite's storage",
24720            );
24721            assert_eq!(
24722                s.placement().estrategia(),
24723                s.placement.estrategia,
24724                "AplicacaoSpec::placement().estrategia() must byte-equal \
24725                 self.placement.estrategia — a strategy-drift would \
24726                 silently split the paired `validate_placement` \
24727                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
24728                 peer caixa-mesh programs.yaml `placement.estrategia` \
24729                 emitter's key from the peer `feira app graph` printer's \
24730                 strategy label",
24731            );
24732            assert_eq!(
24733                s.placement().clusters(),
24734                s.placement.clusters.as_slice(),
24735                "AplicacaoSpec::placement().clusters() must byte-equal \
24736                 self.placement.clusters — a cluster-pool drift would \
24737                 silently split the paired `validate_placement` \
24738                 pre-flight `.is_empty()` refusal probe's traversal from \
24739                 the peer caixa-mesh programs.yaml `placement.clusters` \
24740                 emitter's fan-out from the peer `feira app graph` \
24741                 printer's cluster list",
24742            );
24743        }
24744    }
24745
24746    #[test]
24747    fn validate_placement_reads_through_lifted_placement_accessor() {
24748        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
24749        // per-axis bracket-dispatch seed (`let p = self.placement();`,
24750        // followed by the per-axis fan-out `p.clusters()` /
24751        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
24752        // lifted axis-level accessor family) must key off the lifted
24753        // outer accessor, so any future rebrand on the typed slot's
24754        // outer-composite reader shape lands at exactly one place. Pins
24755        // the multi-axis coherence by exercising each per-axis refusal
24756        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
24757        // `:clusters` pool under the outer accessor's reference
24758        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
24759        // strategy with a `None` `:shard-key` under the same projection,
24760        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
24761        // with a `Some` `:shard-key` under the same projection, and
24762        // (4) the canonical `three_member_spec` `Replicated` fixture
24763        // passes `validate_placement` under the outer accessor's
24764        // reference projection — the accessor's reference-projection
24765        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
24766        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
24767        // without silently short-circuiting any.
24768        //
24769        // Peer of the sibling M3
24770        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24771        // (534dc21) multi-axis coherence pin on the per-`:politicas`
24772        // outer mesh-policy composite-reference axis — extends the
24773        // multi-consumer coherence discipline onto the outermost M3
24774        // mesh-slot type's per-Aplicacao distribution composite-
24775        // reference axis, the second `&Composite`-return accessor on
24776        // the outer [`AplicacaoSpec`] type.
24777
24778        // (1) `PlacementWithoutClusters` refusal under the outer
24779        // accessor's reference projection: an empty `:clusters` pool
24780        // must trip the pre-flight refusal probe. The bracket-dispatch's
24781        // first arm reads `p.clusters()` on the reference returned by
24782        // the outer accessor.
24783        let mut spec = three_member_spec();
24784        spec.placement.clusters = Vec::new();
24785        assert_eq!(
24786            spec.validate().unwrap_err(),
24787            AplicacaoError::PlacementWithoutClusters {
24788                estrategia: PlacementStrategy::Replicated,
24789            },
24790        );
24791        assert!(
24792            std::ptr::eq(spec.placement(), &spec.placement),
24793            "the `validate_placement` per-axis bracket-dispatch's \
24794             traversal input must be the same backing composite the \
24795             accessor's reference projection borrows from",
24796        );
24797
24798        // (2) `ShardedWithoutKey` refusal under the outer accessor's
24799        // reference projection: a `Sharded` strategy with a `None`
24800        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
24801        // The bracket-dispatch's third arm reads `p.estrategia()` for
24802        // the match scrutinee then `p.shard_key()` for the cascade
24803        // scrutinee, both on the reference returned by the outer
24804        // accessor.
24805        let mut spec = three_member_spec();
24806        spec.placement.estrategia = PlacementStrategy::Sharded;
24807        spec.placement.shard_key = None;
24808        assert_eq!(
24809            spec.validate().unwrap_err(),
24810            AplicacaoError::ShardedWithoutKey,
24811        );
24812
24813        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
24814        // reference projection: a non-`Sharded` strategy with a `Some`
24815        // `:shard-key` must trip the declared-but-inert refusal. The
24816        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
24817        // + `p.estrategia()` for the diagnostic on the reference
24818        // returned by the outer accessor.
24819        let mut spec = three_member_spec();
24820        spec.placement.estrategia = PlacementStrategy::Replicated;
24821        spec.placement.shard_key = Some("tenantId".into());
24822        assert_eq!(
24823            spec.validate().unwrap_err(),
24824            AplicacaoError::ShardKeyOnNonSharded {
24825                estrategia: PlacementStrategy::Replicated,
24826                shard_key: "tenantId".into(),
24827            },
24828        );
24829
24830        // (4) Canonical `three_member_spec` `Replicated` fixture passes
24831        // `validate_placement` — every per-axis arm reaches the fall-
24832        // through `Ok(())` without any per-axis refusal firing under the
24833        // outer accessor's reference projection.
24834        let spec = three_member_spec();
24835        assert!(
24836            spec.validate().is_ok(),
24837            "the canonical Replicated placement fixture must pass \
24838             `validate_placement` — every per-axis arm short-circuits on \
24839             valid input under the outer accessor's reference projection",
24840        );
24841        assert_eq!(
24842            spec.placement().estrategia(),
24843            PlacementStrategy::Replicated,
24844            "the outer accessor's reference projection must be the \
24845             canonical Replicated fixture's strategy",
24846        );
24847        assert_eq!(
24848            spec.placement().clusters(),
24849            &["rio", "mar"],
24850            "the outer accessor's reference projection must be the \
24851             canonical Replicated fixture's cluster pool",
24852        );
24853    }
24854
24855    #[test]
24856    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
24857        // The canonical per-`:entrada` outer-composite-optional-
24858        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
24859        // the `:entrada` typed `Option<Entrada>` verbatim as an
24860        // `Option<&Entrada>` reference over the same backing storage
24861        // the raw `self.entrada.as_ref()` field access borrows from,
24862        // byte-equal across every representative fixture in the
24863        // accept-set — the author-omitted `None` shape (the
24864        // "internal-only mesh" partition every downstream external-
24865        // gateway emitter treats as "emit nothing"), the minimal
24866        // singleton `:entrada` composite (host + destination + empty
24867        // paths + default port), the paths-carrying composite (the
24868        // canonical `three_member_spec` fixture's ["/api" "/health"]
24869        // path-list shape every HTTPRoute per-rule fan-out emitter
24870        // reads), and the non-default port composite (the canonical
24871        // custom-port shape the port-fallback resolver reads).
24872        //
24873        // Pins against a future silent detour that returned a fresh-
24874        // cloned `Entrada` copy (which would type-check via a `Clone`
24875        // impl but silently break every downstream caller that
24876        // relied on the reference sharing the composite's backing
24877        // identity), a reference to an operator-resolved overlay
24878        // (the future per-cluster `:entrada-overrides` slot the
24879        // MESH-COMPOSITION §V federation roadmap acknowledges — its
24880        // resolution must land at exactly this accessor body, not
24881        // silently divert the raw slot away from a second consumer),
24882        // a `None` → `Some(Entrada::default)` cluster-default
24883        // projection (which would collapse the load-bearing
24884        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
24885        // the peer `gateway_routes` early-return + `feira app graph`
24886        // internal-only-mesh partition both read), or an axis-
24887        // shuffled projection (a future detour that swapped
24888        // `host` and `para` through the accessor would silently
24889        // split the paired `validate` per-`:entrada` shape-and-
24890        // membership gate's traversal input from the peer
24891        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
24892        // fan-out input from the peer `feira app graph` external-
24893        // gateway summary line).
24894        //
24895        // Peer of the sibling M3
24896        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24897        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
24898        // `:politicas` outer mesh-policy composite-reference axis
24899        // and of the sibling M3
24900        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
24901        // (9abb8f0) `&Placement` byte-equal pin on the per-
24902        // `:placement` outer distribution-composite composite-
24903        // reference axis — extends the outer-accessor byte-equal-
24904        // projection discipline onto the last unlifted outermost M3
24905        // mesh-slot type's per-Aplicacao external-gateway composite-
24906        // reference axis, the third and final `&Composite`-return
24907        // accessor on the outer [`AplicacaoSpec`] type.
24908        let fixtures: Vec<Option<Entrada>> = vec![
24909            None,
24910            Some(Entrada {
24911                host: "checkout.quero.cloud".into(),
24912                para: "cart".into(),
24913                paths: Vec::new(),
24914                port: DEFAULT_SERVICO_PORT,
24915            }),
24916            Some(Entrada {
24917                host: "checkout.quero.cloud".into(),
24918                para: "cart".into(),
24919                paths: vec!["/api".into(), "/health".into()],
24920                port: DEFAULT_SERVICO_PORT,
24921            }),
24922            Some(Entrada {
24923                host: "checkout.quero.cloud".into(),
24924                para: "cart".into(),
24925                paths: vec!["/api".into()],
24926                port: 9443,
24927            }),
24928        ];
24929        for entrada in fixtures {
24930            let s = AplicacaoSpec {
24931                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24932                contratos: Vec::new(),
24933                politicas: MeshPolicy::default(),
24934                placement: Placement::default(),
24935                entrada: entrada.clone(),
24936            };
24937            assert_eq!(
24938                s.entrada(),
24939                entrada.as_ref(),
24940                "AplicacaoSpec::entrada must return :entrada verbatim \
24941                 (got {:?}, expected {:?})",
24942                s.entrada(),
24943                entrada.as_ref(),
24944            );
24945            match (s.entrada(), s.entrada.as_ref()) {
24946                (Some(a), Some(b)) => assert!(
24947                    std::ptr::eq(a, b),
24948                    "AplicacaoSpec::entrada accessor and \
24949                     self.entrada.as_ref() field access must borrow \
24950                     the same backing storage — the accessor is the \
24951                     substrate-primitive typed dispatch every \
24952                     downstream external-gateway composite consumer \
24953                     must route through, and a reference-identity \
24954                     split would silently break every consumer that \
24955                     relied on the borrow sharing the composite's \
24956                     storage",
24957                ),
24958                (None, None) => {}
24959                _ => panic!(
24960                    "AplicacaoSpec::entrada presence bit must byte-\
24961                     equal self.entrada.is_some() — a presence-bit \
24962                     drift would silently split the paired `validate` \
24963                     per-`:entrada` shape-and-membership gate's \
24964                     traversal head from the peer \
24965                     caixa-mesh gateway_routes early-return partition \
24966                     from the peer `feira app graph` internal-only-\
24967                     mesh partition",
24968                ),
24969            }
24970            assert_eq!(
24971                s.entrada().is_some(),
24972                s.entrada.is_some(),
24973                "AplicacaoSpec::entrada().is_some() must byte-equal \
24974                 self.entrada.is_some() — a presence-bit drift would \
24975                 silently split every downstream `Option<&Entrada>` \
24976                 consumer's partition on the internal-only-mesh arm",
24977            );
24978        }
24979    }
24980
24981    #[test]
24982    fn validate_reads_through_lifted_entrada_accessor() {
24983        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
24984        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
24985        // self.entrada() { … }`, followed by the per-axis fan-out
24986        // `validate_entrada_para(&e.para)` /
24987        // `EntradaMemberMissing` membership lookup /
24988        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
24989        // per-`e.paths` `validate_entrada_path` traversal) must key
24990        // off the lifted outer accessor, so any future rebrand on
24991        // the typed slot's outer-composite reader shape lands at
24992        // exactly one place. Pins the multi-axis coherence by
24993        // exercising each per-axis refusal end-to-end: (1) the
24994        // author-omitted `None` shape short-circuits past every
24995        // per-`:entrada` refusal (the internal-only mesh partition
24996        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
24997        // fires on a well-shaped but phantom `:para` under the outer
24998        // accessor's reference projection, and (3) the canonical
24999        // `three_member_spec` `:entrada` fixture passes `validate`
25000        // under the outer accessor's reference projection.
25001        //
25002        // Peer of the sibling M3
25003        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
25004        // (534dc21) multi-axis coherence pin on the per-`:politicas`
25005        // outer mesh-policy composite-reference axis and the sibling
25006        // M3
25007        // [`validate_placement_reads_through_lifted_placement_accessor`]
25008        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
25009        // outer distribution-composite composite-reference axis —
25010        // extends the multi-consumer coherence discipline onto the
25011        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
25012        // external-gateway composite-reference axis, the third and
25013        // final `&Composite`-return accessor on the outer
25014        // [`AplicacaoSpec`] type.
25015
25016        // (1) `None` :entrada — the internal-only-mesh partition
25017        // short-circuits past every per-`:entrada` refusal. The outer
25018        // accessor's reference projection reaches the fall-through
25019        // `Ok(())` on the `None` arm without any per-axis refusal
25020        // firing.
25021        let mut spec = three_member_spec();
25022        spec.entrada = None;
25023        assert!(
25024            spec.validate().is_ok(),
25025            "an author-omitted `:entrada` must pass `validate` — the \
25026             internal-only-mesh partition short-circuits past every \
25027             per-`:entrada` refusal under the outer accessor's \
25028             reference projection",
25029        );
25030        assert!(
25031            spec.entrada().is_none(),
25032            "the outer accessor's reference projection must name the \
25033             internal-only-mesh partition per the `None` fixture",
25034        );
25035
25036        // (2) `EntradaMemberMissing` refusal under the outer accessor's
25037        // reference projection: a well-shaped but phantom `:para` must
25038        // trip the membership-lookup refusal. The gate's second arm
25039        // reads `e.para` on the reference returned by the outer
25040        // accessor.
25041        let mut spec = three_member_spec();
25042        if let Some(e) = spec.entrada.as_mut() {
25043            e.para = "phantom".into();
25044        }
25045        assert_eq!(
25046            spec.validate().unwrap_err(),
25047            AplicacaoError::EntradaMemberMissing {
25048                para: "phantom".into(),
25049            },
25050        );
25051        match (spec.entrada(), spec.entrada.as_ref()) {
25052            (Some(a), Some(b)) => assert!(
25053                std::ptr::eq(a, b),
25054                "the `validate` per-`:entrada` gate's traversal head \
25055                 must be the same backing composite the accessor's \
25056                 reference projection borrows from",
25057            ),
25058            _ => panic!("fixture must carry Some(:entrada)"),
25059        }
25060
25061        // (3) Canonical `three_member_spec` `:entrada` fixture passes
25062        // `validate` — every per-axis arm reaches the fall-through
25063        // `Ok(())` without any per-axis refusal firing under the
25064        // outer accessor's reference projection.
25065        let spec = three_member_spec();
25066        assert!(
25067            spec.validate().is_ok(),
25068            "the canonical `:entrada` fixture must pass `validate` — \
25069             every per-axis arm short-circuits on valid input under \
25070             the outer accessor's reference projection",
25071        );
25072        assert!(
25073            spec.entrada().is_some(),
25074            "the outer accessor's reference projection must be the \
25075             canonical `:entrada` fixture's composite",
25076        );
25077    }
25078
25079    #[test]
25080    fn port_for_destination_reads_through_lifted_entrada_accessor() {
25081        // Peer coherence pin: the
25082        // [`AplicacaoSpec::port_for_destination`] per-destination
25083        // L4-port fallback resolver's composite-projection seed
25084        // (`self.entrada().filter(…).map_or(…)`) must key off the
25085        // lifted outer accessor. Pins the coherence by exercising
25086        // the resolver end-to-end: (1) the `None` `:entrada` shape
25087        // falls through to `DEFAULT_SERVICO_PORT` under the outer
25088        // accessor's reference projection, (2) a non-matching
25089        // destination falls through to `DEFAULT_SERVICO_PORT` under
25090        // the outer accessor's reference projection, and (3) the
25091        // matching destination resolves to the `:entrada :port`
25092        // value under the outer accessor's reference projection.
25093        //
25094        // Peer of the sibling
25095        // [`validate_reads_through_lifted_entrada_accessor`] multi-
25096        // consumer coherence pin on the same per-`:entrada` outer-
25097        // composite axis — extends the multi-consumer coherence
25098        // discipline onto the second per-`:entrada` production
25099        // consumer, the L4-port fallback resolver.
25100
25101        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
25102        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
25103        // arm under the outer accessor's reference projection.
25104        let mut spec = three_member_spec();
25105        spec.entrada = None;
25106        assert_eq!(
25107            spec.port_for_destination("cart"),
25108            DEFAULT_SERVICO_PORT,
25109            "the port-fallback resolver must fall through to \
25110             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
25111             under the outer accessor's reference projection",
25112        );
25113
25114        // (2) Non-matching destination — the resolver's `filter(…)`
25115        // arm rejects a mismatched destination and falls through
25116        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
25117        // reference projection.
25118        let mut spec = three_member_spec();
25119        if let Some(e) = spec.entrada.as_mut() {
25120            e.para = "cart".into();
25121            e.port = 9443;
25122        }
25123        assert_eq!(
25124            spec.port_for_destination("catalog"),
25125            DEFAULT_SERVICO_PORT,
25126            "the port-fallback resolver must fall through to \
25127             DEFAULT_SERVICO_PORT on a non-matching destination \
25128             under the outer accessor's reference projection",
25129        );
25130
25131        // (3) Matching destination — the resolver's `map_or(…)` arm
25132        // returns the `:entrada :port` value under the outer
25133        // accessor's reference projection.
25134        let mut spec = three_member_spec();
25135        if let Some(e) = spec.entrada.as_mut() {
25136            e.para = "cart".into();
25137            e.port = 9443;
25138        }
25139        assert_eq!(
25140            spec.port_for_destination("cart"),
25141            9443,
25142            "the port-fallback resolver must return the \
25143             `:entrada :port` value on a matching destination \
25144             under the outer accessor's reference projection",
25145        );
25146    }
25147
25148    #[test]
25149    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
25150        // The canonical per-`:politicas` `:mtls-required` mTLS-
25151        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
25152        // must return the `:politicas :mtls-required` typed bool
25153        // verbatim as an `Option<bool>`, byte-equal to the raw field
25154        // access across every value in the three-way accept-set —
25155        // `None` (cluster default applies), `Some(true)` (mTLS
25156        // handshake enforced — the sandboxing-by-default arm the
25157        // MeshPolicy's docstring names), `Some(false)` (handshake
25158        // skipped — the explicit debug-edge opt-out).
25159        //
25160        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
25161        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
25162        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
25163        // shape — first `Option<Copy-T>`-return accessor on the M3
25164        // mesh-slot family. Pins against a future silent detour that
25165        // re-derived the toggle from a peer axis (an accidental
25166        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
25167        // whenever a breaker is set), a `None` → `Some(false)` cluster-
25168        // default projection (the canonical `Option<bool>` → `bool`
25169        // collapse footgun the surrounding `is_empty()` predicate
25170        // guards on the peer emptiness axis), or a `Some(true)` /
25171        // `Some(false)` variant swap that landed on one consumer
25172        // without the other.
25173        for required in [None, Some(true), Some(false)] {
25174            let p = MeshPolicy {
25175                mtls_required: required,
25176                ..MeshPolicy::default()
25177            };
25178            assert_eq!(
25179                p.mtls_required(),
25180                required,
25181                "MeshPolicy::mtls_required must return :politicas \
25182                 :mtls-required verbatim (got {:?}, expected {required:?})",
25183                p.mtls_required(),
25184            );
25185            assert_eq!(
25186                p.mtls_required(),
25187                p.mtls_required,
25188                "MeshPolicy::mtls_required must byte-equal the raw \
25189                 .mtls_required field access across every value in the \
25190                 three-way accept-set",
25191            );
25192        }
25193    }
25194
25195    #[test]
25196    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
25197        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
25198        // arm must key off [`MeshPolicy::mtls_required`], not the raw
25199        // `.mtls_required` field access. Structurally: toggling ONLY
25200        // the `mtls_required` slot on an otherwise-default MeshPolicy
25201        // must flip `is_empty()` from `true` (all-`None`) to `false`
25202        // (one axis carries a value); the flip must be observed for
25203        // both `Some(true)` and `Some(false)` since the emptiness
25204        // semantic reads "any axis carries a value" — not "any axis
25205        // carries a truthy value" — the same non-collapsing shape the
25206        // sibling M2 [`crate::LimitsSpec::is_empty`] /
25207        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
25208        // peer `Option<T>`-typed slot surfaces.
25209        //
25210        // Pins against a future silent detour that re-derived the
25211        // emptiness predicate off a peer axis (an accidental
25212        // `.rate_limit.is_none()`-only chain that dropped the
25213        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
25214        // collapse to a truthy-only check (which would silently
25215        // classify `Some(false)` as empty), or an accessor-side
25216        // detour that no longer names the substrate-primitive typed
25217        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
25218        // == false` fallback in the accessor that would silently
25219        // classify both `None` and `Some(false)` as the same value).
25220        //
25221        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
25222        // (7cd2a28) accessor-composition pin on the sibling optional-
25223        // scalar axis — same "the emptiness / shape-gate predicate
25224        // must route through the substrate-primitive typed dispatch"
25225        // discipline extended onto the peer per-`:politicas` emptiness
25226        // predicate.
25227        let empty = MeshPolicy::default();
25228        assert!(
25229            empty.is_empty(),
25230            "MeshPolicy::default() must be is_empty() — every axis \
25231             defaults to None",
25232        );
25233        for required in [Some(true), Some(false)] {
25234            let p = MeshPolicy {
25235                mtls_required: required,
25236                ..MeshPolicy::default()
25237            };
25238            assert!(
25239                !p.is_empty(),
25240                "MeshPolicy::is_empty must return false when \
25241                 :mtls-required is {required:?} — the emptiness \
25242                 predicate reads \"any axis carries a value\", not \
25243                 \"any axis carries a truthy value\"",
25244            );
25245            assert_eq!(
25246                p.mtls_required().is_none(),
25247                p.is_empty(),
25248                "when :mtls-required is the only set axis, \
25249                 is_empty() must equal mtls_required().is_none() — \
25250                 the accessor and the emptiness predicate must \
25251                 route through the same substrate-primitive typed \
25252                 dispatch on the :mtls-required arm",
25253            );
25254        }
25255    }
25256
25257    #[test]
25258    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
25259        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
25260        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
25261        // accessor must return by value, not by reference. Peer of the
25262        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
25263        // borrow-invariant pin on the sibling `Option<String>` slot,
25264        // but extended onto the peer `Option<bool>` copy-invariant
25265        // shape — the accessor's returned `Option<bool>` must outlive
25266        // `&self` (multiple calls must return equal values from a
25267        // dropped-`&self` copy, since the returned Option carries no
25268        // borrow), and calling the accessor twice on the same
25269        // MeshPolicy must yield the same `Option<bool>` verbatim
25270        // (idempotent, no side effects on `&self`).
25271        //
25272        // Pins against a future silent detour that returned
25273        // `Option<&bool>` (which would type-check but silently break
25274        // every downstream caller — [`single_field_overlay`]'s first
25275        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
25276        // detached copy at the call site), an accidental
25277        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
25278        // would also type-check but return `Option<&bool>`), or a
25279        // one-arm-only accessor that reads `Some(*b)` in the Some arm
25280        // but reads a fresh Default::default() in the None arm.
25281        for required in [None, Some(true), Some(false)] {
25282            let p = MeshPolicy {
25283                mtls_required: required,
25284                ..MeshPolicy::default()
25285            };
25286            let first = p.mtls_required();
25287            let second = p.mtls_required();
25288            assert_eq!(
25289                first, second,
25290                "MeshPolicy::mtls_required must be idempotent — two \
25291                 successive calls on the same &self must return the \
25292                 same Option<bool>",
25293            );
25294            assert_eq!(
25295                first, required,
25296                "MeshPolicy::mtls_required must return :politicas \
25297                 :mtls-required verbatim by copy — got {first:?}, \
25298                 expected {required:?}",
25299            );
25300        }
25301    }
25302
25303    #[test]
25304    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
25305        // The canonical per-`:politicas` `:retries` transient-failure-
25306        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
25307        // the `:politicas :retries` typed `u32` verbatim as an
25308        // `Option<u32>`, byte-equal to the raw field access across every
25309        // representative value in the accept-set — `None` (cluster
25310        // default applies — typically "no retries beyond a single
25311        // dispatch attempt" the caixa-mesh `retry_overlay` builder
25312        // documents), `Some(1)` (the lower boundary of the
25313        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
25314        // `AplicacaoSpec::validate_politicas` gate carves out on the
25315        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
25316        // (the upper boundary the same gate carves out on the sibling
25317        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
25318        // past-the-guard sentinel that pins the accessor doesn't perform
25319        // a silent bounds-collapse at the return path).
25320        //
25321        // Sibling of the peer per-`:politicas`
25322        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
25323        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
25324        // peer per-`:politicas` `Option<u32>` shape — second
25325        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
25326        // Pins against a future silent detour that re-derived the retry
25327        // cap from a peer axis (an accidental `.circuit_breaker
25328        // .as_ref().map(|b| b.max_failures)` collapse that read the
25329        // breaker's max-failure count as a retry budget), a
25330        // `None → Some(0)` cluster-default projection (which would
25331        // silently re-introduce the `PolicyRetriesZero` refusal case at
25332        // the emit boundary), or a bounds-collapsing accessor that
25333        // clamped the return through `POLICY_RETRIES_MAX` (the
25334        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25335        // must ship the raw slot verbatim so a validate-time gate
25336        // regression surfaces at the emit boundary rather than being
25337        // silently absorbed).
25338        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
25339            let p = MeshPolicy {
25340                retries,
25341                ..MeshPolicy::default()
25342            };
25343            assert_eq!(
25344                p.retries(),
25345                retries,
25346                "MeshPolicy::retries must return :politicas :retries \
25347                 verbatim (got {:?}, expected {retries:?})",
25348                p.retries(),
25349            );
25350            assert_eq!(
25351                p.retries(),
25352                p.retries,
25353                "MeshPolicy::retries must byte-equal the raw .retries \
25354                 field access across every value in the accept-set",
25355            );
25356        }
25357    }
25358
25359    #[test]
25360    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
25361        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
25362        // must key off [`MeshPolicy::retries`], not the raw `.retries`
25363        // field access. Structurally: toggling ONLY the `retries` slot
25364        // on an otherwise-default MeshPolicy must flip `is_empty()`
25365        // from `true` (all-`None`) to `false` (one axis carries a
25366        // value); the flip must be observed for every value in the
25367        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25368        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
25369        // the emptiness semantic reads "any axis carries a value" —
25370        // not "any axis carries a value the validate gate accepts" —
25371        // the same non-collapsing shape the peer M2
25372        // [`crate::LimitsSpec::is_empty`] /
25373        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25374        //
25375        // Pins against a future silent detour that re-derived the
25376        // emptiness predicate off a peer axis (an accidental
25377        // `.rate_limit.is_none()`-only chain that dropped the
25378        // `retries` arm entirely), a `retries == Some(_)` collapse
25379        // that key-off a validate-gate-clamped bounds check (which
25380        // would silently classify a past-the-guard `Some(u32::MAX)`
25381        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
25382        // check), or an accessor-side detour that no longer names the
25383        // substrate-primitive typed dispatch.
25384        //
25385        // Sibling of the peer per-`:politicas`
25386        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
25387        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
25388        // same "the emptiness predicate must route through the
25389        // substrate-primitive typed dispatch" discipline extended onto
25390        // the peer per-`:politicas` `Option<u32>` axis.
25391        let empty = MeshPolicy::default();
25392        assert!(
25393            empty.is_empty(),
25394            "MeshPolicy::default() must be is_empty() — every axis \
25395             defaults to None",
25396        );
25397        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
25398            let p = MeshPolicy {
25399                retries,
25400                ..MeshPolicy::default()
25401            };
25402            assert!(
25403                !p.is_empty(),
25404                "MeshPolicy::is_empty must return false when \
25405                 :retries is {retries:?} — the emptiness \
25406                 predicate reads \"any axis carries a value\", not \
25407                 \"any axis carries a value the validate gate \
25408                 accepts\"",
25409            );
25410            assert_eq!(
25411                p.retries().is_none(),
25412                p.is_empty(),
25413                "when :retries is the only set axis, is_empty() \
25414                 must equal retries().is_none() — the accessor and \
25415                 the emptiness predicate must route through the same \
25416                 substrate-primitive typed dispatch on the :retries \
25417                 arm",
25418            );
25419        }
25420    }
25421
25422    #[test]
25423    fn mesh_policy_retries_projects_option_u32_by_copy() {
25424        // The by-copy pin: [`MeshPolicy::retries`] returns
25425        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
25426        // accessor must return by value, not by reference. Sibling of
25427        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
25428        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
25429        // extended onto the sibling `Option<u32>` copy-invariant
25430        // shape — the accessor's returned `Option<u32>` must outlive
25431        // `&self` (multiple calls must return equal values from a
25432        // dropped-`&self` copy, since the returned Option carries no
25433        // borrow), and calling the accessor twice on the same
25434        // MeshPolicy must yield the same `Option<u32>` verbatim
25435        // (idempotent, no side effects on `&self`).
25436        //
25437        // Pins against a future silent detour that returned
25438        // `Option<&u32>` (which would type-check but silently break
25439        // every downstream caller — [`crate::render::single_field_overlay`]'s
25440        // first parameter is `Option<T: Clone>`, and `&u32` would
25441        // fold to a detached copy at the call site), an accidental
25442        // `Option::as_ref()` projection (`self.retries.as_ref()` would
25443        // also type-check but return `Option<&u32>`), or a one-arm-
25444        // only accessor that reads `Some(*n)` in the Some arm but
25445        // reads a fresh `Default::default()` (`0_u32`) in the None
25446        // arm.
25447        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
25448            let p = MeshPolicy {
25449                retries,
25450                ..MeshPolicy::default()
25451            };
25452            let first = p.retries();
25453            let second = p.retries();
25454            assert_eq!(
25455                first, second,
25456                "MeshPolicy::retries must be idempotent — two \
25457                 successive calls on the same &self must return the \
25458                 same Option<u32>",
25459            );
25460            assert_eq!(
25461                first, retries,
25462                "MeshPolicy::retries must return :politicas :retries \
25463                 verbatim by copy — got {first:?}, expected {retries:?}",
25464            );
25465        }
25466    }
25467
25468    #[test]
25469    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
25470        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
25471        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
25472        // return the `:politicas :timeout` typed [`Duration`] verbatim
25473        // as an `Option<Duration>`, byte-equal to the raw field access
25474        // across every representative value in the accept-set — `None`
25475        // (cluster default applies — typically the gateway class's
25476        // implementation-side per-request wall-clock cap the caixa-mesh
25477        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
25478        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
25479        // set the surrounding `AplicacaoSpec::validate_politicas` gate
25480        // carves out on the sibling `PolicyTimeoutZero` /
25481        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
25482        // (the upper boundary the same gate carves out on the sibling
25483        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
25484        // (a past-the-guard sentinel that pins the accessor doesn't
25485        // perform a silent bounds-collapse into `None` on the zero-
25486        // Duration arm — validate rejects zero but the accessor must
25487        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
25488        // past-the-guard sentinel that pins the accessor doesn't
25489        // perform a silent bounds-collapse at the return path).
25490        //
25491        // Sibling of the peer per-`:politicas`
25492        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
25493        // `Option<u32>` optional-scalar axis and the peer per-
25494        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
25495        // pin on the sibling `Option<bool>` optional-scalar axis,
25496        // extended onto the peer per-`:politicas` `Option<Duration>`
25497        // shape — third `Option<Copy-T>`-return accessor on the M3
25498        // mesh-slot family. Pins against a future silent detour that
25499        // re-derived the per-call cap from a peer axis (an accidental
25500        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
25501        // read the breaker's rolling-window duration as a per-call
25502        // deadline), a `None → Some(Duration::MAX)` cluster-default
25503        // projection (which would silently re-introduce the
25504        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
25505        // blocking" arm at the emit boundary), or a bounds-collapsing
25506        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
25507        // (the `AplicacaoSpec::validate` gate owns the bounds; the
25508        // accessor must ship the raw slot verbatim so a validate-time
25509        // gate regression surfaces at the emit boundary rather than
25510        // being silently absorbed).
25511        for timeout in [
25512            None,
25513            Some(Duration::from_millis(1)),
25514            Some(POLICY_TIMEOUT_MAX),
25515            Some(Duration::ZERO),
25516            Some(Duration::MAX),
25517        ] {
25518            let p = MeshPolicy {
25519                timeout,
25520                ..MeshPolicy::default()
25521            };
25522            assert_eq!(
25523                p.timeout(),
25524                timeout,
25525                "MeshPolicy::timeout must return :politicas :timeout \
25526                 verbatim (got {:?}, expected {timeout:?})",
25527                p.timeout(),
25528            );
25529            assert_eq!(
25530                p.timeout(),
25531                p.timeout,
25532                "MeshPolicy::timeout must byte-equal the raw .timeout \
25533                 field access across every value in the accept-set",
25534            );
25535        }
25536    }
25537
25538    #[test]
25539    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
25540        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
25541        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
25542        // field access. Structurally: toggling ONLY the `timeout` slot
25543        // on an otherwise-default MeshPolicy must flip `is_empty()`
25544        // from `true` (all-`None`) to `false` (one axis carries a
25545        // value); the flip must be observed for every value in the
25546        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25547        // gate accepts (`Some(Duration::from_millis(1))`,
25548        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
25549        // reads "any axis carries a value" — not "any axis carries a
25550        // value the validate gate accepts" — the same non-collapsing
25551        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
25552        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25553        //
25554        // Pins against a future silent detour that re-derived the
25555        // emptiness predicate off a peer axis (an accidental
25556        // `.rate_limit.is_none()`-only chain that dropped the
25557        // `timeout` arm entirely), a `timeout == Some(_)` collapse
25558        // that key-off a validate-gate-clamped bounds check (which
25559        // would silently classify a past-the-guard `Some(Duration::MAX)`
25560        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
25561        // check), or an accessor-side detour that no longer names the
25562        // substrate-primitive typed dispatch.
25563        //
25564        // Sibling of the peer per-`:politicas`
25565        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
25566        // the sibling `Option<u32>` optional-scalar axis and the peer
25567        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25568        // accessor-composition pin on the sibling `Option<bool>`
25569        // optional-scalar axis — same "the emptiness predicate must
25570        // route through the substrate-primitive typed dispatch"
25571        // discipline extended onto the peer per-`:politicas`
25572        // `Option<Duration>` axis.
25573        let empty = MeshPolicy::default();
25574        assert!(
25575            empty.is_empty(),
25576            "MeshPolicy::default() must be is_empty() — every axis \
25577             defaults to None",
25578        );
25579        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
25580            let p = MeshPolicy {
25581                timeout,
25582                ..MeshPolicy::default()
25583            };
25584            assert!(
25585                !p.is_empty(),
25586                "MeshPolicy::is_empty must return false when \
25587                 :timeout is {timeout:?} — the emptiness \
25588                 predicate reads \"any axis carries a value\", not \
25589                 \"any axis carries a value the validate gate \
25590                 accepts\"",
25591            );
25592            assert_eq!(
25593                p.timeout().is_none(),
25594                p.is_empty(),
25595                "when :timeout is the only set axis, is_empty() \
25596                 must equal timeout().is_none() — the accessor and \
25597                 the emptiness predicate must route through the same \
25598                 substrate-primitive typed dispatch on the :timeout \
25599                 arm",
25600            );
25601        }
25602    }
25603
25604    #[test]
25605    fn mesh_policy_timeout_projects_option_duration_by_copy() {
25606        // The by-copy pin: [`MeshPolicy::timeout`] returns
25607        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
25608        // and the accessor must return by value, not by reference.
25609        // Sibling of the peer per-`:politicas`
25610        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
25611        // sibling `Option<u32>` optional-scalar axis and the peer
25612        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25613        // by-copy pin on the sibling `Option<bool>` optional-scalar
25614        // axis, extended onto the peer per-`:politicas`
25615        // `Option<Duration>` copy-invariant shape — the accessor's
25616        // returned `Option<Duration>` must outlive `&self` (multiple
25617        // calls must return equal values from a dropped-`&self`
25618        // copy, since the returned Option carries no borrow), and
25619        // calling the accessor twice on the same MeshPolicy must
25620        // yield the same `Option<Duration>` verbatim (idempotent, no
25621        // side effects on `&self`).
25622        //
25623        // Pins against a future silent detour that returned
25624        // `Option<&Duration>` (which would type-check but silently
25625        // break every downstream caller — [`crate::render::single_field_overlay`]'s
25626        // first parameter is `Option<T: Clone>`, and `&Duration`
25627        // would fold to a detached copy at the call site), an
25628        // accidental `Option::as_ref()` projection
25629        // (`self.timeout.as_ref()` would also type-check but return
25630        // `Option<&Duration>`), or a one-arm-only accessor that
25631        // reads `Some(*d)` in the Some arm but reads a fresh
25632        // `Default::default()` (`Duration::ZERO`) in the None arm
25633        // (which would silently re-classify every unset `:timeout`
25634        // as the `PolicyTimeoutZero`-refused zero-Duration value at
25635        // the accessor boundary).
25636        for timeout in [
25637            None,
25638            Some(Duration::from_millis(1)),
25639            Some(POLICY_TIMEOUT_MAX),
25640            Some(Duration::ZERO),
25641            Some(Duration::MAX),
25642        ] {
25643            let p = MeshPolicy {
25644                timeout,
25645                ..MeshPolicy::default()
25646            };
25647            let first = p.timeout();
25648            let second = p.timeout();
25649            assert_eq!(
25650                first, second,
25651                "MeshPolicy::timeout must be idempotent — two \
25652                 successive calls on the same &self must return the \
25653                 same Option<Duration>",
25654            );
25655            assert_eq!(
25656                first, timeout,
25657                "MeshPolicy::timeout must return :politicas :timeout \
25658                 verbatim by copy — got {first:?}, expected {timeout:?}",
25659            );
25660        }
25661    }
25662
25663    #[test]
25664    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
25665        // The canonical per-`:politicas` `:rate-limit` Envoy-
25666        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
25667        // [`MeshPolicy::rate_limit`] must return the `:politicas
25668        // :rate-limit` typed [`RateLimit`] verbatim as an
25669        // `Option<RateLimit>`, byte-equal to the raw field access
25670        // across every representative value in the accept-set — `None`
25671        // (cluster default applies — no per-Aplicacao rate declaration,
25672        // the gateway-class per-listener default arm the future caixa-
25673        // mesh `local_rate_limit_overlay` emitter documents),
25674        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
25675        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
25676        // accept-set the surrounding
25677        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25678        // sibling `PolicyRateLimitZero` refusal, paired with the
25679        // canonical-window "1 second" arm of the three-unit
25680        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
25681        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
25682        // (the upper boundary the same gate carves out on the sibling
25683        // `PolicyRateLimitExceedsCap` refusal, paired with the
25684        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
25685        // (a past-the-guard sentinel that pins the accessor doesn't
25686        // perform a silent bounds-collapse into `None` on the
25687        // zero-rate/zero-window arm — validate rejects zero but the
25688        // accessor must ship the raw slot verbatim so a validate-time
25689        // gate regression surfaces at the emit boundary rather than
25690        // being silently absorbed), and
25691        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
25692        // (a past-the-guard sentinel that pins the accessor doesn't
25693        // perform a silent bounds-collapse at the return path).
25694        //
25695        // First `Option<Copy-composite-T>`-return accessor pin on the
25696        // M3 mesh-slot family (peer of the sibling per-`:politicas`
25697        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
25698        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
25699        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
25700        // Copy accessor pins, extended onto the peer per-`:politicas`
25701        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
25702        // and the accessor returns by value). Pins against a future
25703        // silent detour that re-derived the rate declaration from a
25704        // peer axis (an accidental
25705        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
25706        // collapse that read the breaker's trip threshold + rolling
25707        // window as a rate declaration), a `None → Some(default())`
25708        // cluster-default projection (which would silently re-
25709        // introduce a "cluster default is 0/s" arm the emit boundary
25710        // would take as "declared but inert" — the canonical
25711        // declared-but-inert footgun the sibling
25712        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
25713        // amplification-shape axis), a bounds-collapsing accessor
25714        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
25715        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
25716        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
25717        // accessor must ship the raw slot verbatim), or a
25718        // by-reference detour (`Option<&RateLimit>`) that broke every
25719        // downstream consumer keying off `Option<RateLimit>` by-copy.
25720        for rl in [
25721            None,
25722            Some(RateLimit {
25723                rate: 1,
25724                window: Duration::from_secs(1),
25725            }),
25726            Some(RateLimit {
25727                rate: POLICY_RATE_LIMIT_MAX,
25728                window: Duration::from_secs(3600),
25729            }),
25730            Some(RateLimit {
25731                rate: 0,
25732                window: Duration::ZERO,
25733            }),
25734            Some(RateLimit {
25735                rate: u32::MAX,
25736                window: Duration::MAX,
25737            }),
25738        ] {
25739            let p = MeshPolicy {
25740                rate_limit: rl,
25741                ..MeshPolicy::default()
25742            };
25743            assert_eq!(
25744                p.rate_limit(),
25745                rl,
25746                "MeshPolicy::rate_limit must return :politicas :rate-limit \
25747                 verbatim (got {:?}, expected {rl:?})",
25748                p.rate_limit(),
25749            );
25750            assert_eq!(
25751                p.rate_limit(),
25752                p.rate_limit,
25753                "MeshPolicy::rate_limit must byte-equal the raw \
25754                 .rate_limit field access across every value in the \
25755                 accept-set",
25756            );
25757        }
25758    }
25759
25760    #[test]
25761    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
25762        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
25763        // must key off [`MeshPolicy::rate_limit`], not the raw
25764        // `.rate_limit` field access. Structurally: toggling ONLY the
25765        // `rate_limit` slot on an otherwise-default MeshPolicy must
25766        // flip `is_empty()` from `true` (all-`None`) to `false` (one
25767        // axis carries a value); the flip must be observed for every
25768        // representative value in the accept-set the surrounding
25769        // [`AplicacaoSpec::validate_politicas`] gate accepts
25770        // (`Some(RateLimit { rate: 1, window: 1s })`,
25771        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
25772        // since the emptiness semantic reads "any axis carries a
25773        // value" — not "any axis carries a value the validate gate
25774        // accepts" — the same non-collapsing shape the peer M2
25775        // [`crate::LimitsSpec::is_empty`] /
25776        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25777        //
25778        // Pins against a future silent detour that re-derived the
25779        // emptiness predicate off a peer axis (an accidental
25780        // `.timeout.is_none()`-only chain that dropped the
25781        // `rate_limit` arm entirely — the last unlifted inline field
25782        // access on `is_empty` before this lift), a `rate_limit ==
25783        // Some(_)` collapse that key-off a validate-gate-clamped
25784        // bounds check (which would silently classify a past-the-
25785        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
25786        // because it fails the value-shape gate), or an accessor-
25787        // side detour that no longer names the substrate-primitive
25788        // typed dispatch.
25789        //
25790        // Fourth "the emptiness predicate must route through the
25791        // substrate-primitive typed dispatch" composition pin on the
25792        // M3 mesh-slot family — closes the last unlifted composition
25793        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
25794        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
25795        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
25796        // 7073d0f is_empty-composition pins on the sibling primitive-
25797        // Copy axes, extended onto the peer per-`:politicas`
25798        // composite-Copy `Option<RateLimit>` axis).
25799        let empty = MeshPolicy::default();
25800        assert!(
25801            empty.is_empty(),
25802            "MeshPolicy::default() must be is_empty() — every axis \
25803             defaults to None",
25804        );
25805        for rl in [
25806            RateLimit {
25807                rate: 1,
25808                window: Duration::from_secs(1),
25809            },
25810            RateLimit {
25811                rate: POLICY_RATE_LIMIT_MAX,
25812                window: Duration::from_secs(3600),
25813            },
25814        ] {
25815            let p = MeshPolicy {
25816                rate_limit: Some(rl),
25817                ..MeshPolicy::default()
25818            };
25819            assert!(
25820                !p.is_empty(),
25821                "MeshPolicy::is_empty must return false when \
25822                 :rate-limit is {rl:?} — the emptiness predicate \
25823                 reads \"any axis carries a value\", not \"any axis \
25824                 carries a value the validate gate accepts\"",
25825            );
25826            assert_eq!(
25827                p.rate_limit().is_none(),
25828                p.is_empty(),
25829                "when :rate-limit is the only set axis, is_empty() \
25830                 must equal rate_limit().is_none() — the accessor \
25831                 and the emptiness predicate must route through the \
25832                 same substrate-primitive typed dispatch on the \
25833                 :rate-limit arm",
25834            );
25835        }
25836    }
25837
25838    #[test]
25839    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
25840        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25841        // `:rate-limit` value-shape gate must key off
25842        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
25843        // field bind. Structurally: a `MeshPolicy` whose only set
25844        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
25845        // the `PolicyRateLimitZero` refusal exactly, and the same
25846        // MeshPolicy with the rate at the canonical lower boundary
25847        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
25848        // The pair jointly pins the accessor + validate-gate
25849        // composition: any future silent detour that had the accessor
25850        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
25851        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
25852        // silently absorb the `PolicyRateLimitZero` refusal at the
25853        // accessor boundary — the composition pin catches that at
25854        // caixa-core build time.
25855        //
25856        // Sibling of the peer [`validate_politicas`]
25857        // `:mtls-required` / `:retries` / `:timeout` composition pins
25858        // on the sibling primitive-Copy optional-scalar axes — same
25859        // "the validate / shape-gate predicate must route through the
25860        // substrate-primitive typed dispatch" discipline extended
25861        // onto the peer per-`:politicas` composite-Copy
25862        // `Option<RateLimit>` axis. Second composition-with-accessor
25863        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
25864        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
25865        let mut spec = three_member_spec();
25866        spec.politicas = MeshPolicy {
25867            rate_limit: Some(RateLimit {
25868                rate: 0,
25869                window: Duration::from_secs(1),
25870            }),
25871            ..MeshPolicy::default()
25872        };
25873        assert!(
25874            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
25875            "validate_politicas must reject rate == 0 with \
25876             PolicyRateLimitZero — the accessor and the validate gate \
25877             must route through the same substrate-primitive typed \
25878             dispatch on the :rate-limit zero-floor arm",
25879        );
25880        spec.politicas = MeshPolicy {
25881            rate_limit: Some(RateLimit {
25882                rate: 1,
25883                window: Duration::from_secs(1),
25884            }),
25885            ..MeshPolicy::default()
25886        };
25887        assert!(
25888            spec.validate().is_ok(),
25889            "validate_politicas must accept rate == 1 (the canonical \
25890             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
25891             set) with a canonical 1s window",
25892        );
25893    }
25894
25895    #[test]
25896    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
25897        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
25898        // `outlier_detection`-mesh consecutive-failure-ejection scalar
25899        // pin: [`MeshPolicy::circuit_breaker`] must return the
25900        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
25901        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
25902        // raw field access across every representative value in the
25903        // accept-set — `None` (cluster default applies — no
25904        // per-Aplicacao breaker declaration, the gateway-class per-
25905        // listener default arm the future caixa-mesh
25906        // `outlier_detection_overlay` emitter documents),
25907        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
25908        // (the lower boundary of the accept-set the surrounding
25909        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25910        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
25911        // refusals),
25912        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
25913        // (the upper boundary the same gate carves out on the sibling
25914        // `PolicyBreakerMaxFailuresExceedsCap` /
25915        // `PolicyBreakerWindowExceedsCap` refusals),
25916        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
25917        // (a past-the-guard sentinel that pins the accessor doesn't
25918        // perform a silent bounds-collapse into `None` on the
25919        // zero-failures/zero-window arm — validate rejects zero but
25920        // the accessor must ship the raw slot verbatim so a validate-
25921        // time gate regression surfaces at the emit boundary rather
25922        // than being silently absorbed), and
25923        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
25924        // (a past-the-guard sentinel that pins the accessor doesn't
25925        // perform a silent bounds-collapse at the return path).
25926        //
25927        // Second `Option<Copy-composite-T>`-return accessor pin on the
25928        // M3 mesh-slot family (peer of the sibling per-`:politicas`
25929        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
25930        // composite-Copy accessor pin, and of the sibling per-
25931        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
25932        // [`MeshPolicy::retries`] bdfb399 /
25933        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
25934        // accessor pins). Pins against a future silent detour that
25935        // re-derived the breaker declaration from a peer axis (an
25936        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
25937        // collapse that read the rate-limit's bucket capacity + refill
25938        // period as a breaker declaration), a `None → Some(default())`
25939        // cluster-default projection (which would silently re-
25940        // introduce the `PolicyBreakerZeroFailures` /
25941        // `PolicyBreakerZeroWindow` refusal cases at the emit
25942        // boundary), a bounds-collapsing accessor that clamped
25943        // `cb.max_failures` through
25944        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
25945        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
25946        // [`AplicacaoSpec::validate`] gate owns the bounds; the
25947        // accessor must ship the raw slot verbatim), or a
25948        // by-reference detour (`Option<&CircuitBreaker>`) that broke
25949        // every downstream consumer keying off `Option<CircuitBreaker>`
25950        // by-copy.
25951        for cb in [
25952            None,
25953            Some(CircuitBreaker {
25954                max_failures: 1,
25955                window: Duration::from_millis(1),
25956            }),
25957            Some(CircuitBreaker {
25958                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25959                window: POLICY_BREAKER_WINDOW_MAX,
25960            }),
25961            Some(CircuitBreaker {
25962                max_failures: 0,
25963                window: Duration::ZERO,
25964            }),
25965            Some(CircuitBreaker {
25966                max_failures: u32::MAX,
25967                window: Duration::MAX,
25968            }),
25969        ] {
25970            let p = MeshPolicy {
25971                circuit_breaker: cb,
25972                ..MeshPolicy::default()
25973            };
25974            assert_eq!(
25975                p.circuit_breaker(),
25976                cb,
25977                "MeshPolicy::circuit_breaker must return :politicas \
25978                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
25979                p.circuit_breaker(),
25980            );
25981            assert_eq!(
25982                p.circuit_breaker(),
25983                p.circuit_breaker,
25984                "MeshPolicy::circuit_breaker must byte-equal the raw \
25985                 .circuit_breaker field access across every value in \
25986                 the accept-set",
25987            );
25988        }
25989    }
25990
25991    #[test]
25992    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
25993        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
25994        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
25995        // `.circuit_breaker` field access. Structurally: toggling ONLY
25996        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
25997        // must flip `is_empty()` from `true` (all-`None`) to `false`
25998        // (one axis carries a value); the flip must be observed for
25999        // every representative value in the accept-set the surrounding
26000        // [`AplicacaoSpec::validate_politicas`] gate accepts
26001        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
26002        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
26003        // since the emptiness semantic reads "any axis carries a
26004        // value" — not "any axis carries a value the validate gate
26005        // accepts" — the same non-collapsing shape the peer M2
26006        // [`crate::LimitsSpec::is_empty`] /
26007        // [`crate::BehaviorSpec::is_empty`] predicates carry.
26008        //
26009        // Pins against a future silent detour that re-derived the
26010        // emptiness predicate off a peer axis (an accidental
26011        // `.rate_limit.is_none()`-only chain that dropped the
26012        // `circuit_breaker` arm entirely — the last unlifted inline
26013        // field access on `is_empty` before this lift), a
26014        // `circuit_breaker == Some(_)` collapse that key-off a
26015        // validate-gate-clamped bounds check (which would silently
26016        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
26017        // 0, window: 0s })` as empty because it fails the value-shape
26018        // gate), or an accessor-side detour that no longer names the
26019        // substrate-primitive typed dispatch.
26020        //
26021        // Fifth "the emptiness predicate must route through the
26022        // substrate-primitive typed dispatch" composition pin on the
26023        // M3 mesh-slot family — closes the last unlifted composition
26024        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
26025        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
26026        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
26027        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
26028        // composition pins on the sibling primitive-Copy + composite-
26029        // Copy axes, extended onto the peer per-`:politicas`
26030        // composite-Copy `Option<CircuitBreaker>` axis).
26031        let empty = MeshPolicy::default();
26032        assert!(
26033            empty.is_empty(),
26034            "MeshPolicy::default() must be is_empty() — every axis \
26035             defaults to None",
26036        );
26037        for cb in [
26038            CircuitBreaker {
26039                max_failures: 1,
26040                window: Duration::from_millis(1),
26041            },
26042            CircuitBreaker {
26043                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
26044                window: POLICY_BREAKER_WINDOW_MAX,
26045            },
26046        ] {
26047            let p = MeshPolicy {
26048                circuit_breaker: Some(cb),
26049                ..MeshPolicy::default()
26050            };
26051            assert!(
26052                !p.is_empty(),
26053                "MeshPolicy::is_empty must return false when \
26054                 :circuit-breaker is {cb:?} — the emptiness predicate \
26055                 reads \"any axis carries a value\", not \"any axis \
26056                 carries a value the validate gate accepts\"",
26057            );
26058            assert_eq!(
26059                p.circuit_breaker().is_none(),
26060                p.is_empty(),
26061                "when :circuit-breaker is the only set axis, \
26062                 is_empty() must equal circuit_breaker().is_none() — \
26063                 the accessor and the emptiness predicate must route \
26064                 through the same substrate-primitive typed dispatch \
26065                 on the :circuit-breaker arm",
26066            );
26067        }
26068    }
26069
26070    #[test]
26071    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
26072        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26073        // `:circuit-breaker` value-shape gate must key off
26074        // [`MeshPolicy::circuit_breaker`], not the raw
26075        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
26076        // whose only set axis is a `Some(CircuitBreaker { max_failures:
26077        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
26078        // refusal exactly, and the same MeshPolicy with the breaker at
26079        // the canonical lower boundary
26080        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
26081        // pass validate. The pair jointly pins the accessor +
26082        // validate-gate composition: any future silent detour that had
26083        // the accessor omit the `Some(CircuitBreaker { max_failures:
26084        // 0, .. })` arm (a
26085        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
26086        // collapse) would silently absorb the
26087        // `PolicyBreakerZeroFailures` refusal at the accessor
26088        // boundary — the composition pin catches that at caixa-core
26089        // build time.
26090        //
26091        // Sibling of the peer [`validate_politicas`]
26092        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
26093        // composition pins on the sibling primitive-Copy + composite-
26094        // Copy optional-scalar axes — same "the validate / shape-gate
26095        // predicate must route through the substrate-primitive typed
26096        // dispatch" discipline extended onto the peer per-`:politicas`
26097        // composite-Copy `Option<CircuitBreaker>` axis. Second
26098        // composition-with-accessor pin on the M3 mesh-slot
26099        // `Option<CircuitBreaker>` arm alongside the
26100        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
26101        let mut spec = three_member_spec();
26102        spec.politicas = MeshPolicy {
26103            circuit_breaker: Some(CircuitBreaker {
26104                max_failures: 0,
26105                window: Duration::from_millis(1),
26106            }),
26107            ..MeshPolicy::default()
26108        };
26109        assert!(
26110            matches!(
26111                spec.validate(),
26112                Err(AplicacaoError::PolicyBreakerZeroFailures)
26113            ),
26114            "validate_politicas must reject max_failures == 0 with \
26115             PolicyBreakerZeroFailures — the accessor and the validate \
26116             gate must route through the same substrate-primitive \
26117             typed dispatch on the :circuit-breaker zero-floor arm",
26118        );
26119        spec.politicas = MeshPolicy {
26120            circuit_breaker: Some(CircuitBreaker {
26121                max_failures: 1,
26122                window: Duration::from_millis(1),
26123            }),
26124            ..MeshPolicy::default()
26125        };
26126        assert!(
26127            spec.validate().is_ok(),
26128            "validate_politicas must accept a CircuitBreaker at the \
26129             canonical lower boundary (max_failures = 1, window = \
26130             1ms) — the accessor and the validate gate must route \
26131             through the same substrate-primitive typed dispatch on \
26132             the :circuit-breaker arm",
26133        );
26134    }
26135
26136    #[test]
26137    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
26138        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
26139        // Envoy-outlier-detection trip-threshold scalar pin:
26140        // [`CircuitBreaker::max_failures`] must return the
26141        // `:politicas :circuit-breaker :max-failures` typed `u32`
26142        // verbatim, byte-equal to the raw field access across every
26143        // representative value in the accept-set — `1` (the lower
26144        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
26145        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
26146        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
26147        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
26148        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
26149        // refusal), `0` (a past-the-guard sentinel that pins the accessor
26150        // doesn't perform a silent bounds-collapse into `1` on the zero
26151        // arm — validate rejects zero but the accessor must ship the
26152        // raw slot verbatim so a validate-time gate regression surfaces
26153        // at the emit boundary rather than being silently absorbed),
26154        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
26155        // doesn't perform a silent bounds-collapse through
26156        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
26157        //
26158        // First sub-struct required-scalar accessor pin on the M3
26159        // mesh-slot family — sibling in shape to the peer per-`:membros`
26160        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
26161        // (a40b0e3) required-`String`-carry accessor pins and the peer
26162        // per-`:contratos` [`WitContract::source`] /
26163        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
26164        // accessor pins, extended onto the peer per-`CircuitBreaker`
26165        // required-`u32` scalar-value axis. Pins against a future silent
26166        // detour that re-derived the trip threshold from a peer axis (an
26167        // accidental `self.window.as_secs() as u32` collapse that read
26168        // the breaker's rolling-window duration as a failure count), a
26169        // `0 → 1` cluster-default projection (which would silently absorb
26170        // the `PolicyBreakerZeroFailures` refusal case at the accessor
26171        // boundary), or a bounds-collapsing accessor that clamped the
26172        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
26173        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
26174        // must ship the raw slot verbatim).
26175        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
26176            let cb = CircuitBreaker {
26177                max_failures,
26178                window: Duration::from_secs(60),
26179            };
26180            assert_eq!(
26181                cb.max_failures(),
26182                max_failures,
26183                "CircuitBreaker::max_failures must return :politicas \
26184                 :circuit-breaker :max-failures verbatim (got {}, \
26185                 expected {max_failures})",
26186                cb.max_failures(),
26187            );
26188            assert_eq!(
26189                cb.max_failures(),
26190                cb.max_failures,
26191                "CircuitBreaker::max_failures must byte-equal the raw \
26192                 .max_failures field access across every value in the \
26193                 u32 accept-set",
26194            );
26195        }
26196    }
26197
26198    #[test]
26199    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
26200        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26201        // `:circuit-breaker :max-failures` zero-floor arm must key off
26202        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
26203        // field access. Structurally: a `CircuitBreaker { max_failures:
26204        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
26205        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
26206        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
26207        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
26208        // pass validate. The pair jointly pins the accessor +
26209        // validate-gate composition: any future silent detour that had
26210        // the accessor return a fresh `1` on the zero arm (a
26211        // `.max_failures().max(1)` collapse) would silently absorb the
26212        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
26213        // and the validate gate would accept a struct-literal
26214        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
26215        // catches that at caixa-core build time.
26216        //
26217        // Peer of the sibling per-`:politicas`
26218        // [`MeshPolicy::mtls_required`] (c0110f1) /
26219        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
26220        // (7073d0f) accessor-composition pins on the sibling optional-
26221        // scalar axes — same "the validate / shape-gate predicate must
26222        // route through the substrate-primitive typed dispatch"
26223        // discipline extended onto the peer per-`CircuitBreaker`
26224        // required-scalar composition axis.
26225        let mut spec = three_member_spec();
26226        spec.politicas = MeshPolicy {
26227            circuit_breaker: Some(CircuitBreaker {
26228                max_failures: 0,
26229                window: Duration::from_secs(60),
26230            }),
26231            ..MeshPolicy::default()
26232        };
26233        assert!(
26234            matches!(
26235                spec.validate(),
26236                Err(AplicacaoError::PolicyBreakerZeroFailures)
26237            ),
26238            "validate_politicas must reject max_failures == 0 with \
26239             PolicyBreakerZeroFailures — the accessor and the validate \
26240             gate must route through the same substrate-primitive typed \
26241             dispatch on the :max-failures zero-floor arm",
26242        );
26243        spec.politicas = MeshPolicy {
26244            circuit_breaker: Some(CircuitBreaker {
26245                max_failures: 1,
26246                window: Duration::from_secs(60),
26247            }),
26248            ..MeshPolicy::default()
26249        };
26250        assert!(
26251            spec.validate().is_ok(),
26252            "validate_politicas must accept max_failures == 1 (the \
26253             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
26254             accept-set)",
26255        );
26256    }
26257
26258    #[test]
26259    fn circuit_breaker_max_failures_projects_u32_by_copy() {
26260        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
26261        // `u32` by copy — `u32` is `Copy` and the accessor must return
26262        // by value, not by reference. Peer of the sibling
26263        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
26264        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
26265        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
26266        // optional-scalar axes, extended onto the peer
26267        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
26268        // the accessor's returned `u32` must outlive `&self` (multiple
26269        // calls must return equal values from a dropped-`&self` copy,
26270        // since the returned scalar carries no borrow), and calling
26271        // the accessor twice on the same CircuitBreaker must yield the
26272        // same `u32` verbatim (idempotent, no side effects on `&self`).
26273        //
26274        // Pins against a future silent detour that returned `&u32`
26275        // (which would type-check but silently break every downstream
26276        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
26277        // first parameter is `u32`, and `&u32` would fold to a detached
26278        // copy at the call site with a `*` deref the sibling accessors
26279        // don't need), an accidental `.max_failures.wrapping_add(0)`
26280        // detour that returned a fresh copy through an arithmetic
26281        // no-op (breaking a future `const fn` regression), or a
26282        // one-arm-only accessor that returned a saturating value on
26283        // some sentinel input (breaking the pass-through invariant the
26284        // sibling required-scalar accessors carry).
26285        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
26286            let cb = CircuitBreaker {
26287                max_failures,
26288                window: Duration::from_secs(60),
26289            };
26290            let first = cb.max_failures();
26291            let second = cb.max_failures();
26292            assert_eq!(
26293                first, second,
26294                "CircuitBreaker::max_failures must be idempotent — two \
26295                 successive calls on the same &self must return the \
26296                 same u32",
26297            );
26298            assert_eq!(
26299                first, max_failures,
26300                "CircuitBreaker::max_failures must return :politicas \
26301                 :circuit-breaker :max-failures verbatim by copy — \
26302                 got {first}, expected {max_failures}",
26303            );
26304        }
26305    }
26306
26307    #[test]
26308    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
26309        // The canonical per-`:politicas :circuit-breaker` `:window`
26310        // Envoy-outlier-detection rolling-observation-interval scalar
26311        // pin: [`CircuitBreaker::window`] must return the
26312        // `:politicas :circuit-breaker :window` typed `Duration`
26313        // verbatim, byte-equal to the raw field access across every
26314        // representative value in the accept-set — `Duration::from_millis(1)`
26315        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
26316        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
26317        // gate carves out on the sibling `PolicyBreakerZeroWindow`
26318        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
26319        // same gate carves out on the sibling
26320        // `PolicyBreakerWindowExceedsCap` refusal),
26321        // `Duration::ZERO` (a past-the-guard sentinel that pins the
26322        // accessor doesn't perform a silent bounds-collapse into
26323        // `Duration::from_millis(1)` on the zero arm — validate rejects
26324        // zero but the accessor must ship the raw slot verbatim so a
26325        // validate-time gate regression surfaces at the emit boundary
26326        // rather than being silently absorbed),
26327        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
26328        // far above the 1h cap — that pins the accessor doesn't perform
26329        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
26330        // at the return path).
26331        //
26332        // Second sub-struct required-scalar accessor pin on the M3
26333        // mesh-slot family — sibling in shape to the just-landed
26334        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
26335        // (3a74062) required-`u32` accessor pin on the peer
26336        // per-`CircuitBreaker` required-axis, extended onto the
26337        // per-sub-struct required-`Duration` axis. Pins against a
26338        // future silent detour that re-derived the observation window
26339        // from a peer axis (an accidental
26340        // `Duration::from_secs(self.max_failures as u64)` collapse that
26341        // read the breaker's trip count as an observation-interval
26342        // duration), a `Duration::ZERO → Duration::from_millis(1)`
26343        // cluster-default projection (which would silently absorb the
26344        // `PolicyBreakerZeroWindow` refusal case at the accessor
26345        // boundary), or a bounds-collapsing accessor that clamped the
26346        // return through `POLICY_BREAKER_WINDOW_MAX` (the
26347        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
26348        // must ship the raw slot verbatim).
26349        for window in [
26350            Duration::from_millis(1),
26351            POLICY_BREAKER_WINDOW_MAX,
26352            Duration::ZERO,
26353            Duration::from_secs(86_400),
26354        ] {
26355            let cb = CircuitBreaker {
26356                max_failures: 5,
26357                window,
26358            };
26359            assert_eq!(
26360                cb.window(),
26361                window,
26362                "CircuitBreaker::window must return :politicas \
26363                 :circuit-breaker :window verbatim (got {:?}, \
26364                 expected {window:?})",
26365                cb.window(),
26366            );
26367            assert_eq!(
26368                cb.window(),
26369                cb.window,
26370                "CircuitBreaker::window must byte-equal the raw \
26371                 .window field access across every value in the \
26372                 Duration accept-set",
26373            );
26374        }
26375    }
26376
26377    #[test]
26378    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
26379        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26380        // `:circuit-breaker :window` zero-floor arm must key off
26381        // [`CircuitBreaker::window`], not the raw `.window` field
26382        // access. Structurally: a `CircuitBreaker { window:
26383        // Duration::ZERO, .. }` embedded in a
26384        // `:politicas :circuit-breaker` slot must surface the
26385        // `PolicyBreakerZeroWindow` refusal exactly, and a
26386        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
26387        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
26388        // accept-set) must pass validate. The pair jointly pins the
26389        // accessor + validate-gate composition: any future silent
26390        // detour that had the accessor return a fresh
26391        // `Duration::from_millis(1)` on the zero arm (a
26392        // `.window().max(Duration::from_millis(1))` collapse) would
26393        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
26394        // accessor boundary and the validate gate would accept a
26395        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
26396        // — the composition pin catches that at caixa-core build time.
26397        //
26398        // Peer of the sibling per-`CircuitBreaker`
26399        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
26400        // pin on the peer required-scalar `:max-failures` axis — same
26401        // "the validate / shape-gate predicate must route through the
26402        // substrate-primitive typed dispatch" discipline extended onto
26403        // the peer per-`CircuitBreaker` required-`Duration` composition
26404        // axis.
26405        let mut spec = three_member_spec();
26406        spec.politicas = MeshPolicy {
26407            circuit_breaker: Some(CircuitBreaker {
26408                max_failures: 5,
26409                window: Duration::ZERO,
26410            }),
26411            ..MeshPolicy::default()
26412        };
26413        assert!(
26414            matches!(
26415                spec.validate(),
26416                Err(AplicacaoError::PolicyBreakerZeroWindow)
26417            ),
26418            "validate_politicas must reject window == Duration::ZERO \
26419             with PolicyBreakerZeroWindow — the accessor and the \
26420             validate gate must route through the same substrate-\
26421             primitive typed dispatch on the :window zero-floor arm",
26422        );
26423        spec.politicas = MeshPolicy {
26424            circuit_breaker: Some(CircuitBreaker {
26425                max_failures: 5,
26426                window: Duration::from_millis(1),
26427            }),
26428            ..MeshPolicy::default()
26429        };
26430        assert!(
26431            spec.validate().is_ok(),
26432            "validate_politicas must accept window == \
26433             Duration::from_millis(1) (the lower boundary of the \
26434             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
26435        );
26436    }
26437
26438    #[test]
26439    fn circuit_breaker_window_projects_duration_by_copy() {
26440        // The by-copy pin: [`CircuitBreaker::window`] returns
26441        // `Duration` by copy — `Duration` is `Copy` and the accessor
26442        // must return by value, not by reference. Peer of the sibling
26443        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
26444        // (3a74062) by-copy pin on the peer required-scalar
26445        // `:max-failures` axis, extended onto the peer
26446        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
26447        // — the accessor's returned `Duration` must outlive `&self`
26448        // (multiple calls must return equal values from a
26449        // dropped-`&self` copy, since the returned scalar carries no
26450        // borrow), and calling the accessor twice on the same
26451        // CircuitBreaker must yield the same `Duration` verbatim
26452        // (idempotent, no side effects on `&self`).
26453        //
26454        // Pins against a future silent detour that returned
26455        // `&Duration` (which would type-check but silently break every
26456        // downstream `Duration`-by-value consumer —
26457        // [`crate::render::require_positive_canonical_bounded_duration`]'s
26458        // first parameter is `Duration`, and `&Duration` would fold to
26459        // a detached copy at the call site with a `*` deref the sibling
26460        // accessors don't need), an accidental `.window + Duration::ZERO`
26461        // detour that returned a fresh copy through an arithmetic
26462        // no-op (breaking a future `const fn` regression), or a
26463        // one-arm-only accessor that returned a saturating value on
26464        // some sentinel input (breaking the pass-through invariant the
26465        // sibling required-scalar accessors carry).
26466        for window in [
26467            Duration::from_millis(1),
26468            POLICY_BREAKER_WINDOW_MAX,
26469            Duration::ZERO,
26470            Duration::from_secs(86_400),
26471        ] {
26472            let cb = CircuitBreaker {
26473                max_failures: 5,
26474                window,
26475            };
26476            let first = cb.window();
26477            let second = cb.window();
26478            assert_eq!(
26479                first, second,
26480                "CircuitBreaker::window must be idempotent — two \
26481                 successive calls on the same &self must return the \
26482                 same Duration",
26483            );
26484            assert_eq!(
26485                first, window,
26486                "CircuitBreaker::window must return :politicas \
26487                 :circuit-breaker :window verbatim by copy — \
26488                 got {first:?}, expected {window:?}",
26489            );
26490        }
26491    }
26492
26493    #[test]
26494    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
26495        // Apex-identity pair-invariant pin composing both substrate-
26496        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
26497        // and [`WitContract::destination`] — at the emit-side call shape
26498        // every per-`(:de, :para)` CNP L4 port reader now takes. The
26499        // invariant, evaluated per-edge:
26500        //
26501        //   spec.port_for_destination(c.destination()) == expected_port
26502        //
26503        // where `expected_port` is `entrada.port` when
26504        // `c.destination() == entrada.destination()` and
26505        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
26506        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
26507        // pin on the per-`:entrada` axis — that pin encodes the apex
26508        // ingress L4 identity via `entrada.destination()`; this pin
26509        // encodes the per-edge L4 identity via `c.destination()`, and
26510        // both compose on the same substrate-primitive resolver so a
26511        // future refactor that silently split either accessor's apex
26512        // behavior surfaces at caixa-core build time.
26513        let mut spec = three_member_spec();
26514        if let Some(e) = spec.entrada.as_mut() {
26515            e.para = "cart".into();
26516            e.port = 8443;
26517        }
26518        let apex_contract = WitContract {
26519            de: "checkout".into(),
26520            para: "cart".into(),
26521            wit: "wasi:http/proxy".into(),
26522            endpoint: Some("/hello".into()),
26523            subject: None,
26524            slot: None,
26525        };
26526        assert_eq!(
26527            spec.port_for_destination(apex_contract.destination()),
26528            8443,
26529            "`spec.port_for_destination(c.destination())` must equal \
26530             `entrada.port` when the contract callee names the ingress \
26531             apex — the CNP per-edge L4 port and the HTTPRoute apex \
26532             backendRef port share this substrate-primitive resolver.",
26533        );
26534        let non_apex_contract = WitContract {
26535            de: "cart".into(),
26536            para: "payment".into(),
26537            wit: "wasi:http/proxy".into(),
26538            endpoint: Some("/charge".into()),
26539            subject: None,
26540            slot: None,
26541        };
26542        assert_eq!(
26543            spec.port_for_destination(non_apex_contract.destination()),
26544            DEFAULT_SERVICO_PORT,
26545            "`spec.port_for_destination(c.destination())` must fall back \
26546             to the substrate-canonical port floor when the contract \
26547             callee is not the ingress apex — the resolver's non-apex \
26548             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
26549        );
26550    }
26551
26552    #[test]
26553    fn membro_key_consts_are_lower_camel_case_shape() {
26554        // Shape-pin: every `MEMBRO_KEY_*` const must be a
26555        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26556        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26557        // leading capital, no whitespace / dots) — the canonical shape
26558        // the `#[serde(rename_all = "camelCase")]` derive produces on
26559        // [`Membro`]. A future flip to a non-camelCase attribute at
26560        // the derive surfaces both here (this test fails on the
26561        // stale-constant shape) and at
26562        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
26563        // fails on the mismatch between const and derive). Peer with
26564        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
26565        // on the sibling `SupervisorSpec` top-level axis.
26566        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
26567            assert!(
26568                !key.is_empty(),
26569                "MEMBRO_KEY_* must be non-empty (got {key:?})"
26570            );
26571            let first = key.chars().next().unwrap();
26572            assert!(
26573                first.is_ascii_lowercase(),
26574                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
26575                 (got {key:?}, leads with {first:?})",
26576            );
26577            assert!(
26578                key.chars().all(|c| c.is_ascii_alphanumeric()),
26579                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
26580                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26581            );
26582        }
26583    }
26584
26585    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
26586
26587    #[test]
26588    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
26589        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
26590        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
26591        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
26592        // keys the `#[serde(rename_all = "camelCase")]` attribute on
26593        // [`WitContract`] emits for the required-triad. The three
26594        // sibling payload-arm keys already pin under
26595        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
26596        // `STORE_FIELD_NAME` — pin all six alongside so a future
26597        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26598        // verbatim-field-name flip at the derive attribute (any of which
26599        // would silently break every downstream JSON consumer that
26600        // reaches for one of the six via `Value::get(...)`) surfaces
26601        // here as a build-time test failure at `aplicacao.rs`, not as an
26602        // apply-time `.get(<stale-canonical-const>)` returning `None`
26603        // far from the derive-attr drift's commit. Peer with the sibling
26604        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26605        // pin on the M3 `:membros` per-entry axis — same discipline the
26606        // `Membro` per-entry lift established, extended here to the
26607        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
26608        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
26609        // axis on the Aplicacao surface without a lifted serde-key peer.
26610        let c = WitContract {
26611            de: "cart".into(),
26612            para: "catalog".into(),
26613            wit: "wasi:http/proxy".into(),
26614            endpoint: Some("/lookup".into()),
26615            subject: None,
26616            slot: None,
26617        };
26618        let json = serde_json::to_string(&c).unwrap();
26619        for key in [
26620            crate::CONTRATO_KEY_DE,
26621            crate::CONTRATO_KEY_PARA,
26622            crate::CONTRATO_KEY_WIT,
26623            WitTarget::HTTP_FIELD_NAME,
26624        ] {
26625            let quoted = format!("\"{key}\"");
26626            assert!(
26627                json.contains(&quoted),
26628                "serialized WitContract must carry the lifted \
26629                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
26630                 {quoted} verbatim in the JSON emission (got: {json})",
26631            );
26632        }
26633
26634        // Pin the two remaining payload-arm keys by round-tripping a
26635        // `WitContract` under each payload-shape (pub-sub, store) — the
26636        // required-triad appears on every emission but the payload arms
26637        // only surface when their `Option<String>` field is `Some`.
26638        let pubsub = WitContract {
26639            de: "cart".into(),
26640            para: "events".into(),
26641            wit: "nats:pub-sub".into(),
26642            endpoint: None,
26643            subject: Some("orders.placed".into()),
26644            slot: None,
26645        };
26646        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
26647        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
26648        assert!(
26649            pubsub_json.contains(&pubsub_quoted),
26650            "serialized pub-sub WitContract must carry the lifted \
26651             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
26652             verbatim in the JSON emission (got: {pubsub_json})",
26653        );
26654        let store = WitContract {
26655            de: "cart".into(),
26656            para: "sessions".into(),
26657            wit: "wasi:keyvalue/store".into(),
26658            endpoint: None,
26659            subject: None,
26660            slot: Some("cart/$id".into()),
26661        };
26662        let store_json = serde_json::to_string(&store).unwrap();
26663        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
26664        assert!(
26665            store_json.contains(&store_quoted),
26666            "serialized store WitContract must carry the lifted \
26667             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
26668             verbatim in the JSON emission (got: {store_json})",
26669        );
26670    }
26671
26672    #[test]
26673    fn contrato_key_consts_are_pairwise_distinct() {
26674        // Cross-axis drift-detection pin: a future collapse of the six
26675        // canonical [`WitContract`] per-entry byte-strings onto the same
26676        // value (e.g. an accidental copy-paste flip of
26677        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
26678        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
26679        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
26680        // every downstream probe on one axis onto the sibling axis's
26681        // overlay entry and pass every propagation-probe test that
26682        // expected only the stale axis's value. Peer of the sibling
26683        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
26684        // widened here to the six-way axis the `WitContract`
26685        // required-triad + `WitTarget` payload-triad jointly cover.
26686        let all = [
26687            crate::CONTRATO_KEY_DE,
26688            crate::CONTRATO_KEY_PARA,
26689            crate::CONTRATO_KEY_WIT,
26690            WitTarget::HTTP_FIELD_NAME,
26691            WitTarget::PUBSUB_FIELD_NAME,
26692            WitTarget::STORE_FIELD_NAME,
26693        ];
26694        for (i, a) in all.iter().enumerate() {
26695            for b in all.iter().skip(i + 1) {
26696                assert_ne!(
26697                    a, b,
26698                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
26699                     must be pairwise-distinct canonical byte-sequences \
26700                     — got `{a}` == `{b}`",
26701                );
26702            }
26703        }
26704    }
26705
26706    #[test]
26707    fn contrato_key_consts_are_lower_camel_case_shape() {
26708        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
26709        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
26710        // byte-sequence (no `snake_case` underscores, no `kebab-case`
26711        // hyphens, no leading colon, no `PascalCase` leading capital, no
26712        // whitespace / dots) — the canonical shape the
26713        // `#[serde(rename_all = "camelCase")]` derive produces on
26714        // [`WitContract`]. A future flip to a non-camelCase attribute at
26715        // the derive surfaces both here (this test fails on the
26716        // stale-constant shape) and at
26717        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26718        // (that test fails on the mismatch between const and derive).
26719        // Peer with `membro_key_consts_are_lower_camel_case_shape`
26720        // (ce80ca0) on the sibling `Membro` per-entry axis.
26721        for key in [
26722            crate::CONTRATO_KEY_DE,
26723            crate::CONTRATO_KEY_PARA,
26724            crate::CONTRATO_KEY_WIT,
26725            WitTarget::HTTP_FIELD_NAME,
26726            WitTarget::PUBSUB_FIELD_NAME,
26727            WitTarget::STORE_FIELD_NAME,
26728        ] {
26729            assert!(
26730                !key.is_empty(),
26731                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26732                 non-empty (got {key:?})"
26733            );
26734            let first = key.chars().next().unwrap();
26735            assert!(
26736                first.is_ascii_lowercase(),
26737                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
26738                 with an ASCII-lowercase byte (got {key:?}, leads with \
26739                 {first:?})",
26740            );
26741            assert!(
26742                key.chars().all(|c| c.is_ascii_alphanumeric()),
26743                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26744                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
26745                 whitespace (got {key:?})",
26746            );
26747        }
26748    }
26749
26750    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
26751
26752    #[test]
26753    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
26754        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
26755        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
26756        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
26757        // name the exact camelCase JSON keys the
26758        // `#[serde(rename_all = "camelCase")]` attribute on
26759        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
26760        // pin that each canonical byte-sequence appears verbatim in the
26761        // JSON — a future accidental `rename_all = "snake_case"` /
26762        // `"kebab-case"` / verbatim-field-name flip at the derive
26763        // attribute (any of which would silently break every downstream
26764        // JSON consumer that reaches for one of the four consts via
26765        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
26766        // emitter's per-Aplicacao hostname/paths/port projection, the
26767        // future `app-operator` reconciler's per-Aplicacao ingress
26768        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
26769        // materializer's admission-time cross-check) surfaces here as
26770        // a build-time test failure at `aplicacao.rs`, not as an
26771        // apply-time `.get(<stale-canonical-const>)` returning `None`
26772        // far from the derive-attr drift's commit. Peer with the
26773        // sibling
26774        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26775        // (ca463a4) and
26776        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26777        // pins on the M3 collection-slot atom axes — same discipline
26778        // both collection-slot lifts established, extended here to the
26779        // singleton `:entrada` mesh-slot atom axis, the last M3
26780        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
26781        // axis on the Aplicacao surface without a lifted serde-key
26782        // peer.
26783        let e = Entrada {
26784            host: "checkout.quero.cloud".into(),
26785            para: "cart".into(),
26786            paths: vec!["/cart".into()],
26787            port: 8080,
26788        };
26789        let json = serde_json::to_string(&e).unwrap();
26790        for key in [
26791            crate::ENTRADA_KEY_HOST,
26792            crate::ENTRADA_KEY_PARA,
26793            crate::ENTRADA_KEY_PATHS,
26794            crate::ENTRADA_KEY_PORT,
26795        ] {
26796            let quoted = format!("\"{key}\"");
26797            assert!(
26798                json.contains(&quoted),
26799                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
26800                 byte-sequence {quoted} verbatim in the JSON emission \
26801                 (got: {json})",
26802            );
26803        }
26804    }
26805
26806    #[test]
26807    fn entrada_key_consts_are_pairwise_distinct() {
26808        // Cross-axis drift-detection pin: a future collapse of the four
26809        // canonical [`Entrada`] singleton byte-strings onto the same
26810        // value (e.g. an accidental copy-paste flip of
26811        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
26812        // silently reroute every downstream probe on one axis onto the
26813        // sibling axis's overlay entry and pass every propagation-probe
26814        // test that expected only the stale axis's value — the
26815        // Gateway/HTTPRoute emitter would read the hostname string
26816        // where the destination-Servico name was expected (or vice
26817        // versa), the admission-webhook cross-check would compare the
26818        // wrong pair of values, and the resulting Gateway resource
26819        // would either be admitted with garbage or rejected at the
26820        // controller far from the rebrand commit's source. Peer of the
26821        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
26822        // tetrad (40cc4e5), the two-way distinct pin on the
26823        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
26824        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
26825        // triad (ca463a4).
26826        let all = [
26827            crate::ENTRADA_KEY_HOST,
26828            crate::ENTRADA_KEY_PARA,
26829            crate::ENTRADA_KEY_PATHS,
26830            crate::ENTRADA_KEY_PORT,
26831        ];
26832        for (i, a) in all.iter().enumerate() {
26833            for b in all.iter().skip(i + 1) {
26834                assert_ne!(
26835                    a, b,
26836                    "ENTRADA_KEY_* consts must be pairwise-distinct \
26837                     canonical byte-sequences — got `{a}` == `{b}`",
26838                );
26839            }
26840        }
26841    }
26842
26843    #[test]
26844    fn entrada_key_consts_are_lower_camel_case_shape() {
26845        // Shape-pin: every `ENTRADA_KEY_*` const must be a
26846        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26847        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26848        // leading capital, no whitespace / dots) — the canonical shape
26849        // the `#[serde(rename_all = "camelCase")]` derive produces on
26850        // [`Entrada`]. A future flip to a non-camelCase attribute at
26851        // the derive surfaces both here (this test fails on the
26852        // stale-constant shape) and at
26853        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
26854        // test fails on the mismatch between const and derive). Peer
26855        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
26856        // and `contrato_key_consts_are_lower_camel_case_shape`
26857        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
26858        // entry axes.
26859        for key in [
26860            crate::ENTRADA_KEY_HOST,
26861            crate::ENTRADA_KEY_PARA,
26862            crate::ENTRADA_KEY_PATHS,
26863            crate::ENTRADA_KEY_PORT,
26864        ] {
26865            assert!(
26866                !key.is_empty(),
26867                "ENTRADA_KEY_* must be non-empty (got {key:?})"
26868            );
26869            let first = key.chars().next().unwrap();
26870            assert!(
26871                first.is_ascii_lowercase(),
26872                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
26873                 (got {key:?}, leads with {first:?})",
26874            );
26875            assert!(
26876                key.chars().all(|c| c.is_ascii_alphanumeric()),
26877                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
26878                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26879            );
26880        }
26881    }
26882
26883    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
26884
26885    #[test]
26886    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
26887        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
26888        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
26889        // [`crate::POLITICAS_KEY_RETRIES`] /
26890        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
26891        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
26892        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
26893        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
26894        // on [`MeshPolicy`] emits. Three of the five axes
26895        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
26896        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
26897        // camelCase transforms — the derive-attribute is load-bearing
26898        // on those, unlike the sibling `Entrada` / `Membro` /
26899        // `WitContract` structs whose fields are all lowercase-single-
26900        // word and where the derive is a no-op on every axis.
26901        // Serialize a fully-populated [`MeshPolicy`] (every axis
26902        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
26903        // on none of the five slots) and pin that each canonical
26904        // byte-sequence appears verbatim in the JSON — a future
26905        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26906        // verbatim-field-name flip at the derive attribute (any of
26907        // which would silently break every downstream JSON consumer
26908        // that reaches for one of the five consts via
26909        // `Value::get(...)` — the future M4 per-edge `:politicas`
26910        // overlay projection onto Cilium `L7Rules` and Gateway API
26911        // `HTTPRoute` backend timeouts, the future
26912        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26913        // admission-time mesh-policy cross-check, the future
26914        // `feira lint` per-`:politicas` bound-check gate) surfaces here
26915        // as a build-time test failure at `aplicacao.rs`, not as an
26916        // apply-time `.get(<stale-canonical-const>)` returning `None`
26917        // far from the derive-attr drift's commit. Peer with the
26918        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
26919        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26920        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
26921        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
26922        // atom axes — same discipline every M3 sibling lift
26923        // established, extended here to the singleton `:politicas`
26924        // mesh-slot atom axis, closing the last M3 typed-struct
26925        // top-level `#[serde(rename_all = "camelCase")]` axis on the
26926        // Aplicacao surface without a lifted serde-key peer.
26927        let p = MeshPolicy {
26928            timeout: Some(Duration::from_secs(30)),
26929            retries: Some(3),
26930            circuit_breaker: Some(CircuitBreaker {
26931                max_failures: 5,
26932                window: Duration::from_secs(60),
26933            }),
26934            mtls_required: Some(true),
26935            rate_limit: Some(RateLimit {
26936                rate: 100,
26937                window: Duration::from_secs(1),
26938            }),
26939        };
26940        let json = serde_json::to_string(&p).unwrap();
26941        for key in [
26942            crate::POLITICAS_KEY_TIMEOUT,
26943            crate::POLITICAS_KEY_RETRIES,
26944            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26945            crate::POLITICAS_KEY_MTLS_REQUIRED,
26946            crate::POLITICAS_KEY_RATE_LIMIT,
26947        ] {
26948            let quoted = format!("\"{key}\"");
26949            assert!(
26950                json.contains(&quoted),
26951                "serialized MeshPolicy must carry the lifted \
26952                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
26953                 JSON emission (got: {json})",
26954            );
26955        }
26956    }
26957
26958    #[test]
26959    fn politicas_key_consts_are_pairwise_distinct() {
26960        // Cross-axis drift-detection pin: a future collapse of the five
26961        // canonical [`MeshPolicy`] singleton byte-strings onto the same
26962        // value (e.g. an accidental copy-paste flip of
26963        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
26964        // would silently reroute every downstream probe on one axis
26965        // onto the sibling axis's overlay entry and pass every
26966        // propagation-probe test that expected only the stale axis's
26967        // value — the M4 per-edge `:politicas` overlay projection would
26968        // read the retry-count string where the timeout duration was
26969        // expected (or vice versa), the CR materializer's admission
26970        // cross-check would compare the wrong pair of values, and the
26971        // resulting mesh reconciler would either bind the wrong axis
26972        // or reject the resource at reconcile far from the rebrand
26973        // commit's source. Peer of the sibling four-way distinct pin
26974        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
26975        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
26976        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
26977        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
26978        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26979        let all = [
26980            crate::POLITICAS_KEY_TIMEOUT,
26981            crate::POLITICAS_KEY_RETRIES,
26982            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26983            crate::POLITICAS_KEY_MTLS_REQUIRED,
26984            crate::POLITICAS_KEY_RATE_LIMIT,
26985        ];
26986        for (i, a) in all.iter().enumerate() {
26987            for b in all.iter().skip(i + 1) {
26988                assert_ne!(
26989                    a, b,
26990                    "POLITICAS_KEY_* consts must be pairwise-distinct \
26991                     canonical byte-sequences — got `{a}` == `{b}`",
26992                );
26993            }
26994        }
26995    }
26996
26997    #[test]
26998    fn politicas_key_consts_are_lower_camel_case_shape() {
26999        // Shape-pin: every `POLITICAS_KEY_*` const must be a
27000        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27001        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27002        // leading capital, no whitespace / dots) — the canonical shape
27003        // the `#[serde(rename_all = "camelCase")]` derive produces on
27004        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
27005        // at the derive surfaces both here (this test fails on the
27006        // stale-constant shape) and at
27007        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
27008        // (that test fails on the mismatch between const and derive).
27009        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
27010        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27011        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27012        // (ca463a4) on the sibling M3 typed-struct axes.
27013        for key in [
27014            crate::POLITICAS_KEY_TIMEOUT,
27015            crate::POLITICAS_KEY_RETRIES,
27016            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
27017            crate::POLITICAS_KEY_MTLS_REQUIRED,
27018            crate::POLITICAS_KEY_RATE_LIMIT,
27019        ] {
27020            assert!(
27021                !key.is_empty(),
27022                "POLITICAS_KEY_* must be non-empty (got {key:?})"
27023            );
27024            let first = key.chars().next().unwrap();
27025            assert!(
27026                first.is_ascii_lowercase(),
27027                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
27028                 byte (got {key:?}, leads with {first:?})",
27029            );
27030            assert!(
27031                key.chars().all(|c| c.is_ascii_alphanumeric()),
27032                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
27033                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27034            );
27035        }
27036    }
27037
27038    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
27039
27040    #[test]
27041    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
27042        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
27043        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
27044        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
27045        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
27046        // [`CircuitBreaker`] emits inside the
27047        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
27048        // two axes (`max_failures` → `maxFailures`) is a non-trivial
27049        // camelCase transform — the derive-attribute is load-bearing on
27050        // that axis, unlike the sibling `window` field where the derive
27051        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
27052        // pin that each canonical byte-sequence appears verbatim in the
27053        // JSON — a future accidental `rename_all = "snake_case"` /
27054        // `"kebab-case"` / verbatim-field-name flip at the derive
27055        // attribute (any of which would silently break every downstream
27056        // JSON consumer that reaches for one of the two consts via
27057        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
27058        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
27059        // per-edge `:politicas` overlay projection onto the mesh's
27060        // per-backend consecutive-failure-counter tripping threshold, the
27061        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
27062        // admission-time breaker cross-check, the future `feira lint`
27063        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
27064        // here as a build-time test failure at `aplicacao.rs`, not as an
27065        // apply-time `.get(<stale-canonical-const>)` returning `None`
27066        // far from the derive-attr drift's commit. Peer with the sibling
27067        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
27068        // (b55cca7) parent-axis pin — that test pins the outer
27069        // sub-block key the derive on [`MeshPolicy`] emits, this test
27070        // pins the inner keys the derive on the payload type emits, so
27071        // the two together lock the whole [`MeshPolicy`] breaker-tuning
27072        // shape end-to-end at build time.
27073        let cb = CircuitBreaker {
27074            max_failures: 5,
27075            window: Duration::from_secs(60),
27076        };
27077        let json = serde_json::to_string(&cb).unwrap();
27078        for key in [
27079            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27080            crate::CIRCUIT_BREAKER_KEY_WINDOW,
27081        ] {
27082            let quoted = format!("\"{key}\"");
27083            assert!(
27084                json.contains(&quoted),
27085                "serialized CircuitBreaker must carry the lifted \
27086                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
27087                 in the JSON emission (got: {json})",
27088            );
27089        }
27090    }
27091
27092    #[test]
27093    fn circuit_breaker_key_consts_are_pairwise_distinct() {
27094        // Cross-axis drift-detection pin: a future collapse of the two
27095        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
27096        // same value (e.g. an accidental copy-paste flip of
27097        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
27098        // `"maxFailures"`) would silently reroute every downstream
27099        // probe on one axis onto the sibling axis's overlay entry and
27100        // pass every propagation-probe test that expected only the
27101        // stale axis's value — the M4 per-edge `:politicas` overlay
27102        // projection would read the failure-count where the window
27103        // duration was expected (or vice versa), the CR materializer's
27104        // admission cross-check would compare the wrong pair of values,
27105        // and the resulting mesh reconciler would either bind the wrong
27106        // axis or reject the resource at reconcile far from the rebrand
27107        // commit's source. Peer of the sibling five-way distinct pin on
27108        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
27109        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
27110        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
27111        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
27112        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
27113        let all = [
27114            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27115            crate::CIRCUIT_BREAKER_KEY_WINDOW,
27116        ];
27117        for (i, a) in all.iter().enumerate() {
27118            for b in all.iter().skip(i + 1) {
27119                assert_ne!(
27120                    a, b,
27121                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
27122                     canonical byte-sequences — got `{a}` == `{b}`",
27123                );
27124            }
27125        }
27126    }
27127
27128    #[test]
27129    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
27130        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
27131        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27132        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27133        // leading capital, no whitespace / dots) — the canonical shape
27134        // the `#[serde(rename_all = "camelCase")]` derive produces on
27135        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
27136        // at the derive surfaces both here (this test fails on the
27137        // stale-constant shape) and at
27138        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
27139        // (that test fails on the mismatch between const and derive).
27140        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
27141        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
27142        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27143        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27144        // (ca463a4) on the sibling M3 typed-struct axes.
27145        for key in [
27146            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27147            crate::CIRCUIT_BREAKER_KEY_WINDOW,
27148        ] {
27149            assert!(
27150                !key.is_empty(),
27151                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
27152            );
27153            let first = key.chars().next().unwrap();
27154            assert!(
27155                first.is_ascii_lowercase(),
27156                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
27157                 byte (got {key:?}, leads with {first:?})",
27158            );
27159            assert!(
27160                key.chars().all(|c| c.is_ascii_alphanumeric()),
27161                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
27162                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27163            );
27164        }
27165    }
27166
27167    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
27168
27169    #[test]
27170    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
27171        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
27172        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
27173        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
27174        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
27175        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
27176        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
27177        // [`Placement`] emits. One of the four axes (`shard_key` →
27178        // `shardKey`) is a non-trivial camelCase transform — the
27179        // derive-attribute is load-bearing on that axis, unlike the
27180        // sibling `estrategia` / `clusters` / `affinity` axes whose
27181        // source-side field names carry no `_` and where the derive is a
27182        // no-op. Serialize a fully-populated [`Placement`] (both
27183        // `Option`-carrying axes `Some(_)` so
27184        // `skip_serializing_if = "Option::is_none"` fires on neither of
27185        // the two optional slots) and pin that each canonical
27186        // byte-sequence appears verbatim in the JSON — a future
27187        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
27188        // verbatim-field-name flip at the derive attribute (any of which
27189        // would silently break every downstream consumer that reaches
27190        // for one of the four consts via
27191        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
27192        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
27193        // aggregator's per-cluster fanout filter keying off
27194        // `placement.clusters`, the M3 shard-pool dispatch materializer
27195        // keying off `placement.shardKey`, the M3 Adaptive compression
27196        // pass weighting off `placement.affinity`, every downstream
27197        // dispatcher branching on `placement.estrategia`, the future
27198        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
27199        // admission-time placement cross-check, the future `feira lint`
27200        // per-`:placement` bound-check gate) surfaces here as a
27201        // build-time test failure at `aplicacao.rs`, not as an
27202        // apply-time `.get(<stale-canonical-const>)` returning `None`
27203        // far from the derive-attr drift's commit. Peer with the sibling
27204        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
27205        // (b55cca7),
27206        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
27207        // (468e959),
27208        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
27209        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
27210        // (ca463a4), and
27211        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
27212        // pins on the M3 collection-slot / singleton-slot atom axes —
27213        // closes the last M3 typed-struct top-level
27214        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
27215        // surface without a drift-detection pin.
27216        let p = Placement {
27217            estrategia: PlacementStrategy::Sharded,
27218            clusters: vec!["rio".into(), "mar".into()],
27219            affinity: Some("data-locality".into()),
27220            shard_key: Some("$tenantId".into()),
27221        };
27222        let json = serde_json::to_string(&p).unwrap();
27223        for key in [
27224            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27225            crate::M3_PLACEMENT_KEY_CLUSTERS,
27226            crate::M3_PLACEMENT_KEY_AFFINITY,
27227            crate::M3_PLACEMENT_KEY_SHARD_KEY,
27228        ] {
27229            let quoted = format!("\"{key}\"");
27230            assert!(
27231                json.contains(&quoted),
27232                "serialized Placement must carry the lifted \
27233                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
27234                 the JSON emission (got: {json})",
27235            );
27236        }
27237    }
27238
27239    #[test]
27240    fn m3_placement_key_consts_are_pairwise_distinct() {
27241        // Cross-axis drift-detection pin: a future collapse of the four
27242        // canonical [`Placement`] sub-block byte-strings onto the same
27243        // value (e.g. an accidental copy-paste flip of
27244        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
27245        // `"affinity"`) would silently reroute every downstream probe on
27246        // one axis onto the sibling axis's overlay entry and pass every
27247        // propagation-probe test that expected only the stale axis's
27248        // value — the M3 shard-pool dispatch materializer would read the
27249        // affinity placement-hint where the shard-selection template was
27250        // expected (or vice versa), the M3 Adaptive compression pass's
27251        // cross-check would compare the wrong pair of values, and the
27252        // resulting placement engine would either bind the wrong axis or
27253        // reject the resource at reconcile far from the rebrand commit's
27254        // source. Peer of the sibling two-way distinct pin on the
27255        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
27256        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
27257        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
27258        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
27259        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
27260        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
27261        let all = [
27262            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27263            crate::M3_PLACEMENT_KEY_CLUSTERS,
27264            crate::M3_PLACEMENT_KEY_AFFINITY,
27265            crate::M3_PLACEMENT_KEY_SHARD_KEY,
27266        ];
27267        for (i, a) in all.iter().enumerate() {
27268            for b in all.iter().skip(i + 1) {
27269                assert_ne!(
27270                    a, b,
27271                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
27272                     canonical byte-sequences — got `{a}` == `{b}`",
27273                );
27274            }
27275        }
27276    }
27277
27278    #[test]
27279    fn m3_placement_key_consts_are_lower_camel_case_shape() {
27280        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
27281        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27282        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27283        // leading capital, no whitespace / dots) — the canonical shape
27284        // the `#[serde(rename_all = "camelCase")]` derive produces on
27285        // [`Placement`]. A future flip to a non-camelCase attribute at
27286        // the derive surfaces both here (this test fails on the stale-
27287        // constant shape) and at
27288        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
27289        // (that test fails on the mismatch between const and derive).
27290        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
27291        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
27292        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
27293        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27294        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27295        // (ca463a4) on the sibling M3 typed-struct axes.
27296        for key in [
27297            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27298            crate::M3_PLACEMENT_KEY_CLUSTERS,
27299            crate::M3_PLACEMENT_KEY_AFFINITY,
27300            crate::M3_PLACEMENT_KEY_SHARD_KEY,
27301        ] {
27302            assert!(
27303                !key.is_empty(),
27304                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
27305            );
27306            let first = key.chars().next().unwrap();
27307            assert!(
27308                first.is_ascii_lowercase(),
27309                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
27310                 byte (got {key:?}, leads with {first:?})",
27311            );
27312            assert!(
27313                key.chars().all(|c| c.is_ascii_alphanumeric()),
27314                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
27315                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27316            );
27317        }
27318    }
27319
27320    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
27321    //    destination-facing L4 port resolver every per-Aplicacao renderer
27322    //    reaching for a per-destination Servico TCP port axis routes
27323    //    through. The four pin tests below fix the four-way accept-set
27324    //    the resolver must always honor: (:entrada-para-matches,
27325    //    :entrada-para-mismatches, :entrada-none-so-fallback,
27326    //    :entrada-port-non-default-honored) — drift on any arm surfaces
27327    //    at caixa-core build time rather than at cluster-apply time.
27328
27329    #[test]
27330    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
27331        // The typed `:entrada` block's `:para "cart"` matches the
27332        // queried destination, so the resolver returns the author-
27333        // declared `:port` scalar verbatim — the canonical "the
27334        // destination Servico IS the ingress apex, honor the typed
27335        // listener port" arm of the port-resolution dispatch.
27336        let mut spec = three_member_spec();
27337        if let Some(e) = spec.entrada.as_mut() {
27338            e.para = "cart".into();
27339            e.port = 9090;
27340        }
27341        assert_eq!(
27342            spec.port_for_destination("cart"),
27343            9090,
27344            "port_for_destination(entrada.para) must return entrada.port \
27345             verbatim, not the DEFAULT_SERVICO_PORT fallback"
27346        );
27347    }
27348
27349    #[test]
27350    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
27351        // The typed `:entrada` block names `:para "cart"`, but the
27352        // queried destination is `"payment"` — a Servico that
27353        // participates in the mesh graph but is not the ingress apex.
27354        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
27355        // canonical port floor, closing the "non-apex destination reads
27356        // the substrate default" arm. Same fixture the peer
27357        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
27358        // pin at caixa-mesh exercises through the CNP emit-side path;
27359        // this pin exercises the shared underlying resolver directly.
27360        let spec = three_member_spec();
27361        assert_eq!(
27362            spec.port_for_destination("payment"),
27363            DEFAULT_SERVICO_PORT,
27364            "port_for_destination(non-apex-destination) must route \
27365             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
27366        );
27367    }
27368
27369    #[test]
27370    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
27371        // Internal-only Aplicacao — no `:entrada` block declared. Every
27372        // per-destination port query falls back to the lifted
27373        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
27374        // the Aplicacao surface admits `:entrada None` (internal mesh
27375        // with no external gateway); every downstream renderer's per-
27376        // destination port axis must still resolve to a well-defined
27377        // scalar even without an ingress apex.
27378        let mut spec = three_member_spec();
27379        spec.entrada = None;
27380        assert_eq!(
27381            spec.port_for_destination("cart"),
27382            DEFAULT_SERVICO_PORT,
27383            "port_for_destination on an internal-only Aplicacao must \
27384             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
27385             every destination"
27386        );
27387        assert_eq!(
27388            spec.port_for_destination("payment"),
27389            DEFAULT_SERVICO_PORT,
27390            "port_for_destination on an internal-only Aplicacao must \
27391             fall back uniformly across every destination — the fallback \
27392             is not entrada-shape-conditional"
27393        );
27394    }
27395
27396    #[test]
27397    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
27398        // Structural pin against a hypothetical future refactor that
27399        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
27400        // the resolver (a "normalize to the default when the author's
27401        // port matches the substrate default" collapse) — that would
27402        // break renderer sites that carry meaning on the emitted port
27403        // value beyond bare equality (a future per-cluster listener-
27404        // audit that keys off the author-declared port, not the
27405        // resolved-with-fallback port). Pin that a non-default
27406        // entrada.port is returned verbatim so drift here surfaces at
27407        // caixa-core build time.
27408        let mut spec = three_member_spec();
27409        if let Some(e) = spec.entrada.as_mut() {
27410            e.para = "cart".into();
27411            e.port = 8443;
27412        }
27413        assert_ne!(
27414            8443, DEFAULT_SERVICO_PORT,
27415            "test fixture must probe a port distinct from \
27416             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
27417        );
27418        assert_eq!(
27419            spec.port_for_destination("cart"),
27420            8443,
27421            "port_for_destination(entrada.para) must return entrada.port \
27422             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
27423        );
27424    }
27425
27426    #[test]
27427    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
27428        // Apex-identity pair-invariant pin composing both substrate-
27429        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
27430        // and [`Entrada::destination`] — at the emit-side call shape
27431        // every per-Aplicacao renderer's ingress-apex L4 port reader
27432        // now takes. The invariant:
27433        //
27434        //   spec.port_for_destination(entrada.destination()) == entrada.port
27435        //
27436        // holds by construction under today's single-destination
27437        // `:entrada` slot (`destination()` returns `entrada.para`, and
27438        // the resolver's apex arm matches `para == destination` and
27439        // returns `entrada.port`), and every downstream consumer that
27440        // composes the two accessors at the ingress apex — the
27441        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
27442        // `backendRefs[0].port` emit-site path, the peer future M4 CR
27443        // materializer's admission-webhook that promotes the scalar to
27444        // a per-CR override overlay, every future per-Aplicacao snapshot
27445        // renderer's apex-facing L4 port reader — reaches through the
27446        // same composition. Pin the identity across four permutations
27447        // (`:para` × `:port` including a non-default port to exercise
27448        // the honor-verbatim arm and a non-cart `:para` to exercise
27449        // destination-agnostic identity) so a future refactor that
27450        // silently split either accessor's apex behavior surfaces at
27451        // caixa-core build time — a subtle `destination()` renaming
27452        // that returned `entrada.host.as_str()` instead of
27453        // `entrada.para.as_str()` would blow this pin loudly, closing
27454        // the last quiet failure mode the two lifts admit in composition.
27455        //
27456        // Peer discipline with the sibling caixa-mesh cross-crate pin
27457        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
27458        // on the two-renderer pair-invariant axis; this pin encodes the
27459        // same two-consumer coherence rule at the substrate-primitive
27460        // level so the invariant survives even if every renderer is
27461        // deleted.
27462        for (para, port) in [
27463            ("cart", DEFAULT_SERVICO_PORT),
27464            ("cart", 8443u16),
27465            ("payment", 9090u16),
27466            ("catalog", 443u16),
27467        ] {
27468            let mut spec = three_member_spec();
27469            if let Some(e) = spec.entrada.as_mut() {
27470                e.para = para.into();
27471                e.port = port;
27472            }
27473            let expected_port = spec
27474                .entrada()
27475                .expect("three_member_spec carries a typed `:entrada` block")
27476                .port();
27477            let composed_port = {
27478                let entrada = spec.entrada().expect("entrada present");
27479                spec.port_for_destination(entrada.destination())
27480            };
27481            assert_eq!(
27482                composed_port, expected_port,
27483                "`spec.port_for_destination(entrada.destination())` must \
27484                 equal `entrada.port` under today's single-destination \
27485                 `:entrada` slot — this is the apex-identity contract \
27486                 every downstream ingress-apex L4 port reader relies on. \
27487                 Input :entrada :para: {para:?}, :entrada :port: {port}"
27488            );
27489        }
27490    }
27491
27492    #[test]
27493    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
27494        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
27495        // per-`:entrada` apex-arm membership probe must key off
27496        // [`Entrada::destination`], not the raw `.para` field access.
27497        // Structurally: setting ONLY the `:entrada :para` field to a
27498        // fresh non-cart destination on an otherwise-well-formed
27499        // Aplicacao must (1) leave `e.destination()` byte-equal to
27500        // `e.para.as_str()` (the accessor is byte-projective by
27501        // definition), and (2) cause the resolver's apex arm to fire
27502        // and return `entrada.port` at exactly that new destination
27503        // while every other destination string falls through to
27504        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
27505        // membership check. Pins against a future silent detour that
27506        // (a) re-derived the apex-arm membership probe off
27507        // `e.para == destination` in `port_for_destination` instead of
27508        // `e.destination() == destination`, silently disagreeing with
27509        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
27510        // consumers (`entrada.destination()` at
27511        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
27512        // caixa-mesh/src/lib.rs:2739) that already reach through the
27513        // accessor, (b) accessor-side introduced a per-tenant alias
27514        // arm the caller was unaware of, silently rewriting an
27515        // author-declared `:para "cart"` value to a canary-aliased
27516        // form — the raw-field-access resolver would fall through to
27517        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
27518        // while the peer emit-site consumers landed on the aliased
27519        // destination, splitting the ingress-apex L4 port at
27520        // cluster-apply time.
27521        //
27522        // Peer of the sibling
27523        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
27524        // (d0de220) composition pin on the per-`:membros` refusal-arm
27525        // axis — same "the shape-gate predicate must route through the
27526        // substrate-primitive typed dispatch" discipline extended onto
27527        // the per-`:entrada` apex-arm membership-probe axis. Closes
27528        // the last unlifted `.para` production-code read site on
27529        // `Entrada` in `caixa-core` — after this converge every
27530        // `caixa-core` `.para` field access outside the accessor's own
27531        // body and outside the `WitContract` per-`:contratos` sibling
27532        // axis is either a test-side field-setter or a doc-comment
27533        // reference.
27534        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
27535            let mut spec = three_member_spec();
27536            if let Some(e) = spec.entrada.as_mut() {
27537                e.para = para.into();
27538                e.port = port;
27539            }
27540            let e = spec
27541                .entrada
27542                .as_ref()
27543                .expect("three_member_spec carries a typed `:entrada` block");
27544            assert_eq!(
27545                e.destination(),
27546                e.para.as_str(),
27547                "Entrada::destination must byte-equal the .para field \
27548                 access — an accessor-side detour that no longer \
27549                 projects the raw field would silently split this \
27550                 drift-detection test from the port_for_destination \
27551                 apex-arm membership probe",
27552            );
27553            assert_eq!(
27554                spec.port_for_destination(para),
27555                port,
27556                "port_for_destination must key off the accessor-projected \
27557                 destination and return `entrada.port` on the apex arm — \
27558                 input :entrada :para: {para:?}, :entrada :port: {port}",
27559            );
27560            assert_eq!(
27561                spec.port_for_destination("ghost-destination-never-a-member"),
27562                DEFAULT_SERVICO_PORT,
27563                "port_for_destination must fall through to \
27564                 DEFAULT_SERVICO_PORT on a non-matching destination \
27565                 under the accessor-projected membership check — input \
27566                 :entrada :para: {para:?}, :entrada :port: {port}",
27567            );
27568        }
27569    }
27570
27571    #[test]
27572    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
27573        // The canonical per-`:politicas :rate-limit` `:rate`
27574        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
27575        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
27576        // typed `u32` verbatim, byte-equal to the raw field access
27577        // across every representative value in the accept-set — `1` (the
27578        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
27579        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
27580        // carves out on the sibling `PolicyRateLimitZero` refusal),
27581        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
27582        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
27583        // `0` (a past-the-guard sentinel that pins the accessor doesn't
27584        // perform a silent bounds-collapse into `1` on the zero arm —
27585        // validate rejects zero but the accessor must ship the raw slot
27586        // verbatim so a validate-time gate regression surfaces at the
27587        // emit boundary rather than being silently absorbed), `u32::MAX`
27588        // (a past-the-guard sentinel that pins the accessor doesn't
27589        // perform a silent bounds-collapse through
27590        // `POLICY_RATE_LIMIT_MAX` at the return path).
27591        //
27592        // First sub-struct required-scalar accessor pin on the
27593        // `RateLimit` axis — sibling in shape to the peer
27594        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
27595        // required-`u32` accessor pin on the peer per-sub-struct
27596        // required-axis. Pins against a future silent detour that
27597        // re-derived the token capacity from a peer axis (an accidental
27598        // `self.window.as_secs() as u32` collapse that read the
27599        // rate-limit window duration as a token count), a `0 → 1`
27600        // cluster-default projection (which would silently absorb the
27601        // `PolicyRateLimitZero` refusal case at the accessor boundary),
27602        // or a bounds-collapsing accessor that clamped the return
27603        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
27604        // gate owns the bounds; the accessor must ship the raw slot
27605        // verbatim).
27606        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27607            let rl = RateLimit {
27608                rate,
27609                window: Duration::from_secs(1),
27610            };
27611            assert_eq!(
27612                rl.rate(),
27613                rate,
27614                "RateLimit::rate must return :politicas :rate-limit :rate \
27615                 verbatim (got {}, expected {rate})",
27616                rl.rate(),
27617            );
27618            assert_eq!(
27619                rl.rate(),
27620                rl.rate,
27621                "RateLimit::rate must byte-equal the raw .rate field \
27622                 access across every value in the u32 accept-set",
27623            );
27624        }
27625    }
27626
27627    #[test]
27628    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
27629        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27630        // `:rate-limit :rate` zero-floor arm must key off
27631        // [`RateLimit::rate`], not the raw `.rate` field access.
27632        // Structurally: a `RateLimit { rate: 0, window:
27633        // Duration::from_secs(1) }` embedded in a `:politicas
27634        // :rate-limit` slot must surface the `PolicyRateLimitZero`
27635        // refusal exactly, and a `RateLimit { rate: 1, window:
27636        // Duration::from_secs(1) }` (the lower boundary of the
27637        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
27638        // The pair jointly pins the accessor + validate-gate composition:
27639        // any future silent detour that had the accessor return a fresh
27640        // `1` on the zero arm (a `.rate().max(1)` collapse) would
27641        // silently absorb the `PolicyRateLimitZero` refusal at the
27642        // accessor boundary and the validate gate would accept a
27643        // struct-literal `RateLimit { rate: 0, .. }` — the composition
27644        // pin catches that at caixa-core build time.
27645        //
27646        // Peer of the sibling per-`CircuitBreaker`
27647        // [`CircuitBreaker::max_failures`] (3a74062) /
27648        // [`CircuitBreaker::window`] (373957f) accessor-composition
27649        // pins on the peer required-scalar axes — same "the validate /
27650        // shape-gate predicate must route through the substrate-primitive
27651        // typed dispatch" discipline extended onto the peer
27652        // per-`RateLimit` required-`u32` composition axis.
27653        let mut spec = three_member_spec();
27654        spec.politicas = MeshPolicy {
27655            rate_limit: Some(RateLimit {
27656                rate: 0,
27657                window: Duration::from_secs(1),
27658            }),
27659            ..MeshPolicy::default()
27660        };
27661        assert!(
27662            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
27663            "validate_politicas must reject rate == 0 with \
27664             PolicyRateLimitZero — the accessor and the validate gate \
27665             must route through the same substrate-primitive typed \
27666             dispatch on the :rate zero-floor arm",
27667        );
27668        spec.politicas = MeshPolicy {
27669            rate_limit: Some(RateLimit {
27670                rate: 1,
27671                window: Duration::from_secs(1),
27672            }),
27673            ..MeshPolicy::default()
27674        };
27675        assert!(
27676            spec.validate().is_ok(),
27677            "validate_politicas must accept rate == 1 (the lower \
27678             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
27679        );
27680    }
27681
27682    #[test]
27683    fn rate_limit_rate_projects_u32_by_copy() {
27684        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
27685        // `u32` is `Copy` and the accessor must return by value, not by
27686        // reference. Peer of the sibling per-`CircuitBreaker`
27687        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
27688        // peer required-scalar `:max-failures` axis, extended onto the
27689        // peer per-`RateLimit` required-`u32` copy-invariant shape —
27690        // the accessor's returned `u32` must outlive `&self` (multiple
27691        // calls must return equal values from a dropped-`&self` copy,
27692        // since the returned scalar carries no borrow), and calling the
27693        // accessor twice on the same RateLimit must yield the same
27694        // `u32` verbatim (idempotent, no side effects on `&self`).
27695        //
27696        // Pins against a future silent detour that returned `&u32`
27697        // (which would type-check but silently break every downstream
27698        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
27699        // first parameter is `u32`, and `&u32` would fold to a detached
27700        // copy at the call site with a `*` deref the sibling accessors
27701        // don't need), an accidental `.rate.wrapping_add(0)` detour that
27702        // returned a fresh copy through an arithmetic no-op (breaking a
27703        // future `const fn` regression), or a one-arm-only accessor
27704        // that returned a saturating value on some sentinel input
27705        // (breaking the pass-through invariant the sibling required-
27706        // scalar accessors carry).
27707        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27708            let rl = RateLimit {
27709                rate,
27710                window: Duration::from_secs(1),
27711            };
27712            let first = rl.rate();
27713            let second = rl.rate();
27714            assert_eq!(
27715                first, second,
27716                "RateLimit::rate must be idempotent — two successive \
27717                 calls on the same &self must return the same u32",
27718            );
27719            assert_eq!(
27720                first, rate,
27721                "RateLimit::rate must return :politicas :rate-limit :rate \
27722                 verbatim by copy — got {first}, expected {rate}",
27723            );
27724        }
27725    }
27726
27727    #[test]
27728    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
27729        // The canonical per-`:politicas :rate-limit` `:window`
27730        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
27731        // pin: [`RateLimit::window`] must return the
27732        // `:politicas :rate-limit :window` typed `Duration` verbatim,
27733        // byte-equal to the raw field access across every
27734        // representative value in the accept-set — `Duration::from_secs(1)`
27735        // (the `"s"` canonical window, the lower row of
27736        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
27737        // [`AplicacaoSpec::validate_politicas`] gate accepts via
27738        // [`is_canonical_rate_limit_window`]),
27739        // `Duration::from_secs(60)` (the `"m"` canonical window, the
27740        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
27741        // window, the upper row), `Duration::ZERO` (a past-the-guard
27742        // sentinel that pins the accessor doesn't perform a silent
27743        // bounds-collapse into `Duration::from_secs(1)` on the zero
27744        // arm — validate rejects an off-set window through
27745        // `PolicyRateLimitWindowNotCanonical` but the accessor must
27746        // ship the raw slot verbatim so a validate-time gate
27747        // regression surfaces at the emit boundary rather than being
27748        // silently absorbed), `Duration::from_millis(500)` (a
27749        // sub-canonical past-the-guard sentinel that pins the accessor
27750        // doesn't silently normalize a non-canonical fractional
27751        // magnitude onto the nearest canonical row).
27752        //
27753        // Second sub-struct required-scalar accessor pin on the
27754        // `RateLimit` axis — sibling in shape to the just-landed
27755        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
27756        // accessor pin on the peer per-sub-struct required-axis,
27757        // extended onto the per-`RateLimit` required-`Duration` axis.
27758        // Pins against a future silent detour that re-derived the
27759        // refill period from a peer axis (an accidental
27760        // `Duration::from_secs(self.rate as u64)` collapse that read
27761        // the rate-limit token capacity as a refill-interval
27762        // duration), a `Duration::ZERO → Duration::from_secs(1)`
27763        // canonical-default projection (which would silently absorb
27764        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
27765        // accessor boundary), or a canonical-set-collapsing accessor
27766        // that clamped the return through [`rate_limit_window_unit`]
27767        // (the `AplicacaoSpec::validate` gate owns the canonical-set
27768        // membership; the accessor must ship the raw slot verbatim).
27769        for window in [
27770            Duration::from_secs(1),
27771            Duration::from_secs(60),
27772            Duration::from_secs(3600),
27773            Duration::ZERO,
27774            Duration::from_millis(500),
27775        ] {
27776            let rl = RateLimit { rate: 100, window };
27777            assert_eq!(
27778                rl.window(),
27779                window,
27780                "RateLimit::window must return :politicas :rate-limit :window \
27781                 verbatim (got {:?}, expected {window:?})",
27782                rl.window(),
27783            );
27784            assert_eq!(
27785                rl.window(),
27786                rl.window,
27787                "RateLimit::window must byte-equal the raw .window field \
27788                 access across every value in the Duration accept-set",
27789            );
27790        }
27791    }
27792
27793    #[test]
27794    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
27795        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27796        // `:rate-limit :window` canonical-set arm must key off
27797        // [`RateLimit::window`], not the raw `.window` field access.
27798        // Structurally: a `RateLimit { window: Duration::from_millis(500),
27799        // .. }` embedded in a `:politicas :rate-limit` slot must
27800        // surface the `PolicyRateLimitWindowNotCanonical` refusal
27801        // exactly (with the sub-canonical `Duration::from_millis(500)`
27802        // magnitude carried through verbatim), and a `RateLimit
27803        // { window: Duration::from_secs(1), .. }` (the lower row of
27804        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
27805        // The pair jointly pins the accessor + validate-gate
27806        // composition: any future silent detour that had the accessor
27807        // normalize the off-set window to the nearest canonical row
27808        // (a `.window().max(Duration::from_secs(1))` collapse, or a
27809        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
27810        // collapse) would silently absorb the
27811        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
27812        // boundary — including a drift in the error's `window` payload
27813        // (the emit-side diagnostic reader keys off the offending
27814        // magnitude verbatim, so a normalization at the accessor
27815        // boundary would silently pin the wrong magnitude in the
27816        // refusal). The composition pin catches that at caixa-core
27817        // build time.
27818        //
27819        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
27820        // (7f81a60) accessor-composition pin on the peer required-
27821        // scalar `:rate` axis — same "the validate / shape-gate
27822        // predicate must route through the substrate-primitive typed
27823        // dispatch, and the error payload must project through the
27824        // same accessor" discipline extended onto the peer
27825        // per-`RateLimit` required-`Duration` composition axis.
27826        let mut spec = three_member_spec();
27827        spec.politicas = MeshPolicy {
27828            rate_limit: Some(RateLimit {
27829                rate: 100,
27830                window: Duration::from_millis(500),
27831            }),
27832            ..MeshPolicy::default()
27833        };
27834        match spec.validate() {
27835            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
27836                assert_eq!(
27837                    window,
27838                    Duration::from_millis(500),
27839                    "PolicyRateLimitWindowNotCanonical must carry the \
27840                     offending :window magnitude verbatim through the \
27841                     accessor — got {window:?}, expected 500ms",
27842                );
27843            }
27844            other => panic!(
27845                "validate_politicas must reject non-canonical :window \
27846                 with PolicyRateLimitWindowNotCanonical — the accessor \
27847                 and the validate gate must route through the same \
27848                 substrate-primitive typed dispatch on the :window \
27849                 canonical-set arm; got {other:?}",
27850            ),
27851        }
27852        spec.politicas = MeshPolicy {
27853            rate_limit: Some(RateLimit {
27854                rate: 100,
27855                window: Duration::from_secs(1),
27856            }),
27857            ..MeshPolicy::default()
27858        };
27859        assert!(
27860            spec.validate().is_ok(),
27861            "validate_politicas must accept window == Duration::from_secs(1) \
27862             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
27863        );
27864    }
27865
27866    #[test]
27867    fn rate_limit_window_projects_duration_by_copy() {
27868        // The by-copy pin: [`RateLimit::window`] returns `Duration`
27869        // by copy — `Duration` is `Copy` and the accessor must return
27870        // by value, not by reference. Peer of the sibling per-`RateLimit`
27871        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
27872        // required-scalar `:rate` axis, extended onto the peer
27873        // per-`RateLimit` required-`Duration` copy-invariant shape —
27874        // the accessor's returned `Duration` must outlive `&self`
27875        // (multiple calls must return equal values from a
27876        // dropped-`&self` copy, since the returned scalar carries no
27877        // borrow), and calling the accessor twice on the same
27878        // RateLimit must yield the same `Duration` verbatim
27879        // (idempotent, no side effects on `&self`).
27880        //
27881        // Pins against a future silent detour that returned
27882        // `&Duration` (which would type-check but silently break every
27883        // downstream `Duration`-by-value consumer —
27884        // [`is_canonical_rate_limit_window`]'s first parameter is
27885        // `Duration`, and `&Duration` would fold to a detached copy at
27886        // the call site with a `*` deref the sibling accessors don't
27887        // need), an accidental `.window + Duration::ZERO` detour that
27888        // returned a fresh copy through an arithmetic no-op (breaking
27889        // a future `const fn` regression), or a one-arm-only accessor
27890        // that returned a canonical fallback on some sentinel input
27891        // (breaking the pass-through invariant the sibling required-
27892        // scalar accessors carry).
27893        for window in [
27894            Duration::from_secs(1),
27895            Duration::from_secs(60),
27896            Duration::from_secs(3600),
27897            Duration::ZERO,
27898            Duration::from_millis(500),
27899        ] {
27900            let rl = RateLimit { rate: 100, window };
27901            let first = rl.window();
27902            let second = rl.window();
27903            assert_eq!(
27904                first, second,
27905                "RateLimit::window must be idempotent — two successive \
27906                 calls on the same &self must return the same Duration",
27907            );
27908            assert_eq!(
27909                first, window,
27910                "RateLimit::window must return :politicas :rate-limit :window \
27911                 verbatim by copy — got {first:?}, expected {window:?}",
27912            );
27913        }
27914    }
27915
27916    #[test]
27917    fn placement_estrategia_default_pins_m3_canonical_value() {
27918        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
27919        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
27920        // active-active-across-every-named-cluster arm, the closest
27921        // canonical M3 production reference the substrate carries and
27922        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
27923        // for every un-`:placement`-declared Aplicacao. Pinning the arm
27924        // here surfaces a future rebrand of the M3-canonical
27925        // distribution default (a widening to `Sharded` once the
27926        // substrate discovers hash-keyed distribution as the more
27927        // common production shape, a tightening to `SingleNode` for
27928        // stateful Erlang/OTP distributed-app-takeover semantics
27929        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
27930        // operator pins through a future `:placement-overrides` slot)
27931        // as a deliberate test edit, not a silent contract migration.
27932        // Peer of the sibling M2 per-supervisor value pins
27933        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
27934        // /
27935        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
27936        // extended onto the M3 mesh-primitive-defining `:placement
27937        // :estrategia` axis.
27938        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
27939    }
27940
27941    #[test]
27942    fn placement_strategy_default_routes_through_lifted_default() {
27943        // Composition pin: the [`Default for PlacementStrategy`] impl's
27944        // return arm must route through the substrate-canonical
27945        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
27946        // a raw `Self::Replicated` arm. Prior to the lift the impl
27947        // carried an inline `Self::Replicated` arm with no compile-time
27948        // link back to the shared M3-canonical `Replicated` arm the
27949        // paired [`Default for Placement`] impl's struct-literal
27950        // `estrategia` field, the serde-side `#[serde(default)]` on
27951        // [`Placement::estrategia`] that resolves an author-omitted
27952        // wire-form `:placement :estrategia` scalar through the impl,
27953        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
27954        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
27955        // routes through [`Placement::default`] which routes through the
27956        // strategy default) all key off — so a future rebrand of the
27957        // M3-canonical distribution default would have had to be threaded
27958        // through the `Default` impl and the three peer routes in
27959        // lockstep or the four consumers would silently split. Byte-
27960        // parity against the lifted constant closes the split. Peer of
27961        // the sibling
27962        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
27963        // /
27964        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
27965        // composition pins on the M2 per-supervisor axes.
27966        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
27967    }
27968
27969    #[test]
27970    fn placement_default_estrategia_routes_through_lifted_default() {
27971        // Composition pin: the [`Default for Placement`] impl's
27972        // struct-literal `estrategia` field must route through the
27973        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
27974        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
27975        // impl that the sibling
27976        // `placement_strategy_default_routes_through_lifted_default` pin
27977        // already routes onto the constant). Structurally: every
27978        // `Placement::default()` call must yield an `estrategia` field
27979        // byte-equal to the lifted constant so the two paired defaults —
27980        // the [`Default for PlacementStrategy`] impl arm and the
27981        // struct-literal default arm here — cannot silently split on any
27982        // future M3-canonical distribution-default rebrand. Peer of the
27983        // sibling M2
27984        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
27985        // byte-parity pin on the [`Default for SupervisorSpec`]
27986        // struct-literal `estrategia` field extended onto the M3
27987        // mesh-primitive-defining slot family.
27988        assert_eq!(
27989            Placement::default().estrategia,
27990            PLACEMENT_ESTRATEGIA_DEFAULT,
27991        );
27992    }
27993
27994    #[test]
27995    fn placement_serde_default_estrategia_routes_through_lifted_default() {
27996        // Composition pin: the serde-side `#[serde(default)]` on
27997        // [`Placement::estrategia`] — the wire-format author-omitted
27998        // `:placement :estrategia` arm — must resolve onto the substrate-
27999        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
28000        // (via the [`Default for PlacementStrategy`] impl the sibling
28001        // `placement_strategy_default_routes_through_lifted_default` pin
28002        // already routes onto the constant). Structurally: a `Placement`
28003        // deserialized from a payload that omits the `estrategia` key
28004        // must yield an `estrategia` field byte-equal to the lifted
28005        // constant, so the wire-format author-omitted arm and the
28006        // [`PlacementStrategy::default`] impl arm cannot silently split
28007        // on any future M3-canonical distribution-default rebrand. Peer
28008        // of the sibling M2
28009        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
28010        // byte-parity pin on the wire-format author-omitted `:children
28011        // :restart` scalar extended onto the M3 mesh-primitive-defining
28012        // slot family.
28013        let omitted: Placement = serde_json::from_str("{}")
28014            .expect("Placement must deserialize with the estrategia key omitted");
28015        assert_eq!(
28016            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
28017            "an author-omitted :placement :estrategia slot must degrade onto \
28018             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
28019             {:?}, expected {:?})",
28020            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
28021        );
28022    }
28023}