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 fn endpoint(&self) -> Option<&str> {
662        self.endpoint.as_deref()
663    }
664
665    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
666    /// payload-target scalar accessor every consumer that reads the
667    /// edge's NATS / Kafka publish subject payload keys off — returns
668    /// the author-declared `:contratos :subject` byte-string verbatim
669    /// as an `Option<&str>`, borrowed from the typed slot's own
670    /// `Option<String>` storage; `None` when the slot is absent (the
671    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
672    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
673    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
674    /// [`WitTarget::Capability`] edge carries none of the three).
675    ///
676    /// The `:contratos :subject` slot carries the NATS / Kafka publish
677    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
678    /// per-edge target selector — `orders.paid`, `events.>`, whatever
679    /// subject namespace the author names on the pub-sub edge) that
680    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
681    /// arm's `subject: &'a str` payload when the edge's `:wit` world
682    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
683    /// downstream consumer that reads the payload keys off this scalar
684    /// (the [`WitContract::target`] PubSub-arm payload extraction that
685    /// materializes [`WitTarget::PubSub { subject }`] under the paired
686    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
687    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
688    /// key's subject arm that pins the payload as part of the six-tuple
689    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
690    /// future M4 per-edge WIT registry resolver's pub-sub-arm
691    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
692    /// materializer's per-edge NATS admission webhook, the future
693    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
694    /// as a NATS subject the operator pins per-CR).
695    ///
696    /// Prior to this lift the `.subject` field was accessed inline at
697    /// two production sites in `caixa-core/src/aplicacao.rs` — the
698    /// [`WitContract::target`] payload-shape dispatch's `let subject =
699    /// self.subject.as_deref();` binding at the top of the method, and
700    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
701    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
702    /// field-accesses that expressed no compile-time link back to the
703    /// typed slot. A future extension of the `:contratos :subject` axis
704    /// to a richer author surface (an M4 promotion from `Option<String>`
705    /// to a typed NATS-subject-template enum once the WIT registry
706    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
707    /// struct's own `:wit` field docstring, a per-cluster subject-alias
708    /// table the operator pins through a future `:placement`-scoped
709    /// slot, a canonicalization pass that lowercases / dedupes wildcard
710    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
711    /// applies per-tenant) would have had to be threaded through both
712    /// open-coded copies in lockstep or the two consumers would silently
713    /// disagree on which NATS subject a given edge resolves to — the
714    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
715    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
716    /// resolved `"tenant-a.orders.paid"` would silently split the
717    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
718    /// key uniqueness axis, a two-consumer split at the validator far
719    /// from the source `caixa.lisp` with no field naming the payload-
720    /// drift root cause. Lifting the resolution rule to a typed method
721    /// on the substrate primitive means every downstream pub-sub-payload-
722    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
723    /// surface reaches for exactly one typed dispatch — the resolver's
724    /// accept-set migrates as a unit on any future axis addition.
725    ///
726    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
727    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
728    /// carrier axis — second `Option<&str>`-return accessor on the
729    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
730    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
731    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
732    /// key/value-store arm as the last unlifted per-`:contratos`
733    /// `Option<String>` axis. Named `subject()` to match the storage
734    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
735    /// author-facing label const; the accessor's identity name maps
736    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
737    /// docstring already carries.
738    #[must_use]
739    pub fn subject(&self) -> Option<&str> {
740        self.subject.as_deref()
741    }
742
743    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
744    /// shaped payload-target scalar accessor every consumer that reads
745    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
746    /// off — returns the author-declared `:contratos :slot` byte-string
747    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
748    /// own `Option<String>` storage; `None` when the slot is absent
749    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
750    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
751    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
752    /// [`WitTarget::Capability`] edge carries none of the three).
753    ///
754    /// The `:contratos :slot` slot carries the key/value store
755    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
756    /// arm's per-edge target selector — `carts/{cart_id}`,
757    /// `sessions/{tenant}/{sid}`, whatever key-template the author
758    /// names on the store edge) that [`WitContract::target`] projects
759    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
760    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
761    /// accept-set. Every downstream consumer that reads the payload
762    /// keys off this scalar (the [`WitContract::target`] Store-arm
763    /// payload extraction that materializes [`WitTarget::Store { slot }`]
764    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
765    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
766    /// key's store arm that pins the payload as part of the six-tuple
767    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
768    /// the future M4 per-edge WIT registry resolver's store-arm
769    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
770    /// materializer's per-edge key/value admission webhook, the future
771    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
772    /// as a key-template the operator pins per-CR).
773    ///
774    /// Prior to this lift the `.slot` field was accessed inline at two
775    /// production sites in `caixa-core/src/aplicacao.rs` — the
776    /// [`WitContract::target`] payload-shape dispatch's `let slot =
777    /// self.slot.as_deref();` binding at the top of the method, and
778    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
779    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
780    /// field-accesses that expressed no compile-time link back to the
781    /// typed slot. A future extension of the `:contratos :slot` axis
782    /// to a richer author surface (an M4 promotion from `Option<String>`
783    /// to a typed key-template enum once the WIT registry stabilizes
784    /// key-template parameter shapes in tatara-lisp per this struct's
785    /// own `:wit` field docstring, a per-cluster slot-alias table the
786    /// operator pins through a future `:placement`-scoped slot, a
787    /// canonicalization pass that lowercases the bucket prefix, a
788    /// per-CR fully-qualified rewrite the M4 CR materializer applies
789    /// per-tenant) would have had to be threaded through both
790    /// open-coded copies in lockstep or the two consumers would
791    /// silently disagree on which key-template a given edge resolves
792    /// to — the [`WitContract::target`] payload-extraction reading
793    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
794    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
795    /// would silently split the [`WitTarget::Store`]-arm rendered
796    /// payload from the actual dedup-key uniqueness axis, a
797    /// two-consumer split at the validator far from the source
798    /// `caixa.lisp` with no field naming the payload-drift root cause.
799    /// Lifting the resolution rule to a typed method on the substrate
800    /// primitive means every downstream store-payload-facing consumer
801    /// of the Aplicacao's per-`:contratos` payload surface reaches for
802    /// exactly one typed dispatch — the resolver's accept-set migrates
803    /// as a unit on any future axis addition.
804    ///
805    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
806    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
807    /// accessors on the M3 mesh-slot payload-carrier axis — third and
808    /// final `Option<&str>`-return accessor on the per-`:contratos`
809    /// mesh-slot atom, closes the last unlifted per-`:contratos`
810    /// `Option<String>` axis and completes the "optional per-slot
811    /// payload-carrier scalar" projection pattern the peer HTTP /
812    /// pub-sub arms established across the three payload-shape
813    /// dispatch arms. Named `slot()` to match the storage field's
814    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
815    /// author-facing label const; the accessor's identity name maps
816    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
817    /// docstring already carries.
818    #[must_use]
819    pub fn slot(&self) -> Option<&str> {
820        self.slot.as_deref()
821    }
822
823    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
824    /// caller-callee-pair accessor every consumer that constructs an
825    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
826    /// caller-callee pair keys off — returns the author-declared
827    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
828    /// owned `(String, String)` tuple, projected through the lifted
829    /// [`WitContract::source`] / [`WitContract::destination`] scalar
830    /// accessors so any future rebrand on the caller-arm / callee-arm
831    /// projection axis (an M4 per-cluster caller-alias table the
832    /// operator pins through a future `:placement`-scoped slot, a
833    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
834    /// a per-`:membros` alias overlay from the future `:membros
835    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
836    /// acknowledges) reaches every diagnostic-construction site by
837    /// construction.
838    ///
839    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
840    /// owned form" primitive every per-`:contratos` diagnostic variant on
841    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
842    /// nine variants [`AplicacaoError::EmptyWit`],
843    /// [`AplicacaoError::ContratoEndpointEmpty`],
844    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
845    /// [`AplicacaoError::ContratoEndpointInvalid`],
846    /// [`AplicacaoError::ContratoSubjectEmpty`],
847    /// [`AplicacaoError::ContratoSubjectInvalid`],
848    /// [`AplicacaoError::ContratoSlotEmpty`],
849    /// [`AplicacaoError::ContratoSlotInvalid`], and
850    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
851    /// para: String` field pair the constructor site reads verbatim off
852    /// the [`WitContract`] the diagnostic points at, so a diagnostic
853    /// whose `de:` and `para:` labels silently drift off the source
854    /// caller/callee — a per-cluster caller-alias rewrite that landed on
855    /// one variant's inline `de: c.de.clone()` field access but not on
856    /// its sibling variant's, an accidental swap of the `de:` and `para:`
857    /// arms in a copy-paste of the constructor block — would emit a
858    /// build-time error whose "which caixa is at fault" question the
859    /// operator answers wrongly, far from the source `caixa.lisp`.
860    ///
861    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
862    /// pair was inlined at seven [`WitContract::target`] error-
863    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
864    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
865    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
866    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
867    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
868    /// the [`AplicacaoError::ContratoSlotEmpty`] /
869    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
870    /// two [`AplicacaoSpec::validate`] error-construction sites (the
871    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
872    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
873    /// insert-first-seen closure) — nine open-coded `.de.clone() +
874    /// .para.clone()` pairs that expressed no compile-time contract that
875    /// the caller-arm and callee-arm arms of the same diagnostic
876    /// construction reach for the same [`WitContract`] instance or that
877    /// the `de:` and `para:` label pair binds to the fields the author
878    /// declared. Any future rebrand on the axis — an M4 per-cluster
879    /// caller/callee-alias rewrite the operator pins through a future
880    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
881    /// per-CR fully-qualified namespace prefix the M4
882    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
883    /// per-tenant, a canonicalization pass that lowercases the caller +
884    /// callee identifiers post-parse — would have had to be threaded
885    /// through every open-coded copy in lockstep or one variant's
886    /// diagnostic would silently name a different caller/callee pair
887    /// than its peer, silently degrading the "which caixa is at fault"
888    /// self-locating signal every operator-facing typed diagnostic
889    /// exists to carry. Lifting the pair to a typed method on the
890    /// substrate primitive means every downstream diagnostic-construction
891    /// site reaches for exactly one typed dispatch — the resolver's
892    /// projection migrates as a unit on any future axis addition.
893    ///
894    /// Peer of the sibling per-`:contratos` scalar accessor family
895    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
896    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
897    /// scalar-value axes — first composite-projection accessor on the
898    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
899    /// form `.clone()` field-accesses that pair the sibling
900    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
901    /// one typed dispatch. Named `edge_pair()` to reflect the identity
902    /// name of the projected tuple (the typed-edge caller-callee pair,
903    /// distinct from the sibling triple-projection
904    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
905    /// closure in [`WitContract::target`] + the paired
906    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
907    /// site's `(de, para, wit)` triple onto one typed dispatch).
908    #[must_use]
909    pub fn edge_pair(&self) -> (String, String) {
910        (self.source().to_string(), self.destination().to_string())
911    }
912
913    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
914    /// :wit)` triple every per-edge diagnostic constructor that names
915    /// all three axes threads verbatim into its `de:` / `para:` /
916    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
917    /// / missing-target / invalid-wit / capability-with-payload arms
918    /// (eight sites all shape `let (de, para, wit) = edge();
919    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
920    /// accessor landed) and the sibling
921    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
922    /// constructor (which paired `edge_pair()` for the `(de, para)`
923    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
924    /// typed-dispatch + raw-field-access shape the sibling accessor
925    /// family already flagged as a drift risk). Nine total call sites
926    /// collapse onto this helper.
927    ///
928    /// Lifted with the same one-source-of-truth discipline
929    /// [`WitContract::edge_pair`] carries on the paired
930    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
931    /// arms compose through the lifted [`WitContract::source`] /
932    /// [`WitContract::destination`] / [`WitContract::world_ref`]
933    /// scalar accessors byte-for-byte (pinned by the paired
934    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
935    /// composition-pin), so any future rebrand on the per-`:contratos`
936    /// caller / callee / world-ref axis (an M4 per-cluster
937    /// caller/callee-alias rewrite the operator pins through a future
938    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
939    /// per-CR fully-qualified namespace prefix the M4
940    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
941    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
942    /// on `source()` / `destination()`, a per-CR canonicalization pass
943    /// that lowercases the WIT world ref post-parse) migrates as a
944    /// single caixa-core edit rather than a coordinated rewrite of
945    /// nine open-coded triple-constructors.
946    ///
947    /// Peer of the sibling per-`:contratos` composite-projection
948    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
949    /// composite-value axes — closes the last unlifted owned-form
950    /// composite-tuple axis on the per-`:contratos` diagnostic-
951    /// construction surface. Named `edge_triple()` to reflect the
952    /// identity name of the projected tuple (the typed-edge
953    /// caller-callee-wit triple, sibling to the caller-callee-only
954    /// pair `edge_pair()` returns).
955    #[must_use]
956    pub fn edge_triple(&self) -> (String, String, String) {
957        (
958            self.source().to_string(),
959            self.destination().to_string(),
960            self.world_ref().to_string(),
961        )
962    }
963
964    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
965    /// dedups typed edges keys off — routes through the lifted
966    /// [`WitContract::source`] / [`WitContract::destination`] /
967    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
968    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
969    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
970    /// type alias's six axes migrate as a unit on any future axis
971    /// addition (adding a seventh field to [`WitContract`] is one
972    /// [`ContratoIdentity`] alias edit + one accessor addition + one
973    /// arm here, not a coordinated rewrite of every open-coded
974    /// six-tuple builder that dedups on the identity axis).
975    ///
976    /// Sibling of [`WitContract::edge_pair`] /
977    /// [`WitContract::edge_triple`] on the composite-projection axis:
978    /// the pair projects the caller-callee axes, the triple extends it
979    /// with the world-ref, this method extends it with the three
980    /// payload-carrier axes. Every projection returns the same six
981    /// scalar accessors' outputs; the three methods differ only in
982    /// which arms they surface.
983    #[must_use]
984    pub fn identity(&self) -> ContratoIdentity<'_> {
985        (
986            self.source(),
987            self.destination(),
988            self.world_ref(),
989            self.endpoint(),
990            self.subject(),
991            self.slot(),
992        )
993    }
994
995    /// True when this contract targets an HTTP-shaped WIT world.
996    ///
997    /// Declared `pub const fn` — routes through the paired `pub const
998    /// fn` [`Self::world_ref`] scalar accessor and the substrate's
999    /// `pub const fn` free-function classifier [`wit_shape_is_http`]
1000    /// (d46420c). Sibling in `const`-eval posture to the peer
1001    /// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
1002    /// [`Self::is_capability`] WIT-shape-predicate family; the closed
1003    /// 4-arm partition on the raw `:contratos :wit` axis now carries
1004    /// the same `const`-eval-surface posture as the free-function
1005    /// classifier family it composes through. Pinned load-bearing by
1006    /// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
1007    /// test (a future accidental downgrade to non-`const` fires E0015
1008    /// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
1009    /// build time).
1010    #[must_use]
1011    pub const fn is_http(&self) -> bool {
1012        wit_shape_is_http(self.world_ref())
1013    }
1014
1015    /// True when this contract targets a pub-sub-shaped WIT world.
1016    ///
1017    /// Declared `pub const fn` — sibling in `const`-eval posture to
1018    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
1019    /// [`Self::is_capability`] WIT-shape-predicate family. See
1020    /// [`Self::is_http`] for the family-closure rationale.
1021    #[must_use]
1022    pub const fn is_pubsub(&self) -> bool {
1023        wit_shape_is_pubsub(self.world_ref())
1024    }
1025
1026    /// True when this contract targets a key/value-shaped WIT world.
1027    ///
1028    /// Declared `pub const fn` — sibling in `const`-eval posture to
1029    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
1030    /// [`Self::is_capability`] WIT-shape-predicate family. See
1031    /// [`Self::is_http`] for the family-closure rationale.
1032    #[must_use]
1033    pub const fn is_store(&self) -> bool {
1034        wit_shape_is_store(self.world_ref())
1035    }
1036
1037    /// True when this contract targets *none* of the three known payload-
1038    /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
1039    /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1040    /// open on the [`WitContract`] surface. Returns the exact-inverse
1041    /// disjunction of the peer trio — `true` when none of the three
1042    /// prefix-set predicates matches the raw `:contratos :wit` value; the
1043    /// author-declared WIT world is a pure typed capability edge with no
1044    /// payload selector (the shape [`WitContract::target`] projects onto
1045    /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
1046    /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
1047    ///
1048    /// The `:contratos :wit` shape-space is closed at four arms
1049    /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
1050    /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
1051    /// everything else on the payload-less capability arm), and every
1052    /// downstream consumer that must filter contratos by shape-class
1053    /// keys off the four sibling predicates (the [`WitContract::target`]
1054    /// dispatch's implicit `else` after the three payload-shape arm
1055    /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
1056    /// every future substrate-side capability-shape-only emitter — the
1057    /// M4 per-Aplicacao WIT-registry capability-import materializer, the
1058    /// future `feira app graph --capability` per-Aplicacao capability-
1059    /// column filter, the future per-cluster capability-scope reconciler
1060    /// that skips L4/L7 emission for payload-less edges since Cilium
1061    /// can't introspect WASI capability calls, the future
1062    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
1063    /// shape shape-count histogram). Every such consumer reaches for one
1064    /// typed dispatch on the substrate primitive so the "which arm
1065    /// carries the capability-only shape?" answer lives at one caixa-core
1066    /// edit rather than open-coded across per-consumer
1067    /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
1068    /// negations, each of which would silently drop a future fourth
1069    /// payload-arm addition without a compile-time signal at the
1070    /// consumer site.
1071    ///
1072    /// Prior to this lift the "not one of the three known payload
1073    /// shapes" classification sat inline at [`WitContract::target`]'s
1074    /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
1075    /// [`WitTarget::Capability`] admission arm after the three `if
1076    /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
1077    /// { … }` guards) with no named accessor for downstream consumers
1078    /// to reach through. A future substrate-side capability-only
1079    /// filter or a future capability-scope reconciler would have had to
1080    /// re-inline the same triplet negation at every emit site with no
1081    /// compile-time link back to the sibling trio, and a future arm
1082    /// addition (a hypothetical fourth payload-shape prefix set — a
1083    /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
1084    /// import carrier per the sibling [`wit_shape_matches`] docstring's
1085    /// trajectory bullet) would land the new predicate on the payload-
1086    /// carrying trio and silently misclassify the new shape as
1087    /// capability at every triplet-negation consumer site, propagating
1088    /// the drift far from the caixa-core prefix-set commit.
1089    ///
1090    /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
1091    /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
1092    /// trio into a 4-way partition witness on the raw `:contratos :wit`
1093    /// axis, mirroring the paired post-projection [`WitTarget`]
1094    /// `gen_platform::IsVariant`-derived 4-way predicate set
1095    /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
1096    /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
1097    /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
1098    /// arm-set). The two typed axes — pre-projection on the raw
1099    /// `:contratos :wit` string, post-projection on the validated typed
1100    /// view — now carry a matched 4-arm predicate discipline: every
1101    /// arm on the closed [`WitTarget`] set has a peer pre-projection
1102    /// predicate on the [`WitContract`] surface, and any future
1103    /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
1104    /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
1105    /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
1106    /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
1107    /// pre-projection axis through a matching peer prefix-set + peer
1108    /// predicate lift by construction — the compile-time exhaustiveness
1109    /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
1110    /// the post-projection accessor family stays in sync, and the sibling
1111    /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
1112    /// partition-witness pin locks the pre-projection classification in
1113    /// load-bearing so a peer prefix-set addition that widened one arm's
1114    /// accept-set without shrinking the [`Self::is_capability`] accept-set
1115    /// surfaces as a test failure at caixa-core build time rather than a
1116    /// silent per-consumer split at renderer emit time.
1117    ///
1118    /// Composes byte-for-byte through the lifted peer trio
1119    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
1120    /// any future rebrand of any prefix-set const flows through this
1121    /// method by construction without a coordinated per-consumer rewrite
1122    /// (pinned by the sibling
1123    /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
1124    /// composition-witness).
1125    ///
1126    /// Note: purely syntactic classification on the `:wit` prefix-set —
1127    /// unlike [`Self::target`], which additionally rejects value-shape-
1128    /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
1129    /// package) via [`crate::render::is_wit_world_ref`] and payload-
1130    /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
1131    /// structurally malformed returns `true` from `is_capability()` (the
1132    /// prefix set matches nothing), and the surrounding
1133    /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
1134    /// is where the [`AplicacaoError::EmptyWit`] /
1135    /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
1136    /// predicate is the classifier, not the validator.
1137    ///
1138    /// Declared `pub const fn` — closes the WIT-shape-predicate
1139    /// family's `const`-eval-surface pass at the fourth (payload-less)
1140    /// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
1141    /// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
1142    /// See [`Self::is_http`] for the family-closure rationale.
1143    #[must_use]
1144    pub const fn is_capability(&self) -> bool {
1145        wit_shape_is_capability(self.world_ref())
1146    }
1147
1148    /// True when this contract's caller equals its callee — a
1149    /// structurally degenerate typed edge that no `:contratos` entry can
1150    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
1151    /// Servico B" is an *inter*-Servico contract between two distinct
1152    /// graph nodes). A Servico contracting with itself resolves to an
1153    /// in-process call the wasm-engine never routes through the mesh at
1154    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
1155    /// per-edge policy can express the intended shape — the pub-sub
1156    /// path silently rendered a self-allow rule that is a no-op (intra-
1157    /// pod traffic bypasses the mesh entirely), and the synchronous
1158    /// paths surfaced as a misleading `ContratoCycle` whose path was
1159    /// `["cart", "cart"]` — framing a self-edge as a multi-node
1160    /// deadlock. Every downstream consumer that must reject the shape
1161    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
1162    /// gate at caixa-core/src/aplicacao.rs:5559, every future
1163    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
1164    /// axis, every future adjacency-graph builder that must skip self-
1165    /// edges rather than fold them into an incidental cycle) now keys
1166    /// off exactly one typed dispatch on the substrate primitive, so
1167    /// any future rebrand on the axis (an M4-typed-caller enum whose
1168    /// identity comparison rule the accessor could route through, an
1169    /// operator-side per-cluster caller/callee-alias table the
1170    /// materializer resolves per-CR before the equality probe, a
1171    /// promotion of the pointwise `==` to a set-membership check once
1172    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
1173    /// so a per-replica self-edge is rejected under the same predicate)
1174    /// migrates as a single caixa-core edit rather than a coordinated
1175    /// rewrite of every downstream self-edge consumer. Composes
1176    /// byte-for-byte through the lifted [`Self::source`] /
1177    /// [`Self::destination`] scalar accessors — the accessor pair every
1178    /// per-`:contratos` scalar-value axis already routes through — so
1179    /// any future rebrand of the underlying `:de` / `:para` storage
1180    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1181    /// a per-Aplicacao interning arena the M4 CR materializer authors,
1182    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1183    /// same one body without a coordinated per-consumer rewrite.
1184    ///
1185    /// Sibling in shape to the peer per-`:contratos` shape-predicate
1186    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1187    /// on the `:wit` world-ref axis — extended onto the per-edge
1188    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1189    /// partition the WIT-shape-space; `is_self_loop` partitions the
1190    /// caller-callee identity-space. Named `is_self_loop()` to reflect
1191    /// the graph-theoretic identity of the shape (a loop from a graph
1192    /// node to itself, distinct from the sibling multi-node
1193    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1194    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1195    /// variant already carrying the term.
1196    #[must_use]
1197    pub fn is_self_loop(&self) -> bool {
1198        self.source() == self.destination()
1199    }
1200
1201    /// Typed view of the contract's payload target. Enforces that the
1202    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1203    /// fields agree, and that each carried value is itself
1204    /// value-shape valid:
1205    ///
1206    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1207    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1208    ///     `PathPrefix` invariant — same shape required of `:entrada
1209    ///     :paths`)
1210    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1211    ///     non-empty (NATS / Kafka publish without a subject is a
1212    ///     no-op subscribe, never the author's intent)
1213    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1214    ///     non-empty (an empty slot template addresses the bucket
1215    ///     root, defeating the per-key isolation the slot exists for)
1216    ///   - Anything else ⇒ none of the three; the contract is a pure
1217    ///     typed capability edge with no payload selector.
1218    ///
1219    /// Translates the Apollo Federation discipline ("conflicts are
1220    /// errors at compile time, not warnings at runtime";
1221    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1222    /// a contract whose WIT shape disagrees with its target field, or
1223    /// whose target field carries a value-shape-invalid string, is a
1224    /// build error — not a silent renderer drop. The returned
1225    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1226    /// non-empty (and absolute, for `Http`); every downstream consumer
1227    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1228    /// the M4 per-edge policy resolver) can rely on that without
1229    /// re-checking.
1230    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1231        // Route the HTTP-shaped payload-target extraction through the
1232        // lifted [`WitContract::endpoint`] accessor rather than the raw
1233        // `self.endpoint.as_deref()` field access — the two production
1234        // consumers of the per-`:contratos :endpoint` HTTP-shaped
1235        // payload-carrier scalar (this method's Http-arm payload
1236        // extraction, the [`AplicacaoSpec::validate`] duplicate-
1237        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1238        // off exactly one typed dispatch on the substrate primitive, so
1239        // any future rebrand on the axis (an M4 per-cluster endpoint-
1240        // alias rewrite, a per-CR fully-qualified path prefix the M4
1241        // materializer applies per-tenant, an M4 promotion from
1242        // `Option<String>` to a typed HTTP path-template enum) migrates
1243        // as a single caixa-core edit rather than a coordinated rewrite
1244        // of the two call sites — peer of the sibling M3 per-`:placement`
1245        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1246        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1247        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1248        let endpoint = self.endpoint();
1249        let subject = self.subject();
1250        // Route the store-arm payload-carrier scalar through the
1251        // lifted [`WitContract::slot`] accessor rather than the raw
1252        // `self.slot.as_deref()` field access — the two production
1253        // consumers of the per-`:contratos :slot` key/value-store-
1254        // shaped payload-carrier scalar (this method's Store-arm
1255        // payload extraction, the [`AplicacaoSpec::validate`]
1256        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1257        // arm) now key off exactly one typed dispatch on the substrate
1258        // primitive. Closes the last unlifted per-`:contratos`
1259        // `Option<String>` axis, completing the payload-carrier
1260        // accessor family peer of the sibling per-`:contratos`
1261        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1262        // (90de675) lifts across the HTTP / pub-sub arms.
1263        let slot = self.slot();
1264        // Route the local `(de, para, wit)` triple-projection closure
1265        // through the lifted [`WitContract::edge_triple`] typed accessor
1266        // rather than re-inlining `(self.de.clone(), self.para.clone(),
1267        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1268        // triple-carrying diagnostic constructors below (wrong-target /
1269        // missing-target on all three payload arms + capability-with-
1270        // payload + invalid-wit) now key off exactly one typed dispatch
1271        // on the substrate-primitive composite projection, sibling to
1272        // the peer [`WitContract::edge_pair`]-routed
1273        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1274        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1275        // diagnostic constructors on the same per-`:contratos`
1276        // diagnostic-construction surface.
1277        let edge = || self.edge_triple();
1278
1279        // The `:wit` value drives every downstream dispatch — the
1280        // is_http/is_pubsub/is_store prefix matchers below, the
1281        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1282        // exclusion. Until this gate landed `target()` accepted any
1283        // non-empty string and silently demoted unrecognized shapes to
1284        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1285        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1286        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1287        // package, the paste-from-binary footgun a multi-line blob
1288        // accidentally landing in the slot, the un-percent-encoded
1289        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1290        // routing, got L4-only" footgun. Empty is still pre-checked at
1291        // the [`AplicacaoSpec::validate`] call site via the narrower
1292        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1293        // validate layer); the value-shape gate here picks up the
1294        // structurally-invalid non-empty cases the empty check misses,
1295        // and remains correct under direct `target()` calls outside
1296        // validate (the predicate's defensive empty arm returns a
1297        // parser-shaped reason rather than silently falling through to
1298        // the Capability arm). Same trajectory as c4213a4 (WitContract
1299        // endpoint/subject/slot value-shape gates lifted into
1300        // `target()`) on the peer payload axes.
1301        if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
1302            let (de, para, wit) = edge();
1303            return Err(AplicacaoError::ContratoWitInvalid {
1304                de,
1305                para,
1306                wit,
1307                reason,
1308            });
1309        }
1310
1311        if self.is_http() {
1312            if subject.is_some() || slot.is_some() {
1313                let (de, para, wit) = edge();
1314                return Err(AplicacaoError::ContratoWrongTarget {
1315                    de,
1316                    para,
1317                    wit,
1318                    expected: WitTarget::HTTP_FIELD_NAME,
1319                });
1320            }
1321            let ep = endpoint.ok_or_else(|| {
1322                let (de, para, wit) = edge();
1323                AplicacaoError::ContratoMissingTarget {
1324                    de,
1325                    para,
1326                    wit,
1327                    expected: WitTarget::HTTP_FIELD_NAME,
1328                }
1329            })?;
1330            if ep.is_empty() {
1331                let (de, para) = self.edge_pair();
1332                return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
1333            }
1334            if !ep.starts_with('/') {
1335                let (de, para) = self.edge_pair();
1336                return Err(AplicacaoError::ContratoEndpointNotAbsolute {
1337                    de,
1338                    para,
1339                    endpoint: ep.to_string(),
1340                });
1341            }
1342            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1343            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1344            // API v1 HTTPPathMatch.value admission grammar with the
1345            // sibling `:entrada :paths` axis. Until this gate landed
1346            // `target()` only refused the empty string + the missing-
1347            // leading-`/` form; a structurally invalid endpoint
1348            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1349            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1350            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1351            // path-traversal segment, the >1024-byte slug) silently
1352            // passed validate and the failure surfaced at apply time
1353            // as a Cilium policy rejection / silent traffic drop, far
1354            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1355            // grammar `:entrada :paths` already gates (55410e4), now
1356            // shared with `:contratos :endpoint` through the lifted
1357            // `crate::render::is_gateway_api_http_path` predicate.
1358            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1359                let (de, para) = self.edge_pair();
1360                return Err(AplicacaoError::ContratoEndpointInvalid {
1361                    de,
1362                    para,
1363                    endpoint: ep.to_string(),
1364                    reason,
1365                });
1366            }
1367            return Ok(WitTarget::Http { endpoint: ep });
1368        }
1369        if self.is_pubsub() {
1370            if endpoint.is_some() || slot.is_some() {
1371                let (de, para, wit) = edge();
1372                return Err(AplicacaoError::ContratoWrongTarget {
1373                    de,
1374                    para,
1375                    wit,
1376                    expected: WitTarget::PUBSUB_FIELD_NAME,
1377                });
1378            }
1379            let s = subject.ok_or_else(|| {
1380                let (de, para, wit) = edge();
1381                AplicacaoError::ContratoMissingTarget {
1382                    de,
1383                    para,
1384                    wit,
1385                    expected: WitTarget::PUBSUB_FIELD_NAME,
1386                }
1387            })?;
1388            if s.is_empty() {
1389                let (de, para) = self.edge_pair();
1390                return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1391            }
1392            // The `:subject` lands at runtime as the NATS subject the
1393            // producer publishes to and the consumer subscribes from.
1394            // Until this gate landed `target()` only refused the
1395            // empty string; a structurally invalid subject
1396            // (`"foo..bar"` — empty token between separators,
1397            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1398            // server's subject parser rejects, `"foo bar"` —
1399            // un-percent-encoded whitespace, `"foo.café"` —
1400            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1401            // empty leading/trailing tokens, the >256-byte
1402            // paste-from-binary slug) silently passed validate and
1403            // the failure surfaced at runtime as a NATS server-side
1404            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1405            // a silent message drop, far from the source caixa.lisp.
1406            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1407            // trajectory `:contratos :endpoint` (4f0390b) and
1408            // `:contratos :wit` (6226bf4) already gate, now shared
1409            // with `:contratos :subject` through the lifted
1410            // `crate::render::is_nats_subject` predicate.
1411            if let Err(reason) = crate::render::is_nats_subject(s) {
1412                let (de, para) = self.edge_pair();
1413                return Err(AplicacaoError::ContratoSubjectInvalid {
1414                    de,
1415                    para,
1416                    subject: s.to_string(),
1417                    reason,
1418                });
1419            }
1420            return Ok(WitTarget::PubSub { subject: s });
1421        }
1422        if self.is_store() {
1423            if endpoint.is_some() || subject.is_some() {
1424                let (de, para, wit) = edge();
1425                return Err(AplicacaoError::ContratoWrongTarget {
1426                    de,
1427                    para,
1428                    wit,
1429                    expected: WitTarget::STORE_FIELD_NAME,
1430                });
1431            }
1432            let sl = slot.ok_or_else(|| {
1433                let (de, para, wit) = edge();
1434                AplicacaoError::ContratoMissingTarget {
1435                    de,
1436                    para,
1437                    wit,
1438                    expected: WitTarget::STORE_FIELD_NAME,
1439                }
1440            })?;
1441            if sl.is_empty() {
1442                let (de, para) = self.edge_pair();
1443                return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1444            }
1445            // Value-shape gate on the third (and last) typed payload
1446            // axis the `WitContract::target` dispatch carries — the
1447            // peer of [`crate::render::is_gateway_api_http_path`] for
1448            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1449            // for `:subject` (63e18a0). Until this gate landed
1450            // `target()` only refused the empty string; a structurally
1451            // invalid slot (`"check out/$order"` — un-percent-encoded
1452            // whitespace whose runtime behavior varies unpredictably
1453            // across kv backends, `"checkout/\x01order"` — control
1454            // character that Redis admits but corrupts on next read
1455            // and DynamoDB rejects outright, `"chéckout/$order"` —
1456            // un-percent-encoded non-ASCII byte each backend re-encodes
1457            // differently, `"checkout\n/$order"` — embedded newline,
1458            // the 513-byte paste-from-binary slug) silently passed
1459            // validate and surfaced at runtime as a per-backend kv
1460            // write rejection (DynamoDB / etcd) or as a silent
1461            // next-read corruption (Redis-via-RESP3), far from the
1462            // source caixa.lisp with no field naming which `:contratos`
1463            // edge carried the typo. The lifted predicate makes the
1464            // kv-backend intersection-floor a substrate-level
1465            // invariant at validate time, not a runtime "this passed
1466            // validate but the kv backend rejected on first write"
1467            // surprise — closes the typed payload-axis value-shape
1468            // trajectory across all three legs of the four
1469            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1470            // that caixa-mesh + the future kv emitters land in.
1471            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1472                let (de, para) = self.edge_pair();
1473                return Err(AplicacaoError::ContratoSlotInvalid {
1474                    de,
1475                    para,
1476                    slot: sl.to_string(),
1477                    reason,
1478                });
1479            }
1480            return Ok(WitTarget::Store { slot: sl });
1481        }
1482
1483        // Unrecognized WIT world — must not carry any payload target.
1484        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1485            let (de, para, wit) = edge();
1486            return Err(AplicacaoError::ContratoWrongTarget {
1487                de,
1488                para,
1489                wit,
1490                expected: WitTarget::CAPABILITY_EXPECTED,
1491            });
1492        }
1493        Ok(WitTarget::Capability)
1494    }
1495
1496    /// Substrate-canonical post-validation projection of the typed
1497    /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
1498    /// downstream of an [`AplicacaoSpec`] that has already crossed the
1499    /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
1500    /// [`typed_view`]-shaped entry point that composes `validate` into
1501    /// the projection) reaches through when it needs the typed
1502    /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
1503    /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
1504    /// coherence for every `:contratos` entry. The peer accessor to the
1505    /// [`Self::target`] `Result`-returning validator on the same
1506    /// per-`:contratos` typed-projection axis — [`Self::target`] is the
1507    /// pre-validation validator that computes the projection *and* raises
1508    /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
1509    /// (`:wit`, payload) mismatch; this method is the post-validation
1510    /// projection every downstream consumer reaches through once the
1511    /// pre-validation gate has succeeded.
1512    ///
1513    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1514    ///
1515    /// Prior to this lift the "call `.target()` then `.expect(…)` with
1516    /// the same message" pattern sat inline at two production sites with
1517    /// no compile-time link between them: the
1518    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
1519    /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
1520    /// (`c.target().expect("validated by typed_view").http_endpoint()`)
1521    /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
1522    /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
1523    /// (`c.target().expect("validated by typed_view").graph_label()`),
1524    /// each open-coding the same `.target().expect("validated by
1525    /// typed_view")` pair with the message spelled twice. A future
1526    /// vocabulary shift on the panic-message axis (a tightening from
1527    /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
1528    /// validate"` as the substrate's validator entry-point vocabulary
1529    /// sharpens, a per-consumer disambiguation, an M4 promotion of the
1530    /// panic to a `debug_assert` under a `--release` build profile) would
1531    /// have had to be threaded through both open-coded call sites in
1532    /// lockstep or one consumer would silently disagree with the peer on
1533    /// which invariant the panic message names. Same "same shape written
1534    /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
1535    /// discipline the sibling [`Self::edge_pair`] /
1536    /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
1537    /// lifts already establish on the paired composite-projection axis;
1538    /// this lift extends it onto the post-validation typed-view axis.
1539    ///
1540    /// Every future downstream consumer of the projected typed view
1541    /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
1542    /// CR materializer's per-edge admission webhook, the future
1543    /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
1544    /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
1545    /// resolver, the future `feira app graph --l7` / `--pubsub` /
1546    /// `--kv` per-shape column emitters) reaches through this one typed
1547    /// dispatch on the substrate primitive rather than an open-coded
1548    /// per-consumer `.target().expect(…)` pair with the message
1549    /// re-inlined. The invariant the accessor's panic path pins — "this
1550    /// call is only reachable after [`AplicacaoSpec::validate`] has
1551    /// succeeded on the containing spec" — is the substrate's answer to
1552    /// give exactly once, at the primitive, not once per consumer.
1553    ///
1554    /// # Panics
1555    ///
1556    /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
1557    /// would return an `Err` — i.e. if this contract's
1558    /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
1559    /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
1560    /// this accessor only from a code path that has already reached the
1561    /// containing [`AplicacaoSpec`] through a validating entry-point
1562    /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
1563    /// [`typed_view`] compose, the future M4 CR admission webhook's
1564    /// per-CR validate). Use [`Self::target`] instead on any pre-
1565    /// validation code path.
1566    ///
1567    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1568    #[must_use]
1569    pub fn target_projected(&self) -> WitTarget<'_> {
1570        self.target().expect(Self::PROJECTED_INVARIANT_MSG)
1571    }
1572
1573    /// Canonical panic message the [`Self::target_projected`]
1574    /// post-validation projection accessor threads through when the
1575    /// caller has violated the "call only after [`AplicacaoSpec::validate`]
1576    /// has succeeded" precondition. Lifted as a `pub const` on the
1577    /// [`WitContract`] surface so the byte-string lives in one place
1578    /// across the substrate — the [`Self::target_projected`] method
1579    /// body, the two prior production call sites' comments now naming
1580    /// the const, and every future consumer that must format-match the
1581    /// panic-message shape (a future test suite that asserts the panic-
1582    /// message byte-string across a fuzzed invalid-contract corpus,
1583    /// a future custom-panic hook in `caixa-operator` that surfaces the
1584    /// message with per-`:contratos` telemetry, the future admission
1585    /// webhook's per-CR validate-error report) reaches through the same
1586    /// canonical `&'static str`. A future rebrand on the panic-message
1587    /// axis (a tightening from `"validated by typed_view"` to `"validated
1588    /// by AplicacaoSpec::validate"` as the substrate's validator
1589    /// entry-point vocabulary sharpens once caixa-core grows a
1590    /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
1591    /// [`typed_view`]) lands at one caixa-core edit rather than a
1592    /// coordinated per-consumer sweep — same "one canonical declaration
1593    /// per axis, next to the accessor that reads it" discipline the peer
1594    /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
1595    /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
1596    /// const family already establishes on the paired per-consumer-axis
1597    /// diagnostic-scalar surface.
1598    pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
1599}
1600
1601/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1602/// gate (see [`AplicacaoSpec::validate`]): every field that
1603/// distinguishes one contract from another, in declaration order
1604/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1605/// with equal [`ContratoIdentity`]s are the same typed edge declared
1606/// twice — the graph-edge analogue of duplicate `:membros` /
1607/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1608/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1609/// clippy's `type_complexity` lint (and so a future axis added to
1610/// `WitContract` is one alias edit, not a coordinated rewrite of
1611/// every set instantiation).
1612pub type ContratoIdentity<'a> = (
1613    &'a str,
1614    &'a str,
1615    &'a str,
1616    Option<&'a str>,
1617    Option<&'a str>,
1618    Option<&'a str>,
1619);
1620
1621/// Typed view of a [`WitContract`]'s payload target. Each variant
1622/// carries the field its WIT shape requires; constructing a `Http`
1623/// view without an endpoint is impossible by the type system.
1624///
1625/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1626/// instead of probing `Option<String>` fields one by one — the
1627/// "which payload field is set?" question is answered once, at
1628/// validation time.
1629#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1630pub enum WitTarget<'a> {
1631    /// HTTP-shaped WIT world. Carries the configured request path.
1632    Http { endpoint: &'a str },
1633    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1634    ///
1635    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1636    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1637    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1638    /// method name byte-identical to the sibling
1639    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1640    /// arm-discriminator that routes through
1641    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1642    /// through `matches!` on the variant), so the two arm-discriminator
1643    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1644    /// every downstream consumer through the same `is_pubsub()` name.
1645    #[is_variant(name = "pubsub")]
1646    PubSub { subject: &'a str },
1647    /// Key-value-shaped WIT world. Carries the slot template.
1648    Store { slot: &'a str },
1649    /// A typed capability edge with no payload selector — the WIT
1650    /// world stands on its own (rare; reserved for plain capability
1651    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1652    Capability,
1653}
1654
1655impl<'a> WitTarget<'a> {
1656    /// Canonical author-facing `:contratos` payload field name for the
1657    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1658    /// [`AplicacaoError::ContratoMissingTarget`] /
1659    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1660    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1661    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1662    /// the `feira app graph` verb prints. Peer of
1663    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1664    /// on the payload-field-name axis; declared as a peer const next
1665    /// to the [`WitTarget::Http`] variant so a future rename on the
1666    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1667    /// :endpoint …)))` field lands in exactly one place, not scattered
1668    /// across the [`WitContract::target`] gate's six `expected:`
1669    /// literals, the label template, and every downstream consumer
1670    /// that prints a per-arm prefix. Same trajectory as the peer
1671    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1672    /// for the arm's shape, next to the variant declaration.
1673    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1674    /// Canonical author-facing `:contratos` payload field name for the
1675    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1676    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1677    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1678    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1679    /// Canonical author-facing `:contratos` payload field name for the
1680    /// key/value-store-shaped arm. Peer of
1681    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1682    /// on the payload-field-name axis; see
1683    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1684    pub const STORE_FIELD_NAME: &'static str = "slot";
1685
1686    /// Canonical stable human-readable label the payload-less
1687    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1688    /// the byte-string every consumer that formats a payload-less
1689    /// typed capability edge as text lands on (the
1690    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1691    /// naming which identical edge was declared twice, the future
1692    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1693    /// policy resolver's audit view, the operator's mesh-graph audit).
1694    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1695    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1696    /// author-facing label-scalar consts — the same
1697    /// "one canonical declaration per arm, next to the variant, so a
1698    /// future rename lands in one place" discipline extended to the
1699    /// payload-less arm. Until this lift landed the byte-string sat
1700    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1701    /// match arm, once in the pin test asserting the label's
1702    /// [`WitTarget::Capability`] output — with no compile-time link
1703    /// between the two: a rebrand on either side (an operator-facing
1704    /// vocabulary shift, a per-consumer disambiguation like
1705    /// `"(capability — no payload; typed edge only)"`) would silently
1706    /// desynchronize until a downstream consumer surfaced the drift at
1707    /// runtime.
1708    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1709
1710    /// Canonical `expected:` scalar the
1711    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1712    /// through for the payload-less [`WitTarget::Capability`] arm — the
1713    /// byte-string authors read as "this WIT world's shape is not one
1714    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1715    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1716    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1717    /// [`Self::STORE_FIELD_NAME`] consts on the
1718    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1719    /// same "which payload field name goes in the diagnostic" dispatch
1720    /// the three payload-arm consts cover, extended to the payload-less
1721    /// arm. Until this lift landed the byte-string sat twice — once
1722    /// inline in the [`Self::target`] Capability-arm rejection at the
1723    /// production dispatch, once in the pin test asserting the
1724    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1725    /// no compile-time link between the two: a rebrand on either side
1726    /// (an author-facing vocabulary shift to `"capability"` /
1727    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1728    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1729    /// [`WitTarget::Capability`] into per-shape peers) would silently
1730    /// desynchronize until a downstream consumer surfaced the drift at
1731    /// runtime. Same "one canonical declaration per arm, next to the
1732    /// variant, so a future rename lands in one place" discipline the
1733    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1734    /// established for the payload-less arm's human-readable label
1735    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1736    /// so both halves of the "how does the Capability arm surface at
1737    /// its two consumer axes (human-readable label, wrong-target
1738    /// diagnostic)" pipeline route through peer consts declared next
1739    /// to the variant.
1740    ///
1741    /// Pairwise-distinctness against the three payload-arm scalars
1742    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1743    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1744    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1745    /// test — the 4-way closure of the 3-way
1746    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1747    /// the `ContratoWrongTarget::expected` axis, matching the peer
1748    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1749    /// scalar-value distinctness discipline the sibling M3 typed-enum
1750    /// discriminator axis already carries.
1751    pub const CAPABILITY_EXPECTED: &'static str = "none";
1752
1753    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1754    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1755    /// as under [`Self::graph_label`] — the sibling
1756    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1757    /// payload-column axis (the graph verb spells payload-less as
1758    /// `(capability-only)`, distinct from the duplicate-`:contratos`
1759    /// diagnostic's `(capability — no payload)` on the human-readable
1760    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1761    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1762    /// family — extends the "one canonical declaration per arm, next to
1763    /// the variant, so a future rename lands in one place" discipline
1764    /// onto the third payload-less-arm consumer axis (`feira app graph`
1765    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1766    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1767    /// axis).
1768    ///
1769    /// Until this lift landed the byte-string sat inline in
1770    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1771    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1772    /// `"(capability-only)".to_string()` literal, with no compile-time link
1773    /// back to the [`WitTarget::Capability`] variant declaration nor to
1774    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1775    /// peer consts already carrying the "one canonical declaration per
1776    /// payload-less-arm consumer axis" discipline. A rebrand on either
1777    /// side (the graph verb's operator-facing vocabulary tightening from
1778    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1779    /// the WIT registry vocabulary sharpens, an M4 split of
1780    /// [`Self::Capability`] into per-shape peers) would silently
1781    /// desynchronize the graph-verb byte-string from the paired
1782    /// per-arm-adjacent const and land two spellings of the same axis in
1783    /// two spots.
1784    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1785
1786    /// The `(author-facing field name, payload)` pair this typed target
1787    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1788    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1789    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1790    /// [`Self::Store`], `None` for the payload-less
1791    /// [`Self::Capability`] arm.
1792    ///
1793    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1794    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1795    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1796    /// (returns the first component) route through, so a future
1797    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1798    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1799    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1800    /// exactly one new match-arm here (a compile-time exhaustiveness
1801    /// error otherwise), not a coordinated three-way rewrite of the
1802    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1803    /// + every downstream consumer that reaches for the pair.
1804    ///
1805    /// Until this lift landed the three payload arms sat in
1806    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1807    /// invocations (one per variant, each hand-quoting the paired
1808    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1809    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1810    /// "same shape, written N times" duplication THEORY.md §I.3.5
1811    /// ("Generation first, composition second, hand-authoring last;
1812    /// the duplication budget is zero") promotes to a build-time
1813    /// concern, with each per-arm site paired to its own const with no
1814    /// compile-time link between the format template and the arm's
1815    /// payload extraction.
1816    #[must_use]
1817    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1818        match *self {
1819            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1820            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1821            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1822            WitTarget::Capability => None,
1823        }
1824    }
1825
1826    /// The canonical author-facing `:contratos` payload field name
1827    /// this typed target arm carries (`Http` → `Some("endpoint")`,
1828    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1829    /// `None` for the payload-less `Capability` arm.
1830    ///
1831    /// Routes through [`Self::payload_pair`] — the single 4-arm
1832    /// dispatch [`Self::label`] also reads — so a future variant
1833    /// addition is one match-arm edit at [`Self::payload_pair`], not a
1834    /// per-consumer rewrite. Same "exhaustive-match at one canonical
1835    /// dispatch, thin projections at each consumer" trajectory the
1836    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1837    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1838    #[must_use]
1839    pub const fn field_name(&self) -> Option<&'static str> {
1840        match self.payload_pair() {
1841            Some((f, _)) => Some(f),
1842            None => None,
1843        }
1844    }
1845
1846    /// The underlying scalar the payload-carrying arm carries — the
1847    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
1848    /// subject ([`Self::PubSub`] `:subject`), or slot template
1849    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
1850    /// `&'a str` storage — or `None` on the payload-less
1851    /// [`Self::Capability`] arm.
1852    ///
1853    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
1854    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
1855    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
1856    /// the paired sub-selector axis. Both per-half accessors read from
1857    /// one authoritative match, so a future [`WitTarget`] variant
1858    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
1859    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
1860    /// on [`Self::payload_pair`] and both per-half projections + every
1861    /// downstream consumer picks the new arm up by construction — no
1862    /// coordinated N-way rewrite across the paired accessor dispatches,
1863    /// the [`Self::label`] / [`Self::graph_label`] format templates,
1864    /// and every future WIT-registry-shaped consumer.
1865    ///
1866    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
1867    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
1868    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
1869    /// both per-half projections as thin readers, every downstream
1870    /// consumer through the same match" discipline extended onto the
1871    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
1872    /// gap between the two paired-dispatch surfaces: the peer
1873    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
1874    /// the first-component projection until this lift; the second-
1875    /// component sibling now sits alongside so both halves reach every
1876    /// future consumer through the same substrate-primitive dispatch.
1877    ///
1878    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
1879    #[must_use]
1880    pub const fn payload(&self) -> Option<&'a str> {
1881        match self.payload_pair() {
1882            Some((_, p)) => Some(p),
1883            None => None,
1884        }
1885    }
1886
1887    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
1888    /// consumer that fans on the L7-HTTP-shaped payload keys off —
1889    /// returns the [`Self::Http`]-arm's author-declared request path
1890    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
1891    /// projected target is [`Self::Http { endpoint }`], `None` on the
1892    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
1893    /// [`Self::Capability`], each of which carries no HTTP endpoint by
1894    /// definition).
1895    ///
1896    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
1897    /// `path:` rule payload every substrate-side L7-introspecting
1898    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
1899    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
1900    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
1901    /// on the L7 introspection branch; every peer WIT shape stays
1902    /// L4-only because Cilium can't introspect NATS / key-value / plain
1903    /// capability edges), and every future L7-introspecting consumer
1904    /// of the projected target's HTTP endpoint (the future M4
1905    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
1906    /// materializer's per-edge L7 admission-webhook overlay, the
1907    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
1908    /// path bucket-key resolver, the future per-`:contratos`-edge
1909    /// mTLS-required overlay's HTTP-shape scope filter, the future
1910    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
1911    /// through the same typed dispatch.
1912    ///
1913    /// Prior to this lift the sole production consumer of the projected-
1914    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
1915    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
1916    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
1917    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
1918    /// }`) — reached the payload through a raw per-arm `if let` pattern-
1919    /// match that expressed no compile-time link back to the substrate
1920    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
1921    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
1922    /// scalar accessor on the peer per-`:contratos` raw-field axis but
1923    /// with no post-projection peer on the typed-view surface. A future
1924    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
1925    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
1926    /// gRPC-shaped worlds per this enum's own docstring at
1927    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
1928    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
1929    /// would have had to be threaded through the caixa-mesh L7 emit
1930    /// branch's raw `if let` in lockstep — either coalescing the two
1931    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
1932    /// emit path per-arm — with no substrate-primitive dispatch making
1933    /// the "which arms count as L7-HTTP-shaped for path-emission
1934    /// purposes" question the substrate's answer to give. Lifting the
1935    /// resolution to a typed method on the substrate primitive means
1936    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
1937    /// projected-target HTTP endpoint reaches for exactly one typed
1938    /// dispatch — the resolver's accept-set migrates as a unit on any
1939    /// future arm-family widening, and the caixa-mesh L7 emit branch
1940    /// reads through the same substrate primitive.
1941    ///
1942    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
1943    /// (7020470) `Option<&str>` scalar accessor on the raw
1944    /// `:contratos :endpoint` field-access axis — same "one typed
1945    /// dispatch on the substrate primitive, thin projections at each
1946    /// consumer" discipline extended onto the peer post-projection typed-
1947    /// view surface (the [`WitContract::endpoint`] pre-projection
1948    /// accessor returns `Some` for any author-declared `:endpoint`
1949    /// value regardless of the paired `:wit` world's HTTP-shape
1950    /// classification — the raw slot before validation crosses it —
1951    /// while this post-projection [`Self::http_endpoint`] accessor
1952    /// returns `Some` iff the target has been projected onto the
1953    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
1954    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
1955    /// coherence; the two accessors close the pre-projection /
1956    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
1957    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
1958    /// the three payload-carrying arms) — extends the per-arm
1959    /// projection family onto the [`Self::Http`] specialization axis
1960    /// that the pan-arm accessor's shape blends into a single arm-
1961    /// agnostic view; paired with [`Self::pubsub_subject`] /
1962    /// [`Self::store_slot`] on the sibling per-arm axes so every
1963    /// per-payload-arm shape carries a named post-projection accessor
1964    /// on the same shape as `http_endpoint`, closing the per-arm-shape
1965    /// accept-set the substrate primitive owns.
1966    #[must_use]
1967    pub const fn http_endpoint(&self) -> Option<&'a str> {
1968        match *self {
1969            WitTarget::Http { endpoint } => Some(endpoint),
1970            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1971        }
1972    }
1973
1974    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
1975    /// consumer that fans on the pub-sub-shaped payload keys off —
1976    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
1977    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
1978    /// the projected target is [`Self::PubSub { subject }`], `None` on
1979    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
1980    /// [`Self::Capability`], each of which carries no NATS-shaped
1981    /// subject by definition).
1982    ///
1983    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
1984    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
1985    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
1986    /// CR materializer's `spec.subjects[]` projection, the future
1987    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
1988    /// bucket-key resolver, the future `feira app graph --pubsub`
1989    /// per-Aplicacao subject column, any future substrate-lifted
1990    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
1991    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
1992    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
1993    /// future pub-sub-shape consumer reaches for the same typed
1994    /// dispatch this accessor exposes so the "which arm carries the
1995    /// subject scalar?" answer lives at one caixa-core edit rather
1996    /// than open-coded across per-consumer `if let WitTarget::PubSub
1997    /// { subject } = c.target()…` pattern-matches.
1998    ///
1999    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2000    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2001    /// the pre-projection [`WitContract::subject`] scalar accessor on
2002    /// the raw `:contratos :subject` field-access axis — same "one
2003    /// typed dispatch on the substrate primitive, thin projections at
2004    /// each consumer" discipline extended onto the per-arm pub-sub
2005    /// post-projection axis. The pre-projection accessor returns
2006    /// `Some` for any author-declared `:subject` value regardless of
2007    /// the paired `:wit` world's pub-sub-shape classification (the raw
2008    /// slot before validation crosses it); this post-projection
2009    /// accessor returns `Some` iff the target has been projected onto
2010    /// the [`Self::PubSub`] arm, i.e. only after the
2011    /// [`WitContract::target`] gate has admitted the
2012    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2013    /// the pre-/post-projection pair on the pub-sub-subject axis to
2014    /// match the pair the [`WitContract::endpoint`] +
2015    /// [`Self::http_endpoint`] surfaces already close on the peer
2016    /// HTTP-endpoint axis.
2017    ///
2018    /// Sibling of the unified pan-arm [`Self::payload`]
2019    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2020    /// extends the per-arm projection family onto the [`Self::PubSub`]
2021    /// specialization axis that the pan-arm accessor's shape blends
2022    /// into a single arm-agnostic view; the pair
2023    /// (`pubsub_subject`, `store_slot`) closes the trio
2024    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2025    /// payload arm now carries its own per-arm-shape post-projection
2026    /// accessor.
2027    #[must_use]
2028    pub const fn pubsub_subject(&self) -> Option<&'a str> {
2029        match *self {
2030            WitTarget::PubSub { subject } => Some(subject),
2031            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2032        }
2033    }
2034
2035    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2036    /// every consumer that fans on the store-shaped payload keys off —
2037    /// returns the [`Self::Store`]-arm's author-declared slot template
2038    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2039    /// projected target is [`Self::Store { slot }`], `None` on the
2040    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2041    /// [`Self::Capability`], each of which carries no
2042    /// key/value-store slot by definition).
2043    ///
2044    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2045    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2046    /// every future substrate-side store-introspecting per-`(:de,
2047    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2048    /// namespace / prefix reconciler's per-slot projection, the future
2049    /// per-store-backend routing overlay's slot-shape gate, the future
2050    /// `feira app graph --store` per-Aplicacao slot column, any future
2051    /// substrate-lifted store-shape emitter that reads a projected
2052    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2053    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2054    /// Every future store-shape consumer reaches for the same typed
2055    /// dispatch this accessor exposes so the "which arm carries the
2056    /// slot scalar?" answer lives at one caixa-core edit rather than
2057    /// open-coded across per-consumer
2058    /// `if let WitTarget::Store { slot } = c.target()…`
2059    /// pattern-matches.
2060    ///
2061    /// Peer of the sibling [`Self::http_endpoint`] +
2062    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2063    /// axes and of the pre-projection [`WitContract::slot`] scalar
2064    /// accessor on the raw `:contratos :slot` field-access axis — same
2065    /// "one typed dispatch on the substrate primitive, thin projections
2066    /// at each consumer" discipline extended onto the per-arm store
2067    /// post-projection axis. Closes the pre-/post-projection pair on
2068    /// the store-slot axis to match the pairs the
2069    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2070    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2071    /// already close on the peer HTTP-endpoint and pub-sub-subject
2072    /// axes; the substrate-side pre-/post-projection accessor family
2073    /// now spans all three payload arms as a matched trio, so any
2074    /// future arm-shape widening (a `Rest`/`Grpc` split of
2075    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2076    /// lands one accessor without threading through the sibling
2077    /// pre-projection or the peer per-arm post-projection surfaces a
2078    /// compile-time exhaustiveness error at the substrate primitive,
2079    /// not a silent per-consumer split at renderer emit time.
2080    ///
2081    /// Sibling of the unified pan-arm [`Self::payload`]
2082    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2083    /// closes the per-arm projection family onto the [`Self::Store`]
2084    /// specialization axis that the pan-arm accessor's shape blends
2085    /// into a single arm-agnostic view. The trio
2086    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2087    /// pan-arm accept-set on every payload-carrying arm: exactly one
2088    /// per-arm accessor returns `Some(payload)` and the two peers
2089    /// return `None`, and every payload-less [`Self::Capability`]
2090    /// input returns `None` on all three — the partition the sibling
2091    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2092    /// pin locks in load-bearing.
2093    #[must_use]
2094    pub const fn store_slot(&self) -> Option<&'a str> {
2095        match *self {
2096            WitTarget::Store { slot } => Some(slot),
2097            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2098        }
2099    }
2100
2101    /// Render this typed target as a stable human-readable label
2102    /// (`:endpoint "/charge"`, `:subject "events.x"`,
2103    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2104    /// the WIT world is a pure capability edge).
2105    ///
2106    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2107    /// gate so the diagnostic names *which* identical edge was
2108    /// declared twice (not just which `(de, para, wit)` triple).
2109    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2110    /// on the payload-carrying arms (`Some((field, payload)) →
2111    /// format!(":{field} {payload:?}")`) and through the lifted
2112    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2113    /// [`Self::Capability`] arm — so a future variant addition (the
2114    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2115    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2116    /// `Queue`-shaped peer) becomes a single new match-arm on
2117    /// [`Self::payload_pair`] rather than a rewrite of this template
2118    /// (and every downstream consumer that reaches for the label
2119    /// shape: the per-edge policy resolver in M4, the `feira app
2120    /// graph` view, the operator's mesh-graph audit). Until this
2121    /// lift landed the three payload arms carried three near-identical
2122    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2123    /// [`Self::Capability`] arm carried the payload-less byte-string
2124    /// twice (once inline here, once in the pin test) — closing the
2125    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2126    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2127    /// / 4a1e490) peer-const lifts already established for the
2128    /// payload-carrying arms.
2129    #[must_use]
2130    pub fn label(&self) -> String {
2131        match self.payload_pair() {
2132            Some((field, payload)) => format!(":{field} {payload:?}"),
2133            None => Self::CAPABILITY_LABEL.to_string(),
2134        }
2135    }
2136
2137    /// Render this typed target as the `feira app graph` per-`:contratos`
2138    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2139    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2140    /// payload-less arm).
2141    ///
2142    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2143    /// on the payload-carrying arms (`Some((field, payload)) →
2144    /// format!("{field}={payload}")`) and through the lifted
2145    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2146    /// [`Self::Capability`] arm — so a future variant addition
2147    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2148    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2149    /// `Queue`-shaped peer) becomes one match-arm edit at
2150    /// [`Self::payload_pair`], propagating through this graph-verb
2151    /// projection at zero call-site cost, sibling to the peer
2152    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2153    /// same 4-arm dispatch.
2154    ///
2155    /// Until this lift landed the [`caixa-feira`]
2156    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2157    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2158    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2159    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2160    /// `format!("{}={endpoint}", ...)` template and hard-coding
2161    /// `"(capability-only)"` as a fifth payload-less scalar with no link
2162    /// back to the paired [`WitTarget::Capability`] variant declaration.
2163    /// A future variant addition would have had to be threaded through
2164    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2165    /// verb's inline match in lockstep or the two projections would
2166    /// silently disagree on the arm-set the graph verb prints — the
2167    /// duplicate-`:contratos` diagnostic reading one shape while the
2168    /// graph verb's payload column silently dropped the new arm to
2169    /// `(capability-only)`. Lifting the graph-verb projection onto the
2170    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2171    /// the axis: both projections migrate as a unit.
2172    ///
2173    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2174    /// quoting) shape is graph-verb-canonical — distinct from the
2175    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2176    /// duplicate-`:contratos` diagnostic seeds (see
2177    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2178    /// on the payload-less axis for the paired distinction).
2179    #[must_use]
2180    pub fn graph_label(&self) -> String {
2181        match self.payload_pair() {
2182            Some((field, payload)) => format!("{field}={payload}"),
2183            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2184        }
2185    }
2186}
2187
2188/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2189/// pretty-printed byte-string every consumer that formats a typed
2190/// payload target as user-facing text lands on (the
2191/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2192/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2193/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2194/// graph` per-`:contratos`-edge payload column that reaches the graph
2195/// verb through `format!("{target}")`, the future M4 per-edge policy
2196/// resolver's per-edge audit-log line, the operator's mesh-graph
2197/// per-edge inspection view) reaches for the same lifted
2198/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2199/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2200/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2201/// routes through — extending the three-path-convergence
2202/// (`Debug` for structural inspection, `Display` for user-facing text,
2203/// per-arm typed accessor for the canonical byte-string) discipline the
2204/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2205/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2206/// onto the fourth (and only remaining) typed-shape-discriminator axis
2207/// on the caixa surface.
2208///
2209/// Pre-lift the two paths were structurally independent — every consumer
2210/// reaching for a payload byte-string past the [`WitTarget::label`]
2211/// helper had to pick between three paths ([`WitTarget::label`],
2212/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2213/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2214/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2215/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2216/// that reached for `format!("{target}")` — the canonical shape every
2217/// user-facing pretty-print site on the sibling typed-enum axes already
2218/// uses — would silently land on the `Debug` derive's structural output
2219/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2220/// than the `label()` helper's stable byte-string (`:endpoint
2221/// "/charge"` — the author-facing `:contratos` keyword form) the
2222/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2223/// already threads through. The two spellings would diverge silently in
2224/// every downstream diagnostic / graph / audit line reached through
2225/// `format!` rather than through the `label()` helper. Routing
2226/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2227/// path: every `format!("{v}")` call reaches the same
2228/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2229/// and the duplicate-`:contratos` gate already route through, so a
2230/// future variant addition (the M4-and-later per-edge WIT registry may
2231/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2232/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2233/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2234/// match — rather than fanning out through hand-rolled per-arm
2235/// [`std::fmt::Display`] arms.
2236///
2237/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2238/// is the typed view returned by [`WitContract::target`], not a
2239/// closed-set discriminator enum with a gen-platform Discriminant
2240/// registration, so the `Debug` derive's structural output (which every
2241/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2242/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2243/// shape for structural inspection; `Display` (via `label`) reveals the
2244/// stable author-facing payload projection.
2245///
2246/// Pin tests
2247/// [`tests::wit_target_display_routes_through_label_helper`] and
2248/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2249/// assert the two paths agree byte-for-byte on every variant, so a
2250/// future variant addition or `label()` reimplementation that hand-rolls
2251/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2252/// build error visible at caixa-core test time, not a silent
2253/// per-consumer dispatch miss at diagnostic / audit / graph time.
2254impl std::fmt::Display for WitTarget<'_> {
2255    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2256        f.write_str(&self.label())
2257    }
2258}
2259
2260// ── one Aplicacao member ─────────────────────────────────────────────
2261
2262/// A Servico participating in the Aplicacao. Same shape as
2263/// `crate::supervisor::ChildSpec` but without a restart policy —
2264/// supervision is per-Servico (each member has its own
2265/// `:supervisor`), the Aplicacao orchestrates *placement*.
2266#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2267#[serde(rename_all = "camelCase")]
2268pub struct Membro {
2269    /// Member caixa's `:nome`. Resolves through the same dep
2270    /// resolution path as `crate::dep::Dep`.
2271    pub caixa: String,
2272
2273    /// Semver constraint.
2274    pub versao: String,
2275}
2276
2277impl Membro {
2278    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2279    /// accessor every consumer that reads the member's Servico identity
2280    /// keys off — returns the author-declared `:membros :caixa`
2281    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2282    /// own [`String`] storage.
2283    ///
2284    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2285    /// participating in the Aplicacao — validated by
2286    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2287    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2288    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2289    /// [`validate_no_self_membership`]) — and every downstream consumer
2290    /// that fans on the member's identity keys off this scalar (the
2291    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2292    /// lookup, the per-`:membros` duplicate gate's dedup key, the
2293    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2294    /// identity, the self-membership gate, the
2295    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2296    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2297    /// CR materializer's per-member resolver).
2298    ///
2299    /// Prior to this lift the `.caixa` byte-string was read inline at
2300    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2301    /// set collector at
2302    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2303    /// [`validate_membros`] validation-side member-caixa gate at
2304    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2305    /// per-member duplicate-gate dedup key at
2306    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2307    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2308    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2309    /// [`validate_no_self_membership`] self-loop gate at
2310    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2311    /// expressed no compile-time link back to the typed slot. Every
2312    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2313    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2314    /// `name:` axis, so a future extension of the `:membros :caixa`
2315    /// axis to a richer author surface — a per-cluster alias table the
2316    /// operator pins through a future `:placement`-scoped slot, a
2317    /// namespace-qualified rewrite the M4 CR materializer applies
2318    /// per-CR, a per-member overlay from the future `:membros
2319    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2320    /// acknowledges — would have had to be threaded through every
2321    /// open-coded copy in lockstep or one consumer would silently
2322    /// disagree with the peers on which caixa a given member resolves
2323    /// to. A member-set lookup that treated the name as `"cart"` while
2324    /// the peer adjacency map treated it as `"tenant-a/cart"` would
2325    /// silently split the `:contratos` membership-lookup diagnostic from
2326    /// the cycle-detector's node identity — a two-consumer split at the
2327    /// validator far from the source `caixa.lisp` with no field naming
2328    /// the identity-drift root cause. Lifting the resolution rule to a
2329    /// typed method on the substrate primitive means every downstream
2330    /// consumer of the Aplicacao's per-`:membros` identity surface
2331    /// reaches for exactly one typed dispatch — the resolver's
2332    /// accept-set migrates as a unit on any future axis addition.
2333    ///
2334    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2335    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2336    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2337    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2338    /// destination-Servico scalar accessors — same "one typed dispatch
2339    /// on the substrate primitive, thin projections at each consumer"
2340    /// discipline extended onto the per-`:membros` member-caixa `:nome`
2341    /// byte-string axis. Named `nome()` to match the tatara-lisp
2342    /// author-surface term the field's docstring already reaches for
2343    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2344    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2345    /// already carries — the accessor's name maps directly onto the
2346    /// canonical caixa-identity vocabulary rather than shadowing the
2347    /// field's storage-side `caixa` label.
2348    #[must_use]
2349    pub const fn nome(&self) -> &str {
2350        self.caixa.as_str()
2351    }
2352
2353    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2354    /// requirement scalar accessor every consumer that reads the
2355    /// member's version pin keys off — returns the author-declared
2356    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2357    /// from the typed slot's own [`String`] storage.
2358    ///
2359    /// The `:membros :versao` slot carries the Cargo-shaped semver
2360    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2361    /// pins which release of the member-caixa the Aplicacao composes
2362    /// against — the same requirement grammar the peer `:deps :versao`
2363    /// / `:children :versao` axes carry, resolved through the shared
2364    /// [`crate::render::require_valid_versao_requirement`] cascade and
2365    /// the shared [`crate::version::parse_requirement`] parser. Every
2366    /// downstream consumer that fans on the member's version pin keys
2367    /// off this scalar (the [`validate_membros`] per-member requirement
2368    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2369    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
2370    /// m.nome(), m.versao_requirement())` line, every future per-cluster
2371    /// version-lock overlay the operator pins through a future
2372    /// `:placement`-scoped slot, the future
2373    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2374    /// version resolver, the future `feira app deploy` pipeline's
2375    /// per-member lacre BLAKE3-closure lookup).
2376    ///
2377    /// Prior to this lift the `.versao` byte-string was accessed inline
2378    /// at two `&str`-shaped sites — the [`validate_membros`]
2379    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2380    /// …)` and the `feira app graph` per-member printer's `println!(
2381    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2382    /// prior to this lift) — two open-coded field-accesses that expressed
2383    /// no compile-time link back to the typed slot. A future extension of
2384    /// the `:membros :versao` axis to a richer author surface (a
2385    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2386    /// flow, a lacre-projected concrete-version rewrite the operator
2387    /// materializes at CR-admission time, a future `:membros :versao-lock`
2388    /// per-cluster override slot) would have had to be threaded through
2389    /// every open-coded copy in lockstep or one consumer would silently
2390    /// disagree with the peers on which release constraint a given
2391    /// member resolves to. Lifting the resolution rule to a typed method
2392    /// on the substrate primitive means every downstream requirement-
2393    /// facing consumer reaches for exactly one typed dispatch — the
2394    /// resolver's accept-set migrates as a unit on any future axis
2395    /// addition.
2396    ///
2397    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2398    /// member-caixa `:nome` scalar accessor — the pair
2399    /// `(nome(), versao_requirement())` jointly projects the
2400    /// `(caixa, versao)` field pair every renderer that fans on
2401    /// per-member identity + version pin keys off, closing the last
2402    /// unlifted per-`:membros` scalar axis so every downstream
2403    /// per-`:membros` reader now routes through a typed dispatch on the
2404    /// substrate primitive. Named `versao_requirement()` rather than
2405    /// `versao()` because the field's storage-side `.versao` label is
2406    /// already the author-surface term (`:versao`); the accessor's name
2407    /// carries the semantic role — the semver *requirement* string the
2408    /// shared [`crate::version::parse_requirement`] entry-point consumes
2409    /// — so a raw field access and a typed dispatch read differently at
2410    /// every consumer site.
2411    ///
2412    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2413    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2414    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2415    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2416    /// destination-Servico scalar accessors — same "one typed dispatch
2417    /// on the substrate primitive, thin projections at each consumer"
2418    /// discipline extended onto the per-`:membros` member-`:versao`
2419    /// semver-requirement byte-string axis.
2420    #[must_use]
2421    pub const fn versao_requirement(&self) -> &str {
2422        self.versao.as_str()
2423    }
2424}
2425
2426// ── mesh-level policies ──────────────────────────────────────────────
2427
2428/// Mesh policies that apply to every `:contratos` edge unless
2429/// overridden per-edge in M4. V0 is a single global policy block.
2430#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2431#[serde(rename_all = "camelCase")]
2432pub struct MeshPolicy {
2433    /// Per-call timeout. Authored as a duration string (`"30s"`).
2434    #[serde(
2435        default,
2436        skip_serializing_if = "Option::is_none",
2437        with = "supervisor::duration_codec"
2438    )]
2439    pub timeout: Option<Duration>,
2440
2441    /// Number of retries on transient failure. None = no retries.
2442    #[serde(default, skip_serializing_if = "Option::is_none")]
2443    pub retries: Option<u32>,
2444
2445    /// Circuit breaker config. Trips after N failures within W
2446    /// duration; closes after a cooldown.
2447    #[serde(default, skip_serializing_if = "Option::is_none")]
2448    pub circuit_breaker: Option<CircuitBreaker>,
2449
2450    /// Whether mTLS is required for every contrato. Default: true
2451    /// (sandboxing-by-default; explicit opt-out only).
2452    #[serde(default, skip_serializing_if = "Option::is_none")]
2453    pub mtls_required: Option<bool>,
2454
2455    /// Token-bucket rate limit. Authored as `"100/s"` or
2456    /// `"5000/m"`; stored as `(rate, window)`.
2457    #[serde(
2458        default,
2459        skip_serializing_if = "Option::is_none",
2460        with = "rate_limit_codec"
2461    )]
2462    pub rate_limit: Option<RateLimit>,
2463}
2464
2465impl MeshPolicy {
2466    /// True when no `:politicas` axis carries a value — every field is
2467    /// `None`. The same emptiness contract every other M2/M3 typed
2468    /// surface carries ([`crate::LimitsSpec::is_empty`],
2469    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2470    /// typed slot onto a cluster artifact key off this predicate to
2471    /// decide "emit the slot" vs "skip the slot entirely", so an
2472    /// authored-but-unset `:politicas (())` round-trips to a rendered
2473    /// artifact that's structurally identical to one that omits the
2474    /// slot. Lifted as a typed predicate (rather than per-renderer
2475    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2476    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2477    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2478    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2479    /// not a coordinated rewrite of every consumer that's reaching
2480    /// for the emptiness semantic.
2481    #[must_use]
2482    pub const fn is_empty(&self) -> bool {
2483        self.timeout().is_none()
2484            && self.retries().is_none()
2485            && self.circuit_breaker().is_none()
2486            && self.mtls_required().is_none()
2487            && self.rate_limit().is_none()
2488    }
2489
2490    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
2491    /// per-call-deadline scalar accessor every consumer of the
2492    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
2493    /// returns the author-declared `:politicas :timeout` typed
2494    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
2495    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
2496    /// is `Copy`, so the accessor returns by value; no borrow of
2497    /// `&self` past the call). `None` when the slot is absent (the
2498    /// "cluster default applies — typically the gateway class's
2499    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
2500    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
2501    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
2502    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
2503    /// round-trips to a rendered `HTTPRoute` structurally identical to
2504    /// one that omits the slot).
2505    ///
2506    /// The `:politicas :timeout` slot carries the "no infinite blocking"
2507    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
2508    /// the typed slot's `Option<Duration>` accept-set (zero-floor
2509    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
2510    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
2511    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
2512    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
2513    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
2514    /// Every downstream consumer that reads the per-call cap keys off
2515    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2516    /// renderers key off to decide "emit :politicas overlay" vs "skip
2517    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2518    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
2519    /// fans the deadline into every rule via
2520    /// [`crate::render::single_field_overlay`], the future M4 per-
2521    /// Aplicacao Gateway API reconciler materialization pass, the
2522    /// future per-`:contratos`-edge timeout-override overlay the
2523    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
2524    ///
2525    /// Prior to this lift the `.timeout` field was accessed inline at
2526    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
2527    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
2528    /// …)` call — two open-coded field-accesses that expressed no
2529    /// compile-time link back to the typed slot. A future extension of
2530    /// the `:politicas :timeout` axis to a richer author surface — a
2531    /// per-`:contratos`-edge timeout override the operator pins through
2532    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
2533    /// roadmap acknowledges, a per-cluster timeout-default overlay the
2534    /// M4 CR materializer resolves per-CR, a split of the single
2535    /// per-call `Duration` into a richer `{request, backendRequest}`
2536    /// pair once the Gateway API's per-rule `timeouts` block grows the
2537    /// upstream-facing backendRequest arm alongside the client-facing
2538    /// request arm — would have had to be threaded through both open-
2539    /// coded copies in lockstep or the emptiness predicate and the
2540    /// caixa-mesh emit path would silently disagree on which per-call
2541    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
2542    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
2543    /// == false` while the renderer's overlay-emit path silently read
2544    /// a drifted other value, or vice versa: an author's `:timeout
2545    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
2546    /// the emptiness predicate still classified the policy as non-
2547    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
2548    /// | grep -A2 timeouts` audit would land on a route whose author's
2549    /// typed slot value silently vanished at the renderer layer).
2550    /// Lifting the resolution to a typed method on the substrate
2551    /// primitive means every downstream consumer of the Aplicacao's
2552    /// per-`:politicas` deadline surface reaches for exactly one typed
2553    /// dispatch — the resolver's accept-set migrates as a unit on any
2554    /// future axis addition.
2555    ///
2556    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
2557    /// family (sibling of the peer per-`:politicas`
2558    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
2559    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
2560    /// `Option<bool>` accessor — same "one typed dispatch on the
2561    /// substrate primitive, thin projections at each consumer"
2562    /// discipline extended onto the peer per-`:politicas` typed-
2563    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
2564    /// numeric-Copy-T scalar" projection pattern the sibling
2565    /// `Option<u32>` / `Option<bool>` lifts opened, since every
2566    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
2567    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
2568    /// than a scalar). Named `timeout()` to match the storage field's
2569    /// name; the accessor's identity maps onto the canonical MESH-
2570    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
2571    #[must_use]
2572    pub const fn timeout(&self) -> Option<Duration> {
2573        self.timeout
2574    }
2575
2576    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
2577    /// retry-budget scalar accessor every consumer of the Aplicacao's
2578    /// Gateway API v1.x per-rule retry-cap keys off — returns the
2579    /// author-declared `:politicas :retries` typed `u32` verbatim as an
2580    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
2581    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
2582    /// value; no borrow of `&self` past the call). `None` when the slot
2583    /// is absent (the "cluster default applies — typically 'no retries
2584    /// beyond a single dispatch attempt'" arm the caixa-mesh
2585    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
2586    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
2587    /// this predicate too, so an authored-but-unset `:politicas
2588    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
2589    /// identical to one that omits the slot).
2590    ///
2591    /// The `:politicas :retries` slot carries the "transient failure
2592    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
2593    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
2594    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2595    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
2596    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
2597    /// count scalar the caixa-mesh `retry_overlay` builder writes.
2598    /// Every downstream consumer that reads the retry cap keys off this
2599    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2600    /// renderers key off to decide "emit :politicas overlay" vs "skip
2601    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2602    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
2603    /// the value into every rule via [`crate::render::single_field_overlay`],
2604    /// the future M4 per-Aplicacao Gateway API reconciler
2605    /// materialization pass, the future per-`:contratos`-edge retry-
2606    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
2607    /// acknowledges).
2608    ///
2609    /// Prior to this lift the `.retries` field was accessed inline at
2610    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
2611    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
2612    /// …)` call — two open-coded field-accesses that expressed no
2613    /// compile-time link back to the typed slot. A future extension of
2614    /// the `:politicas :retries` axis to a richer author surface — a
2615    /// per-`:contratos`-edge retry override the operator pins through a
2616    /// future `:contratos :retries` slot, a per-cluster retry-default
2617    /// overlay the M4 CR materializer resolves per-CR, a promotion of
2618    /// the plain `u32` attempt-count to a richer `{attempts, codes,
2619    /// backoff}` sub-block once the Gateway API grows the peer
2620    /// `retry.codes` / `retry.backoff` axes — would have had to be
2621    /// threaded through both open-coded copies in lockstep or the
2622    /// emptiness predicate and the caixa-mesh emit path would silently
2623    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
2624    /// (a `:politicas` block whose only axis is a `Some :retries` would
2625    /// satisfy `is_empty() == false` while the renderer's overlay-emit
2626    /// path silently read a drifted other value, or vice versa: an
2627    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
2628    /// block while the emptiness predicate still classified the policy
2629    /// as non-empty). Lifting the resolution to a typed method on the
2630    /// substrate primitive means every downstream consumer of the
2631    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
2632    /// one typed dispatch — the resolver's accept-set migrates as a
2633    /// unit on any future axis addition.
2634    ///
2635    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
2636    /// family (sibling of the peer per-`:politicas`
2637    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
2638    /// same "one typed dispatch on the substrate primitive, thin
2639    /// projections at each consumer" discipline extended onto the
2640    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
2641    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
2642    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
2643    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
2644    /// fold on). Named `retries()` to match the storage field's name;
2645    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
2646    /// §III.2 vocabulary the slot's docstring already carries.
2647    #[must_use]
2648    pub const fn retries(&self) -> Option<u32> {
2649        self.retries
2650    }
2651
2652    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
2653    /// enforcement-toggle scalar accessor every consumer of the
2654    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
2655    /// — returns the author-declared `:politicas :mtls-required` typed
2656    /// bool verbatim as an `Option<bool>`, copied out of the typed
2657    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
2658    /// the accessor returns by value; no borrow of `&self` past the
2659    /// call). `None` when the slot is absent (the "cluster default
2660    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
2661    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
2662    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
2663    /// this predicate too, so an authored-but-unset `:politicas
2664    /// (:mtls-required ())` round-trips to a rendered
2665    /// `CiliumNetworkPolicy` structurally identical to one that omits
2666    /// the slot).
2667    ///
2668    /// The `:politicas :mtls-required` slot carries the "explicit opt-
2669    /// out only, sandboxing-by-default" mTLS-enforcement toggle
2670    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
2671    /// `{None, Some(true), Some(false)}` accept-set maps onto the
2672    /// Cilium `authentication.mode` bijection through
2673    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
2674    /// handshake enforced), `Some(false) → "disabled"` (handshake
2675    /// skipped — the debug-edge opt-out), `None` → omit the block
2676    /// (cluster default applies). Every downstream consumer that
2677    /// reads the toggle keys off this scalar (the
2678    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2679    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2680    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
2681    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
2682    /// ingress rule via [`crate::render::single_field_overlay`], the
2683    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
2684    /// materialization pass, the future per-`:contratos`-edge mTLS
2685    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2686    ///
2687    /// Prior to this lift the `.mtls_required` field was accessed
2688    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2689    /// `self.mtls_required.is_none()` arm and caixa-mesh's
2690    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
2691    /// two open-coded field-accesses that expressed no compile-time
2692    /// link back to the typed slot. A future extension of the
2693    /// `:politicas :mtls-required` axis to a richer author surface —
2694    /// a per-`:contratos`-edge mTLS override the operator pins through
2695    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
2696    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
2697    /// M4 CR materializer resolves per-CR, a three-valued
2698    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
2699    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
2700    /// would have had to be threaded through both open-coded copies in
2701    /// lockstep or the emptiness predicate and the caixa-mesh emit
2702    /// path would silently disagree on which toggle a given
2703    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
2704    /// axis is a `Some`
2705    /// `:mtls-required` would satisfy `is_empty() == false` while the
2706    /// renderer's overlay-emit path silently read a drifted other
2707    /// value, or vice versa). Lifting the resolution to a typed method
2708    /// on the substrate primitive means every downstream consumer of
2709    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
2710    /// for exactly one typed dispatch — the resolver's accept-set
2711    /// migrates as a unit on any future axis addition.
2712    ///
2713    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2714    /// family (peer of the sibling per-`:placement`
2715    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2716    /// same "one typed dispatch on the substrate primitive, thin
2717    /// projections at each consumer" discipline extended onto the
2718    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2719    /// the "optional per-slot Copy-T scalar" projection pattern the
2720    /// sibling per-`:politicas` `:retries` (Option<u32>) /
2721    /// `:timeout` (Option<Duration>) future lifts fold on). Named
2722    /// `mtls_required()` to match the storage field's name; the
2723    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2724    /// §III.2 vocabulary the slot's docstring already carries.
2725    #[must_use]
2726    pub const fn mtls_required(&self) -> Option<bool> {
2727        self.mtls_required
2728    }
2729
2730    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2731    /// `local_rate_limit`-mesh token-bucket-declaration scalar
2732    /// accessor every consumer of the Aplicacao's per-`:politicas`
2733    /// per-`(rate, window)` rate-limit surface keys off — returns the
2734    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2735    /// verbatim as an `Option<RateLimit>`, copied out of the typed
2736    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2737    /// `Copy`, so the accessor returns by value; no borrow of `&self`
2738    /// past the call). `None` when the slot is absent (the "cluster
2739    /// default applies — typically 'no per-Aplicacao rate declaration,
2740    /// gateway-class per-listener default applies'" arm the future
2741    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2742    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2743    /// `rate_limit().is_none()` arm reads this predicate too, so an
2744    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2745    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2746    /// identical to one that omits the slot).
2747    ///
2748    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2749    /// token-bucket rate declaration" contract (MESH-COMPOSITION
2750    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2751    /// (rate lower-bounded by 1 through
2752    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2753    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2754    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2755    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2756    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2757    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2758    /// `:politicas` overlay emits. Every downstream consumer that
2759    /// reads the rate declaration keys off this scalar (the
2760    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2761    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2762    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2763    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2764    /// `rl.window` against [`is_canonical_rate_limit_window`], the
2765    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2766    /// the future per-`:contratos`-edge rate-limit override the
2767    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2768    ///
2769    /// Prior to this lift the `.rate_limit` field was accessed inline
2770    /// at two sites — [`MeshPolicy::is_empty`]'s
2771    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2772    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2773    /// field-accesses that expressed no compile-time link back to the
2774    /// typed slot. A future extension of the `:politicas :rate-limit`
2775    /// axis to a richer author surface — a per-`:contratos`-edge
2776    /// rate-limit override the operator pins through a future
2777    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2778    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2779    /// the M4 CR materializer resolves per-CR, a promotion of the
2780    /// plain `(rate, window)` scalar pair to a richer
2781    /// `{rate, window, burst, key}` sub-block once Envoy's
2782    /// `local_rate_limit` grows the peer `burst_size` /
2783    /// `descriptor_key` axes — would have had to be threaded through
2784    /// both open-coded copies in lockstep or the emptiness predicate
2785    /// and the validate gate would silently disagree on which rate
2786    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2787    /// block whose only axis is a `Some :rate-limit` would satisfy
2788    /// `is_empty() == false` while the validate path silently read a
2789    /// drifted other value, or vice versa: an author's
2790    /// `:rate-limit "100/s"` would omit the value-shape gate while the
2791    /// emptiness predicate still classified the policy as non-empty).
2792    /// Lifting the resolution to a typed method on the substrate
2793    /// primitive means every downstream consumer of the Aplicacao's
2794    /// per-`:politicas` rate-limit surface reaches for exactly one
2795    /// typed dispatch — the resolver's accept-set migrates as a unit
2796    /// on any future axis addition.
2797    ///
2798    /// First `Option<Copy-composite-T>`-return accessor on the M3
2799    /// mesh-slot family — closes the last un-lifted per-`:politicas`
2800    /// scalar-value axis. Peer of the sibling per-`:politicas`
2801    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2802    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2803    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2804    /// "one typed dispatch on the substrate primitive, thin
2805    /// projections at each consumer" discipline extended onto the
2806    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2807    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2808    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2809    /// sub-accessors rather than a top-level accessor because
2810    /// consumers reach for the axes not the aggregate). Named
2811    /// `rate_limit()` to match the storage field's name; the
2812    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2813    /// §III.2 vocabulary the slot's docstring already carries.
2814    #[must_use]
2815    pub const fn rate_limit(&self) -> Option<RateLimit> {
2816        self.rate_limit
2817    }
2818
2819    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2820    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2821    /// declaration scalar accessor every consumer of the Aplicacao's
2822    /// per-`:politicas` breaker declaration keys off — returns the
2823    /// author-declared `:politicas :circuit-breaker` typed
2824    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2825    /// copied out of the typed slot's own `Option<CircuitBreaker>`
2826    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2827    /// by value; no borrow of `&self` past the call). `None` when the
2828    /// slot is absent (the "cluster default applies — typically 'no
2829    /// per-Aplicacao breaker declaration, gateway-class per-listener
2830    /// default applies'" arm the future caixa-mesh
2831    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2832    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2833    /// arm reads this predicate too, so an authored-but-unset
2834    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2835    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2836    /// that omits the slot).
2837    ///
2838    /// The `:politicas :circuit-breaker` slot carries the
2839    /// "per-Aplicacao consecutive-transient-failure trip declaration"
2840    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2841    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2842    /// zero-floor rejected through
2843    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2844    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2845    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2846    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2847    /// canonical-form pinned through
2848    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2849    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2850    /// bijection the future `CiliumClusterwideEnvoyConfig`
2851    /// per-`:politicas` overlay emits. Every downstream consumer that
2852    /// reads the breaker declaration keys off this scalar (the
2853    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2854    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2855    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2856    /// that brackets `cb.max_failures()` against
2857    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2858    /// [`POLICY_BREAKER_WINDOW_MAX`] via
2859    /// [`crate::render::require_positive_canonical_bounded_duration`],
2860    /// the future M4 per-Aplicacao Envoy reconciler materialization
2861    /// pass, the future per-`:contratos`-edge breaker override the
2862    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2863    ///
2864    /// Prior to this lift the `.circuit_breaker` field was accessed
2865    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2866    /// `self.circuit_breaker.is_none()` arm and the
2867    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2868    /// bind — two open-coded field-accesses that expressed no
2869    /// compile-time link back to the typed slot. A future extension of
2870    /// the `:politicas :circuit-breaker` axis to a richer author
2871    /// surface — a per-`:contratos`-edge breaker override the operator
2872    /// pins through a future `:contratos :circuit-breaker` slot the
2873    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2874    /// breaker-default overlay the M4 CR materializer resolves per-CR,
2875    /// a promotion of the plain `(max_failures, window)` scalar pair to
2876    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2877    /// sub-block once Envoy's `outlier_detection` grows the peer
2878    /// ejection-percentage / ejection-time axes — would have had to be
2879    /// threaded through both open-coded copies in lockstep or the
2880    /// emptiness predicate and the validate gate would silently
2881    /// disagree on which breaker declaration a given [`MeshPolicy`]
2882    /// resolves to (a `:politicas` block whose only axis is a
2883    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2884    /// the validate path silently read a drifted other value, or vice
2885    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2886    /// "60s"))` would omit the value-shape gate while the emptiness
2887    /// predicate still classified the policy as non-empty). Lifting
2888    /// the resolution to a typed method on the substrate primitive
2889    /// means every downstream consumer of the Aplicacao's
2890    /// per-`:politicas` breaker surface reaches for exactly one typed
2891    /// dispatch — the resolver's accept-set migrates as a unit on any
2892    /// future axis addition.
2893    ///
2894    /// Second `Option<Copy-composite-T>`-return accessor on the M3
2895    /// mesh-slot family (sibling of the peer per-`:politicas`
2896    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2897    /// on the same composite-Copy shape, and of the sibling per-
2898    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2899    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2900    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2901    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2902    /// same "one typed dispatch on the substrate primitive, thin
2903    /// projections at each consumer" discipline extended onto the last
2904    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2905    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2906    /// match the storage field's name; the accessor's identity maps
2907    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2908    /// docstring already carries. Closes the last unlifted
2909    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2910    /// reader now routes through a typed dispatch on the substrate
2911    /// primitive.
2912    #[must_use]
2913    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2914        self.circuit_breaker
2915    }
2916}
2917
2918#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2919#[serde(rename_all = "camelCase")]
2920pub struct CircuitBreaker {
2921    pub max_failures: u32,
2922    #[serde(with = "supervisor::duration_codec_required")]
2923    pub window: Duration,
2924}
2925
2926impl CircuitBreaker {
2927    /// Substrate-canonical per-`:politicas :circuit-breaker`
2928    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2929    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2930    /// breaker trip-count keys off — returns the author-declared
2931    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2932    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2933    /// so the accessor returns by value; no borrow of `&self` past the
2934    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2935    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2936    /// axis; a `CircuitBreaker` past pattern-match is definitionally
2937    /// present, and its `:max-failures` field carries the trip count as a
2938    /// required-axis scalar).
2939    ///
2940    /// The `:politicas :circuit-breaker :max-failures` axis carries the
2941    /// "consecutive-transient-failure trip threshold" contract
2942    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2943    /// (zero-floor rejected through
2944    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2945    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2946    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2947    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2948    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2949    /// Every downstream consumer that reads the trip threshold keys off
2950    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2951    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2952    /// canonical `require_positive_bounded_u32` helper, the future M4
2953    /// per-Aplicacao Envoy config reconciler materialization pass, the
2954    /// future per-`:contratos`-edge breaker-override overlay the
2955    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2956    ///
2957    /// Prior to this lift the `.max_failures` field was accessed inline
2958    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2959    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2960    /// open-coded field-access that expressed no compile-time link back
2961    /// to the typed sub-struct axis. A future extension of the
2962    /// `:max-failures` axis to a richer author surface — a
2963    /// per-`:contratos`-edge breaker override the operator pins through a
2964    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2965    /// #3 roadmap acknowledges, a per-cluster max-failures-default
2966    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2967    /// plain `u32` trip count to a richer
2968    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2969    /// tuple once Envoy's `outlier_detection` block's peer axes come into
2970    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2971    /// count arms — would have had to be threaded through every open-
2972    /// coded copy in lockstep or the validate gate and the future M4
2973    /// emit path would silently disagree on which trip threshold a given
2974    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2975    /// would satisfy validate while the emit path silently read a drifted
2976    /// other value, or vice versa: a validated typed slot would land at
2977    /// the emit boundary as a no-op breaker whose trip threshold is
2978    /// structurally never reached). Lifting the resolution to a typed
2979    /// method on the substrate primitive means every downstream consumer
2980    /// of the Aplicacao's per-`:politicas :circuit-breaker`
2981    /// trip-threshold surface reaches for exactly one typed dispatch —
2982    /// the resolver's accept-set migrates as a unit on any future axis
2983    /// addition.
2984    ///
2985    /// First sub-struct scalar accessor on the M3 mesh-slot family
2986    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2987    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2988    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2989    /// closes the last unlifted per-`:politicas` scalar-value axis after
2990    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
2991    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
2992    /// Same "one typed dispatch on the substrate primitive, thin
2993    /// projections at each consumer" discipline the peer
2994    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
2995    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
2996    /// [`Membro::versao_requirement`] (a40b0e3),
2997    /// [`Entrada::destination`] (6db982c) accessors carry on their
2998    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
2999    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
3000    /// match the storage field's name; the accessor's identity maps onto
3001    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3002    /// docstring already carries.
3003    #[must_use]
3004    pub const fn max_failures(&self) -> u32 {
3005        self.max_failures
3006    }
3007
3008    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
3009    /// Envoy-outlier-detection rolling-observation-interval scalar
3010    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3011    /// breaker rolling-window duration keys off — returns the
3012    /// author-declared `:politicas :circuit-breaker :window` typed
3013    /// `Duration` verbatim, copied out of the typed slot's own
3014    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
3015    /// by value; no borrow of `&self` past the call). Non-optional (the
3016    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
3017    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
3018    /// `CircuitBreaker` past pattern-match is definitionally present,
3019    /// and its `:window` field carries the rolling-observation interval
3020    /// as a required-axis scalar).
3021    ///
3022    /// The `:politicas :circuit-breaker :window` axis carries the
3023    /// "consecutive-transient-failure rolling-observation interval"
3024    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3025    /// `Duration` accept-set (zero-floor rejected through
3026    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
3027    /// residue rejected through
3028    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
3029    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
3030    /// Envoy `outlier_detection.interval` per-cluster
3031    /// ejection-observation-interval scalar (equivalently the future
3032    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3033    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3034    /// consumer that reads the rolling-observation interval keys off
3035    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3036    /// integer-millisecond canonical-form + cap bracket at
3037    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
3038    /// [`crate::render::require_positive_canonical_bounded_duration`]
3039    /// helper, the future M4 per-Aplicacao Envoy config reconciler
3040    /// materialization pass, the future per-`:contratos`-edge
3041    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3042    /// acknowledges).
3043    ///
3044    /// Prior to this lift the `.window` field was accessed inline at
3045    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
3046    /// `require_positive_canonical_bounded_duration(cb.window, …)`
3047    /// call — one open-coded field-access that expressed no compile-
3048    /// time link back to the typed sub-struct axis. A future extension
3049    /// of the `:window` axis to a richer author surface — a
3050    /// per-`:contratos`-edge window override the operator pins through
3051    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
3052    /// #3 roadmap acknowledges, a per-cluster window-default overlay
3053    /// the M4 CR materializer resolves per-CR, a promotion of the plain
3054    /// `Duration` observation interval to a richer
3055    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
3056    /// once Envoy's `outlier_detection` block's peer axes come into
3057    /// scope, a per-Envoy-cluster minimum-request-volume gate before
3058    /// the window arms — would have had to be threaded through every
3059    /// open-coded copy in lockstep or the validate gate and the future
3060    /// M4 emit path would silently disagree on which observation
3061    /// interval a given [`CircuitBreaker`] resolves to (an author's
3062    /// `:window "60s"` would satisfy validate while the emit path
3063    /// silently read a drifted other value, or vice versa: a validated
3064    /// typed slot would land at the emit boundary as a breaker whose
3065    /// observation window is structurally so wide that no realistic
3066    /// failure-rate shape can trip it). Lifting the resolution to a
3067    /// typed method on the substrate primitive means every downstream
3068    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
3069    /// observation-window surface reaches for exactly one typed
3070    /// dispatch — the resolver's accept-set migrates as a unit on any
3071    /// future axis addition.
3072    ///
3073    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
3074    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
3075    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
3076    /// required-axis, extended onto the per-sub-struct required-`Duration`
3077    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
3078    /// axis. Same "one typed dispatch on the substrate primitive, thin
3079    /// projections at each consumer" discipline the peer
3080    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3081    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3082    /// [`Membro::versao_requirement`] (a40b0e3),
3083    /// [`Entrada::destination`] (6db982c) accessors carry on their
3084    /// respective per-mesh-slot-atom scalar-value axes, extended onto
3085    /// the per-sub-struct required-`Duration` axis. Named `window()` to
3086    /// match the storage field's name; the accessor's identity maps onto
3087    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3088    /// docstring already carries.
3089    #[must_use]
3090    pub const fn window(&self) -> Duration {
3091        self.window
3092    }
3093}
3094
3095#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3096pub struct RateLimit {
3097    /// Requests per window.
3098    pub rate: u32,
3099    /// Window duration.
3100    pub window: Duration,
3101}
3102
3103impl RateLimit {
3104    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
3105    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
3106    /// every consumer of the Aplicacao's per-`:contratos`-edge
3107    /// rate-limit-bucket capacity keys off — returns the author-declared
3108    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
3109    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
3110    /// returns by value; no borrow of `&self` past the call). Non-optional
3111    /// (the surrounding `Option<RateLimit>` is the "slot present?"
3112    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
3113    /// `RateLimit` past pattern-match is definitionally present, and its
3114    /// `:rate` field carries the token-bucket capacity as a required-axis
3115    /// scalar).
3116    ///
3117    /// The `:politicas :rate-limit` `:rate` axis carries the
3118    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
3119    /// the typed slot's `u32` accept-set (zero-floor rejected through
3120    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
3121    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
3122    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
3123    /// token-bucket-capacity scalar (equivalently the future
3124    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3125    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3126    /// consumer that reads the token-bucket capacity keys off this
3127    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3128    /// cap bracket that gates on the canonical
3129    /// [`crate::render::require_positive_bounded_u32`] helper, the
3130    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3131    /// emits the `<n>/<s|m|h>` author surface, the future M4
3132    /// per-Aplicacao Envoy config reconciler materialization pass, the
3133    /// future per-`:contratos`-edge rate-limit-override overlay the
3134    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3135    ///
3136    /// Prior to this lift the `.rate` field was accessed inline at three
3137    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
3138    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
3139    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
3140    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
3141    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
3142    /// field-accesses that expressed no compile-time link back to the
3143    /// typed sub-struct axis. A future extension of the `:rate` axis
3144    /// to a richer author surface — a per-`:contratos`-edge rate
3145    /// override the operator pins through a future `:contratos :rate`
3146    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
3147    /// per-cluster rate-default overlay the M4 CR materializer resolves
3148    /// per-CR, a promotion of the plain `u32` token capacity to a
3149    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
3150    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3151    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
3152    /// before the token arms — would have had to be threaded through
3153    /// every open-coded copy in lockstep or the validate gate, the
3154    /// codec's render path, and the future M4 emit path would silently
3155    /// disagree on which token capacity a given [`RateLimit`] resolves
3156    /// to (an author's `:rate-limit "100/s"` would satisfy validate
3157    /// while the render / emit paths silently read a drifted other
3158    /// value, or vice versa: a validated typed slot would land at the
3159    /// emit boundary as a no-op limiter whose token capacity is
3160    /// structurally so high that no realistic per-edge traffic shape
3161    /// can drain it). Lifting the resolution to a typed method on the
3162    /// substrate primitive means every downstream consumer of the
3163    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
3164    /// reaches for exactly one typed dispatch — the resolver's
3165    /// accept-set migrates as a unit on any future axis addition.
3166    ///
3167    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
3168    /// in shape to the peer per-`CircuitBreaker`
3169    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
3170    /// on the peer per-sub-struct required-axis, extended onto the
3171    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
3172    /// required-axis scalar" projection pattern the sibling
3173    /// [`RateLimit::window`] future lift folds on. Same "one typed
3174    /// dispatch on the substrate primitive, thin projections at each
3175    /// consumer" discipline the peer [`WitContract::source`] /
3176    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
3177    /// (0804823), [`Membro::nome`] (4a32abf),
3178    /// [`Membro::versao_requirement`] (a40b0e3),
3179    /// [`Entrada::destination`] (6db982c),
3180    /// [`CircuitBreaker::max_failures`] (3a74062),
3181    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
3182    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
3183    /// to match the storage field's name; the accessor's identity maps
3184    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3185    /// docstring already carries.
3186    #[must_use]
3187    pub const fn rate(&self) -> u32 {
3188        self.rate
3189    }
3190
3191    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
3192    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
3193    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3194    /// rate-limit-bucket refill period keys off — returns the
3195    /// author-declared `:politicas :rate-limit` typed `Duration`
3196    /// verbatim, copied out of the typed slot's own `Duration` storage
3197    /// (`Duration` is `Copy`, so the accessor returns by value; no
3198    /// borrow of `&self` past the call). Non-optional (the surrounding
3199    /// `Option<RateLimit>` is the "slot present?" projection at the
3200    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
3201    /// pattern-match is definitionally present, and its `:window`
3202    /// field carries the token-bucket refill period as a required-axis
3203    /// scalar).
3204    ///
3205    /// The `:politicas :rate-limit` `:window` axis carries the
3206    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
3207    /// — the typed slot's `Duration` accept-set (constrained to the
3208    /// three canonical windows `{1s, 60s, 3600s}` the
3209    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
3210    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
3211    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
3212    /// per-cluster token-bucket-refill-period scalar (equivalently the
3213    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3214    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3215    /// consumer that reads the token-bucket refill period keys off
3216    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
3217    /// canonical-window gate that keys off
3218    /// [`is_canonical_rate_limit_window`], the
3219    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3220    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
3221    /// [`rate_limit_window_unit`] and non-canonical fallback via
3222    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
3223    /// reconciler materialization pass, the future per-`:contratos`-
3224    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
3225    /// roadmap acknowledges).
3226    ///
3227    /// Prior to this lift the `.window` field was accessed inline at
3228    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
3229    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
3230    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
3231    /// error-payload construction on refusal, and the two
3232    /// [`rate_limit_codec::render`] arms
3233    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
3234    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
3235    /// open-coded field-accesses that expressed no compile-time link
3236    /// back to the typed sub-struct axis. A future extension of the
3237    /// `:window` axis to a richer author surface — a per-`:contratos`-
3238    /// edge window override the operator pins through a future
3239    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
3240    /// acknowledges, a per-cluster window-default overlay the M4 CR
3241    /// materializer resolves per-CR, a promotion of the plain
3242    /// `Duration` refill period to a richer
3243    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
3244    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3245    /// axis comes into scope, an addition of a `"d"` day suffix once
3246    /// Envoy's `rate_limit_action` grows daily-bucket support — would
3247    /// have had to be threaded through every open-coded copy in
3248    /// lockstep or the validate gate, the codec's render path, and
3249    /// the future M4 emit path would silently disagree on which
3250    /// refill period a given [`RateLimit`] resolves to (an author's
3251    /// `:rate-limit "100/s"` would satisfy validate while the render
3252    /// / emit paths silently read a drifted other value, or vice
3253    /// versa: a validated typed slot would land at the emit boundary
3254    /// as a limiter whose refill period is structurally so long that
3255    /// no realistic per-edge traffic shape stays inside the token
3256    /// budget). Lifting the resolution to a typed method on the
3257    /// substrate primitive means every downstream consumer of the
3258    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
3259    /// reaches for exactly one typed dispatch — the resolver's
3260    /// accept-set migrates as a unit on any future axis addition.
3261    ///
3262    /// Second sub-struct scalar accessor on the `RateLimit` axis —
3263    /// sibling in shape to the just-landed [`RateLimit::rate`]
3264    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
3265    /// required-axis, extended onto the per-sub-struct
3266    /// required-`Duration` axis; closes the last unlifted
3267    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
3268    /// per-sub-struct accessor coverage is now complete across both
3269    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
3270    /// the substrate primitive, thin projections at each consumer"
3271    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
3272    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
3273    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
3274    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
3275    /// [`Membro::nome`] (4a32abf),
3276    /// [`Membro::versao_requirement`] (a40b0e3),
3277    /// [`Entrada::destination`] (6db982c) accessors carry on their
3278    /// respective per-mesh-slot-atom scalar-value axes. Named
3279    /// `window()` to match the storage field's name; the accessor's
3280    /// identity maps onto the canonical MESH-COMPOSITION §III.2
3281    /// vocabulary the slot's docstring already carries.
3282    #[must_use]
3283    pub const fn window(&self) -> Duration {
3284        self.window
3285    }
3286
3287    /// Recognize this rate-limit's `:window` as a canonical
3288    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
3289    /// exactly matches one of the three closed-set arm-Durations
3290    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
3291    /// non-canonical magnitude the codec's round-trip would break on
3292    /// (sub-second residue, or a second-magnitude outside the set
3293    /// [`RateLimitUnit::ALL`] enumerates).
3294    ///
3295    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
3296    /// returns `Some` here — the validate gate's
3297    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
3298    /// rejects every window this accessor returns `None` on. Downstream
3299    /// consumers past validate (the codec's [`rate_limit_codec::render`]
3300    /// path, the future M4 per-Aplicacao Envoy config reconciler's
3301    /// materialization pass, the future per-`:contratos`-edge rate-limit-
3302    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3303    /// acknowledges) that read the typed unit off a validated slot can
3304    /// pattern-match on the returned `Some` without re-checking
3305    /// canonicality at the consumer layer — the typed enum surface is
3306    /// the load-bearing carrier of the canonicality invariant.
3307    ///
3308    /// Preferred over the free [`is_canonical_rate_limit_window`]
3309    /// module-private helper at any call site that has the typed
3310    /// [`RateLimit`] in hand (the codec's `render` arm at
3311    /// [`rate_limit_codec::render`], the validate gate's canonical-form
3312    /// arm in [`AplicacaoSpec::validate_politicas`], any future
3313    /// per-`:contratos` edge-override overlay resolver): those consumers
3314    /// reach for the typed enum without going through the
3315    /// `.window()` scalar-projection layer, and get the enum value
3316    /// directly (which the codec's render arm can then format via
3317    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
3318    /// "typed sub-struct scalar accessor, one dispatch on the substrate
3319    /// primitive" discipline the sibling [`RateLimit::rate`] and
3320    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
3321    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
3322    /// projection axis (the third scalar accessor on the [`RateLimit`]
3323    /// axis, first typed-enum-return projection).
3324    ///
3325    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
3326    /// the canonical [`RateLimitUnit`] arm now carries the same
3327    /// `const`-eval-surface posture the sibling `pub const fn`
3328    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
3329    /// this typed sub-struct already carry, composing through the
3330    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
3331    /// reverse-resolver in `const` context. Any downstream substrate-
3332    /// side `const`-context consumer of the typed unit (a module-scope
3333    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
3334    /// invariant pin on a typed fixture, a future M4 admission-webhook
3335    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
3336    /// resolver over a typed [`RateLimit`], any future `const fn`
3337    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3338    /// the substrate primitive) now reaches the same typed dispatch on
3339    /// the substrate primitive at const-eval time as at runtime.
3340    ///
3341    /// Pinned load-bearing at the substrate-primitive level by
3342    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
3343    /// eval-surface pin via `const fn` wrapper).
3344    #[must_use]
3345    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
3346        RateLimitUnit::from_window(self.window)
3347    }
3348}
3349
3350/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
3351/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
3352/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
3353///
3354/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
3355/// the `:politicas :rate-limit` unit surface reads from
3356/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
3357/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
3358/// [`is_canonical_rate_limit_window`] predicate the
3359/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
3360/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
3361/// projection) now lives inside this typed enum's `match self` arms — a
3362/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
3363/// `rate_limit_action` grows daily-bucket support) is one new variant
3364/// plus the exhaustiveness arms on the four methods, so every consumer
3365/// picks it up by compile-time construction rather than a runtime
3366/// table-scan miss.
3367///
3368/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
3369/// scanned via `find_map` at every projection call — an untyped runtime
3370/// walk that carried no compile-time link between the parse arm's
3371/// accepted suffixes, the render arm's emitted suffixes, and the
3372/// validate gate's accepted windows. A future rate-limit-unit addition
3373/// that landed one row without threading through the other consumers
3374/// (or a copy-paste flip that collapsed two rows onto one suffix) would
3375/// silently split the accepted-set across the three consumers — the
3376/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
3377/// for a 24h window that parse can't round-trip, the validate gate
3378/// misses one canonical window. Lifting the pairs onto a typed
3379/// closed-set enum with exhaustive `match` arms makes any such
3380/// half-landed extension a caixa-core build error (the compiler enforces
3381/// arm coverage on every method), not a silent per-consumer drift
3382/// surfacing at apply time. Same "closed-set typed-enum discriminator"
3383/// discipline the sibling [`PlacementStrategy`] (cc8f749),
3384/// [`crate::supervisor::RestartStrategy`],
3385/// [`crate::supervisor::RestartPolicy`],
3386/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
3387/// closed-set typed enums carry on their respective closed-set axes —
3388/// extended onto the seventh closed-set typed-enum discriminator axis
3389/// on the caixa typed surface (the `:politicas :rate-limit :window`
3390/// canonical-unit axis).
3391#[derive(
3392    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3393)]
3394pub enum RateLimitUnit {
3395    /// 1-second window — canonical author-surface suffix `"s"`
3396    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3397    /// with a 1s magnitude.
3398    Second,
3399    /// 1-minute window — canonical author-surface suffix `"m"`
3400    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3401    /// with a 60s magnitude.
3402    Minute,
3403    /// 1-hour window — canonical author-surface suffix `"h"`
3404    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3405    /// with a 3600s magnitude.
3406    Hour,
3407}
3408
3409impl RateLimitUnit {
3410    /// Exhaustive iteration surface for every consumer that reads the
3411    /// full canonical-unit set (the byte-parity witness against the
3412    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
3413    /// webhook's accepted-suffix listing in its rejection body, any
3414    /// future round-trip fuzz harness). A future variant addition to
3415    /// [`RateLimitUnit`] extends this slice as a single edit and every
3416    /// consumer picks up the new entry by construction — the compiler-
3417    /// checked exhaustiveness on the sibling method `match` arms is the
3418    /// build-time guarantee that no arm forgets to grow.
3419    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
3420
3421    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
3422    /// string every `<n>/<unit>` rate-limit shape carries after its
3423    /// `/` separator. The single source of truth the codec's parse and
3424    /// render arms both dispatch on: the parse arm matches an incoming
3425    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
3426    /// output; the render arm emits the entry's `as_suffix` verbatim
3427    /// after the rate magnitude.
3428    #[must_use]
3429    pub const fn as_suffix(self) -> &'static str {
3430        match self {
3431            Self::Second => "s",
3432            Self::Minute => "m",
3433            Self::Hour => "h",
3434        }
3435    }
3436
3437    /// Canonical `Duration` for this unit — the token-bucket refill
3438    /// period the [`RateLimit::window`] axis carries when the surrounding
3439    /// slot's `:rate-limit` author surface named this unit.
3440    #[must_use]
3441    pub const fn window(self) -> Duration {
3442        Duration::from_secs(match self {
3443            Self::Second => 1,
3444            Self::Minute => 60,
3445            Self::Hour => 3_600,
3446        })
3447    }
3448
3449    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
3450    /// `None` when `suffix` is outside the closed-set arm-string set
3451    /// [`Self::as_suffix`] emits. The single `str → Self` projection
3452    /// [`rate_limit_codec::parse`] consumes.
3453    #[must_use]
3454    pub fn from_suffix(suffix: &str) -> Option<Self> {
3455        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
3456    }
3457
3458    /// Recognize a canonical rate-limit `Duration` as one of the three
3459    /// arms, or `None` when `window` carries sub-second residue or a
3460    /// second-magnitude outside the closed-set arm-window set
3461    /// [`Self::window`] emits. The single `Duration → Self` projection
3462    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
3463    /// both consume.
3464    ///
3465    /// `pub const fn` — the reverse `Duration → Self` projection now
3466    /// carries the same `const`-eval-surface posture the sibling
3467    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
3468    /// projection accessors on this closed-set typed enum already
3469    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
3470    /// typed-`RateLimit`-projection sibling composes through in `const`
3471    /// context. Routes byte-for-byte through the peer `pub const fn`
3472    /// [`Self::window`] canonical-`Duration` projection so any future
3473    /// arm-magnitude edit on the sibling accessor reaches this reverse
3474    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
3475    /// per-arm probes each dispatch through one `pub const fn` on the
3476    /// substrate primitive rather than a hand-authored per-arm second-
3477    /// magnitude literal that would silently drift on any future
3478    /// [`Self::window`] arm-magnitude edit.
3479    ///
3480    /// Prior to the `const` lift the body dispatched through
3481    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
3482    /// iterator-driven linear scan whose iterator methods
3483    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
3484    /// `PartialEq` dispatch each carry non-`const` bounds on stable
3485    /// Rust 1.94, so any downstream substrate-side `const`-context
3486    /// consumer of the reverse resolver (a module-scope
3487    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
3488    /// invariant pin on a typed fixture, a future M4
3489    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
3490    /// webhook `const fn` per-`:politicas` canonical-window floor over a
3491    /// typed [`RateLimit`] scalar, any future `const fn`
3492    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3493    /// the substrate primitive that wants to fan on the canonical unit
3494    /// at compile time) surfaced as a downstream E0015 far from the
3495    /// resolver's own declaration. The `pub const fn` posture closes
3496    /// the drift structurally at caixa-core build time.
3497    ///
3498    /// Pinned load-bearing at the substrate-primitive level by
3499    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
3500    /// eval-surface pin via `const fn` wrapper) and
3501    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
3502    /// (composition-witness pin against the peer `Self::window` scalar
3503    /// dispatch).
3504    #[must_use]
3505    pub const fn from_window(window: Duration) -> Option<Self> {
3506        if window.subsec_nanos() != 0 {
3507            return None;
3508        }
3509        // Route through the peer `pub const fn` [`Self::window`]
3510        // canonical-`Duration` projection so any future arm-magnitude
3511        // edit on the sibling accessor reaches this reverse resolver by
3512        // construction — the per-arm `secs` comparison keys off
3513        // `Duration::as_secs` (`pub const fn`), not a hand-authored
3514        // per-arm second-magnitude literal that would silently drift.
3515        let secs = window.as_secs();
3516        if secs == Self::Second.window().as_secs() {
3517            Some(Self::Second)
3518        } else if secs == Self::Minute.window().as_secs() {
3519            Some(Self::Minute)
3520        } else if secs == Self::Hour.window().as_secs() {
3521            Some(Self::Hour)
3522        } else {
3523            None
3524        }
3525    }
3526
3527    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
3528    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
3529    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
3530    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
3531    /// consumes.
3532    ///
3533    /// The peer `Duration → &'static str` axis folded onto the substrate
3534    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
3535    /// production consumers ([`rate_limit_codec::render`] and
3536    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
3537    /// migrated (61421a6): the free helper's `Duration → &str` projection
3538    /// is now the two-step composition
3539    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
3540    /// reads through the typed accessor. This lift closes the peer
3541    /// `&str → Duration` axis by folding the vestigial module-private
3542    /// `rate_limit_window_from_unit` delegate onto this associated method
3543    /// — the codec's parse arm and every future wire-side consumer of the
3544    /// `&str → Duration` projection (a future admission-webhook that
3545    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
3546    /// before it's promoted to a validated typed slot, a future
3547    /// `feira lint` shape-probe that reads the author-surface bytes
3548    /// verbatim) now reach for exactly one typed dispatch on the
3549    /// substrate primitive.
3550    ///
3551    /// Same "closed-set typed-enum discriminator with canonical
3552    /// projections per axis" discipline the sibling [`Self::as_suffix`]
3553    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
3554    /// methods carry — this associated method closes the fifth (and last
3555    /// unlifted) projection axis on the arm-table, so the closed-set enum
3556    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
3557    /// consumer of the `:politicas :rate-limit :window` axis reaches
3558    /// through. A future rate-limit-unit addition (a `"d"` day suffix
3559    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
3560    /// `"ms"` sub-second window once high-throughput per-edge policies
3561    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
3562    /// variant plus one arm per method — the compiler enforces
3563    /// exhaustiveness on every consumer's `match self` arms and picks
3564    /// the new unit up by construction across all five projections.
3565    #[must_use]
3566    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
3567        Self::from_suffix(suffix).map(Self::window)
3568    }
3569}
3570
3571/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
3572/// every consumer that formats a canonical rate-limit unit as user-
3573/// facing text (future M4 admission-webhook rejection bodies naming
3574/// the accepted-suffix set, future `feira app graph` per-`:politicas`
3575/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
3576/// codec's parse arm accepts and the render arm emits. Same
3577/// as_str-through-Display convergence discipline the sibling
3578/// [`PlacementStrategy`], [`crate::CaixaKind`],
3579/// [`crate::supervisor::RestartStrategy`], and
3580/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
3581impl std::fmt::Display for RateLimitUnit {
3582    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3583        f.write_str(self.as_suffix())
3584    }
3585}
3586
3587/// Upper-bound ceiling on the `:politicas :timeout` axis — every
3588/// validated [`MeshPolicy::timeout`] past
3589/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
3590/// (inclusive on both ends, integer-millisecond magnitudes by the
3591/// canonical-form gate immediately preceding).
3592///
3593/// The typed field is `Option<Duration>` (the zero-floor arm
3594/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
3595/// `Duration::ZERO`, and the canonical-form arm
3596/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
3597/// sub-millisecond residue), so a programmatic struct literal
3598/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
3599/// 24h) and the equivalent author-surface form
3600/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
3601/// integer-hour magnitude) both round-trip cleanly through serde — a
3602/// structurally unbounded `Duration` ceiling. A `:timeout` value far
3603/// above the documented production-playbook band (Envoy default `15s`,
3604/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
3605/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
3606/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
3607/// at `~3600s`) silently degenerates the mesh-policy contract: the
3608/// per-call deadline is structurally so long that no realistic
3609/// synchronous-`:contratos` traversal can reach it, so the typed slot
3610/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
3611/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
3612/// blocking" degenerates to a nominal-only contract on the
3613/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
3614/// the sibling `:politicas :retries` axis and the
3615/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
3616/// `:politicas :circuit-breaker :max-failures` axis — all three close
3617/// the "structurally unbounded ceiling on a typed `:politicas` axis"
3618/// footgun the prior zero-floor-and-canonical-form-only checks left
3619/// open.
3620///
3621/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3622/// shared duration codec emits (`"<n>h"` for any integer-hour
3623/// magnitude) — every value in the canonical authoring form's
3624/// `<integer><unit>` grammar at or below this cap renders to a clean
3625/// canonical string. The cap sits an order of magnitude above every
3626/// documented production-playbook recommendation band (Envoy default
3627/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
3628/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
3629/// configured maximum (`proxy_read_timeout` typical max `3600s`),
3630/// below the clearly-pathological "effectively no timeout" floor
3631/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
3632/// want for a long-running synchronous workflow, but a hard wall above
3633/// which the mesh-level deadline is structurally a non-deadline.
3634/// Lifted as a typed `pub const` so the bound has exactly one source
3635/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3636/// materializer's admission webhook and the caixa-mesh-side
3637/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3638/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3639/// other typed upper bound in this crate carries
3640/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3641/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3642/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3643/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3644pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
3645
3646/// Upper-bound ceiling on the `:politicas :retries` axis — every
3647/// validated [`MeshPolicy::retries`] past
3648/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
3649///
3650/// The typed slot is `Option<u32>` (`None` = no retries on transient
3651/// failure; `Some(0)` already rejected by the
3652/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
3653/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
3654/// .. }`) and the equivalent author-surface form
3655/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
3656/// serde / the codec — a structurally unbounded `u32` ceiling. The
3657/// runtime substrate that consumes the value (Envoy's
3658/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3659/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3660/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3661/// admission cap is 10) translates a four-billion-retry policy into a
3662/// thundering-herd amplification vector on transient failure — the
3663/// caller's one request fans out to `retries` server-side calls per
3664/// edge per traversal, multiplying load by `(retries+1)^depth` across
3665/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3666/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3667/// invariant on the retry axis; both belong at the typed-slot layer.
3668///
3669/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3670/// upstream mesh-policy schema that documents one) and sits above the
3671/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3672/// every documented production playbook): a value the author can
3673/// plausibly want, but a hard wall above which the policy is
3674/// structurally a footgun. Lifted as a typed `pub const` so the bound
3675/// has exactly one source of truth — a future axis reaching for the
3676/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3677/// materializer's admission webhook, the caixa-mesh-side
3678/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3679/// one place. Same shape every other typed upper bound in this crate
3680/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3681/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3682/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3683/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3684pub const POLICY_RETRIES_MAX: u32 = 10;
3685
3686/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3687/// axis — every validated [`CircuitBreaker::max_failures`] past
3688/// [`AplicacaoSpec::validate_politicas`] lies in
3689/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3690///
3691/// The typed field is `u32` (the zero-floor arm
3692/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3693/// `0` — a breaker that trips on the first call), so a programmatic
3694/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3695/// and the equivalent author-surface form
3696/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3697/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3698/// `max_failures` value far above the documented production-playbook
3699/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3700/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3701/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3702/// typical 5–50) silently disables the breaker's protection role:
3703/// the threshold is structurally so high that no realistic
3704/// failures-per-`:window` traffic shape can reach it, so the breaker
3705/// never trips and the typed slot becomes a no-op carried on every
3706/// emitted Envoy / Cilium L7 overlay. Pairs with the
3707/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3708/// axis — both close the "structurally unbounded `u32` ceiling on a
3709/// typed policy axis" footgun the prior zero-floor-only checks left
3710/// open.
3711///
3712/// The `1000` ceiling sits an order of magnitude above every
3713/// documented upstream production-playbook recommendation band (the
3714/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3715/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3716/// the clearly-pathological "effectively no protection"
3717/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3718/// plausibly want at hyperscale, but a hard wall above which the
3719/// policy is structurally a no-op. Lifted as a typed `pub const` so
3720/// the bound has exactly one source of truth — the future M4
3721/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3722/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3723/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3724/// one place. Same shape every other typed upper bound in this crate
3725/// carries ([`POLICY_RETRIES_MAX`],
3726/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3727/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3728/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3729pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3730
3731/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3732/// every validated [`CircuitBreaker::window`] past
3733/// [`AplicacaoSpec::validate_politicas`] lies in
3734/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3735/// integer-millisecond magnitudes by the canonical-form gate
3736/// immediately preceding).
3737///
3738/// The typed field is `Duration` (the zero-floor arm
3739/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3740/// `Duration::ZERO`, and the canonical-form arm
3741/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3742/// sub-millisecond residue), so a programmatic struct literal
3743/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3744/// and the equivalent author-surface form
3745/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3746/// integer-hour magnitude) both round-trip cleanly through serde — a
3747/// structurally unbounded `Duration` ceiling. A `:window` value far
3748/// above the documented production-playbook band (Hystrix
3749/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3750/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3751/// Istio `outlierDetection.interval` default `10s`, Envoy
3752/// `outlier_detection.interval` default `10s`, AWS App Mesh
3753/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3754/// breaker's role: a rolling-window failure counter whose window is
3755/// hours long is operationally a lifetime counter, the breaker's
3756/// "recent failures" memory is structurally so long that transient
3757/// failures are never forgotten, and the typed slot becomes a no-op
3758/// trigger that trips once and stays tripped for the lifetime of the
3759/// component carried on every emitted Envoy / Cilium L7 overlay.
3760///
3761/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3762/// shared duration codec emits (`"<n>h"` for any integer-hour
3763/// magnitude) — every value in the canonical authoring form's
3764/// `<integer><unit>` grammar at or below this cap renders to a clean
3765/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3766/// cap on the first typed-`Duration` `:politicas` axis: the two
3767/// duration-typed `:politicas` axes now share a single uniform top
3768/// edge so the next typed-slot wiring (the future caixa-mesh
3769/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3770/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3771/// admission webhook) reaches for either field knowing the value is
3772/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3773/// sits two orders of magnitude above every documented upstream
3774/// production-playbook recommendation band (Hystrix / resilience4j /
3775/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3776/// and below the clearly-pathological "rolling window degenerates to
3777/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3778/// author can plausibly want for a very-low-traffic long-tail
3779/// failure-detection window, but a hard wall above which the breaker's
3780/// rolling-window contract is structurally a lifetime-counter contract.
3781/// Lifted as a typed `pub const` so the bound has exactly one source
3782/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3783/// materializer's admission webhook and the caixa-mesh-side
3784/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3785/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3786/// other typed upper bound in this crate carries
3787/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3788/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3789/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3790/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3791/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3792pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3793
3794/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3795/// every validated [`RateLimit::rate`] past
3796/// [`AplicacaoSpec::validate_politicas`] lies in
3797/// `1..=POLICY_RATE_LIMIT_MAX`.
3798///
3799/// The typed field is `u32` (the zero-floor arm
3800/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3801/// zero-rate limit denies every request, the canonical "I forgot
3802/// that 0 means deny-everything" footgun), so a programmatic struct
3803/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3804/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3805/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3806/// round-trip cleanly through serde — a structurally unbounded `u32`
3807/// ceiling. The runtime substrate consuming the value (Envoy's
3808/// `local_rate_limit.token_bucket.max_tokens`, the future
3809/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3810/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3811/// rate-limit into a no-op rate-limiter: the bucket capacity is
3812/// structurally so high no realistic per-edge traffic shape can
3813/// drain it, the limiter never trips, and the typed slot becomes a
3814/// "rate-limit declared, no enforcement" footgun — the canonical
3815/// declared-but-inert shape every other `:politicas` cap arm
3816/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3817/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3818///
3819/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3820/// above every documented upstream production-playbook recommendation
3821/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3822/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3823/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3824/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3825/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3826/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3827/// `u32::MAX`): a value the author can plausibly want at hyperscale
3828/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3829/// /h-window arm), but a hard wall above which the policy is
3830/// structurally a no-op carried verbatim on every emitted Envoy /
3831/// Cilium L7 overlay. The cap brackets all three canonical windows
3832/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3833/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3834/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3835/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3836/// has exactly one source of truth — the future M4
3837/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3838/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3839/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3840/// one place. Same shape every other typed upper bound in this crate
3841/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3842/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3843/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3844/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3845/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3846/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3847pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3848
3849// `:entrada :host` total-length and per-label cap axes route through
3850// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3851// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3852// pair of aplicacao-private aliases the previous `validate_entrada_host`
3853// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3854// = 63`) were structurally the same K8s Gateway API v1 Hostname
3855// admission-schema bounds — the total-length cap on the OpenAPI
3856// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3857// same regex — that the peer axes at the caixa-core::render level pin,
3858// so hoisting both readers onto the shared lifted constants closes the
3859// third-occurrence duplication threshold structurally: the M4
3860// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3861// label validator, the future per-`Certificate` SAN emitter, and every
3862// other per-Gateway-API-Hostname landing site reach the same one place
3863// as the `:entrada :host` gate does — no per-axis alias drift surface
3864// between them, by construction.
3865
3866/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
3867/// extractor expression — the upper bound `validate_placement_shard_key`
3868/// enforces on every well-shaped shard-key past validate. The realistic
3869/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3870/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3871/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3872/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3873/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3874/// in `:shard-key`" footgun at validate time rather than at the future
3875/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3876const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3877
3878/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3879/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3880/// that maps the shared parser-shaped reason into the
3881/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3882/// is self-locating (the offending `caixa:` is named verbatim) and
3883/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3884/// fix it in one edit. Same diagnostic shape as
3885/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3886/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3887fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3888    // Empty is already gated by `MembroCaixaEmpty` at the call site;
3889    // re-checking here keeps the predicate usable from any future
3890    // call site (the M4 CR materializer) without an empty-check
3891    // footgun. The shared
3892    // [`crate::render::require_valid_dns_1123_label`] helper brackets
3893    // the empty-first + shape cascade every peer name axis
3894    // (`:placement :clusters`, `:placement :affinity`, `:contratos
3895    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3896    // `:upgrade-from :module`) routes through, so drift between the
3897    // eight axes' accepted DNS-1123-label sets is structurally
3898    // impossible.
3899    crate::render::require_valid_dns_1123_label(
3900        caixa,
3901        || AplicacaoError::MembroCaixaEmpty,
3902        |reason| AplicacaoError::MembroCaixaInvalid {
3903            caixa: caixa.to_string(),
3904            reason,
3905        },
3906    )
3907}
3908
3909/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3910/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3911/// that maps the shared parser-shaped reason into the
3912/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3913///
3914/// Cluster names land in DNS-1123-label territory across every consumer:
3915/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3916/// the `lareira-fleet-programs` aggregator applies to scope programs to
3917/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3918/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3919/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3920/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3921/// side schema enforces the DNS-1123 label rule on admission; a
3922/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3923/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3924/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3925/// only gate and the failure surfaces as a no-match at filter time —
3926/// the workload doesn't land in the named cluster, with no diagnostic
3927/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3928/// build time mirrors the `:membros :caixa` value-shape trajectory
3929/// (3f9d7a0) on the peer name axis.
3930///
3931/// The diagnostic carries the offending `cluster:` verbatim plus a
3932/// parser-shaped `reason:` naming the specific violation, so the
3933/// author can grep their caixa.lisp for `:clusters` and fix it in
3934/// one edit. Same diagnostic shape as
3935/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3936fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3937    // Empty is already gated by `PlacementClusterEmpty` at the call
3938    // site; re-checking here keeps the predicate usable from any
3939    // future call site (the M4 CR materializer's per-cluster validator)
3940    // without an empty-check footgun. Routes through the shared
3941    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3942    // name axes each land on.
3943    crate::render::require_valid_dns_1123_label(
3944        cluster,
3945        || AplicacaoError::PlacementClusterEmpty,
3946        |reason| AplicacaoError::PlacementClusterInvalid {
3947            cluster: cluster.to_string(),
3948            reason,
3949        },
3950    )
3951}
3952
3953/// Reject `:placement :affinity` hints whose shape can never legitimately
3954/// land in any downstream selector or label-keyed routing axis. Thin
3955/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3956/// shared parser-shaped reason into the
3957/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3958/// diagnostic is self-locating (the offending `:affinity` is named
3959/// verbatim) and the author can grep their caixa.lisp for
3960/// `:affinity "<hint>"` and fix it in one edit.
3961///
3962/// The `:affinity` slot carries a placement-engine hint — canonical
3963/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3964/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3965/// compression overlay and the future M4 placement-engine's per-hint
3966/// routing axis. Each downstream consumer (caixa-mesh's
3967/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3968/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3969/// `spec.placement.affinity` admission rule, the future M4 per-hint
3970/// node-affinity / pod-affinity rule generator keying off the same
3971/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3972/// selector) requires the value to be a DNS-1123 label — K8s label
3973/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3974/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3975/// admission rule the apiserver enforces.
3976///
3977/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3978/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3979/// Python-module-name leak), `:affinity "data.locality"` (the
3980/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3981/// `:affinity "data-locality-"` (boundary-hyphen violation),
3982/// `:affinity "data locality"` (paste-from-doc whitespace),
3983/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3984/// 64-byte over-cap slug silently passed the empty-only check and the
3985/// failure surfaced as a no-match at the M3 Adaptive compression
3986/// overlay's filter time (`placement.affinity` carried a malformed
3987/// value, no node matched, the workload landed on the default
3988/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3989/// the empty-:affinity / empty-shard-key / zero-:politicas /
3990/// empty-:contratos-target gates already close on every other
3991/// declare-but-no-opinion axis. Lifting the rejection to a build-time
3992/// gate closes the fifth typed slot on the Aplicacao surface to land
3993/// on the canonical DNS-1123 label floor (after the four Servico-name
3994/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
3995/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
3996/// b0e8748).
3997///
3998/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
3999/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
4000/// validated values are guaranteed-accepted by the apiserver without
4001/// re-validation at any downstream renderer or admission layer.
4002fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
4003    // Empty is gated separately at the call site for a self-locating
4004    // diagnostic; re-checking here keeps the predicate usable from any
4005    // future call site (the M4 CR materializer's per-affinity
4006    // validator) without an empty-check footgun. Routes through the
4007    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4008    // peer name axes each land on.
4009    crate::render::require_valid_dns_1123_label(
4010        affinity,
4011        || AplicacaoError::PlacementAffinityEmpty,
4012        |reason| AplicacaoError::PlacementAffinityInvalid {
4013            affinity: affinity.to_string(),
4014            reason,
4015        },
4016    )
4017}
4018
4019/// Reject `:placement :shard-key` extractor expressions whose shape can
4020/// never legitimately drive the future M4 Akka-style cluster-sharding
4021/// reconciler's hash-extractor pass. Maps the per-byte / length checks
4022/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
4023/// diagnostic is self-locating (the offending `:shard-key` value is
4024/// named verbatim alongside the parser-shaped reason) and the author can
4025/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
4026/// edit.
4027///
4028/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
4029/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
4030/// expression naming the message property to hash on. The realistic
4031/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
4032/// property name; `$tenantId` — Akka entity-id placeholder;
4033/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
4034/// `${tenant}` — interpolation-style template) all sit in the printable
4035/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
4036/// multi-line blob landing in `:shard-key`, an embedded space from a
4037/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
4038/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
4039/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
4040/// check and the failure surfaces at the future M4 reconciler's hash
4041/// pass as a runtime extractor-evaluation error far from the source
4042/// `caixa.lisp`, with no field naming which member's `:shard-key`
4043/// carried the offending value.
4044///
4045/// The contract — the printable ASCII single-token intersection-floor
4046/// every Akka-style entity-id extractor implementation admits:
4047///
4048///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
4049///     peer DNS-1123-label-shaped `:placement :affinity` /
4050///     `:placement :clusters` identifier axes; realistic shard-keys sit
4051///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
4052///     blob footguns at validate time;
4053///   - every byte in the printable ASCII range `0x21..=0x7E` —
4054///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
4055///     `"$tenantId\n"` from paste-from-aligned-doc /
4056///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
4057///     `\x7F` — the canonical "embedded null from a copy-paste-binary
4058///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
4059///     un-Punycode-encoded IDN that round-trips inconsistently across
4060///     NFC/NFD normalization).
4061///
4062/// The accepted set is broader than the DNS-1123 label floor the peer
4063/// `:placement :clusters` / `:placement :affinity` axes use because the
4064/// `:shard-key` value is not a K8s `metadata.name` / label-selector
4065/// landing site; it's an extractor expression the future Akka-style
4066/// reconciler reads as a property reference. The realistic forms
4067/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
4068/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
4069/// but every Akka-style entity-id extractor parses. The
4070/// printable-ASCII-token floor accepts every shape any such extractor
4071/// would accept while rejecting the cross-implementation footguns
4072/// (whitespace breaks token boundaries; non-ASCII round-trips
4073/// inconsistently across YAML emitters and NFC/NFD normalization;
4074/// control characters silently corrupt the next read).
4075///
4076/// Until this gate landed `validate_placement` only refused the
4077/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
4078/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
4079/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
4080/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
4081/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
4082/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
4083/// control character from paste-from-binary, the 64-byte over-cap
4084/// paste-from-doc multi-line slug) silently passed validate. The future
4085/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
4086/// would then surface the malformed value either as a runtime
4087/// extractor-evaluation error (whitespace breaks the extractor's token
4088/// boundary, no match) or as a silently-different shard assignment
4089/// across YAML emitters (non-ASCII normalizes differently between the
4090/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
4091/// parser, the same entity ID maps to two distinct shards on a
4092/// re-render). Lifting the shape gate to caixa-build time makes the
4093/// extractor-floor invariant a structural property of every validated
4094/// `Placement`: every `Sharded` placement past `validate_placement` has
4095/// a `:shard-key` the future M4 reconciler can hash without
4096/// re-validating at the runtime layer.
4097///
4098/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
4099/// [`AplicacaoError::ContratoSubjectInvalid`] /
4100/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
4101/// on the peer `:contratos` payload axes — each lifts the
4102/// runtime-side parser's intersection-floor to a caixa-build-time gate,
4103/// closing the canonical "this passed validate but the runtime parser
4104/// rejected it" surprise.
4105fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
4106    // Empty is gated separately at the call site via the more
4107    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
4108    // re-checking here keeps the predicate usable from any future call
4109    // site (the M4 CR materializer's per-shard-key validator) without
4110    // an empty-check footgun.
4111    if key.is_empty() {
4112        return Err(AplicacaoError::ShardedKeyEmpty);
4113    }
4114    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
4115        return Err(AplicacaoError::ShardKeyInvalid {
4116            shard_key: key.to_string(),
4117            reason: format!(
4118                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
4119                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
4120                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
4121                 well under 32 bytes, this length suggests a paste-from-doc \
4122                 multi-line blob landed in `:shard-key` instead of a single-token \
4123                 extractor expression)",
4124                key.len()
4125            ),
4126        });
4127    }
4128    for &b in key.as_bytes() {
4129        if (0x21..=0x7E).contains(&b) {
4130            continue;
4131        }
4132        let reason = if b == b' ' {
4133            "contains a space (Akka-style entity-id extractor expressions are \
4134             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
4135             whitespace breaks the extractor's token boundary at the runtime layer, \
4136             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
4137             a multi-token blob in one `:shard-key` slot)"
4138                .to_string()
4139        } else if b == b'\t' {
4140            "contains a tab character (paste-from-aligned-doc footgun; the \
4141             Akka-style entity-id extractor reads `:shard-key` as a single-token \
4142             reference, embedded whitespace breaks the token boundary at the \
4143             runtime hash-extractor pass)"
4144                .to_string()
4145        } else if b == b'\n' || b == b'\r' {
4146            format!(
4147                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
4148                 paste-from-multiline-doc footgun; the Akka-style entity-id \
4149                 extractor reads `:shard-key` as a single-token reference, embedded \
4150                 newlines either truncate the value at the YAML emitter layer or \
4151                 break the token boundary at the runtime hash-extractor pass)"
4152            )
4153        } else if b < 0x20 || b == 0x7F {
4154            format!(
4155                "contains control character 0x{b:02x} (the canonical \
4156                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
4157                 control characters silently corrupt round-trip serialization \
4158                 across YAML emitters and break the runtime hash-extractor's \
4159                 single-token parser)"
4160            )
4161        } else {
4162            format!(
4163                "contains non-ASCII byte 0x{b:02x} (the canonical \
4164                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
4165                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
4166                 across YAML emitter implementations — the same entity ID can \
4167                 silently map to two distinct shards on a re-render. Use a \
4168                 printable-ASCII extractor expression like `tenantId`, \
4169                 `$tenantId`, or `metadata.tenantId`)"
4170            )
4171        };
4172        return Err(AplicacaoError::ShardKeyInvalid {
4173            shard_key: key.to_string(),
4174            reason,
4175        });
4176    }
4177    Ok(())
4178}
4179
4180/// Reject `:contratos :de` / `:contratos :para` values whose shape
4181/// can never legitimately match a validated `:membros :caixa`. Thin
4182/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4183/// shared parser-shaped reason into the
4184/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
4185/// diagnostic is self-locating (which slot — `:de` or `:para` — and
4186/// the offending value verbatim) and the author can grep their
4187/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
4188/// one edit.
4189///
4190/// Until this gate landed an empty or DNS-1123-malformed `:de` /
4191/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
4192/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
4193/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
4194/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
4195/// un-Punycode-encoded IDN) silently passed the per-axis check and
4196/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
4197/// membership lookup — diagnostic-framed as "this caixa is not in
4198/// `:membros`" when the root cause is "this `:de` value is not a
4199/// well-shaped Servico-name identifier and could never legitimately
4200/// match any validated member". Because every `:membros :caixa` is
4201/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
4202/// `names` HashSet structurally never contains an empty / malformed
4203/// string, so the membership lookup arm misframes every empty /
4204/// malformed input. Lifting the shape arm ahead of the lookup
4205/// preserves the legitimate `ContratoMemberMissing` arm (a
4206/// well-shaped `:de` that simply isn't in `:membros` — a phantom
4207/// reference) while routing every structurally-impossible-to-match
4208/// input through the narrower self-locating shape diagnostic.
4209///
4210/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4211/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
4212/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
4213/// to land on the canonical [`crate::render::is_dns_1123_label`]
4214/// floor. The `slot: &'static str` field carries the kebab-case
4215/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
4216/// per-callback-slot diagnostic shape and the
4217/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
4218/// (85f102c) cross-list-tag pattern.
4219fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
4220    // Routes through the shared
4221    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4222    // name axes each land on. The `slot: &'static str` field flows
4223    // through both error variants so the diagnostic names which
4224    // per-edge axis (`:de` vs `:para`) the offending value came from.
4225    crate::render::require_valid_dns_1123_label(
4226        caixa,
4227        || AplicacaoError::ContratoCaixaEmpty { slot },
4228        |reason| AplicacaoError::ContratoCaixaInvalid {
4229            slot,
4230            caixa: caixa.to_string(),
4231            reason,
4232        },
4233    )
4234}
4235
4236/// Reject `:entrada :para` values whose shape can never legitimately
4237/// match a validated `:membros :caixa`. Thin wrapper around
4238/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
4239/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
4240/// variant, so the diagnostic is self-locating (the offending
4241/// `:entrada :para` value is named verbatim) and the author can grep
4242/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
4243///
4244/// Until this gate landed an empty or DNS-1123-malformed `:entrada
4245/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
4246/// ADR typo, `:para "my_cart"` the Python-module-name leak,
4247/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
4248/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
4249/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
4250/// silently passed the per-axis check and surfaced as
4251/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
4252/// — diagnostic-framed as "this caixa is not in `:membros`" when the
4253/// root cause is "this `:entrada :para` value is not a well-shaped
4254/// Servico-name identifier and could never legitimately match any
4255/// validated member". Because every `:membros :caixa` is shape-
4256/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
4257/// `HashSet` structurally never contains an empty / malformed string,
4258/// so the membership lookup arm misframes every empty / malformed
4259/// input. Lifting the shape arm ahead of the lookup preserves the
4260/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
4261/// simply isn't in `:membros` — a phantom reference) while routing
4262/// every structurally-impossible-to-match input through the narrower
4263/// self-locating shape diagnostic.
4264///
4265/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4266/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
4267/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
4268/// fourth and last Aplicacao-level Servico-name reference axis to
4269/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
4270/// No `slot: &'static str` field because there is only one axis
4271/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
4272/// the simpler shape mirrors [`validate_membro_caixa`] and
4273/// [`validate_placement_cluster`].
4274fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
4275    // Empty is gated separately at the call site for a self-locating
4276    // diagnostic; re-checking here keeps the predicate usable from any
4277    // future call site (the M4 CR materializer's per-`:entrada`
4278    // validator) without an empty-check footgun. Routes through the
4279    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4280    // peer name axes each land on.
4281    crate::render::require_valid_dns_1123_label(
4282        para,
4283        || AplicacaoError::EntradaParaEmpty,
4284        |reason| AplicacaoError::EntradaParaInvalid {
4285            para: para.to_string(),
4286            reason,
4287        },
4288    )
4289}
4290
4291/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
4292/// would refuse at admission time. The contract — exactly the regex
4293/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
4294/// and `HTTPRoute.spec.hostnames[]`,
4295/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
4296/// (max length 253; per-label max length 63):
4297///
4298///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
4299///     uppercase, no underscore, no Unicode/IDN — IDN must be
4300///     pre-encoded as Punycode `xn--…` by the author);
4301///   - exactly one optional leading wildcard label (`*.`); a wildcard
4302///     in any non-leading label position is rejected;
4303///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
4304///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
4305///   - total length 1..=253 bytes;
4306///   - no IPv4 literal (Gateway API forbids IP literals);
4307///   - no scheme (`https://`, `http://`), no port (`:8080`), no
4308///     whitespace, no path (`/`).
4309///
4310/// Lifted as a typed gate (rather than an inline cascade in
4311/// `validate()`) so the contract lives in one place — every future
4312/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4313/// materializer's host validator, the future per-`:entrada` SAN
4314/// emission for cert-manager Certificates, the multi-`:entrada`
4315/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
4316/// for the same predicate, not its own. Same compounding shape as
4317/// `is_canonical_rate_limit_window` (808017c) and
4318/// [`WitTarget::label`] (previously the free `contrato_target_label`
4319/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
4320/// per-variant label match is compiler-checked-exhaustive).
4321///
4322/// The diagnostic carries the offending `host:` verbatim plus a
4323/// parser-shaped `reason:` naming the specific violation, so the
4324/// author can grep their caixa.lisp for `:host "<host>"` and fix it
4325/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
4326/// (9888b13).
4327fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
4328    // Empty is already gated by `EmptyEntradaHost` at the call site;
4329    // re-checking here keeps the predicate usable from any future
4330    // call site (M4 CR materializer) without an empty-check footgun.
4331    if host.is_empty() {
4332        return Err(AplicacaoError::EmptyEntradaHost);
4333    }
4334    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
4335        return Err(AplicacaoError::EntradaHostInvalid {
4336            host: host.to_string(),
4337            reason: format!(
4338                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
4339                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
4340                host.len(),
4341                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
4342            ),
4343        });
4344    }
4345    if host.contains("://") {
4346        return Err(AplicacaoError::EntradaHostInvalid {
4347            host: host.to_string(),
4348            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
4349                     Gateway API takes the bare hostname)"
4350                .to_string(),
4351        });
4352    }
4353    if host.contains('/') {
4354        return Err(AplicacaoError::EntradaHostInvalid {
4355            host: host.to_string(),
4356            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
4357                     matching is in `:entrada :paths`)"
4358                .to_string(),
4359        });
4360    }
4361    // After the `://` scheme-prefix and `/` path arms have ruled out the
4362    // two `:`-bearing shapes the Gateway API actively rejects with
4363    // location-shaped diagnostics, any remaining `:` in the host body is
4364    // either the canonical "I put the port in the `:host` slot"
4365    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
4366    // slot lives one axis away on the same `:entrada` block) or an
4367    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
4368    // Hostname forbids identically to the IPv4-literal arm below. Both
4369    // shapes silently fell through the `://` and `/` arms before this
4370    // lift and surfaced as a deep `label "<rest>:<port>" contains
4371    // invalid character ':'` diagnostic from the per-byte loop near the
4372    // bottom of this predicate, which named the offending byte but not
4373    // the canonical authoring fix — for the port case the author has to
4374    // know the `:entrada` block carries a separate `:port u16` slot
4375    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
4376    // move the value over; for the IPv6 case the author has to know
4377    // Gateway API v1 forbids IP literals across the board. The contract
4378    // doc-comment above already promises "no port (`:8080`)" verbatim
4379    // in the rejected-shape enumeration but the predicate's
4380    // implementation refused the `:` only as a side-effect of the
4381    // per-label `[a-z0-9-]` character-class loop; this arm brings the
4382    // implementation in line with the documented contract by surfacing
4383    // the canonical fix at the top-level shape gate, peer with how the
4384    // `://` arm names the scheme prefix and the `/` arm names the
4385    // `:entrada :paths` axis. Same compounding trajectory the recent
4386    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
4387    // — the typed slot's rejected set matches the apiserver's rejected
4388    // set, structurally, with a self-locating diagnostic at the
4389    // offending axis instead of a deep parser-shape leak.
4390    if host.contains(':') {
4391        return Err(AplicacaoError::EntradaHostInvalid {
4392            host: host.to_string(),
4393            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
4394                     slot — a separate `u16` axis on the same `:entrada` block, \
4395                     defaulting to 8080 — not in the host body; drop the `:<port>` \
4396                     suffix and author the bare hostname. If you intended an IPv6 \
4397                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
4398                     Hostname forbids IP literals identically to the IPv4-literal \
4399                     arm — use a DNS name)"
4400                .to_string(),
4401        });
4402    }
4403    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
4404    // predicate — the same single source of truth every peer
4405    // ASCII-whitespace scan in caixa-core flows through: the four
4406    // typed-magnitude codec sites (`limits::parse_byte_size` backing
4407    // `:limits :memory`, `limits::parse_duration` backing `:limits
4408    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
4409    // `aplicacao::rate_limit_codec::parse` backing `:politicas
4410    // :rate-limit`) and the shared duration codec
4411    // (`supervisor::duration_codec::parse`) backing `:supervisor
4412    // :restart-window` / `:politicas :timeout` / `:politicas
4413    // :circuit-breaker :window`. This landing closes the last string-typed
4414    // slot in caixa-core still calling `.bytes().any(|b|
4415    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
4416    // across every typed slot now shares one predicate, so a future
4417    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
4418    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
4419    // deliberately excluded from the peer non-ASCII predicate) can
4420    // extend at this shared site in one edit rather than seven
4421    // independent scans diverging over time. Naming the offending byte
4422    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
4423    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
4424    // the offending byte verbatim" discipline every peer codec site
4425    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
4426    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
4427    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
4428        return Err(AplicacaoError::EntradaHostInvalid {
4429            host: host.to_string(),
4430            reason: format!(
4431                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
4432                 Hostname is a single-token DNS name — leading, trailing, \
4433                 or embedded whitespace breaks the K8s apiserver's Hostname \
4434                 regex at admission time; the paste-from-aligned-doc / \
4435                 paste-from-shell-history / paste-from-CSV footgun silently \
4436                 lands a multi-token blob in `:entrada :host`. Strip every \
4437                 whitespace byte and author the bare hostname — space \
4438                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
4439                 refuse identically)"
4440            ),
4441        });
4442    }
4443    // Peer of the ASCII-whitespace scan above: route the non-ASCII
4444    // subset of Unicode `White_Space` through the shared
4445    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
4446    // single source of truth every peer non-ASCII-whitespace scan in
4447    // caixa-core flows through: `limits::parse_byte_size` (`:limits
4448    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
4449    // `limits::parse_millicores` (`:limits :cpu`),
4450    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
4451    // and `supervisor::duration_codec::parse` (`:supervisor
4452    // :restart-window` / `:politicas :timeout` / `:politicas
4453    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
4454    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
4455    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
4456    // paste-from-web-doc), or an EM-SPACE-split host
4457    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
4458    // survived this predicate's ASCII byte-scan (none of the UTF-8
4459    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
4460    // `u8::is_ascii_whitespace`), then landed on the per-label
4461    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
4462    // predicate with the generic `label "…" must start and end with an
4463    // alphanumeric` diagnostic — a "far from source at build-time"
4464    // leak that names the label-shape violation but not the
4465    // paste-from-typography origin the author actually needs to fix.
4466    // Peer with the four codec sites the 1b75b38 landing pinned: the
4467    // typed slot's diagnostic axis names the offending codepoint
4468    // (`U+XXXX`) verbatim rather than laundering the value through a
4469    // downstream label-shape arm, so the author can grep their
4470    // caixa.lisp for the invisible codepoint at the surfaced position
4471    // rather than eyeball a multi-byte host for embedded NBSP / LINE
4472    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
4473    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
4474    // drift between any two typed-slot sites' non-ASCII-whitespace
4475    // rejection set becomes a single-edit fix at the shared predicate
4476    // rather than N independent inline scans diverging over time, and
4477    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
4478    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
4479    // `char::is_whitespace`" class the peer non-ASCII predicate's
4480    // doc-comment names as the follow-up trajectory) extends at the
4481    // shared predicate in one edit rather than seven.
4482    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
4483        return Err(AplicacaoError::EntradaHostInvalid {
4484            host: host.to_string(),
4485            reason: format!(
4486                "contains non-ASCII Unicode whitespace character {ch:?} \
4487                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
4488                 single-token DNS name limited to `[a-z0-9-]` labels; \
4489                 the paste-from-typography footgun silently lands an \
4490                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
4491                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
4492                 `U+3000`, and every other member of the Unicode \
4493                 `White_Space` property outside the ASCII byte range) \
4494                 in `:entrada :host`, which the K8s apiserver's \
4495                 Hostname regex refuses at admission time far from the \
4496                 caixa.lisp source line. Strip every non-ASCII \
4497                 whitespace character and author the bare hostname \
4498                 with only ASCII bytes (write \"checkout.quero.cloud\" \
4499                 verbatim)",
4500                codepoint = ch as u32,
4501            ),
4502        });
4503    }
4504
4505    // Strip the optional single leading wildcard label *before* the
4506    // trailing-dot check so the bare `"*."` form surfaces the more
4507    // self-locating "wildcard without domain" diagnostic instead of
4508    // the generic "trailing dot" one.
4509    let (had_wildcard, rest) = match host.strip_prefix("*.") {
4510        Some(r) => (true, r),
4511        None => (false, host),
4512    };
4513    if had_wildcard && rest.is_empty() {
4514        return Err(AplicacaoError::EntradaHostInvalid {
4515            host: host.to_string(),
4516            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
4517        });
4518    }
4519    if rest.contains('*') {
4520        return Err(AplicacaoError::EntradaHostInvalid {
4521            host: host.to_string(),
4522            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
4523                     no inner or trailing `*` labels"
4524                .to_string(),
4525        });
4526    }
4527    if rest.ends_with('.') {
4528        return Err(AplicacaoError::EntradaHostInvalid {
4529            host: host.to_string(),
4530            reason: "must not have a trailing `.` (Gateway API hostnames are not \
4531                     fully-qualified with a root dot; the apiserver regex rejects \
4532                     trailing dots)"
4533                .to_string(),
4534        });
4535    }
4536
4537    // Reject pure IPv4 literals: four dot-separated labels, every
4538    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
4539    // literals as Hostnames.
4540    let labels: Vec<&str> = rest.split('.').collect();
4541    if labels.len() == 4
4542        && labels
4543            .iter()
4544            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
4545    {
4546        return Err(AplicacaoError::EntradaHostInvalid {
4547            host: host.to_string(),
4548            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
4549                     literals; use a DNS name)"
4550                .to_string(),
4551        });
4552    }
4553
4554    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
4555    // hyphen, with non-hyphen at both boundaries.
4556    for label in &labels {
4557        if label.is_empty() {
4558            return Err(AplicacaoError::EntradaHostInvalid {
4559                host: host.to_string(),
4560                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
4561            });
4562        }
4563        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
4564            return Err(AplicacaoError::EntradaHostInvalid {
4565                host: host.to_string(),
4566                reason: format!(
4567                    "label {label:?} exceeds DNS-1123 label max length of \
4568                     {cap} bytes (got {} bytes)",
4569                    label.len(),
4570                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
4571                ),
4572            });
4573        }
4574        let bytes = label.as_bytes();
4575        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
4576            return Err(AplicacaoError::EntradaHostInvalid {
4577                host: host.to_string(),
4578                reason: format!(
4579                    "label {label:?} must start and end with an alphanumeric \
4580                     (no leading or trailing `-`)"
4581                ),
4582            });
4583        }
4584        for &b in bytes {
4585            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
4586            if !valid {
4587                let msg = if b.is_ascii_uppercase() {
4588                    format!(
4589                        "label {label:?} contains uppercase character {ch:?} \
4590                         (Gateway API hostnames are lowercase-only; use {lower:?})",
4591                        ch = b as char,
4592                        lower = label.to_ascii_lowercase()
4593                    )
4594                } else if b == b'_' {
4595                    format!(
4596                        "label {label:?} contains `_` (Gateway API hostnames \
4597                         allow only `[a-z0-9-]`; use `-` instead)"
4598                    )
4599                } else {
4600                    format!(
4601                        "label {label:?} contains invalid character {ch:?} \
4602                         (Gateway API hostnames allow only `[a-z0-9-]`)",
4603                        ch = b as char
4604                    )
4605                };
4606                return Err(AplicacaoError::EntradaHostInvalid {
4607                    host: host.to_string(),
4608                    reason: msg,
4609                });
4610            }
4611        }
4612    }
4613    Ok(())
4614}
4615
4616/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
4617/// would refuse at admission time. Thin wrapper around
4618/// [`crate::render::is_gateway_api_http_path`] that maps the shared
4619/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
4620/// variant, preserving the more self-locating
4621/// [`AplicacaoError::EntradaPathEmpty`] /
4622/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
4623/// path fails those narrower invariants first.
4624///
4625/// The contract is the canonical HTTP-path grammar — `1..=
4626/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
4627/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
4628/// whitespace/control/non-ASCII bytes — shared with the
4629/// `:contratos :endpoint` axis through the lifted predicate so drift
4630/// between either landing site and the K8s apiserver-side
4631/// HTTPPathMatch.value OpenAPI schema is a build error visible at
4632/// the predicate, not a per-renderer "this passed validate but failed
4633/// admission" surprise. The diagnostic carries the offending `path:`
4634/// verbatim plus a parser-shaped `reason:` naming the specific
4635/// violation, so the author can grep their caixa.lisp for `:paths`
4636/// and fix it in one edit. Same diagnostic shape as
4637/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
4638/// axis.
4639fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
4640    // Empty and missing-leading-`/` are already gated at the call
4641    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
4642    // checking here keeps the per-axis narrower diagnostics in force
4643    // when the predicate is reached directly (and `is_gateway_api_http_path`
4644    // itself defends against `bytes[0]`-style indexing on empty
4645    // input).
4646    if path.is_empty() {
4647        return Err(AplicacaoError::EntradaPathEmpty);
4648    }
4649    if !path.starts_with('/') {
4650        return Err(AplicacaoError::EntradaPathNotAbsolute {
4651            path: path.to_string(),
4652        });
4653    }
4654    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
4655        AplicacaoError::EntradaPathInvalid {
4656            path: path.to_string(),
4657            reason,
4658        }
4659    })
4660}
4661
4662mod rate_limit_codec {
4663    // `Duration` is no longer named here — the codec routes through
4664    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4665    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4666    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4667    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4668    // closed-set enum's arm-table rather than through vestigial free-helper
4669    // delegates.
4670    use super::{RateLimit, RateLimitUnit};
4671    use serde::{Deserialize, Deserializer, Serializer};
4672
4673    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4674        match v {
4675            Some(rl) => s.serialize_str(&render(*rl)),
4676            None => s.serialize_none(),
4677        }
4678    }
4679
4680    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4681        let opt: Option<String> = Option::deserialize(d)?;
4682        match opt {
4683            None => Ok(None),
4684            Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
4685        }
4686    }
4687
4688    fn parse(s: &str) -> Result<RateLimit, String> {
4689        // Whitespace-rejection arm — peer with the leading-`+`
4690        // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
4691        // same canonical-form render-determinism axis. Until this gate
4692        // landed the parser silently tolerated leading / trailing /
4693        // internal whitespace via the top-level `s.trim()` and the
4694        // per-part `rate_str.trim()` / `unit.trim()` calls, so every
4695        // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
4696        // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
4697        // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
4698        // serde silently round-tripped to `"100/s"` on the next emit
4699        // (a *different* canonical string) — breaking the THEORY.md
4700        // Part V render-determinism contract on the same
4701        // canonical-form-drift axis the leading-`+` arm below (the
4702        // 4eeae98 predecessor) and the leading-zero arm below (the
4703        // 4f46830 predecessor) already close.
4704        //
4705        // The canonical author shape is `<integer>/<s|m|h>` with no
4706        // whitespace bytes anywhere — every string [`render`] emits
4707        // carries none, so the parser's accepted set must match for
4708        // serialize / deserialize to round-trip losslessly. This gate
4709        // makes the pre-existing `s.trim()` / `rate_str.trim()` /
4710        // `unit.trim()` calls below strict no-ops on the accepted set
4711        // (every byte-position match they would perform is now already
4712        // trimmed away by the accepted set itself), while the arm
4713        // surfaces every rejected whitespace-carrying shape with a
4714        // self-locating diagnostic naming the offending byte and the
4715        // canonical form the author intended, peer with every prior
4716        // canonical-form-drift arm on this codec.
4717        //
4718        // Routed through the lifted
4719        // [`crate::render::find_ascii_whitespace_byte`] predicate — the
4720        // same source of truth the four peer typed-magnitude codec
4721        // sites (`limits::parse_byte_size`, `limits::parse_duration`,
4722        // `limits::parse_millicores`, `supervisor::duration_codec`)
4723        // share. `u8::is_ascii_whitespace()` at the predicate covers
4724        // the five WhatWG-conformant ASCII whitespace bytes (space,
4725        // tab, LF, FF, CR); the "single lifted predicate" discipline
4726        // the peer non-ASCII arm below carries on the strictly-
4727        // complementary Unicode `White_Space` class extends here to
4728        // the ASCII byte set as well.
4729        if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
4730            return Err(format!(
4731                "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4732                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4733                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4734                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4735                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4736                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4737                 on first serialize — breaking the THEORY.md Part V render-determinism \
4738                 contract every typed slot carries. Strip every whitespace byte (write \
4739                 `\"100/s\"` verbatim)"
4740            ));
4741        }
4742        // Non-ASCII Unicode `White_Space` arm — the strictly-
4743        // complementary class the ASCII arm above cannot see.
4744        // `str::trim` at the top of every peer codec uses
4745        // `char::is_whitespace` (Unicode `White_Space`, strictly
4746        // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
4747        // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4748        // survives the byte-scan (its UTF-8 bytes are not in
4749        // `is_ascii_whitespace`), gets silently stripped by the
4750        // top-level `s.trim()` below, and the value round-trips
4751        // through `render` to a *different* canonical form
4752        // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
4753        // render-determinism contract every typed slot carries.
4754        // Closed here (`:politicas :rate-limit`) and at the three
4755        // peer codec sites (`limits::parse_byte_size`,
4756        // `limits::parse_duration`, `supervisor::duration_codec`)
4757        // through the shared
4758        // [`crate::render::find_non_ascii_whitespace_char`] predicate
4759        // — the "single lifted predicate across all four codec sites
4760        // in one follow-up run" the 24a8ad4 commit body's `Forward
4761        // compounding` bullet named as the next compounding step.
4762        if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
4763            return Err(format!(
4764                "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4765                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4766                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4767                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4768                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4769                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4770                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4771                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4772                 silently strips it at parse entry, and the value round-trips through \
4773                 `render` to a *different* canonical form (`\"100/s\"`) on first \
4774                 serialize — breaking the THEORY.md Part V render-determinism contract \
4775                 every typed slot carries. Strip every non-ASCII whitespace character \
4776                 (write `\"100/s\"` verbatim with only ASCII bytes)",
4777                cp = ch as u32
4778            ));
4779        }
4780        let s = s.trim();
4781        let (rate_str, unit) = s
4782            .split_once('/')
4783            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4784        let rate_trim = rate_str.trim();
4785        // The canonical authoring form for `:politicas :rate-limit` is
4786        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4787        // non-negative integer with no decimal point and no leading
4788        // sign, so the parser's accepted set must match for
4789        // serialize/deserialize to round-trip without canonical-form
4790        // drift. Until this gate landed the parser accepted any
4791        // `u32::from_str`-shaped magnitude — and current Rust
4792        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4793        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4794        // serde silently round-tripped to `"100/s"` on the next emit
4795        // (a *different* canonical string) — breaking the THEORY.md
4796        // Part V render-determinism contract on the fifth typed-codec
4797        // surface in caixa-core (peer with the four duration codecs the
4798        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4799        // already covered: `supervisor::duration_codec` backing three
4800        // typed-duration slots, `limits::parse_duration` backing
4801        // `:limits :wall-clock`, `limits::parse_byte_size` backing
4802        // `:limits :memory`). The fractional / decimal-shaped sibling
4803        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4804        // existing rejection arm, but the diagnostic is value-laundered
4805        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4806        // doesn't name the canonical-form remediation or the round-trip
4807        // drift the next emit would produce); this gate lifts the
4808        // fractional arm onto the same canonical-form diagnostic the
4809        // peer codecs carry.
4810        //
4811        // Strict canonical form: every byte of the magnitude is an
4812        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4813        // inputs the gate distinguishes "non-canonical-but-numeric"
4814        // (parses as f64 or i64 — surfaced with a self-locating
4815        // diagnostic naming the canonical authoring form and the
4816        // round-trip drift the rejected shape would produce on first
4817        // serialize) from "garbage" (parses as neither — surfaced with
4818        // the existing narrower `"not a u32"` wording so its
4819        // diagnostic shape remains stable for the parser-shape footgun
4820        // case).
4821        //
4822        // Routed through the lifted
4823        // [`crate::render::is_digit_only_magnitude`] predicate — the
4824        // same source of truth the four peer typed-magnitude codec
4825        // sites share.
4826        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4827        if !digit_only {
4828            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4829            if numeric {
4830                return Err(format!(
4831                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4832                     canonical authoring form for `:politicas :rate-limit` is \
4833                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4834                     with no decimal point and no leading `+` / `-` sign. A fractional / \
4835                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4836                     through `render` to a *different* canonical form (`\"1/s\"`, \
4837                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
4838                     THEORY.md Part V render-determinism contract every typed slot \
4839                     carries. Pick an integer rate that fits the desired window \
4840                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4841                ));
4842            }
4843            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4844        }
4845        // Leading-zero arm — peer with the prior `"+100/s"` arm above
4846        // (4eeae98's predecessor) on the same canonical-form
4847        // render-determinism axis. The digit-only gate accepts
4848        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4849        // them losslessly (= 100, 0, 7), but `render` emits the
4850        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4851        // a *different* canonical string on the next emit, breaking
4852        // the THEORY.md Part V render-determinism contract the same
4853        // way `"+100/s"` did before the leading-`+` arm landed. The
4854        // single-byte magnitude `"0"` itself round-trips losslessly
4855        // through `render` (`render(0)` emits `"0/s"`) — the
4856        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4857        // what refuses rate-zero authoring, so `"0/s"` stays in the
4858        // accepted set at this codec layer and the diagnostic
4859        // partitioning between canonical-form drift (this arm) and
4860        // semantic-zero (the downstream gate) remains stable.
4861        // Peer with the future leading-zero arms on the three peer
4862        // typed-magnitude codecs the trajectory acknowledges:
4863        // `supervisor::duration_codec`, `limits::parse_duration`,
4864        // `limits::parse_byte_size` — each carries the same
4865        // canonical-form-drift class today; this gate lands the
4866        // discipline on the fourth typed-magnitude codec in
4867        // caixa-core first because the peer `"+100/s"` arm above is
4868        // the closest predecessor on the trajectory.
4869        //
4870        // Routed through the lifted
4871        // [`crate::render::is_leading_zero_padded_magnitude`]
4872        // predicate — the same source of truth the four peer
4873        // typed-magnitude codec sites share.
4874        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4875            return Err(format!(
4876                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4877                 canonical authoring form for `:politicas :rate-limit` is \
4878                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4879                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4880                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4881                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4882                 first serialize — breaking the THEORY.md Part V render-determinism \
4883                 contract every typed slot carries. Strip the leading zeros (write \
4884                 `\"100/s\"` instead of `\"0100/s\"`)"
4885            ));
4886        }
4887        // The digit-only gate guarantees every byte is `[0-9]`, and
4888        // the leading-zero arm above guarantees the magnitude is
4889        // either the single byte `"0"` or starts with `[1-9]`, so
4890        // the only way `u32::from_str` can fail here is overflow
4891        // (the magnitude exceeds `u32::MAX`). Surface that with an
4892        // overflow-shaped wording so the diagnostic names the
4893        // offending magnitude verbatim rather than collapsing onto
4894        // the non-canonical arm. Same shape
4895        // `supervisor::duration_codec` (1c55a2a) carries on the peer
4896        // duration-codec axis.
4897        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4898            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4899        })?;
4900        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
4901        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
4902        // arm reads the `&str → Duration` projection through the
4903        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4904        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
4905        // with [`super::RateLimitUnit::window`]) rather than the vestigial
4906        // module-private `rate_limit_window_from_unit` free helper the
4907        // predecessor 61421a6 left as the last unlifted delegate on this
4908        // axis. One typed dispatch on the substrate primitive instead of
4909        // one runtime call through the free-helper delegate; the sole
4910        // production consumer of the `&str → Duration` axis (this parse
4911        // arm) now reaches for exactly one typed method on the closed-set
4912        // enum, sibling to the codec's render arm's
4913        // [`super::RateLimit::canonical_unit`] dispatch on the paired
4914        // `Duration → RateLimitUnit` axis and to the validate gate's
4915        // [`super::RateLimit::canonical_unit`] shape-probe on the
4916        // canonical-window axis. A future rate-limit-unit addition (a
4917        // `"d"` day suffix once Envoy's `rate_limit_action` grows
4918        // daily-bucket support, a `"ms"` sub-second window once
4919        // high-throughput per-edge policies come into scope per
4920        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
4921        // on the closed-set enum, and the compiler enforces exhaustiveness
4922        // on every consumer's `match self` arms — this parse arm's
4923        // accepted-suffix set, the render arm's emitted-suffix set, the
4924        // validate gate's canonical-window set, and every future
4925        // per-`:contratos`-edge rate-limit-override overlay all pick it up
4926        // by construction.
4927        let unit = unit.trim();
4928        let window = RateLimitUnit::window_from_suffix(unit)
4929            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4930        Ok(RateLimit { rate, window })
4931    }
4932
4933    fn render(rl: RateLimit) -> String {
4934        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4935        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4936        // this render arm reads the `Duration → RateLimitUnit` projection
4937        // through the substrate primitive [`super::RateLimit::canonical_unit`]
4938        // (returns `None` on every non-canonical window — the sub-second /
4939        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4940        // formats the returned typed enum through its
4941        // [`std::fmt::Display`] impl (which routes through
4942        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4943        // the substrate primitive instead of one runtime `find_map`
4944        // walk through the free-helper delegate chain
4945        // [`super::rate_limit_window_unit`] (the vestigial free helper's
4946        // sole production consumer was this arm; every other consumer of
4947        // the `Duration → unit` axis — the validate gate below and the
4948        // future M4 per-Aplicacao Envoy config reconciler — now reads
4949        // the same typed method).
4950        //
4951        // A future rate-limit-unit addition (a `"d"` day suffix once
4952        // Envoy's `rate_limit_action` grows daily-bucket support) is
4953        // one variant + one arm per method on the closed-set enum, and
4954        // the compiler enforces exhaustiveness on every consumer's
4955        // `match self` arms — the codec's `parse` accepted-suffix set,
4956        // this render arm's emitted-suffix set, the validate gate's
4957        // canonical-window set, and every future per-`:contratos`-edge
4958        // rate-limit-override overlay all pick it up by construction.
4959        if let Some(unit) = rl.canonical_unit() {
4960            format!("{}/{unit}", rl.rate())
4961        } else {
4962            // Defensive fallback for non-canonical windows. Note:
4963            // [`AplicacaoSpec::validate_politicas`] rejects any
4964            // non-canonical `:rate-limit :window` via
4965            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4966            // a validated `RateLimit` never reaches this branch. The
4967            // emitted `<n>/<k>s` form is *not* round-trippable through
4968            // [`parse`] (which accepts only the closed-set
4969            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
4970            // explicit count) — the validate gate is what makes the
4971            // round-trip a structural property; this branch exists only
4972            // so a programmatic non-validated serialize doesn't panic.
4973            format!("{}/{}s", rl.rate(), rl.window().as_secs())
4974        }
4975    }
4976}
4977
4978// ── placement strategy ───────────────────────────────────────────────
4979
4980/// How the Aplicacao distributes across clusters. Three options:
4981///
4982/// - `SingleNode` — one cluster runs the app at a time; takeover on
4983///   death (Erlang/OTP distributed-app semantics).
4984/// - `Replicated` — every named cluster runs an instance (active-active).
4985/// - `Sharded` — entities distribute by hash key across clusters
4986///   (Akka cluster sharding).
4987#[derive(
4988    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4989)]
4990pub enum PlacementStrategy {
4991    SingleNode,
4992    Replicated,
4993    Sharded,
4994}
4995
4996/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
4997/// distribution-strategy default for the `:placement :estrategia` axis —
4998/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
4999/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
5000/// so every substrate-side consumer that resolves "what
5001/// [`PlacementStrategy`] variant does an author-omitted `:placement
5002/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
5003/// primitive [`PlacementStrategy`].
5004///
5005/// The `:placement :estrategia` default axis has three production
5006/// consumers on the substrate side today: the [`Default for
5007/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
5008/// impl's struct-literal `estrategia` field, and the serde-side
5009/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
5010/// author-omitted `:placement :estrategia` scalar through the [`Default
5011/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
5012/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
5013/// impl and implicit `PlacementStrategy::default()` routes at the sibling
5014/// consumers, with no compile-time link back to the paired
5015/// [`crate::manifest::Caixa::aplicacao_view`] fold's
5016/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
5017/// production consumer that resolves an author-omitted `:placement` slot
5018/// (entirely omitted, not just the `:estrategia` scalar within a declared
5019/// `:placement` block) through [`Placement::default`] which then routes
5020/// through this same discriminator. A future coherent rebrand of the
5021/// `:placement :estrategia` default (a widening to `Sharded` once the
5022/// substrate discovers hash-keyed distribution as the more common
5023/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
5024/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
5025/// names, a per-cluster overlay the operator pins through a future
5026/// `:placement-overrides` slot) would have had to migrate a lifted
5027/// discriminator on one path and open-coded discriminators on the peers
5028/// in lockstep or the four consumers would silently drift out of
5029/// pairing. Lifting the resolution rule to a typed `pub const` on the
5030/// substrate primitive means the M3-mesh-canonical `:placement
5031/// :estrategia` default migrates as one unit on any future axis change.
5032///
5033/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
5034/// §II.2's active-active-across-every-named-cluster arm — the closest
5035/// canonical M3 production reference the substrate carries, matching the
5036/// caixa-mesh default axis every M3 renderer already keys off (a
5037/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
5038/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
5039/// under the substrate's fleet-programs aggregator without an explicit
5040/// `:placement :estrategia` override). The two alternatives the closed
5041/// [`PlacementStrategy::ALL`] accept-set carries
5042/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
5043/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
5044/// Akka-style hash-keyed distribution across clusters,
5045/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
5046/// postures an author declares explicitly, never a posture an omitted
5047/// slot should silently assume.
5048///
5049/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
5050/// exactly one source of truth on the `:placement :estrategia` axis, on
5051/// the same substrate-primitive lift discipline the sibling M2
5052/// per-supervisor default set carries
5053/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
5054/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
5055/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
5056/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
5057/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
5058/// ([`crate::render::DEFAULT_NAMESPACE`],
5059/// [`crate::render::DEFAULT_LIBRARY_NAME`],
5060/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
5061/// the M3 mesh-primitive-defining slot family to converge onto the
5062/// substrate-primitive-lift discipline the M2 supervisor-slot family
5063/// already carries end-to-end.
5064pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
5065
5066impl Default for PlacementStrategy {
5067    fn default() -> Self {
5068        // Route the [`Default for PlacementStrategy`] impl through the
5069        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
5070        // `pub const` rather than a raw `Self::Replicated` arm — one
5071        // source of truth for the M3-mesh-canonical active-active-
5072        // across-every-named-cluster `:placement :estrategia` default
5073        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
5074        // lift discipline the sibling M2 per-supervisor default set
5075        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
5076        // paired halves) carries end-to-end. Pinned by
5077        // `placement_strategy_default_routes_through_lifted_default`.
5078        PLACEMENT_ESTRATEGIA_DEFAULT
5079    }
5080}
5081
5082impl PlacementStrategy {
5083    /// Exhaustive iteration surface for every consumer that reads the
5084    /// full closed-set (the future M4 admission-webhook's accepted-
5085    /// strategy listing in its rejection body, a future `feira app
5086    /// placement --list` CLI-side surfacing of the accepted arm-set,
5087    /// any future round-trip fuzz harness). A future variant addition
5088    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
5089    /// names as a trajectory item) extends this slice as a single edit
5090    /// and every consumer picks up the new entry by construction — the
5091    /// compiler-checked exhaustiveness on the sibling method `match`
5092    /// arms is the build-time guarantee that no arm forgets to grow.
5093    /// Same shape as the sibling closed-set typed enums'
5094    /// [`RateLimitUnit::ALL`] (6bce03d) and
5095    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5096    /// surfaces — the third closed-set typed enum on the caixa surface
5097    /// to converge onto the same discipline.
5098    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
5099
5100    /// Canonical camelCase-schema discriminator scalar this variant
5101    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
5102    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
5103    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5104    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
5105    /// every substrate consumer that dispatches on the strategy (the
5106    /// `lareira-fleet-programs` aggregator, the future `app-operator`
5107    /// reconciler, the M3 Adaptive compression pass) reads the same
5108    /// byte-string the `Serialize` derive emits — the pin test in
5109    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
5110    /// asserts the two paths agree.
5111    #[must_use]
5112    pub const fn as_str(self) -> &'static str {
5113        match self {
5114            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
5115            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
5116            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
5117        }
5118    }
5119
5120    /// Substrate-canonical reverse projection on the `:placement
5121    /// :estrategia` closed-set axis — parses the camelCase-schema
5122    /// discriminator scalar back to the typed variant, or `None` when
5123    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
5124    /// emits. Dispatches on the same lifted
5125    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5126    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5127    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
5128    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
5129    /// the round-trip migrate through one caixa-core edit on any future
5130    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
5131    /// §II.5 hint names as a trajectory item lands one variant + one
5132    /// arm per method and the compiler enforces exhaustiveness on every
5133    /// consumer's `match self` arms).
5134    ///
5135    /// Prior to this lift the substrate carried only the forward
5136    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
5137    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
5138    /// derive that emits the same byte-string under
5139    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
5140    /// consumer that wanted to parse a wire-form strategy scalar had to
5141    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
5142    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
5143    /// compile-time link back to the typed variant's canonical lifted
5144    /// constant. A future variant rename or a per-arm serde-attribute
5145    /// drift would silently split the wire byte-string one non-serde
5146    /// consumer parsed from the one the emitter wrote, with the
5147    /// failure surfacing at parse time far from the rebrand commit.
5148    ///
5149    /// Same closed-set-reverse-projection discipline the sibling
5150    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
5151    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
5152    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
5153    /// defining `:placement :estrategia` closed-set axis, the third
5154    /// substrate-side closed-set typed enum to converge on the two-way
5155    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
5156    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
5157    /// and side-step the [`std::str::FromStr`]-collision clippy
5158    /// (`clippy::should_implement_trait`) the plain `from_str` name
5159    /// carries; a future explicit [`std::str::FromStr`] impl can layer
5160    /// on top by delegating to this canonical arm-dispatch method.
5161    ///
5162    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
5163    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
5164    /// picks the diagnostic form appropriate for its use site — a
5165    /// future `feira app placement --set` CLI-side arg-parse that wants
5166    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
5167    /// Sharded)"` diagnostic builds one on top by iterating
5168    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
5169    /// path folds `None` onto its per-CR structured refusal body.
5170    #[must_use]
5171    pub fn from_wire(s: &str) -> Option<Self> {
5172        match s {
5173            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
5174            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
5175            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
5176            _ => None,
5177        }
5178    }
5179
5180    /// Substrate-canonical per-arm predicate naming the cross-slot
5181    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
5182    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
5183    /// consumes the paired [`Placement::shard_key`] axis (and therefore
5184    /// requires — and is the only strategy that permits — a non-empty
5185    /// `:shard-key` on the paired slot). Today the accept-set is the
5186    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
5187    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
5188    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
5189    /// distributed-app takeover — §II.1) and `Replicated` (active-active
5190    /// across every named cluster) have no hash-keyed routing axis to
5191    /// consume the slot and refuse a declared-but-inert `:shard-key`
5192    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
5193    ///
5194    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
5195    /// satisfies `placement.shard_key().is_some() ==
5196    /// placement.estrategia().requires_shard_key()` by construction — the
5197    /// cross-slot partition the pin
5198    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
5199    /// locks load-bearing, so every downstream consumer that reaches for
5200    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5201    /// CR materializer's per-CR shard-key resolver, the future
5202    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
5203    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
5204    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
5205    /// shard-key requirement probe, a future author-facing tatara-lisp
5206    /// linter that flags `(:placement (:estrategia Replicated :shard-key
5207    /// "tenantId"))` shapes before `feira lint` reaches
5208    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
5209    /// the substrate primitive — the predicate names *the cross-slot
5210    /// invariant*, not the arm identity.
5211    ///
5212    /// Prior to this lift the "does this strategy consume `:shard-key`"
5213    /// classification lived under the `gen_platform::IsVariant`-derived
5214    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
5215    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
5216    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
5217    /// } else { None }` cascade, the
5218    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
5219    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
5220    /// "tenantId".to_string())` cascade, and the
5221    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
5222    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
5223    /// cascade). Each site conflated two semantically distinct questions:
5224    /// "is the variant `Sharded`?" (arm-identity, what
5225    /// [`Self::is_sharded`] answers) and "does the variant consume
5226    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
5227    /// The two questions land on the same three-way answer under today's
5228    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
5229    /// future arm addition that consumed `:shard-key` under a different
5230    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
5231    /// §II.5 roadmap-hint names that hash-partitions across the cluster
5232    /// pool by client-IP hash rather than an author-declared extractor
5233    /// expression, a hypothetical `WeightedShard` variant that carries a
5234    /// shard-key + per-cluster weight table under a promoted M5
5235    /// adaptive-placement engine) or an addition that did *not* consume
5236    /// `:shard-key` on a semantically Sharded-shaped arm would silently
5237    /// split the two questions. Any consumer that read
5238    /// `.is_sharded().then(…)` for the shard-key requirement gate would
5239    /// silently misclassify the new arm as non-consuming — a fixture
5240    /// builder would omit `:shard-key` where the new arm required one and
5241    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
5242    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
5243    /// commit, a future M4 CR materializer would fall through the
5244    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
5245    /// silently emit an empty extractor at the Akka reconciler layer.
5246    ///
5247    /// Lifting the classification as a substrate-primitive method on the
5248    /// closed-set typed enum names the cross-slot invariant on the
5249    /// primitive that owns the partition: every future arm addition
5250    /// declares its `:shard-key` consumption in one place (this predicate's
5251    /// `match self` arm-set), and every downstream consumer that reaches
5252    /// for the paired shape reads through one typed dispatch. Same
5253    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
5254    /// per-arm predicate on the pre-projection WIT-shape axis and the
5255    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
5256    /// paired predicate on the post-projection typed-view axis — a
5257    /// per-arm semantic-classification predicate paired with the
5258    /// arm-identity predicate the derive already emits, closing the drift
5259    /// footgun on the cross-slot invariant axis.
5260    ///
5261    /// Method-named `requires_shard_key` (not `has_shard_key`, not
5262    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
5263    /// invariant reads as "this strategy *requires* the paired
5264    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
5265    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
5266    /// merely omit it. The `has_*` framing would read as an accessor
5267    /// (returning the presence of an already-carried value) rather than a
5268    /// requirement (naming the invariant the paired slot must satisfy).
5269    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
5270    /// shape as the sibling [`WitContract::is_capability`] /
5271    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
5272    /// arm-family, so every consumer reaches for `.requires_shard_key()`
5273    /// as a drop-in replacement for the `.is_sharded()` conflated read
5274    /// without a return-shape migration.
5275    #[must_use]
5276    pub const fn requires_shard_key(self) -> bool {
5277        match self {
5278            Self::Sharded => true,
5279            Self::SingleNode | Self::Replicated => false,
5280        }
5281    }
5282}
5283
5284// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5285// cross-slot-invariant per-arm predicate: the module-scope const-eval
5286// assertions below trip at caixa-core build time (not test time) if a
5287// future edit rewires the predicate's arm-set away from the singleton
5288// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5289// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5290// runtime pin covers the same truth-table with a more descriptive
5291// diagnostic on failure; these const-eval items add a build-time failure
5292// surface strictly stronger than the runtime pin (a downstream renderer's
5293// `const`-context reader that composed against a rebound predicate would
5294// still surface here before the test suite even ran) and side-step the
5295// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5296// would otherwise accumulate on the caixa-core module baseline.
5297const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5298const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5299const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5300
5301/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5302/// the pretty-printed byte-string every consumer that formats the strategy
5303/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5304/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5305/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5306/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5307/// admission-webhook rejection body) reaches for the same lifted
5308/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5309/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5310/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5311/// `Serialize` derive already emits under
5312/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5313/// [`PlacementStrategy::as_str`] helper already returns.
5314///
5315/// Until this lift landed the sibling OTP-shape typed enums —
5316/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5317/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5318/// so [`std::fmt::Display`] routes through the same discriminant string
5319/// the wire format emits) — carried a stable [`std::fmt::Display`]
5320/// surface but [`PlacementStrategy`] did not; every consumer reaching
5321/// for a strategy byte-string past the wire format had to pick between
5322/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5323/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5324/// derive), any two of which a future variant rename or
5325/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5326/// desynchronize — with the failure surfacing as a downstream renderer /
5327/// operator's per-strategy dispatch reading one spelling while the wire
5328/// format emitted another, far from the source rebrand commit and with
5329/// no field naming the drift. Routing `Display` through
5330/// [`PlacementStrategy::as_str`] makes the three paths
5331/// (`Debug` for structural inspection, `Display` for user-facing text,
5332/// `Serialize` for the wire format) converge on the same lifted
5333/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
5334/// the diagnostic byte-string, and the pretty-printed byte-string move
5335/// as a single unit through one canonical declaration each, by
5336/// construction. Same trajectory as [`PlacementStrategy::as_str`]
5337/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
5338/// closes the third path.
5339///
5340/// Pin tests
5341/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
5342/// and
5343/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
5344/// assert the three paths agree byte-for-byte on every variant, so a
5345/// future variant rename or per-arm serde attribute drift is a build
5346/// error visible at caixa-core test time, not a silent per-consumer
5347/// dispatch miss at apply / reconcile time.
5348impl std::fmt::Display for PlacementStrategy {
5349    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5350        f.write_str(self.as_str())
5351    }
5352}
5353
5354/// Where the Aplicacao runs.
5355#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5356#[serde(rename_all = "camelCase")]
5357pub struct Placement {
5358    /// Distribution strategy.
5359    #[serde(default)]
5360    pub estrategia: PlacementStrategy,
5361
5362    /// Named clusters that host this Aplicacao. Required for
5363    /// `Replicated` and `SingleNode`; for `Sharded` declares the
5364    /// shard pool.
5365    #[serde(default)]
5366    pub clusters: Vec<String>,
5367
5368    /// Optional hint to the placement engine: `"data-locality"`,
5369    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
5370    #[serde(default, skip_serializing_if = "Option::is_none")]
5371    pub affinity: Option<String>,
5372
5373    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
5374    #[serde(default, skip_serializing_if = "Option::is_none")]
5375    pub shard_key: Option<String>,
5376}
5377
5378impl Placement {
5379    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
5380    /// `:shard-key` extractor-expression scalar accessor every consumer
5381    /// of the Aplicacao's hash-keyed distribution routing keys off —
5382    /// returns the author-declared `:placement :shard-key` byte-string
5383    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
5384    /// own `Option<String>` storage; `None` when the slot is absent
5385    /// (the canonical shape under `:estrategia Replicated` /
5386    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
5387    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
5388    /// partition — `validate` refuses any `Placement` past this call
5389    /// that lands `Some` on a non-`Sharded` strategy or `None` on
5390    /// `Sharded`).
5391    ///
5392    /// The `:placement :shard-key` slot carries the Akka-style
5393    /// cluster-sharding entity-id extractor expression
5394    /// (MESH-COMPOSITION §II.4) — validated by
5395    /// [`validate_placement_shard_key`] to be a non-empty printable-
5396    /// ASCII single-token reference (`tenantId`, `$tenantId`,
5397    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
5398    /// future M4 Akka-style cluster-sharding reconciler hashes without
5399    /// re-validating at the runtime layer), and every downstream
5400    /// consumer that reads the key keys off this scalar (the
5401    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
5402    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5403    /// declared-but-inert refusal diagnostic, the caixa-mesh
5404    /// per-Aplicacao `placement.shardKey` emit path the substrate
5405    /// operator's per-entity hash-routing reader consumes, the future
5406    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5407    /// per-shard-key resolver).
5408    ///
5409    /// Prior to this lift the `.shard_key` field was accessed inline at
5410    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
5411    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
5412    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
5413    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
5414    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
5415    /// — two open-coded field-accesses that expressed no compile-time
5416    /// link back to the typed slot. A future extension of the
5417    /// `:placement :shard-key` axis to a richer author surface — a
5418    /// per-cluster override the operator pins through a future
5419    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
5420    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
5421    /// alias table the M4 CR materializer resolves per-CR, a
5422    /// per-Aplicacao dynamic `:shard-key` derivation the future
5423    /// adaptive placement engine computes from `:affinity` weights —
5424    /// would have had to be threaded through both open-coded copies in
5425    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
5426    /// arm refusal would silently disagree on which extractor
5427    /// expression a given Placement resolves to. Lifting the resolution
5428    /// rule to a typed method on the substrate primitive means every
5429    /// downstream consumer of the Aplicacao's per-`:placement`
5430    /// hash-key surface reaches for exactly one typed dispatch — the
5431    /// resolver's accept-set migrates as a unit on any future axis
5432    /// addition.
5433    ///
5434    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
5435    /// [`WitContract::destination`] / [`WitContract::world_ref`]
5436    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
5437    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
5438    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
5439    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
5440    /// typed dispatch on the substrate primitive, thin projections at
5441    /// each consumer" discipline extended onto the per-`:placement`
5442    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
5443    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
5444    /// — opens the "optional per-slot scalar" projection pattern the
5445    /// sibling per-`:placement` `:affinity`, per-`:politicas`
5446    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
5447    /// match the storage field's name; the accessor's identity name
5448    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
5449    /// slot's docstring already carries.
5450    #[must_use]
5451    pub fn shard_key(&self) -> Option<&str> {
5452        self.shard_key.as_deref()
5453    }
5454
5455    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
5456    /// compression-hint scalar accessor every weighting-consumer of the
5457    /// Aplicacao's per-hint routing surface keys off — returns the
5458    /// author-declared `:placement :affinity` byte-string verbatim as
5459    /// an `Option<&str>`, borrowed from the typed slot's own
5460    /// `Option<String>` storage; `None` when the slot is absent (the
5461    /// canonical shape of an Aplicacao that leaves the compression
5462    /// weighting up to the placement engine's cluster-default arm — no
5463    /// author-authored `data-locality` / `low-latency` / etc. hint
5464    /// biases the routing).
5465    ///
5466    /// The `:placement :affinity` slot carries the M3 Adaptive-
5467    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
5468    /// by [`validate_placement_affinity`] to be a DNS-1123 label
5469    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
5470    /// K8s-conformant label-selector shape every apiserver-side pod-
5471    /// affinity / node-affinity materializer already gates on
5472    /// admission), and every downstream consumer that reads the hint
5473    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
5474    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
5475    /// `placement.affinity` overlay emit path the substrate operator's
5476    /// per-hint weighting-consumer reads, the future M4
5477    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
5478    /// pod-affinity / node-affinity selector resolver).
5479    ///
5480    /// Prior to this lift the `.affinity` field was accessed inline at
5481    /// the sole caixa-core site — the
5482    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
5483    /// `if let Some(a) = &self.placement.affinity { …
5484    /// validate_placement_affinity(a)? … }` cascade — one open-coded
5485    /// field-access that expressed no compile-time link back to the
5486    /// typed slot. A future extension of the `:placement :affinity`
5487    /// axis to a richer author surface — a per-cluster override the
5488    /// operator pins through a future `:placement :affinity-overrides`
5489    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
5490    /// tenant hint alias table the M4 CR materializer resolves per-CR,
5491    /// a per-Aplicacao dynamic `:affinity` derivation the future
5492    /// adaptive placement engine computes from `:clusters` topology —
5493    /// would have had to be threaded through the open-coded copy in
5494    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
5495    /// materializer reader that landed on the axis, or the per-hint
5496    /// value-shape gate and its downstream weighting consumers would
5497    /// silently disagree on which hint a given Placement resolves to.
5498    /// Lifting the resolution rule to a typed method on the substrate
5499    /// primitive means every downstream consumer of the Aplicacao's
5500    /// per-`:placement` compression-hint surface reaches for exactly
5501    /// one typed dispatch — the resolver's accept-set migrates as a
5502    /// unit on any future axis addition.
5503    ///
5504    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
5505    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
5506    /// optional-scalar axis — same "one typed dispatch on the substrate
5507    /// primitive, thin projections at each consumer" discipline extended
5508    /// onto the per-`:placement` M3-Adaptive-compression-hint
5509    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
5510    /// return accessor on the M3 mesh-slot family; closes the last
5511    /// un-lifted per-`:placement` `Option<String>` axis. Named
5512    /// `affinity()` to match the storage field's name; the accessor's
5513    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
5514    /// vocabulary the slot's docstring already carries.
5515    #[must_use]
5516    pub fn affinity(&self) -> Option<&str> {
5517        self.affinity.as_deref()
5518    }
5519
5520    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
5521    /// strategy scalar accessor every consumer that dispatches on the
5522    /// Aplicacao's per-cluster distribution shape keys off — returns the
5523    /// author-declared `:placement :estrategia` variant verbatim as a
5524    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
5525    /// `PlacementStrategy` storage.
5526    ///
5527    /// The `:placement :estrategia` slot carries the closed-set
5528    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
5529    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
5530    /// `Replicated` — active-active across every named cluster; `Sharded`
5531    /// — Akka-style hash-keyed entity distribution across the cluster pool
5532    /// per §II.4) that every downstream consumer of the Aplicacao's
5533    /// per-cluster fan-out shape keys off. Validated by
5534    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
5535    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
5536    /// matches!(estrategia, Sharded)` — the cross-slot partition the
5537    /// [`Placement::shard_key`] accessor's docstring pins), and every
5538    /// downstream consumer that reads the strategy keys off this scalar
5539    /// (the [`AplicacaoSpec::validate_placement`]
5540    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
5541    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
5542    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
5543    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5544    /// declared-but-inert refusal's
5545    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
5546    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
5547    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
5548    /// emit path the substrate operator's per-strategy fan-out reader
5549    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5550    /// materializer's per-strategy admission-webhook resolver).
5551    ///
5552    /// Prior to this lift the `.estrategia` field was accessed inline at
5553    /// four sites — the [`AplicacaoSpec::validate_placement`]
5554    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
5555    /// `estrategia: self.placement.estrategia`, the same method's
5556    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
5557    /// partition dispatch, the non-`Sharded`-arm
5558    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
5559    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
5560    /// per-Aplicacao strategy print line at
5561    /// `println!("… {} …", spec.placement.estrategia, …)`
5562    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
5563    /// expressed no compile-time link back to the typed slot. A future
5564    /// extension of the `:placement :estrategia` axis to a richer author
5565    /// surface (a per-cluster override the operator pins through a future
5566    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
5567    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
5568    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
5569    /// derivation the future adaptive placement engine computes from
5570    /// `:affinity` + `:clusters` topology) would have had to be threaded
5571    /// through every open-coded copy in lockstep — one consumer reading
5572    /// the raw variant while a peer read the operator-resolved variant
5573    /// would silently split the `PlacementWithoutClusters` /
5574    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
5575    /// partition-dispatch input, a two-consumer split at the validator
5576    /// far from the source `caixa.lisp` with no field naming the
5577    /// strategy-drift root cause. Lifting the resolution rule to a typed
5578    /// method on the substrate primitive means every downstream consumer
5579    /// of the Aplicacao's per-`:placement` distribution-strategy surface
5580    /// reaches for exactly one typed dispatch — the resolver's accept-set
5581    /// migrates as a unit on any future axis addition.
5582    ///
5583    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
5584    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
5585    /// same "one typed dispatch on the substrate primitive, thin
5586    /// projections at each consumer" discipline extended onto the
5587    /// per-`:placement` distribution-strategy `Copy`-composite-enum
5588    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
5589    /// family; first `Copy`-return accessor on the M3 mesh-slot
5590    /// `Placement` type — companion to the sibling per-`:placement`
5591    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5592    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
5593    /// optional-scalar axes, closing the last unlifted per-`:placement`
5594    /// scalar-value axis (the closed-set `PlacementStrategy`
5595    /// distribution-strategy discriminator) so every downstream
5596    /// per-`:placement` reader now routes through a typed dispatch on
5597    /// the substrate primitive. Named `estrategia()` to match the storage
5598    /// field's name; the accessor's identity name maps onto the
5599    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
5600    /// already carries. Declared `pub const fn` (matching the peer M3
5601    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5602    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5603    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5604    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5605    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5606    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5607    /// [`RateLimit`] — every one a `pub const fn`) so every future
5608    /// substrate-side `const`-context consumer of the resolved
5609    /// distribution-strategy variant (a `const _: () = assert!(…)`
5610    /// module-scope invariant pin on a per-fixture typed [`Placement`],
5611    /// a future M4 admission-webhook `const fn` resolver over a typed
5612    /// [`Placement`], any `const fn` composer that fans on the strategy
5613    /// at compile time) reaches through the same typed dispatch on the
5614    /// substrate primitive at const-eval time as at runtime. Pinned by
5615    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
5616    /// const-eval posture at module scope via `const _:() = …` items so
5617    /// any future accidental downgrade to non-`const` trips at caixa-core
5618    /// build time.
5619    #[must_use]
5620    pub const fn estrategia(&self) -> PlacementStrategy {
5621        self.estrategia
5622    }
5623
5624    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
5625    /// per-cluster distribution-target slice accessor every consumer that
5626    /// walks the Aplicacao's declared cluster-pool keys off — returns the
5627    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
5628    /// `&[String]` slice-view, borrowed from the typed slot's own
5629    /// `Vec<String>` storage (a zero-copy slice-view over the same
5630    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5631    /// through). Non-optional: the empty slice is the load-bearing
5632    /// pre-validation sentinel every downstream consumer of the paired
5633    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
5634    /// off — every strategy in the closed
5635    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
5636    /// requires a non-empty list (`SingleNode` / `Replicated` use the
5637    /// list as hosting / takeover candidates per Erlang/OTP distributed-
5638    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
5639    /// shard pool per Akka cluster-sharding convention, §II.4), so the
5640    /// `.is_empty()` probe is the shared pre-condition every
5641    /// [`AplicacaoSpec::validate_placement`] arm heads on.
5642    ///
5643    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
5644    /// 1123-label per-cluster distribution-target list — the same
5645    /// set-not-multiset shape the sibling `:membros :caixa` /
5646    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
5647    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
5648    /// pins the shape). Every downstream consumer that fans on the list
5649    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
5650    /// pre-flight `.is_empty()` probe that trips
5651    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
5652    /// per-cluster value-shape + duplicate-detection fan-out loop, the
5653    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
5654    /// that materializes the list verbatim onto every
5655    /// programs.yaml entry the substrate operator's per-cluster
5656    /// `placement.clusters | contains .Values.cluster` filter reads,
5657    /// the `feira app graph` per-Aplicacao cluster print line, the
5658    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5659    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
5660    /// placement engine's cluster-topology reader).
5661    ///
5662    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
5663    /// inline at three production sites — the
5664    /// [`AplicacaoSpec::validate_placement`] pre-flight
5665    /// `self.placement.clusters.is_empty()` refusal probe, the same
5666    /// method's per-cluster validate loop's
5667    /// `for c in &self.placement.clusters` traversal head, and the
5668    /// `feira app graph` per-Aplicacao print line's
5669    /// `spec.placement.clusters` `{:?}` formatter argument
5670    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
5671    /// that expressed no compile-time link back to the typed slot. A
5672    /// future extension of the `:placement :clusters` axis to a richer
5673    /// author surface (a per-tenant cluster-pool overlay the operator
5674    /// pins through a future `:placement :clusters-overrides` slot the
5675    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
5676    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
5677    /// the future M5 adaptive-placement engine computes from
5678    /// `:affinity` weights + live cluster-topology probes, a promotion
5679    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
5680    /// partition once the substrate operator's cluster-membership
5681    /// reconciler comes into typed scope) would have had to be threaded
5682    /// through all three open-coded copies in lockstep or one consumer
5683    /// would silently disagree with the peers on which cluster-pool a
5684    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
5685    /// reading the raw slot while the peer per-cluster validate loop
5686    /// read an operator-resolved slot would silently split the paired
5687    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
5688    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
5689    /// input from the pre-flight input, a three-consumer split at the
5690    /// validator and formatter far from the source `caixa.lisp` with
5691    /// no field naming the cluster-pool-drift root cause. Lifting the
5692    /// resolution rule to a typed method on the substrate primitive
5693    /// means every downstream consumer of the Aplicacao's
5694    /// per-`:placement` cluster-pool surface reaches for exactly one
5695    /// typed dispatch — the resolver's accept-set migrates as a unit
5696    /// on any future axis addition.
5697    ///
5698    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
5699    /// slot — sibling to the seed M2
5700    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
5701    /// slice-return accessor on the peer per-`:supervisor` static-
5702    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
5703    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
5704    /// primitive, thin projections at each consumer" discipline. The
5705    /// three peer `Vec`-carry axes still unlifted at the time of this
5706    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
5707    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
5708    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
5709    /// [`crate::UpgradeFromEntry::instructions`]
5710    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5711    /// — inherit this accessor's discipline as future compounding runs
5712    /// migrate their consumers onto the shared slice-return shape.
5713    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
5714    /// type, sibling to the two `Option<&str>`-return
5715    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5716    /// (74ec2d3) accessors and the `Copy`-return
5717    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
5718    /// unlifted per-`:placement` field axis (the `Vec<String>`
5719    /// distribution-target-list carrier) so every downstream
5720    /// per-`:placement` reader now routes through a typed dispatch on
5721    /// the substrate primitive. Named `clusters()` to match the storage
5722    /// field's name verbatim and the tatara-lisp author-surface term
5723    /// (`:clusters`) the field's own docstring already carries; the
5724    /// accessor's identity maps onto the canonical MESH-COMPOSITION
5725    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
5726    /// for. Returns `&[String]` (not `&Vec<String>`) because every
5727    /// downstream consumer of the cluster list treats it as a read-only
5728    /// sequence — the slice-view is the narrowest borrow that supports
5729    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
5730    /// `.len()`) without leaking the backing `Vec`'s
5731    /// grow/push/reserve surface that no consumer of the typed view
5732    /// reaches for (the storage-side `Vec` remains reachable through
5733    /// the `pub clusters` field for the mutation-carrying serde
5734    /// round-trip and per-test fixture-mutation paths).
5735    #[must_use]
5736    pub fn clusters(&self) -> &[String] {
5737        self.clusters.as_slice()
5738    }
5739}
5740
5741impl Default for Placement {
5742    fn default() -> Self {
5743        Self {
5744            // Route the struct-literal `estrategia` default arm through
5745            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
5746            // typed `pub const` rather than the transitively-derived
5747            // [`PlacementStrategy::default`] route — one source of truth
5748            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
5749            // active-active-across-every-named-cluster arm
5750            // (MESH-COMPOSITION §II.2) that both this struct-literal
5751            // altitude and the sibling [`Default for PlacementStrategy`]
5752            // impl already key off through the same substrate primitive.
5753            // Pinned by
5754            // `placement_default_estrategia_routes_through_lifted_default`.
5755            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
5756            clusters: Vec::new(),
5757            affinity: None,
5758            shard_key: None,
5759        }
5760    }
5761}
5762
5763// ── external entry point ─────────────────────────────────────────────
5764
5765/// External entry point — what an outside caller sees. Renders to a
5766/// Gateway / Ingress + a route to the named member Servico.
5767#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5768#[serde(rename_all = "camelCase")]
5769pub struct Entrada {
5770    /// Public hostname (e.g. `"checkout.quero.cloud"`).
5771    pub host: String,
5772
5773    /// Member Servico the gateway routes to. Must be in `:membros`.
5774    pub para: String,
5775
5776    /// Optional path filter — if set, only matching paths route to
5777    /// this Aplicacao (the rest fall through to other route rules).
5778    #[serde(default)]
5779    pub paths: Vec<String>,
5780
5781    /// Default port on the destination Servico (the trigger.service.port).
5782    #[serde(default = "default_port")]
5783    pub port: u16,
5784}
5785
5786impl Entrada {
5787    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
5788    /// every HTTPRoute-aware renderer keys off — returns the author-
5789    /// declared `:entrada :paths` list verbatim when non-empty, and the
5790    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
5791    /// all fallback otherwise (so an Aplicacao author who declares an
5792    /// external `:entrada` block but no per-path rule surface still
5793    /// gets a route whose sole `HTTPPathMatch` matches every incoming
5794    /// request under the paired
5795    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
5796    ///
5797    /// Prior to this lift the "if `:entrada :paths` is empty use the
5798    /// substrate catch-all; else return each declared path verbatim"
5799    /// cascade lived inline at
5800    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
5801    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
5802    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
5803    /// substrate ships today, with no typed method on the substrate
5804    /// primitive that named the rule. A future path-resolution axis
5805    /// addition — a per-cluster `:entrada :default-path` override the
5806    /// operator pins through a future `:placement`-scoped slot, an
5807    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5808    /// admission-webhook floor that materializes the catch-all before
5809    /// the CR lands, a future per-`:entrada :paths` overlay from a
5810    /// per-cluster policy the future `feira app deploy` pipeline
5811    /// consumes — would have to be threaded through every renderer's
5812    /// inline copy of the cascade in lockstep or one consumer would
5813    /// silently disagree with the peers on which path list a given
5814    /// `:entrada` block resolves to. Lifting the rule to a typed
5815    /// method on the substrate primitive means every downstream
5816    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
5817    /// per-cluster overlay resolver, every future per-Aplicacao
5818    /// snapshot renderer) reaches for exactly one typed dispatch —
5819    /// the resolver's accept-set moves as a unit on any future axis
5820    /// addition.
5821    ///
5822    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
5823    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
5824    /// per-`:entrada` scalar-value axes — extends the "one typed
5825    /// dispatch on the substrate primitive, thin projections at each
5826    /// consumer" discipline onto the per-`:entrada` path-list
5827    /// resolution axis every HTTPRoute-aware renderer consumes. Same
5828    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
5829    /// sibling `:politicas` primitive — one typed method on the
5830    /// substrate primitive that names the cascade every renderer
5831    /// otherwise re-inlines.
5832    #[must_use]
5833    pub fn resolved_paths(&self) -> Vec<&str> {
5834        // Route the internal cascade-head + per-entry projection reads
5835        // through the lifted [`Self::paths`] slice accessor rather than
5836        // the raw `self.paths` field access — the substrate-primitive
5837        // per-`:entrada` path-list resolver's two internal reads now
5838        // key off the canonical raw-slot surface every downstream
5839        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
5840        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
5841        // entrada summary line's `{:?}` Debug print) routes through, so
5842        // any future rebrand on the typed slot's raw-slot reader lands
5843        // at exactly one place. Same two-consumer coherence discipline
5844        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
5845        // the peer M3 mesh-slot `Vec<String>`-carry axis.
5846        if self.paths().is_empty() {
5847            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
5848        } else {
5849            self.paths().iter().map(String::as_str).collect()
5850        }
5851    }
5852
5853    /// Substrate-canonical per-`:entrada` DNS-hostname singular
5854    /// accessor every Gateway-API `Listener.hostname` reader keys off
5855    /// — returns the author-declared `:entrada :host` byte-string
5856    /// verbatim as a `&str`, borrowed from the typed slot's own
5857    /// [`String`] storage.
5858    ///
5859    /// Named the "singular" half of the DNS-hostname resolver pair on
5860    /// the substrate primitive: the parent-Gateway per-listener
5861    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
5862    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
5863    /// hostname per listener), and this accessor is the typed dispatch
5864    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
5865    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
5866    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
5867    /// per-Aplicacao ingress-hostname surface projects onto.
5868    ///
5869    /// Prior to this lift the `entrada.host.clone()` byte-string was
5870    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
5871    /// per-listener singular `hostname:` axis
5872    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
5873    /// per-HTTPRoute plural `spec.hostnames[]` axis
5874    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
5875    /// consumers read the same `entrada.host` field but the two-site
5876    /// duplication expressed no compile-time contract that the singular
5877    /// Gateway-listener filter and the plural `HTTPRoute` filter list
5878    /// stay in lockstep on future extensions of the `:entrada` slot to
5879    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
5880    /// overlay, a per-cluster SNI fan-out the operator pins through a
5881    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
5882    /// Aplicacao` CR materializer's per-listener virtual-host filter
5883    /// admission-webhook overlay). Any such extension would have to be
5884    /// threaded through every renderer's inline copy of the resolution
5885    /// in lockstep or the Gateway listener's `hostname:` filter would
5886    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
5887    /// — a Gateway-API-conformance divergence whose apply-time symptom
5888    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
5889    /// `NoMatchingParent` — the API server rejects the route because
5890    /// its `hostnames[]` filter doesn't intersect the parent listener's
5891    /// `hostname` filter) is far from the source `caixa.lisp` and never
5892    /// surfaces in the emitted YAML. Lifting the singular and plural
5893    /// resolvers to typed methods on the substrate primitive means
5894    /// every consumer of the Aplicacao's ingress-hostname surface
5895    /// reaches for exactly one typed dispatch, and the pair-invariant
5896    /// `hostnames() == vec![hostname()]` pinned by the sibling
5897    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
5898    /// keeps the two axes in lockstep by construction.
5899    ///
5900    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
5901    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
5902    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
5903    /// the substrate primitive, thin projections at each consumer"
5904    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5905    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5906    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5907    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
5908    /// `:entrada` scalar-value + list-value axes.
5909    #[must_use]
5910    pub const fn hostname(&self) -> &str {
5911        self.host.as_str()
5912    }
5913
5914    /// Substrate-canonical per-`:entrada` DNS-hostname plural
5915    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
5916    /// keys off — returns the singleton `[hostname()]` list under
5917    /// today's single-hostname-per-Aplicacao author surface, and the
5918    /// authoritative multi-hostname list under a future
5919    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
5920    ///
5921    /// Plural half of the DNS-hostname resolver pair — see the
5922    /// companion [`Entrada::hostname`] docstring for the two-consumer
5923    /// lift + pair-invariant discipline (`hostnames() ==
5924    /// vec![hostname()]`, pinned load-bearing by the sibling
5925    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
5926    /// test).
5927    ///
5928    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
5929    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
5930    /// per-rule path-list axis — same `Vec<&str>` shape, same
5931    /// substrate-primitive-owns-the-resolver discipline extended to
5932    /// the per-HTTPRoute virtual-host filter-list axis.
5933    #[must_use]
5934    pub fn hostnames(&self) -> Vec<&str> {
5935        vec![self.hostname()]
5936    }
5937
5938    /// Substrate-canonical per-`:entrada` destination-Servico scalar
5939    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
5940    /// the author-declared `:entrada :para` byte-string verbatim as a
5941    /// `&str`, borrowed from the typed slot's own [`String`] storage.
5942    ///
5943    /// The `:entrada :para` slot names the single member Servico the
5944    /// external Gateway routes to (validated by
5945    /// [`AplicacaoSpec::validate`] to be a
5946    /// [`Membro::caixa`] the Aplicacao declares — a stray
5947    /// `:para` that doesn't name a member is
5948    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
5949    /// backend-attachment miss at cluster-apply time). Under today's
5950    /// single-destination author surface `:entrada :para` is the ingress
5951    /// apex Servico's canonical identity; under a hypothetical
5952    /// future multi-backend author surface (a `:entrada
5953    /// :split :backends` weighted-fan-out overlay for canary /
5954    /// blue-green traffic-split rollouts, per-path override for
5955    /// path-based per-Servico routing beyond the single-apex model,
5956    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5957    /// per-CR admission-webhook that promotes the scalar to a
5958    /// weighted list) this accessor is the substrate primitive's typed
5959    /// dispatch every downstream `HTTPRoute`-aware consumer routes
5960    /// through, so the resolution shape migrates as a unit on one
5961    /// caixa-core edit rather than a coordinated rewrite across every
5962    /// renderer's inline field-access.
5963    ///
5964    /// Prior to this lift the `entrada.para` byte-string was accessed
5965    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
5966    /// `metadata.name` composer's per-destination discriminator arg
5967    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
5968    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
5969    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
5970    /// (`entrada.para.clone()`,
5971    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
5972    /// consumers read the same `entrada.para` field but the two-site
5973    /// duplication expressed no compile-time contract that the HTTPRoute
5974    /// name-discriminator and the per-rule backend name stay in
5975    /// lockstep on future extensions of the `:entrada` slot to a
5976    /// multi-destination author surface. Any such extension would have
5977    /// to be threaded through every renderer's inline copy of the
5978    /// destination projection in lockstep or the HTTPRoute
5979    /// `metadata.name` would silently reference a different destination
5980    /// than its own `backendRefs[]` — an operator-side
5981    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
5982    /// grep-by-name lookup would land on a route whose `backendRefs[]`
5983    /// silently point at a peer Servico, dropping every external
5984    /// `:entrada` flow at the gateway with the destination-drift root
5985    /// cause invisible in the emitted YAML.
5986    ///
5987    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
5988    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
5989    /// the per-listener singular / per-HTTPRoute plural filter axes and
5990    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
5991    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
5992    /// typed dispatch on the substrate primitive, thin projections at
5993    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5994    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5995    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5996    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
5997    /// sibling per-`:entrada` scalar-value + list-value axes — this
5998    /// accessor closes the last unlifted per-`:entrada` scalar axis
5999    /// (the destination-Servico byte-string) so every downstream
6000    /// per-`:entrada` reader now routes through a typed dispatch on
6001    /// the substrate primitive.
6002    #[must_use]
6003    pub const fn destination(&self) -> &str {
6004        self.para.as_str()
6005    }
6006
6007    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
6008    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
6009    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
6010    /// reader keys off — returns the author-declared `:entrada :port`
6011    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
6012    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
6013    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
6014    /// [`AplicacaoError::EntradaPortZero`], not a silent
6015    /// admission-webhook rejection at cluster-apply time).
6016    ///
6017    /// The `:entrada :port` slot carries the destination Servico's
6018    /// canonical in-cluster L4 listener port (`trigger.service.port` on
6019    /// the `pleme-computeunit` library chart), and every downstream
6020    /// consumer that reads the port keys off this scalar (the
6021    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
6022    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
6023    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
6024    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6025    /// CR materializer's per-Aplicacao gateway port resolver).
6026    ///
6027    /// Prior to this lift the `.port` field was accessed inline at two
6028    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
6029    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
6030    /// the [`AplicacaoSpec::port_for_destination`] resolver's
6031    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
6032    /// open-coded field-accesses that expressed no compile-time link
6033    /// back to the typed slot. A future extension of the `:entrada :port`
6034    /// axis to a richer author surface — a per-cluster override the
6035    /// operator pins through a future `:placement :default-port` slot the
6036    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
6037    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
6038    /// heterogeneous listener ports, an M4
6039    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6040    /// admission-webhook floor that promotes the scalar to a
6041    /// per-destination map — would have had to be threaded through both
6042    /// open-coded copies in lockstep or the structural-floor validator
6043    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
6044    /// silently disagree on which port a given [`Entrada`] resolves to.
6045    /// Lifting the resolution rule to a typed method on the substrate
6046    /// primitive means every downstream consumer of the Aplicacao's
6047    /// per-`:entrada` L4-port surface reaches for exactly one typed
6048    /// dispatch — the resolver's accept-set migrates as a unit on any
6049    /// future axis addition.
6050    ///
6051    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
6052    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
6053    /// accessors on the per-`:entrada` scalar-value axis — same "one
6054    /// typed dispatch on the substrate primitive, thin projections at
6055    /// each consumer" discipline extended onto the per-`:entrada`
6056    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
6057    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
6058    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
6059    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
6060    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
6061    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
6062    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
6063    /// storage field's name; the accessor's identity name maps onto the
6064    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
6065    /// already carries. Declared `pub const fn` (matching the peer M3
6066    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6067    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6068    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6069    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6070    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6071    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6072    /// [`RateLimit`], and the sibling per-`:placement`
6073    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
6074    /// enum scalar axis — every one a `pub const fn`) so every future
6075    /// substrate-side `const`-context consumer of the resolved
6076    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
6077    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
6078    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
6079    /// admission-webhook `const fn` per-CR gateway-port floor over a
6080    /// typed [`Entrada`], any `const fn` composer that fans on the port
6081    /// at compile time) reaches through the same typed dispatch on the
6082    /// substrate primitive at const-eval time as at runtime. Pinned by
6083    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
6084    /// const-eval posture at module scope via `const _:() = …` items so
6085    /// any future accidental downgrade to non-`const` trips at caixa-core
6086    /// build time.
6087    #[must_use]
6088    pub const fn port(&self) -> u16 {
6089        self.port
6090    }
6091
6092    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
6093    /// slice accessor every HTTPRoute-aware renderer keys off when it
6094    /// wants the raw author-declared path-list (not the fallback-
6095    /// applied projection [`Self::resolved_paths`] returns) — returns
6096    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
6097    /// borrowed from the typed slot's own [`Vec<String>`] storage.
6098    ///
6099    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
6100    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
6101    /// (1449891) closes the fallback-applying arm every per-Aplicacao
6102    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
6103    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
6104    /// catch-all; non-empty slot → per-entry verbatim projection); this
6105    /// accessor closes the raw-slot arm every consumer that must see the
6106    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
6107    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
6108    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
6109    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
6110    /// external-gateway summary line's `{:?}` Debug print — which must
6111    /// name the author's declaration, not the substrate's fallback, so
6112    /// an author reading their graph output can grep their caixa.lisp
6113    /// for the exact list they authored) routes through.
6114    ///
6115    /// Prior to this lift the `.paths` field was accessed inline at four
6116    /// production sites: the two internal reads in [`Self::resolved_paths`]
6117    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
6118    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
6119    /// value-shape gate's `for p in &e.paths` traversal head, and the
6120    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
6121    /// Debug print — four open-coded field-accesses that expressed no
6122    /// compile-time link back to the typed slot. A future extension of
6123    /// the `:entrada :paths` axis to a richer author surface — a
6124    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
6125    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
6126    /// spec supports through `matches[].method`), a per-path per-header
6127    /// filter overlay (`matches[].headers[]`), a per-cluster override
6128    /// the operator pins through a future `:placement :path-overlay`
6129    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6130    /// per-CR admission-webhook that normalized the list at admission
6131    /// time — would have had to be threaded through every open-coded
6132    /// copy in lockstep or the validator's per-entry gate would silently
6133    /// disagree with the renderer's per-entry emit on which list a given
6134    /// `:entrada` block resolves to. Lifting the resolution to a typed
6135    /// method on the substrate primitive means every downstream consumer
6136    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
6137    /// exactly one typed dispatch — the resolver's accept-set migrates
6138    /// as a unit on any future axis addition.
6139    ///
6140    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
6141    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
6142    /// carry axis — same "one typed dispatch on the substrate primitive,
6143    /// thin projections at each consumer" discipline extended onto the
6144    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
6145    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
6146    /// carrier) so every downstream per-`:entrada` reader now routes
6147    /// through a typed dispatch on the substrate primitive. Returns
6148    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
6149    /// treats the list as a read-only sequence — the slice-view is the
6150    /// narrowest borrow that supports every present + roadmapped consumer
6151    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
6152    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
6153    /// view reaches for (the storage-side `Vec` remains reachable through
6154    /// the `pub paths` field for the mutation-carrying serde round-trip
6155    /// and per-test fixture-mutation paths).
6156    #[must_use]
6157    pub fn paths(&self) -> &[String] {
6158        self.paths.as_slice()
6159    }
6160}
6161
6162/// Canonical default L4 port every typed Servico exposes on its
6163/// in-cluster K8s Service (the `trigger.service.port` axis the
6164/// `pleme-computeunit` library chart emits, the `:entrada :port` author
6165/// surface defaults to when the author omits the slot, and the
6166/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
6167/// `:entrada` block matches the per-`:contratos` destination Servico).
6168/// The single source of truth all three typed-port consumers reach for:
6169///
6170///   - [`Entrada::port`]'s serde default (via the
6171///     [`default_port`] helper this constant feeds); the author surface
6172///     `(:entrada (:host … :para …))` without an explicit `:port` slot
6173///     reads back as a typed [`Entrada`] carrying this exact value;
6174///   - the
6175///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
6176///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
6177///     fallback, fired when the typed `:entrada` block doesn't name
6178///     the per-`:contratos` destination Servico — the typed
6179///     `:contratos` graph carries no per-destination port axis (the
6180///     destination port is the destination Servico's
6181///     `lareira-<nome>` chart's `trigger.service.port`, which the
6182///     Aplicacao-level renderer has no visibility into without a
6183///     resolver round-trip), so the renderer falls back to the
6184///     substrate's canonical Servico-port assumption — by
6185///     construction the same value the destination's own
6186///     `pleme-computeunit` chart emits, the same value the
6187///     destination's own typed `:entrada :port` slot defaults to;
6188///   - every future per-Servico renderer the absorption-roadmap
6189///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6190///     CR materializer's per-edge port resolver, the future
6191///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
6192///     emitter's per-route bucket key, the future caixa-otel
6193///     collector-pipeline emitter's per-Servico scrape port).
6194///
6195/// Until this lift landed the value `8080` lived at two production-code
6196/// call-sites: the [`default_port`] helper at
6197/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
6198/// and the `.unwrap_or(8080)` literal at
6199/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
6200/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
6201/// resolver). A future Servico-port rebrand — the substrate moving the
6202/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
6203/// gateway grows direct `:80` listeners, to `8443` once the substrate
6204/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
6205/// override the operator pins through a future
6206/// `:placement :default-port` slot — without a coordinated edit on
6207/// both sides would silently emit Servicos listening on one port and
6208/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
6209/// The CNP's apply-time symptom (the policy is admitted but every L4
6210/// flow on the destination Servico's actual port silently drops because
6211/// it doesn't match the whitelisted port) is far from the rebrand
6212/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
6213/// in hubble traces, not in `kubectl describe`. Lifting the literal to
6214/// a shared constant closes the drift footgun structurally — both
6215/// consumers read from the same `u16`, so any rebrand reaches both
6216/// sites by construction.
6217///
6218/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
6219/// per-renderer canonical-K8s-axis constant — the namespace string
6220/// and the canonical Servico port both lived as duplicated literals
6221/// across caixa-core / caixa-mesh / caixa-flux before their respective
6222/// lifts. Same "the typed constant lives in one place" discipline the
6223/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
6224/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
6225/// shared-string axes.
6226///
6227/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
6228pub const DEFAULT_SERVICO_PORT: u16 = 8080;
6229
6230/// Structural floor for the typed `:entrada :port` axis — every
6231/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
6232/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
6233///
6234/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
6235/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
6236/// interprets as "let the kernel pick a free port at bind time", not a
6237/// well-defined destination the substrate's per-`:entrada` Gateway API
6238/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
6239/// carrying `port: 0` degenerates to a nominal-only routing target: the
6240/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
6241/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
6242/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
6243/// at build time rather than at `kubectl apply` time), and the
6244/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
6245/// (caixa-mesh/src/lib.rs:2657 through
6246/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
6247/// [`Entrada::port`] typed value — silently emits a policy whose
6248/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
6249/// actual listener, dropping every L4 flow at the eBPF data plane far
6250/// from the source caixa.lisp with no field naming the port-zero-drift
6251/// root cause.
6252///
6253/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
6254/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
6255/// on the top edge (unlike the peer capped-`u32` `:politicas` /
6256/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
6257/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
6258/// well below `u32::MAX` and therefore need explicit typed caps).
6259///
6260/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
6261/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
6262/// scalar every `(:entrada (:host … :para …))` slot without an explicit
6263/// `:port` inherits through the serde default hook; this constant names
6264/// the accept-set floor every declared port must satisfy. The pair is
6265/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
6266/// substrate's default must satisfy its own accept-set floor by
6267/// construction) — a future rebrand that accidentally moved
6268/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
6269/// negative-cast typo, a per-cluster override the operator pins through
6270/// a future `:placement :default-port` slot that lands out-of-range)
6271/// would silently invalidate the serde-default emission at every
6272/// author-side `(:entrada (:host … :para …))` slot — the compile-time
6273/// invariant pin
6274/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
6275/// closes the drift footgun at caixa-core build time.
6276///
6277/// Lifted as a typed `pub const` (rather than an inline `0` literal at
6278/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
6279/// has exactly one source of truth — the future M4
6280/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6281/// gateway resolver, the future per-Servico
6282/// `computeunit.trigger.service.port` renderer's per-CR port-value
6283/// validator, and every downstream test-fixture navigator asserting
6284/// the accept-set floor all read from one place. Same shape every
6285/// other typed bracket-floor / bracket-ceiling in this crate carries
6286/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6287/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6288/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6289/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6290/// [`POLICY_RATE_LIMIT_MAX`]).
6291pub const SERVICO_PORT_MIN: u16 = 1;
6292
6293const fn default_port() -> u16 {
6294    DEFAULT_SERVICO_PORT
6295}
6296
6297// ── the typed view ───────────────────────────────────────────────────
6298
6299/// Typed composition view of the flat Aplicacao slots on
6300/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6301/// validation + downstream renderer consumption.
6302#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6303#[serde(rename_all = "camelCase")]
6304pub struct AplicacaoSpec {
6305    pub membros: Vec<Membro>,
6306    pub contratos: Vec<WitContract>,
6307    pub politicas: MeshPolicy,
6308    pub placement: Placement,
6309    pub entrada: Option<Entrada>,
6310}
6311
6312impl AplicacaoSpec {
6313    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6314    /// per-Aplicacao member-list slice-return accessor every
6315    /// per-Aplicacao member-list reader keys off — returns the author-
6316    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6317    /// over the same backing buffer the raw `self.membros.as_slice()`
6318    /// field access borrows from.
6319    ///
6320    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6321    /// member list — the load-bearing identity of the application graph
6322    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
6323    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
6324    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
6325    /// accessor) with a `:versao` semver-requirement string (through
6326    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
6327    /// and every downstream consumer that fans on the member-set keys
6328    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
6329    /// membership-lookup `HashSet<&str>` seed's collect input, the
6330    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
6331    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
6332    /// per-member DNS-1123 / semver-requirement / duplicate-detection
6333    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
6334    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
6335    /// programs.yaml per-`:membros` fan-out emitter's per-entry
6336    /// mapping-composition loop, the `feira app graph` per-Aplicacao
6337    /// member-count print line and per-member tree traversal,
6338    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
6339    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
6340    /// placement engine's per-member weight-topology reader).
6341    ///
6342    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
6343    /// inline at six production sites — the [`AplicacaoSpec::validate`]
6344    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
6345    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
6346    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
6347    /// probe, the same method's per-member `for m in &self.membros`
6348    /// validate-loop traversal head, the
6349    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6350    /// `for m in &self.membros` adjacency-list seed, the
6351    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
6352    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
6353    /// paired with the peer `for m in &spec.membros` per-entry fan-out
6354    /// loop, and the `feira app graph` per-Aplicacao print line's
6355    /// `spec.membros.len()` count formatter argument paired with the
6356    /// peer `for m in &spec.membros` per-member tree traversal — six
6357    /// open-coded field-accesses that expressed no compile-time link
6358    /// back to the typed slot. A future extension of the `:membros`
6359    /// axis to a richer author surface (a per-cluster member-set
6360    /// overlay the operator pins through a future
6361    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
6362    /// roadmap acknowledges, a per-tenant member-alias table the M4
6363    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
6364    /// CR at admission time, a per-Aplicacao dynamic member-set
6365    /// derivation the future adaptive-placement engine computes from
6366    /// weighted membership topology, a promotion of the plain
6367    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
6368    /// Orleans-style virtual-actor dynamic-membership comes into typed
6369    /// scope) would have had to be threaded through all six open-coded
6370    /// copies in lockstep or one consumer would silently disagree with
6371    /// the peers on which member-set a given Aplicacao resolves to —
6372    /// the `HashSet<&str>` name-set seed reading the raw slot while
6373    /// the peer `.is_empty()` refusal probe read an operator-resolved
6374    /// slot would silently split the `:contratos` membership-lookup
6375    /// input from the pre-flight-refusal input, a six-consumer split
6376    /// at the validator + programs.yaml emitter + graph printer far
6377    /// from the source `caixa.lisp` with no field naming the member-
6378    /// set-drift root cause. Lifting the resolution rule to a typed
6379    /// method on the substrate primitive means every downstream
6380    /// consumer of the Aplicacao's per-`:membros` member-list surface
6381    /// reaches for exactly one typed dispatch — the resolver's accept-
6382    /// set migrates as a unit on any future axis addition.
6383    ///
6384    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
6385    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6386    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6387    /// static-child-list `Vec`-carry axis, and to the M3
6388    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6389    /// on the peer per-`:placement` distribution-target-list `Vec`-
6390    /// carry axis. Same "one typed dispatch on the substrate primitive,
6391    /// thin projections at each consumer" discipline. The two peer
6392    /// `Vec`-carry axes still unlifted at the time of this lift —
6393    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
6394    /// WIT-typed edge list) and
6395    /// [`crate::UpgradeFromEntry::instructions`]
6396    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6397    /// — inherit this accessor's discipline as future compounding runs
6398    /// migrate their consumers onto the shared slice-return shape.
6399    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
6400    /// `AplicacaoSpec` type itself, extending the discipline beyond
6401    /// the inner per-slot types ([`crate::Placement`],
6402    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
6403    /// view every renderer consumes. Named `membros()` to match the
6404    /// storage field's name verbatim and the tatara-lisp author-
6405    /// surface term (`:membros`) the field's own docstring already
6406    /// carries; the accessor's identity maps onto the canonical
6407    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
6408    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
6409    /// every downstream consumer of the member list treats it as a
6410    /// read-only sequence — the slice-view is the narrowest borrow
6411    /// that supports every present + roadmapped consumer
6412    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6413    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6414    /// the typed view reaches for (the storage-side `Vec` remains
6415    /// reachable through the `pub membros` field for the mutation-
6416    /// carrying serde round-trip and per-test fixture-mutation paths).
6417    #[must_use]
6418    pub fn membros(&self) -> &[Membro] {
6419        self.membros.as_slice()
6420    }
6421
6422    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
6423    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
6424    /// accessor every per-Aplicacao contract-list reader keys off —
6425    /// returns the author-declared `:contratos` list verbatim as a
6426    /// `&[WitContract]` slice-view over the same backing buffer the raw
6427    /// `self.contratos.as_slice()` field access borrows from.
6428    ///
6429    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
6430    /// WIT-typed edge list — the load-bearing set of directed edges
6431    /// on the application graph whose nodes are the `:membros` entries
6432    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
6433    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
6434    /// six-tuple is the edge identity every downstream duplicate gate
6435    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
6436    /// Servico caller name + a `:para` destination-Servico callee name
6437    /// (through the lifted [`WitContract::source`] +
6438    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
6439    /// caller/callee-Servico axis) with a `:wit` world-reference
6440    /// (through the lifted [`WitContract::world_ref`] (0804823)
6441    /// accessor) and the target-shape-appropriate payload-carrier
6442    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
6443    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
6444    /// (ed22b66) accessor on the per-target-shape payload-carrier
6445    /// axis). Every downstream consumer that fans on the edge-set
6446    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
6447    /// name-set / self-edge / target-shape / dedup fan-out loop, the
6448    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
6449    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
6450    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
6451    /// grouping loop, the `feira app graph` per-Aplicacao contract-
6452    /// count print line and per-contract tree traversal, every future
6453    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
6454    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
6455    /// mesh-policy overlay resolver's per-contract typed-edge weight
6456    /// reader).
6457    ///
6458    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
6459    /// accessed inline at four production sites — the
6460    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
6461    /// per-edge validate-loop traversal head (which drives every
6462    /// per-edge name-set membership lookup, self-edge check,
6463    /// target-shape dispatch, and dedup `HashSet` insert), the
6464    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6465    /// `for c in &self.contratos` adjacency-list seed head (which
6466    /// drives every per-edge sync-vs-pub-sub partition and per-edge
6467    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
6468    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
6469    /// `BTreeMap` grouping loop head (which drives every per-CNP
6470    /// fan-out emit), and the `feira app graph` per-Aplicacao print
6471    /// line's `spec.contratos.len()` count formatter argument paired
6472    /// with the peer `for c in &spec.contratos` per-contract tree
6473    /// traversal — four open-coded field-accesses that expressed no
6474    /// compile-time link back to the typed slot. A future extension
6475    /// of the `:contratos` axis to a richer author surface (a
6476    /// per-cluster contract overlay the operator pins through a
6477    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
6478    /// federation roadmap acknowledges, a per-tenant edge-policy
6479    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6480    /// materializer resolves per-CR at admission time, a per-edge
6481    /// weight scalar the future adaptive-placement engine reads to
6482    /// bias sync-subgraph routing, a promotion of the plain
6483    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
6484    /// once virtual-actor-style dynamic-edge composition comes into
6485    /// typed scope) would have had to be threaded through all four
6486    /// open-coded copies in lockstep or one consumer would silently
6487    /// disagree with the peers on which edge-set a given Aplicacao
6488    /// resolves to — the validator's per-edge dedup `HashSet` seed
6489    /// reading the raw slot while the peer sync-cycle adjacency-list
6490    /// seed read an operator-resolved slot would silently split the
6491    /// build-time edge-set gate from the runtime deadlock-detection
6492    /// gate, a four-consumer split at the validator, the cycle
6493    /// detector, the CNP emitter, and the graph printer far from
6494    /// the source `caixa.lisp` with no field naming the edge-set-
6495    /// drift root cause. Lifting the resolution rule to a typed method on the
6496    /// substrate primitive means every downstream consumer of the
6497    /// Aplicacao's per-`:contratos` edge-list surface reaches for
6498    /// exactly one typed dispatch — the resolver's accept-set
6499    /// migrates as a unit on any future axis addition.
6500    ///
6501    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
6502    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6503    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6504    /// static-child-list `Vec`-carry axis, to the M3
6505    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6506    /// on the peer per-`:placement` distribution-target-list `Vec`-
6507    /// carry axis, and to the immediately-adjacent sibling M3
6508    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
6509    /// the peer per-`:membros` node-list `Vec`-carry axis — the
6510    /// per-`:contratos` edge-list accessor is the natural pair of
6511    /// the per-`:membros` node-list accessor (graph edges over graph
6512    /// nodes; every graph-shaped consumer reads both). Same "one
6513    /// typed dispatch on the substrate primitive, thin projections
6514    /// at each consumer" discipline. The last remaining `Vec`-carry
6515    /// axis still unlifted at the time of this lift —
6516    /// [`crate::UpgradeFromEntry::instructions`]
6517    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
6518    /// list) — inherits this accessor's discipline as future
6519    /// compounding runs migrate its consumers onto the shared slice-
6520    /// return shape. Second `&[T]`-return accessor on the top-level
6521    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
6522    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
6523    /// `:contratos` are the two `Vec` fields on the outer typed
6524    /// composition view — `:politicas`, `:placement`, `:entrada` are
6525    /// scalar/option-shaped and already route through their per-slot
6526    /// accessor families). Named `contratos()` to match the storage
6527    /// field's name verbatim and the tatara-lisp author-surface term
6528    /// (`:contratos`) the field's own docstring already carries; the
6529    /// accessor's identity maps onto the canonical MESH-COMPOSITION
6530    /// §III.1 vocabulary the slot's docstring already reaches for.
6531    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
6532    /// every downstream consumer of the contract list treats it as a
6533    /// read-only sequence — the slice-view is the narrowest borrow
6534    /// that supports every present + roadmapped consumer
6535    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6536    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6537    /// the typed view reaches for (the storage-side `Vec` remains
6538    /// reachable through the `pub contratos` field for the mutation-
6539    /// carrying serde round-trip and per-test fixture-mutation paths).
6540    #[must_use]
6541    pub fn contratos(&self) -> &[WitContract] {
6542        self.contratos.as_slice()
6543    }
6544
6545    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
6546    /// per-Aplicacao mesh-policy composite-reference accessor every
6547    /// per-Aplicacao policy-block reader keys off — returns the author-
6548    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
6549    /// reference over the same backing storage the raw `&self.politicas`
6550    /// field access borrows from.
6551    ///
6552    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
6553    /// mesh-policy composite — the load-bearing container of every
6554    /// mesh-level operational-policy axis every downstream mesh-artifact
6555    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
6556    /// mesh-policy overlay is the single typed surface a
6557    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
6558    /// from). Every per-`:politicas` axis threads through a lifted
6559    /// per-slot accessor on the [`MeshPolicy`] type: the
6560    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
6561    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
6562    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
6563    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
6564    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
6565    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
6566    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
6567    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
6568    /// accessor. Every downstream consumer that reaches for a policy
6569    /// axis first passes through this outer accessor onto the composite
6570    /// and then dispatches onto the per-axis accessor — the two-level
6571    /// dispatch means every per-`:politicas` reader now routes through
6572    /// a typed dispatch on the substrate primitive at both altitudes.
6573    ///
6574    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
6575    /// accessed inline at four production sites — the
6576    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
6577    /// &self.politicas;` traversal seed (which drives every per-axis
6578    /// zero-floor + upper-cap + canonical-form bracket dispatch through
6579    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
6580    /// `p.rate_limit()` on the axis-level lifted accessors), the
6581    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
6582    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
6583    /// chain (which drives every per-`(:de, :para)` CNP
6584    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
6585    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
6586    /// timeout + retry overlay emitter's paired
6587    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
6588    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
6589    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
6590    /// open-coded outer-field accesses that expressed no compile-time
6591    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
6592    /// future extension of the `:politicas` outer axis to a richer
6593    /// author surface (a per-cluster policy overlay the operator pins
6594    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
6595    /// §V federation roadmap acknowledges, a per-tenant policy-alias
6596    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6597    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6598    /// policy-composite derivation the future adaptive-placement engine
6599    /// computes from a per-cluster load-topology reader, a promotion of
6600    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
6601    /// partition once virtual-actor-style dynamic-mesh-policy
6602    /// composition comes into typed scope) would have had to be threaded
6603    /// through all four open-coded copies in lockstep or one consumer
6604    /// would silently disagree with the peers on which mesh-policy
6605    /// composite a given Aplicacao resolves to — the validator's
6606    /// per-axis bracket-dispatch seed reading the raw slot while the
6607    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
6608    /// would silently split the build-time policy-shape gate from the
6609    /// runtime CNP-emission gate, a four-consumer split at the
6610    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
6611    /// the source `caixa.lisp` with no field naming the policy-drift
6612    /// root cause. Lifting the resolution rule to a typed method on the
6613    /// substrate primitive means every downstream consumer of the
6614    /// Aplicacao's per-`:politicas` mesh-policy composite surface
6615    /// reaches for exactly one typed dispatch — the resolver's accept-
6616    /// set migrates as a unit on any future axis addition.
6617    ///
6618    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
6619    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
6620    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6621    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
6622    /// close the two `Vec`-carry axes on the outer typed composition
6623    /// view; the outer `:politicas` composite-reference axis is the
6624    /// natural pair to the paired outer `Vec`-carry accessors on the
6625    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
6626    /// emitter reads all four axes as one unit (graph nodes + graph
6627    /// edges + mesh policy + placement pool). Peer to the same
6628    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
6629    /// slot: every M2 `SupervisorSpec`-scoped composite reader
6630    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
6631    /// `restart_window`, `children`) already routes through the M2
6632    /// `SupervisorSpec` accessor family — this lift extends the same
6633    /// "one typed dispatch on the substrate primitive at the outer
6634    /// composition altitude" discipline to the M3 mesh-slot
6635    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
6636    /// remaining peer outer-composite axes still unlifted at the time
6637    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
6638    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
6639    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
6640    /// inherit this accessor's discipline as future compounding runs
6641    /// migrate their consumers onto the shared reference-return shape.
6642    /// Named `politicas()` to match the storage field's name verbatim
6643    /// and the tatara-lisp author-surface term (`:politicas`) the
6644    /// field's own docstring already carries; the accessor's identity
6645    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
6646    /// slot's docstring already reaches for. Returns `&MeshPolicy`
6647    /// (not the owning composite by copy or clone) because every
6648    /// downstream consumer of the mesh-policy composite treats it as a
6649    /// read-only per-axis dispatch source — the reference-view is the
6650    /// narrowest borrow that supports every present + roadmapped
6651    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
6652    /// emptiness probe) without cloning the composite through every
6653    /// consumer's fast path.
6654    #[must_use]
6655    pub fn politicas(&self) -> &MeshPolicy {
6656        &self.politicas
6657    }
6658
6659    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
6660    /// per-Aplicacao distribution-composite composite-reference accessor
6661    /// every per-Aplicacao placement-block reader keys off — returns the
6662    /// author-declared `:placement` composite verbatim as a `&Placement`
6663    /// reference over the same backing storage the raw `&self.placement`
6664    /// field access borrows from.
6665    ///
6666    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
6667    /// distribution composite — the load-bearing container of every
6668    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
6669    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
6670    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
6671    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
6672    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
6673    /// `:affinity` hint). Every per-`:placement` axis threads through a
6674    /// lifted per-slot accessor on the [`Placement`] type: the
6675    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
6676    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
6677    /// per-cluster distribution-target slice-return accessor, the
6678    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
6679    /// optional-scalar accessor, and the [`Placement::shard_key`]
6680    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
6681    /// downstream consumer that reaches for a placement axis first passes
6682    /// through this outer accessor onto the composite and then dispatches
6683    /// onto the per-axis accessor — the two-level dispatch means every
6684    /// per-`:placement` reader now routes through a typed dispatch on the
6685    /// substrate primitive at both altitudes.
6686    ///
6687    /// Prior to this lift the `.placement` `Placement` composite was
6688    /// accessed inline at three production sites — the
6689    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
6690    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
6691    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
6692    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
6693    /// cluster `.clusters()` validate-loop traversal head, the per-
6694    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
6695    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
6696    /// paired with the shape-gate cascade's `.shard_key()` /
6697    /// `.estrategia()` diagnostic-carry pair), the
6698    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
6699    /// per-entry placement-block emitter's outer
6700    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
6701    /// seed (which fans onto every per-cluster `programs[]` entry as a
6702    /// self-describing distribution overlay the aggregator filters by),
6703    /// and the `feira app graph` per-Aplicacao print line's paired
6704    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
6705    /// then-inner-accessor chains (which drive the human-readable
6706    /// distribution summary of the typed Aplicacao view) — three open-
6707    /// coded outer-field accesses that expressed no compile-time link
6708    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
6709    /// extension of the `:placement` outer axis to a richer author surface
6710    /// (a per-cluster placement overlay the operator pins through a
6711    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
6712    /// federation roadmap acknowledges, a per-tenant placement-alias
6713    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6714    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6715    /// placement-composite derivation the future M5 adaptive-placement
6716    /// engine computes from a per-cluster load-topology reader, a
6717    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
6718    /// partition once Orleans-style virtual-actor dynamic-placement comes
6719    /// into typed scope) would have had to be threaded through all three
6720    /// open-coded copies in lockstep or one consumer would silently
6721    /// disagree with the peers on which placement composite a given
6722    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
6723    /// seed reading the raw slot while the peer
6724    /// `programs_for_aplicacao` emitter read an operator-resolved slot
6725    /// would silently split the build-time distribution-shape gate from
6726    /// the runtime programs.yaml distribution-annotation gate, a three-
6727    /// consumer split at the validator, the programs.yaml emitter, and
6728    /// the `feira app graph` printer far from the source `caixa.lisp`
6729    /// with no field naming the placement-drift root cause. Lifting the
6730    /// resolution rule to a typed method on the substrate primitive
6731    /// means every downstream consumer of the Aplicacao's per-
6732    /// `:placement` distribution composite surface reaches for exactly
6733    /// one typed dispatch — the resolver's accept-set migrates as a unit
6734    /// on any future axis addition.
6735    ///
6736    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
6737    /// `AplicacaoSpec` type itself — sibling to the seed
6738    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
6739    /// composite-reference accessor on the peer per-`:politicas` outer-
6740    /// composite axis, and to the paired slice-return accessors
6741    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6742    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
6743    /// the two `Vec`-carry axes on the outer typed composition view; the
6744    /// outer `:placement` composite-reference axis is the natural pair
6745    /// to the peer `:politicas` composite-reference axis on the two
6746    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
6747    /// how-to-run policy overlay, `:placement` carries the where-to-run
6748    /// distribution composite — every whole-Aplicacao mesh-artifact
6749    /// emitter reads both as one unit). Same "one typed dispatch on the
6750    /// substrate primitive, thin projections at each consumer"
6751    /// discipline the peer per-`:politicas` composite-reference axis
6752    /// already routes through. The one remaining outer-composite axis
6753    /// still unlifted at the time of this lift —
6754    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
6755    /// external-gateway composite) — inherits this accessor's discipline
6756    /// as the next compounding run migrates its consumers onto the shared
6757    /// reference-return shape, closing the outer-composite altitude on
6758    /// every M3 mesh-slot axis. Named `placement()` to match the storage
6759    /// field's name verbatim and the tatara-lisp author-surface term
6760    /// (`:placement`) the field's own docstring already carries; the
6761    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
6762    /// vocabulary the slot's docstring already reaches for. Returns
6763    /// `&Placement` (not the owning composite by copy or clone) because
6764    /// every downstream consumer of the placement composite treats it as
6765    /// a read-only per-axis dispatch source — the reference-view is the
6766    /// narrowest borrow that supports every present + roadmapped consumer
6767    /// (per-axis accessor dispatch, serde composite-serialization) without
6768    /// cloning the composite through every consumer's fast path.
6769    #[must_use]
6770    pub fn placement(&self) -> &Placement {
6771        &self.placement
6772    }
6773
6774    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
6775    /// per-Aplicacao external-gateway composite optional-composite-
6776    /// reference accessor every per-Aplicacao gateway-block reader
6777    /// keys off — returns the author-declared `:entrada` composite
6778    /// verbatim as an `Option<&Entrada>` reference over the same
6779    /// backing storage the raw `self.entrada.as_ref()` field access
6780    /// borrows from, with `None` naming the internal-only mesh shape
6781    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
6782    /// gateway_routes emitter treats as "emit nothing" and the peer
6783    /// `feira app graph` printer treats as "internal-only mesh").
6784    ///
6785    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
6786    /// external-gateway composite — the load-bearing container of
6787    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
6788    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
6789    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
6790    /// hostname axis, §III.4 for the `:para` destination-Servico
6791    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
6792    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
6793    /// axis threads through a lifted per-slot accessor on the
6794    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
6795    /// Gateway-API `Listener.hostname` scalar accessor, the paired
6796    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
6797    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
6798    /// backendRefs destination-Servico scalar accessor, the
6799    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
6800    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
6801    /// scalar accessor. Every downstream consumer that reaches for
6802    /// an entrada axis first passes through this outer accessor onto
6803    /// the composite and then dispatches onto the per-axis accessor
6804    /// — the two-level dispatch means every per-`:entrada` reader
6805    /// now routes through a typed dispatch on the substrate primitive
6806    /// at both altitudes.
6807    ///
6808    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
6809    /// was accessed inline at four production sites — the
6810    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
6811    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
6812    /// (which drives every per-axis refusal on the composite: the
6813    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
6814    /// `EntradaMemberMissing` membership lookup against the
6815    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
6816    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
6817    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
6818    /// per-path shape gate on each entry of `e.paths`), the
6819    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
6820    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
6821    /// composite-projection seed (which drives the destination-
6822    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
6823    /// backendRefs port emitter fans on), the
6824    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
6825    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
6826    /// early-return seed (which drives the "no `:entrada` ⇒ no
6827    /// external artifacts" partition on the whole-Aplicacao Gateway-
6828    /// API emitter's fan-out), and the `feira app graph` per-
6829    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
6830    /// external-gateway summary emitter (which drives the human-
6831    /// readable `entrada: host → para (paths=…, port=…)` /
6832    /// `entrada: (internal-only mesh)` partition on the typed
6833    /// Aplicacao view) — four open-coded outer-field accesses that
6834    /// expressed no compile-time link back to the typed slot at the
6835    /// [`AplicacaoSpec`] altitude. A future extension of the
6836    /// `:entrada` outer axis to a richer author surface (a
6837    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
6838    /// at admission time so an Aplicacao can expose a public-web +
6839    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
6840    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
6841    /// operator can pin a per-cluster hostname override without
6842    /// re-authoring the `caixa.lisp`, a promotion of the plain
6843    /// `Option<Entrada>` to a richer `{single, multi}` partition once
6844    /// the multi-`:entrada` roadmap lands) would have had to be
6845    /// threaded through all four open-coded copies in lockstep or one
6846    /// consumer would silently disagree with the peers on which
6847    /// entrada composite a given Aplicacao resolves to — the
6848    /// validator's per-axis bracket-dispatch seed reading the raw
6849    /// slot while the peer `gateway_routes` emitter read an
6850    /// operator-resolved slot would silently split the build-time
6851    /// gateway-shape gate from the runtime Gateway + HTTPRoute
6852    /// emission gate, a four-consumer split at the validator, the
6853    /// `port_for_destination` L4-port resolver, the `gateway_routes`
6854    /// emitter, and the `feira app graph` printer far from the
6855    /// source `caixa.lisp` with no field naming the entrada-drift
6856    /// root cause. Lifting the resolution rule to a typed method on
6857    /// the substrate primitive means every downstream consumer of
6858    /// the Aplicacao's per-`:entrada` external-gateway composite
6859    /// surface reaches for exactly one typed dispatch — the
6860    /// resolver's accept-set migrates as a unit on any future axis
6861    /// addition.
6862    ///
6863    /// Third and final `&Composite`-return accessor on the top-level
6864    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
6865    /// unlifted outer-composite axis on the outer typed composition
6866    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
6867    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
6868    /// accessor on the per-`:politicas` outer-composite axis and to
6869    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
6870    /// distribution-composite composite-reference accessor on the
6871    /// per-`:placement` outer-composite axis; extends the outer-
6872    /// composite reference-return discipline the two peers already
6873    /// route through onto the last unlifted per-`AplicacaoSpec`
6874    /// outer-composite axis. The `:entrada` outer-composite axis is
6875    /// the natural pair to the two peer outer-composite axes on the
6876    /// three operationally-symmetric M3 mesh-slot outer composites
6877    /// (`:politicas` carries the how-to-run policy overlay,
6878    /// `:placement` carries the where-to-run distribution composite,
6879    /// `:entrada` carries the who-can-reach-it external-gateway
6880    /// composite — every whole-Aplicacao mesh-artifact emitter reads
6881    /// all three as one unit). Same "one typed dispatch on the
6882    /// substrate primitive, thin projections at each consumer"
6883    /// discipline the peer outer-composite axes already route through.
6884    /// Named `entrada()` to match the storage field's name verbatim
6885    /// and the tatara-lisp author-surface term (`:entrada`) the
6886    /// field's own docstring already carries; the accessor's
6887    /// identity maps onto the canonical MESH-COMPOSITION §III.4
6888    /// vocabulary the slot's docstring already reaches for. Returns
6889    /// `Option<&Entrada>` (not the owning composite by copy or
6890    /// clone) because every downstream consumer of the entrada
6891    /// composite treats it as a read-only per-axis dispatch source
6892    /// — the reference-view is the narrowest borrow that supports
6893    /// every present + roadmapped consumer (per-axis accessor
6894    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
6895    /// port-fallback projection, early-return partition on the
6896    /// `None` arm) without cloning the composite through every
6897    /// consumer's fast path. The `Option` half of the return-type
6898    /// preserves the load-bearing "author-omitted `:entrada` ⇒
6899    /// internal-only mesh" partition (not a default composite the
6900    /// downstream must reject on emptiness) — the accessor projects
6901    /// the raw `Option<Entrada>` slot's presence bit through the
6902    /// reference-return unchanged.
6903    #[must_use]
6904    pub fn entrada(&self) -> Option<&Entrada> {
6905        self.entrada.as_ref()
6906    }
6907
6908    /// Validate the typed shape:
6909    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
6910    ///     and a non-empty `:versao`; no two entries share the same
6911    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
6912    ///     not a multiset)
6913    ///   - every `:contratos` :de + :para must be in `:membros`
6914    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
6915    ///     contract is an inter-Servico edge, so a Servico contracting
6916    ///     with itself is a build error under every WIT shape
6917    ///     (MESH-COMPOSITION §III.1)
6918    ///   - no two `:contratos` entries agree on
6919    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
6920    ///     edges are a set, not a multiset (peer of the `:membros` /
6921    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
6922    ///   - `:entrada :para` must be in `:membros`
6923    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
6924    ///     `:placement Replicated`/`SingleNode` must NOT declare
6925    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
6926    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
6927    ///     between strategy and shard-key is symmetric: every validated
6928    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
6929    ///     Sharded`
6930    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
6931    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
6932    ///     the shard pool (MESH-COMPOSITION §III.1)
6933    ///   - every `:clusters` entry is non-empty and unique
6934    ///   - `:placement :affinity`, when set, is non-empty
6935    ///   - the synchronous-`:contratos` subgraph is acyclic
6936    ///     (MESH-COMPOSITION §III.3)
6937    ///   - every declared `:politicas` value is operationally meaningful
6938    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
6939    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
6940    ///     omit the field instead to express "no policy on this axis")
6941    pub fn validate(&self) -> Result<(), AplicacaoError> {
6942        self.validate_membros()?;
6943        let names: std::collections::HashSet<&str> =
6944            self.membros().iter().map(Membro::nome).collect();
6945
6946        // Identity key for the typed-edge duplicate gate below: every
6947        // field that distinguishes one contract from another. Two
6948        // entries that agree on all six are *the same edge declared
6949        // twice*, the typed-graph analogue of duplicate `:membros` /
6950        // `:placement :clusters` / `:entrada :paths` entries (which
6951        // are already build errors at this layer). Rejecting it at the
6952        // validate gate closes a renderer-side footgun: caixa-mesh's
6953        // `cilium_network_policies` keys each emitted policy by
6954        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
6955        // (de, para) and identical payload would land as two K8s
6956        // objects with colliding `metadata.name`, rejected at apply
6957        // time far from the source caixa.lisp.
6958        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
6959            std::collections::HashSet::new();
6960        for c in self.contratos() {
6961            // Per-axis value-shape gate on every `:contratos` name
6962            // reference, before any graph-membership lookup. Empty +
6963            // DNS-1123-malformed `:de`/`:para` values silently fell
6964            // through to `ContratoMemberMissing` at the lookup arm
6965            // because every `:membros :caixa` is shape-validated
6966            // (3f9d7a0), so the `names` set structurally cannot contain
6967            // an empty / malformed string and the membership-lookup
6968            // diagnostic always misframed the root cause as
6969            // "this caixa is not in `:membros`". The shape gate runs
6970            // ahead of the lookup so structurally-impossible-to-match
6971            // inputs route through the narrower self-locating
6972            // diagnostic, preserving the legitimate "well-shaped
6973            // phantom reference" arm. `:de` runs before `:para` per
6974            // the canonical edge-direction order the existing
6975            // membership lookup, self-edge check, target dispatch,
6976            // and diagnostic strings already use.
6977            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
6978            // + the paired [`AplicacaoError::ContratoMemberMissing`]
6979            // diagnostic's `caixa:` carrier through the lifted
6980            // [`WitContract::source`] / [`WitContract::destination`]
6981            // scalar accessors rather than the raw `&c.de` / `&c.para`
6982            // `&String`-borrow arg site + the raw `c.de.clone()` /
6983            // `c.para.clone()` field-access `String`-carry sites — the
6984            // last unlifted per-`:contratos` raw-field-access sites in
6985            // the M3 mesh-slot validator's per-edge per-arm shape-gate
6986            // arg + phantom-name diagnostic wrap-envelope emit surface.
6987            // `c.source()` is byte-identical to `&c.de` (pinned by the
6988            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
6989            // + `wit_contract_source_borrows_from_de_storage` accessor
6990            // tests) and `c.destination()` is byte-identical to `&c.para`
6991            // (pinned by the sibling
6992            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
6993            // + `wit_contract_destination_borrows_from_para_storage`
6994            // accessor tests) — so a future rebrand of either underlying
6995            // storage flows through the accessor's one body without a
6996            // coordinated per-consumer rewrite across the M3 mesh
6997            // validator's per-edge shape-gate + phantom-name refusal
6998            // arms. Peer of the sibling per-`:contratos` self-loop
6999            // arm's `.source().to_string()` / `.world_ref().to_string()`
7000            // `String`-carry sites the earlier convergence lifted onto
7001            // the same accessor pair.
7002            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
7003            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
7004            if !names.contains(c.source()) {
7005                return Err(AplicacaoError::ContratoMemberMissing {
7006                    caixa: c.source().to_string(),
7007                });
7008            }
7009            if !names.contains(c.destination()) {
7010                return Err(AplicacaoError::ContratoMemberMissing {
7011                    caixa: c.destination().to_string(),
7012                });
7013            }
7014            // A `:contratos` entry is an *inter*-Servico contract
7015            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
7016            // typed edge between two distinct graph nodes. An edge whose
7017            // `:de` equals its `:para` is a Servico contracting with
7018            // itself — a degenerate edge under every WIT shape. The
7019            // synchronous shapes were caught only incidentally, and with
7020            // a misleading diagnostic: `detect_sync_cycles` reported
7021            // `cart → cart` as a `ContratoCycle` whose path is
7022            // `["cart", "cart"]` — framing a self-edge as a multi-node
7023            // deadlock. The pub-sub shape slipped through entirely
7024            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
7025            // `nats:pub-sub` edge from a member to itself silently
7026            // validated, then rendered a `CiliumNetworkPolicy` whose
7027            // endpointSelector and fromEndpoints both name the same
7028            // program — a self-allow rule that is a no-op, since
7029            // intra-pod traffic never traverses the mesh). A self-edge's
7030            // runtime meaning is an in-process call, which doesn't go
7031            // through the mesh at all, so no `:contratos` edge can carry
7032            // it. Firing the gate before the `:wit`/`target()` shape
7033            // checks means the structural "this edge can't exist" error
7034            // precedes the narrower payload-shape diagnostics, and shape-
7035            // agnostically covers all four `WitTarget` arms (HTTP / Store
7036            // / Capability / PubSub) at one point — closing the pub-sub
7037            // hole and replacing the misleading cycle diagnostic in one
7038            // gate. Peer of the duplicate-`:contratos` / duplicate-
7039            // `:membros` set gates: both reject a structurally
7040            // ill-formed graph at the typed surface, before the renderer
7041            // emits a K8s object that fails or no-ops far from the source
7042            // caixa.lisp.
7043            // Route the per-`:contratos` structural self-edge probe
7044            // through the lifted [`WitContract::is_self_loop`] typed
7045            // predicate rather than the raw `c.de == c.para` field-
7046            // equality check — the one production consumer of the per-
7047            // `:contratos` caller-equals-callee endpoint-equality axis
7048            // now keys off exactly one typed dispatch on the substrate
7049            // primitive, so any future rebrand of the axis (an M4-typed-
7050            // caller enum whose identity comparison rule the predicate
7051            // could route through, a per-cluster caller/callee-alias
7052            // table the M4 CR materializer resolves per-CR before the
7053            // equality probe) migrates as a single caixa-core edit
7054            // rather than a coordinated rewrite of the gate + every
7055            // downstream self-edge consumer. Peer of the sibling
7056            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
7057            // [`WitContract::is_store`] shape-predicate routing on the
7058            // `:wit` world-ref axis, extended onto the per-edge
7059            // endpoint-equality axis.
7060            //
7061            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
7062            // diagnostic's `caixa:` / `wit:` carriers through the
7063            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
7064            // scalar accessors rather than the raw `c.de.clone()` /
7065            // `c.wit.clone()` field-access `String`-carry sites — the
7066            // last unlifted per-`:contratos` raw-field-access
7067            // `.clone()` sites in the M3 mesh-slot validator's self-
7068            // edge refusal arm. `.source().to_string()` is byte-
7069            // identical to `.de.clone()` (pinned by the sibling
7070            // `source_returns_de_byte_equal_across_permutations` accessor
7071            // test), and `.world_ref().to_string()` is byte-identical
7072            // to `.wit.clone()` (pinned by the sibling
7073            // `world_ref_returns_wit_byte_equal_across_permutations`
7074            // accessor test) — so a future rebrand of either underlying
7075            // storage flows through the accessor's one body without a
7076            // coordinated per-consumer rewrite across the M3 mesh
7077            // validator.
7078            if c.is_self_loop() {
7079                return Err(AplicacaoError::ContratoSelfLoop {
7080                    caixa: c.source().to_string(),
7081                    wit: c.world_ref().to_string(),
7082                });
7083            }
7084            if c.world_ref().is_empty() {
7085                let (de, para) = c.edge_pair();
7086                return Err(AplicacaoError::EmptyWit { de, para });
7087            }
7088            // Shape ↔ target consistency — surfaces "HTTP wit without
7089            // :endpoint", "NATS wit with :endpoint set", etc. as named
7090            // build errors instead of silent renderer drops. Threaded
7091            // through the duplicate-edge diagnostic below (via
7092            // [`WitTarget::label`]) so the "which typed target arm did
7093            // the duplicate carry" question is answered by the typed
7094            // enum's variant discriminator, not by re-probing the raw
7095            // `Option<String>` payload fields.
7096            let target_view = c.target()?;
7097            // Contract identity: (de, para, wit, endpoint, subject, slot).
7098            // Two contracts that match on all six are the same typed edge
7099            // declared twice — author error, not a legitimate variant of
7100            // "same caller-callee pair, different payload" (e.g.
7101            // cart→catalog at /products vs /search), which keeps distinct
7102            // identity keys via the differing endpoint payloads.
7103            //
7104            // Route the six-axis dedup key through the lifted
7105            // [`WitContract::identity`] composite-projection accessor
7106            // rather than the inline six-tuple builder — the two
7107            // substrate primitives on the per-`:contratos` identity axis
7108            // (the [`ContratoIdentity`] type alias's six axes, this
7109            // dedup-key's six tuple arms) now migrate as a unit on any
7110            // future axis addition. Peer of the sibling per-`:contratos`
7111            // composite-projection [`WitContract::edge_pair`] /
7112            // [`WitContract::edge_triple`] accessors on the
7113            // caller-callee / caller-callee-wit prefix axes; extends
7114            // the discipline onto the full-identity axis that carries
7115            // the three payload-shape arms too.
7116            let key = c.identity();
7117            crate::render::insert_first_seen(&mut seen_contracts, key, || {
7118                // Route the per-`:contratos` duplicate-gate diagnostic's
7119                // `(de, para, wit)` triple through the lifted
7120                // [`WitContract::edge_triple`] typed accessor rather
7121                // than pairing `edge_pair()` for the `(de, para)` prefix
7122                // with a raw `c.wit.clone()` for the `wit:` tail — the
7123                // paired-with-raw-field-access shape was the last
7124                // per-`:contratos` diagnostic constructor bypassing the
7125                // substrate-primitive composite projection, sibling to
7126                // the eight [`AplicacaoError::Contrato*`] triple-
7127                // carrying constructors [`WitContract::target`]'s edge
7128                // closure feeds through the same accessor.
7129                let (de, para, wit) = c.edge_triple();
7130                AplicacaoError::ContratoDuplicate {
7131                    de,
7132                    para,
7133                    wit,
7134                    target: target_view.label(),
7135                }
7136            })?;
7137        }
7138
7139        // Cycles in the synchronous-edge subgraph are build errors
7140        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
7141        // are "acyclic by construction" because the publisher fires
7142        // and forgets, so no caller blocks on a downstream that loops
7143        // back to it.
7144        self.detect_sync_cycles()?;
7145
7146        if let Some(e) = self.entrada() {
7147            // Route the per-`:entrada` composite-reference read
7148            // through the lifted [`AplicacaoSpec::entrada`] accessor
7149            // rather than the raw `&self.entrada` field access — the
7150            // shape-and-membership gate's traversal head is now the
7151            // canonical read-side surface every per-Aplicacao entrada
7152            // consumer routes through, closing the fourth of four
7153            // open-coded outer-field accesses on the per-`:entrada`
7154            // outer-composite axis.
7155            //
7156            // Shape gate on `:entrada :para` runs ahead of the
7157            // membership lookup. Every `:membros :caixa` past
7158            // `validate_membro_caixa` is a valid DNS-1123 label
7159            // (3f9d7a0), so the `names` set structurally cannot
7160            // contain an empty / malformed string and the membership-
7161            // lookup diagnostic always misframed the root cause as
7162            // "this caixa is not in `:membros`". The shape gate
7163            // routes structurally-impossible-to-match inputs through
7164            // the narrower self-locating diagnostic, preserving the
7165            // legitimate "well-shaped phantom reference" arm — the
7166            // same trajectory the peer `:membros :caixa` (3f9d7a0),
7167            // `:placement :clusters` (6c8c00b), and `:contratos :de`
7168            // / `:para` (8d5af6b) axes already follow. This closes
7169            // the fourth and last Aplicacao-level Servico-name
7170            // reference axis on the canonical DNS-1123 floor.
7171            // Route the per-`:entrada :para` byte-string reads through
7172            // the lifted [`Entrada::destination`] accessor rather than
7173            // the raw `e.para` field access — the three
7174            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
7175            // (shape-gate `validate_entrada_para` arg, membership
7176            // lookup, `EntradaMemberMissing` diagnostic carry) now key
7177            // off exactly one typed dispatch on the substrate
7178            // primitive, closing the last unlifted per-`:entrada :para`
7179            // raw-field-access axis on the M3 mesh-slot validator.
7180            // The `.destination().to_string()` at the diagnostic site
7181            // is byte-identical to `.para.clone()` — pinned by the
7182            // sibling `destination_returns_entrada_para_byte_equal` +
7183            // `destination_borrows_from_entrada_para_storage` accessor
7184            // tests — so a future rebrand of the underlying `:para`
7185            // storage (a lift from `String` to a typed
7186            // `ServicoName(String)` newtype, a per-Aplicacao interning
7187            // arena the M4 CR materializer authors, a
7188            // `smol_str::SmolStr` inline-buffer swap) flows through
7189            // the accessor's one body without a coordinated
7190            // per-consumer rewrite across the M3 mesh validator.
7191            validate_entrada_para(e.destination())?;
7192            if !names.contains(e.destination()) {
7193                return Err(AplicacaoError::EntradaMemberMissing {
7194                    para: e.destination().to_string(),
7195                });
7196            }
7197            // Route the per-`:entrada :host` byte-string reads through
7198            // the lifted [`Entrada::hostname`] accessor rather than
7199            // the raw `e.host` field access — the emptiness gate and
7200            // the shape-gate `validate_entrada_host` arg now key off
7201            // exactly one typed dispatch on the substrate primitive,
7202            // closing the last unlifted per-`:entrada :host` raw-
7203            // field-access axis on the M3 mesh-slot validator. Peer
7204            // of the sibling per-`:entrada :para` convergence above
7205            // and pinned by the existing
7206            // `hostname_returns_entrada_host_byte_equal` +
7207            // `hostnames_returns_singleton_of_hostname_accessor`
7208            // accessor tests, so any future
7209            // Gateway-API-shaped host renormalization (a wildcard-
7210            // label lift, a trailing-`.` FQDN substitution, an IDNA
7211            // Punycode round-trip the SNI fan-out overlay authors)
7212            // flows through the accessor's one body without a
7213            // coordinated per-consumer rewrite across the M3 mesh
7214            // validator.
7215            if e.hostname().is_empty() {
7216                return Err(AplicacaoError::EmptyEntradaHost);
7217            }
7218            // The `:host` lands verbatim as a K8s Gateway API v1
7219            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
7220            // both apiserver-validated against the same restrictive
7221            // pattern: lowercase RFC 1123 DNS subdomain, optional
7222            // single leading wildcard label (`*.`), max length 253,
7223            // per-label max length 63, no IP literals, no scheme,
7224            // no port. Until this gate landed `validate()` only
7225            // refused the empty string (`EmptyEntradaHost`); a
7226            // structurally invalid hostname (`"https://example.com"`,
7227            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
7228            // `"_underscored.example.com"`, `"FOO.example.com"`,
7229            // `"checkout.quero.cloud."`) silently passed validate
7230            // and the apiserver `field is invalid` error surfaced at
7231            // `kubectl apply` time, far from the source caixa.lisp.
7232            // Lifting the gate to caixa-build time mirrors the
7233            // `:entrada :paths` value-shape trajectory (eb3456d) and
7234            // closes the last unstructured `:entrada` axis.
7235            validate_entrada_host(e.hostname())?;
7236            // Structural-floor gate on `:entrada :port`: every
7237            // validated `Entrada::port` past this gate lies in
7238            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
7239            // type-inferred ceiling closes the top edge, so no companion
7240            // upper-cap arm is needed here — unlike the peer capped-
7241            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
7242            // `require_positive_bounded_u32` bracket covers both edges).
7243            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
7244            // accept-set-floor const rather than the prior inline
7245            // `if e.port == 0` byte-check so a future rebrand of the
7246            // accept-set floor (a hypothetical unprivileged-only
7247            // migration lifting the floor to `1024`, a per-cluster
7248            // scoping the operator pins through a future
7249            // `:placement :port-floor` slot as the M4 typed-slot
7250            // trajectory adds it, the future
7251            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7252            // per-Aplicacao gateway resolver reaching for the same
7253            // floor) is a one-line edit on the canonical
7254            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
7255            // rewrite across the emit site + the pin test + every
7256            // future per-target renderer the substrate adds.
7257            if e.port() < SERVICO_PORT_MIN {
7258                return Err(AplicacaoError::EntradaPortZero);
7259            }
7260            // Each `:entrada :paths` entry becomes a K8s Gateway API
7261            // HTTPRoute `matches[].path.value`. The Gateway API rejects
7262            // values that don't start with `/` for `type: PathPrefix`,
7263            // and an empty value is meaningless. Surface those as build
7264            // errors (MESH-COMPOSITION §III.3) rather than apply-time
7265            // failures. Empty `:paths` itself is fine — caixa-mesh
7266            // falls back to a single `/` catch-all.
7267            let mut seen = std::collections::HashSet::new();
7268            // Route the per-entry value-shape gate's traversal head
7269            // through the lifted [`Entrada::paths`] slice accessor
7270            // rather than the raw `&e.paths` field access — the
7271            // per-Aplicacao `:entrada :paths` validate loop now keys
7272            // off the canonical raw-slot surface every downstream
7273            // per-`:entrada` path-list consumer (the sibling
7274            // [`Entrada::resolved_paths`] fallback-applying resolver
7275            // internal reads, `feira app graph`'s per-Aplicacao entrada
7276            // summary line's `{:?}` Debug print) routes through, so any
7277            // future rebrand on the typed slot's raw-slot reader lands
7278            // at exactly one place. Same convergence discipline as the
7279            // sibling [`Placement::clusters`] (a6e18d7) reader-site
7280            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
7281            // axis.
7282            for p in e.paths() {
7283                if p.is_empty() {
7284                    return Err(AplicacaoError::EntradaPathEmpty);
7285                }
7286                if !p.starts_with('/') {
7287                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
7288                }
7289                // Per-entry value-shape gate: the path lands verbatim
7290                // as a K8s Gateway API HTTPRoute `matches[].path.value`
7291                // (caixa-mesh/src/lib.rs:498), apiserver-validated
7292                // against `maxLength: 1024` + the Gateway API webhook's
7293                // path-grammar rules (no `//`, no `/./`, no `/../`, no
7294                // query/fragment separators, no whitespace, no control
7295                // characters, no non-ASCII bytes). Until this gate
7296                // landed `validate` only refused the empty string and
7297                // missing-leading-slash (eb3456d); a structurally
7298                // invalid path (`"/api?q=1"`, `"/api#frag"`,
7299                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
7300                // 1025-byte URL-shaped slug) silently passed validate
7301                // and the failure surfaced at `kubectl apply` time as
7302                // a Gateway API webhook rejection, far from the source
7303                // caixa.lisp, with no field naming the offending
7304                // `:paths` entry. Lifting the gate to caixa-build time
7305                // mirrors the `:entrada :host` value-shape trajectory
7306                // (c7d05ec) on the sibling axis — every author surface
7307                // that emits a Gateway API field now matches the
7308                // apiserver's accepted set at validate time.
7309                validate_entrada_path(p)?;
7310                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
7311                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
7312                })?;
7313            }
7314        }
7315
7316        self.validate_placement()?;
7317
7318        self.validate_politicas()?;
7319
7320        Ok(())
7321    }
7322
7323    /// Reject `:membros` values that are operationally meaningless. The
7324    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
7325    /// every entry names a Servico that participates in the Aplicacao,
7326    /// and the rendered programs.yaml fan-out emits one entry per
7327    /// `:membros`. Three authoring footguns are closed here:
7328    ///
7329    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
7330    ///     a `programs:` entry whose `name:` is the empty string, which
7331    ///     downstream `lareira-fleet-programs` rejects at template time
7332    ///     with a non-localized error;
7333    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
7334    ///     an empty semver constraint, so the failure surfaces far from
7335    ///     the source caixa.lisp;
7336    ///   - duplicate `:caixa` names — two entries with the same name
7337    ///     produce duplicate programs.yaml entries (one silently
7338    ///     overwrites the other in the cluster's HelmRelease values), and
7339    ///     contract membership lookups against `:contratos` collapse the
7340    ///     two onto one node, masking authoring mistakes.
7341    ///
7342    /// Same value-shape discipline as `:placement :clusters` (where empty
7343    /// + duplicate cluster names are rejected) and `:entrada :paths`
7344    /// (where empty + duplicate path entries are rejected). Lifting these
7345    /// invariants to the typed surface mirrors the MESH-COMPOSITION
7346    /// §III.3 promise that the `:membros` set — the load-bearing identity
7347    /// of the application graph — is well-formed by construction.
7348    fn validate_membros(&self) -> Result<(), AplicacaoError> {
7349        if self.membros().is_empty() {
7350            return Err(AplicacaoError::NoMembros);
7351        }
7352        let mut seen = std::collections::HashSet::new();
7353        for m in self.membros() {
7354            // Route the `MembroCaixaEmpty` refusal-arm's per-member
7355            // empty-`:caixa` shape-gate through the typed
7356            // [`Membro::nome`] accessor rather than the raw `.caixa`
7357            // field access — the last un-lifted `.caixa` production-
7358            // code read site on the per-`:membros` member-caixa `:nome`
7359            // axis, sibling to the six caixa-core validator read sites
7360            // (member-set collector, per-member value-shape gate,
7361            // duplicate dedup key, cycle-detector adjacency-map seed,
7362            // self-loop gate) the 4a32abf lift already routed through
7363            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
7364            // per-`programs[]` entry-`name:` `String`-carry converge.
7365            // Prior to this converge the `MembroCaixaEmpty` refusal
7366            // arm was the solitary consumer bypassing the typed
7367            // dispatch — the same-loop iteration's very next call
7368            // `validate_membro_caixa(m.nome())` already routed through
7369            // the accessor, so an author landing an empty-`:caixa`
7370            // entry hit the accessor on the shape-gate line but
7371            // bypassed it on the emptiness line one line above. A
7372            // future extension of the `:membros :caixa` axis to a
7373            // richer author surface (a per-cluster alias table pinned
7374            // through a future `:placement`-scoped slot, a namespace-
7375            // qualified rewrite the M4 CR materializer applies per-CR,
7376            // a per-member overlay from the future `:membros
7377            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
7378            // that lands on the accessor would silently disagree
7379            // between the emptiness gate and every peer consumer —
7380            // an author-declared `:caixa "checkout"` value the
7381            // accessor rewrote to `""` under a future alias arm would
7382            // pass the raw `.is_empty()` gate here while the peer
7383            // `validate_membro_caixa(m.nome())` call one line below
7384            // (and every downstream emit-side consumer routing through
7385            // the accessor) tripped on the empty-value shape far from
7386            // this diagnostic. Pinned by the drift-detection test
7387            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
7388            // below.
7389            if m.nome().is_empty() {
7390                return Err(AplicacaoError::MembroCaixaEmpty);
7391            }
7392            // Every emitted cluster artifact's `metadata.name` derives
7393            // from a `:membros :caixa` value verbatim — the rendered
7394            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
7395            // the [`crate::LABEL_PROGRAM`] label value on every CNP
7396            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
7397            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
7398            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
7399            // `metadata.name` when the member is the `:entrada :para`
7400            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
7401            // schema enforces the DNS-1123 label rule on admission;
7402            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
7403            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
7404            // mistaken-identity slug) silently passes the prior empty-/
7405            // duplicate-only gate and the failure surfaces at `kubectl
7406            // apply` time as a `metadata.name: Invalid value` rejection,
7407            // far from the source caixa.lisp, with no field naming the
7408            // offending `:membros` entry. Lifting the gate to caixa-build
7409            // time mirrors the `:entrada :host` value-shape trajectory
7410            // (c7d05ec) on the peer axis — every author surface that
7411            // emits a K8s name now matches the apiserver's accepted set
7412            // at validate time.
7413            validate_membro_caixa(m.nome())?;
7414            // The author surface for `:versao` is the same Cargo-shaped
7415            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
7416            // `"*"`) every `:deps` entry carries — and the lacre pipeline
7417            // resolves both axes through the same
7418            // [`crate::version::parse_requirement`] entry-point. The
7419            // shared [`crate::render::require_valid_versao_requirement`]
7420            // helper brackets the empty-first + parse cascade both peer
7421            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
7422            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
7423            // route through, so drift between the three axes' accepted
7424            // requirement sets is structurally impossible and the parse-
7425            // side no-op the empty-first arm closes (semver's empty
7426            // parse yields an implicit `*`) lives in exactly one
7427            // predicate.
7428            crate::render::require_valid_versao_requirement(
7429                m.versao_requirement(),
7430                || AplicacaoError::MembroVersaoEmpty {
7431                    caixa: m.nome().to_string(),
7432                },
7433                |reason| AplicacaoError::MembroVersaoInvalid {
7434                    caixa: m.nome().to_string(),
7435                    versao: m.versao_requirement().to_string(),
7436                    reason,
7437                },
7438            )?;
7439            crate::render::insert_first_seen(&mut seen, m.nome(), || {
7440                AplicacaoError::MembroDuplicate {
7441                    caixa: m.nome().to_string(),
7442                }
7443            })?;
7444        }
7445        Ok(())
7446    }
7447
7448    /// Reject `:placement` values that are operationally meaningless or
7449    /// internally contradictory. Each strategy variant has the same
7450    /// invariants on `:clusters` (non-empty list, non-empty unique
7451    /// entries) — the §III.1 author surface is uniform on this axis,
7452    /// even though the *meaning* of the list differs by strategy
7453    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
7454    /// shard pool).
7455    ///
7456    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
7457    /// are the same authoring footgun closed for `:politicas` zero
7458    /// values and `:entrada` empty paths: the field is *declared* but
7459    /// carries no meaning, so downstream renderers either skip it
7460    /// silently (cluster-fanout drops the empty entry, no diagnostic)
7461    /// or apply it literally and fail at admission time. Lifting both
7462    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
7463    /// violation is a build error" promise.
7464    ///
7465    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
7466    /// is required exactly when `:estrategia Sharded` (hash-keyed
7467    /// distribution, Akka cluster-sharding convention, §II.4) and
7468    /// refused on `:estrategia Replicated`/`SingleNode` (where no
7469    /// hash-keyed routing axis consumes it). The partition closes the
7470    /// "I think I configured sharding" footgun where an author writes
7471    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
7472    /// the typed slot's value silently vanishes at the renderer layer
7473    /// — every validated `Placement` past this call satisfies
7474    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
7475    fn validate_placement(&self) -> Result<(), AplicacaoError> {
7476        // Every strategy needs at least one named cluster: `Replicated`
7477        // and `SingleNode` use the list as hosting/takeover candidates
7478        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
7479        // §II.1), while `Sharded` uses it as the shard pool
7480        // (Akka cluster-sharding convention — §II.4). An empty list is
7481        // meaningless under any of the three.
7482        //
7483        // Route the paired pre-flight `.is_empty()` refusal probe and
7484        // the per-cluster validate loop's traversal head through the
7485        // lifted [`Placement::clusters`] slice-return accessor rather
7486        // than the raw `self.placement.clusters` field access — the
7487        // two production consumers of the per-`:placement` cluster-
7488        // pool `Vec`-carry now key off exactly one typed dispatch on
7489        // the substrate primitive, so any future rebrand on the axis
7490        // (a per-tenant cluster-pool overlay the operator pins through
7491        // a future `:placement :clusters-overrides` slot, a per-
7492        // Aplicacao dynamic cluster-pool derivation the future M5
7493        // adaptive-placement engine computes from `:affinity` weights)
7494        // migrates as a single caixa-core edit rather than a
7495        // coordinated rewrite of the paired arms — sibling of the
7496        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
7497        // arm migration on the per-`:supervisor` static-child-list
7498        // `Vec`-carry axis.
7499        //
7500        // Route the per-`:placement` outer-composite reference read
7501        // through the lifted [`AplicacaoSpec::placement`] outer accessor
7502        // rather than the raw `&self.placement` field access — the
7503        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
7504        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
7505        // axis-level lifted accessor family) now routes through the
7506        // substrate-primitive typed dispatch at the outer composition
7507        // altitude, the same shape the peer caixa-mesh
7508        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
7509        // and the sibling `feira app graph` per-Aplicacao print line
7510        // now key off after this accessor lift.
7511        let p = self.placement();
7512        if p.clusters().is_empty() {
7513            return Err(AplicacaoError::PlacementWithoutClusters {
7514                estrategia: p.estrategia(),
7515            });
7516        }
7517        let mut seen = std::collections::HashSet::new();
7518        for c in p.clusters() {
7519            // Per-entry value-shape gate: the cluster name lands in
7520            // every K8s context / `lareira-fleet-programs` aggregator
7521            // filter / future M4 CR materializer's per-cluster axis
7522            // a validated `:clusters` entry passes through, each
7523            // enforcing the DNS-1123 label rule on admission. Same
7524            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
7525            // on the peer name axis — both axes' validated values
7526            // are guaranteed-accepted by the apiserver without
7527            // re-validation at any downstream renderer or admission
7528            // layer.
7529            validate_placement_cluster(c)?;
7530            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
7531                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
7532            })?;
7533        }
7534        // Route the per-`:placement :affinity` per-hint value-shape
7535        // gate through the typed [`Placement::affinity`] accessor rather
7536        // than the raw `&self.placement.affinity` field access — the
7537        // sole open-coded field-access site on the per-`:placement`
7538        // M3-Adaptive-compression-hint axis the accessor lift now owns.
7539        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
7540        // the accessor's `Option<&str>` return type;
7541        // [`validate_placement_affinity`]'s `&str` parameter accepts
7542        // the narrower borrow without a re-allocation, so the routing
7543        // change is byte-for-byte in the pass arm and remains
7544        // byte-for-byte in every failure diagnostic
7545        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
7546        // String` field is populated inside
7547        // [`validate_placement_affinity`] via the peer `.to_string()`
7548        // path on the same borrowed slice). Peer of the sibling
7549        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
7550        // routing through [`Placement::shard_key`] at the caixa-core
7551        // site above — extends the "read `:placement` optional-scalars
7552        // through the typed accessor" discipline to the second
7553        // `Option<String>`-shape slot on the M3 mesh-slot family.
7554        //
7555        // Per-hint value-shape gate: the `:affinity` value lands
7556        // verbatim in the M3 Adaptive compression overlay
7557        // (caixa-mesh's `placement.affinity` emission) and every
7558        // future M4 placement-engine routing axis keying off the
7559        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
7560        // selector — each enforces the DNS-1123 label rule on
7561        // admission. Same typed-shape trajectory as `:placement
7562        // :clusters` (6c8c00b) on the sibling slot and the four
7563        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
7564        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
7565        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
7566        // on the Aplicacao surface to land on the canonical
7567        // [`crate::render::is_dns_1123_label`] floor.
7568        if let Some(a) = p.affinity() {
7569            validate_placement_affinity(a)?;
7570        }
7571        match p.estrategia() {
7572            // Route the `Sharded`-arm shape-gate cascade through the
7573            // typed [`Placement::shard_key`] accessor rather than the
7574            // raw `&self.placement.shard_key` field access — one of the
7575            // two open-coded field-access sites on the per-`:placement`
7576            // Akka-cluster-sharding-key axis the accessor lift now
7577            // owns. The `Some(k)`-bound `k` narrows from `&String` to
7578            // `&str` under the accessor's `Option<&str>` return type;
7579            // `str::is_empty` and [`validate_placement_shard_key`]'s
7580            // `&str` parameter both accept the narrower borrow without
7581            // a re-allocation.
7582            PlacementStrategy::Sharded => match p.shard_key() {
7583                None => return Err(AplicacaoError::ShardedWithoutKey),
7584                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
7585                // Per-axis value-shape gate on the Akka-cluster-sharding
7586                // `:shard-key` extractor expression. The shape gate runs
7587                // after the more self-locating `ShardedKeyEmpty` arm so
7588                // a `:shard-key ""` surfaces the narrower empty
7589                // diagnostic first; every non-empty `:shard-key` past
7590                // this call is guaranteed to be a printable-ASCII
7591                // single-token reference the future M4 Akka-style
7592                // cluster-sharding reconciler can hash without
7593                // re-validating at the runtime layer. Mirrors the
7594                // payload-axis shape gates on the peer `:contratos`
7595                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
7596                // 63e18a0 / c4213a4) — each lifts the runtime parser's
7597                // intersection-floor to a caixa-build-time gate.
7598                Some(k) => validate_placement_shard_key(k)?,
7599            },
7600            // `:shard-key` is the Akka-cluster-sharding axis
7601            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
7602            // across the cluster pool. `Replicated` (active-active across
7603            // every named cluster) and `SingleNode` (Erlang/OTP
7604            // distributed-app takeover/failover, §II.1) have no hash-keyed
7605            // routing axis to consume the slot; downstream renderers
7606            // (caixa-mesh's `placement.shardKey` overlay at
7607            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
7608            // sharding reconciler) ignore `:shard-key` outside the
7609            // `Sharded` arm by construction. Until this gate landed an
7610            // author who wrote `:placement (:estrategia Replicated
7611            // :shard-key "tenantId")` (an off-by-one strategy typo, a
7612            // copy-paste from a Sharded sibling caixa, the "I think I
7613            // configured sharding" footgun) silently passed validate and
7614            // the typed slot's value vanished at the renderer layer with
7615            // no diagnostic — the canonical "declared-but-inert" footgun
7616            // the empty-:affinity / empty-shard-key / zero-:politicas /
7617            // empty-:contratos-target gates already close on every other
7618            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
7619            // Lifting the rejection to a build-time gate closes the
7620            // Sharded ↔ non-Sharded partition over the typed
7621            // `:placement` slot: every validated `Placement` past this
7622            // call has `shard_key.is_some()` iff `estrategia ==
7623            // Sharded`, structurally — the future Akka reconciler can
7624            // reach for `placement.shard_key` knowing it's `Some` exactly
7625            // when the strategy consumes it, without re-deriving the
7626            // partition from inline strategy probes.
7627            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
7628                // Route the non-`Sharded`-arm declared-but-inert refusal
7629                // through the typed [`Placement::shard_key`] accessor —
7630                // the second of the two open-coded field-access sites the
7631                // accessor lift now owns. The `Some(k)`-bound `k` narrows
7632                // from `&String` to `&str`; the `AplicacaoError::
7633                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
7634                // materializes the owned `String` via `k.to_string()`
7635                // (peer to the sibling per-Membro `String`-carry sites
7636                // 4127bb6 routed through `m.nome().to_string()` /
7637                // `m.versao_requirement().to_string()`), so the whole
7638                // `Sharded` ↔ non-`Sharded` partition on the
7639                // `:shard-key` axis now flows through the same typed
7640                // dispatch as the sibling `Sharded`-arm shape gate.
7641                if let Some(k) = p.shard_key() {
7642                    return Err(AplicacaoError::ShardKeyOnNonSharded {
7643                        estrategia: p.estrategia(),
7644                        shard_key: k.to_string(),
7645                    });
7646                }
7647            }
7648        }
7649        Ok(())
7650    }
7651
7652    /// Reject `:politicas` values that are operationally meaningless.
7653    /// Each axis is optional — omitting it expresses "no policy on this
7654    /// axis". Carrying a *zero* value for a declared axis is the bug
7655    /// this function rejects: zero is either
7656    ///
7657    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
7658    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
7659    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
7660    ///     "every Aplicacao declares :politicas :timeout (no infinite
7661    ///     blocking)", or
7662    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
7663    ///     first call; a 0-rate rate-limit denies every request).
7664    ///
7665    /// Lifting these "0 means the opposite of what you think" idioms to
7666    /// the typed Aplicacao surface as build errors mirrors the §III.3
7667    /// promise that contract drift, capability leaks, and cycles are all
7668    /// build errors — not runtime surprises.
7669    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
7670        // Route the per-`:politicas` composite-reference read through
7671        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
7672        // than the raw `&self.politicas` field access — the per-axis
7673        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
7674        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
7675        // the substrate-primitive typed dispatch at the outer
7676        // composition altitude AND at every per-axis altitude, matching
7677        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
7678        // timeout/retry-overlay emitters that already key off the same
7679        // per-axis accessor family. The four-axis fan-out is now
7680        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
7681        // `p.retries` field-access sites (co-resident with the peer
7682        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
7683        // b0e741a / 21a6c3b already lifted) now route through
7684        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
7685        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
7686        // access axis on the M3 mesh-slot family.
7687        let p = self.politicas();
7688        if let Some(t) = p.timeout() {
7689            // Zero-floor + integer-millisecond canonical-form +
7690            // upper-cap bracket on the typed `:timeout` axis. See
7691            // [`crate::render::require_positive_canonical_bounded_duration`]
7692            // for the full three-arm ordering discipline (zero-floor
7693            // strictly precedes the canonical-form arm so
7694            // `Duration::ZERO` surfaces the self-locating
7695            // `PolicyTimeoutZero` diagnostic naming the omit-axis
7696            // remediation; canonical-form strictly precedes the cap
7697            // arm so a sub-millisecond above-cap `Duration` surfaces
7698            // the more fundamental round-trip-shape diagnostic first)
7699            // and the four peer typed-`Duration` sites that now share
7700            // this canonical bracket. Every validated value lies in
7701            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
7702            // granularity — the same top-and-bottom-edge discipline
7703            // [`POLICY_RETRIES_MAX`] and
7704            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
7705            // capped-`u32` `:politicas` axes.
7706            crate::render::require_positive_canonical_bounded_duration(
7707                t,
7708                POLICY_TIMEOUT_MAX,
7709                || AplicacaoError::PolicyTimeoutZero,
7710                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
7711                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
7712            )?;
7713        }
7714        if let Some(r) = p.retries() {
7715            // Zero-floor + upper-cap bracket on the typed `:retries`
7716            // axis. See [`crate::render::require_positive_bounded_u32`]
7717            // for the ordering discipline (zero-floor arm strictly
7718            // precedes cap arm so `Some(0)` surfaces the self-locating
7719            // `PolicyRetriesZero` diagnostic with its omit-axis
7720            // remediation directly named, not the misleading
7721            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
7722            // this bracket landed the top edge ran all the way to
7723            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
7724            // Some(100_000), .. }` (or the equivalent author-surface
7725            // `(:retries 100000)` / `(:retries 4294967295)` typo
7726            // landing in the slot) silently passed validate. The
7727            // runtime substrate consuming the value (Envoy's
7728            // `retry_policy.num_retries`, the future
7729            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7730            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7731            // policy into a thundering-herd amplification vector —
7732            // the caller's one request fans out to `retries`
7733            // server-side calls per edge per traversal, multiplying
7734            // load by `(retries+1)^depth` across the
7735            // synchronous-`:contratos` subgraph at the precise moment
7736            // the substrate is already failing (transient failure is
7737            // the trigger), exactly the failure mode AWS App Mesh's
7738            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
7739            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
7740            // the sibling capped-`u32` `:politicas` axes
7741            // (`max_failures`, `rate_limit.rate`) and the peer capped-
7742            // `u32` axes in `:supervisor :max-restarts` +
7743            // `:limits :cpu`; all five now route through the same
7744            // canonical bracket helper.
7745            crate::render::require_positive_bounded_u32(
7746                r,
7747                POLICY_RETRIES_MAX,
7748                || AplicacaoError::PolicyRetriesZero,
7749                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
7750            )?;
7751        }
7752        if let Some(cb) = p.circuit_breaker() {
7753            // Zero-floor + upper-cap bracket on the typed
7754            // `:max-failures` axis. See
7755            // [`crate::render::require_positive_bounded_u32`] for the
7756            // ordering discipline (zero-floor arm strictly precedes
7757            // cap arm so `max_failures == 0` surfaces the
7758            // self-locating `PolicyBreakerZeroFailures` diagnostic
7759            // with its omit-axis remediation directly named, not the
7760            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
7761            // false` cap-arm miss). Until this bracket landed the top
7762            // edge ran all the way to `u32::MAX` and a struct-literal
7763            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
7764            // equivalent author-surface `(:max-failures 100000)` /
7765            // `(:max-failures 4294967295)` typo landing in the slot)
7766            // silently passed validate. The runtime substrate
7767            // consuming the value (Envoy's
7768            // `outlier_detection.consecutive_5xx`, the future
7769            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7770            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7771            // breaker policy into a no-op — the trip threshold is
7772            // structurally so high that no realistic
7773            // failures-per-`:window` traffic shape can reach it, the
7774            // breaker never trips, and every typed-slot consumer
7775            // emits an Envoy / Cilium L7 overlay carrying a
7776            // protection that is structurally never enforced. The
7777            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
7778            // peer with `retries` and `rate_limit.rate` on the same
7779            // helper.
7780            crate::render::require_positive_bounded_u32(
7781                cb.max_failures(),
7782                POLICY_BREAKER_MAX_FAILURES_MAX,
7783                || AplicacaoError::PolicyBreakerZeroFailures,
7784                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
7785            )?;
7786            // Zero-floor + integer-millisecond canonical-form +
7787            // upper-cap bracket on the typed `:window` axis. See
7788            // [`crate::render::require_positive_canonical_bounded_duration`]
7789            // for the full three-arm ordering discipline (peer to the
7790            // `:timeout` site immediately above); every validated
7791            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
7792            // (1ms..=1h), integer-millisecond granularity — the same
7793            // top-and-bottom-edge discipline
7794            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
7795            // duration-typed `:politicas :timeout` axis.
7796            crate::render::require_positive_canonical_bounded_duration(
7797                cb.window(),
7798                POLICY_BREAKER_WINDOW_MAX,
7799                || AplicacaoError::PolicyBreakerZeroWindow,
7800                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
7801                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
7802            )?;
7803        }
7804        if let Some(rl) = p.rate_limit() {
7805            // Zero-floor + upper-cap bracket on the typed
7806            // `:rate-limit` rate axis. See
7807            // [`crate::render::require_positive_bounded_u32`] for the
7808            // ordering discipline (zero-floor arm strictly precedes
7809            // cap arm so `rl.rate == 0` surfaces the self-locating
7810            // `PolicyRateLimitZero` diagnostic with its omit-axis
7811            // remediation directly named, not the misleading
7812            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
7813            // Until this bracket landed the top edge ran all the way
7814            // to `u32::MAX` and a struct-literal
7815            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
7816            // author-surface `(:rate-limit "4294967295/s")` /
7817            // `(:rate-limit "100000000/m")` typo landing in the slot)
7818            // silently passed validate. The runtime substrate
7819            // consuming the value (Envoy's
7820            // `local_rate_limit.token_bucket.max_tokens`, the future
7821            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7822            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7823            // rate-limit policy into a no-op limiter: the bucket
7824            // capacity is structurally so high that no realistic
7825            // per-edge traffic shape can drain it, the limiter never
7826            // trips, and every typed-slot consumer emits a "rate
7827            // declared" L7 overlay carrying enforcement that is
7828            // structurally never reached — the canonical
7829            // declared-but-inert footgun the sibling
7830            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
7831            // the peer no-op-breaker shape. The bracket set is
7832            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
7833            // `max_failures` on the same helper. The rate bracket
7834            // strictly precedes the window-canonical gate so a
7835            // structurally absurd rate magnitude surfaces the more
7836            // fundamental amplification-shape diagnostic before the
7837            // narrower codec-round-trip-shape diagnostic on `:window`.
7838            crate::render::require_positive_bounded_u32(
7839                rl.rate(),
7840                POLICY_RATE_LIMIT_MAX,
7841                || AplicacaoError::PolicyRateLimitZero,
7842                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
7843            )?;
7844            // The `:rate-limit` author surface is the canonical
7845            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
7846            // accepts exactly the three-unit set (1s/60s/3600s) the
7847            // [`rate_limit_codec::render`] formatter emits the canonical
7848            // unit suffix for. A `RateLimit` whose `:window` is anything
7849            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
7850            // programmatically (struct literals in Rust + the typed
7851            // `Duration` field) but renders to a `<n>/<k>s` fragment
7852            // (the codec's fall-through) the parser then rejects on
7853            // round-trip — silently breaking the THEORY.md §V.2.7
7854            // render-determinism contract for any consumer that
7855            // serializes-then-deserializes the typed slot. Lifting the
7856            // canonical-window invariant to a build-time gate at
7857            // `validate_politicas` makes the codec's round-trip property
7858            // a structural property of the validated typed value:
7859            // every `RateLimit` past `AplicacaoSpec::validate` has a
7860            // window the codec round-trips losslessly, so the next
7861            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
7862            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
7863            // §III.2 #3) reaches for `rate_limit.window` knowing the
7864            // value is in the codec's accepted set without re-validating
7865            // at the renderer layer. Same trajectory as c4213a4 (typed
7866            // WitContract endpoint/subject/slot value-shape gates) and
7867            // the b0c8389 :behavior + :upgrade-from script-path lifts:
7868            // the typed slot's valid set matches its codec's accepted
7869            // set, structurally.
7870            // Route the canonical-window shape-gate through the substrate
7871            // primitive [`RateLimit::canonical_unit`] rather than the free
7872            // module-private [`is_canonical_rate_limit_window`] predicate:
7873            // both projections resolve `Duration → Option<RateLimitUnit>`
7874            // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
7875            // arm on the closed-set typed enum), but the accessor is the
7876            // typed method every downstream consumer of the validated slot
7877            // ([`rate_limit_codec::render`]'s canonical arm above, the
7878            // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7879            // per-`:politicas :rate-limit` admission webhook, the future
7880            // per-`:contratos`-edge rate-limit-override overlay
7881            // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
7882            // production consumers of the canonical-unit axis (the codec
7883            // render and this validate gate) now key off exactly one typed
7884            // dispatch on the substrate primitive, so any future extension
7885            // to `canonical_unit` (a per-cluster canonical-window overlay
7886            // the operator pins through a future `:contratos :rate-limit
7887            // -unit-overrides` slot, a per-tenant unit-alias table the M4
7888            // CR materializer resolves per-CR) reaches both consumers by
7889            // construction rather than a coordinated rewrite of every
7890            // free-helper call site.
7891            if rl.canonical_unit().is_none() {
7892                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
7893                    window: rl.window(),
7894                });
7895            }
7896        }
7897        Ok(())
7898    }
7899
7900    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
7901    /// A synchronous edge is any contract whose typed [`WitTarget`] is
7902    /// `Http`, `Store`, or `Capability` — the caller blocks on the
7903    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
7904    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
7905    /// block on its subscribers, so they can never close a sync loop.
7906    ///
7907    /// Iterative DFS with three-coloring; the reported cycle is the
7908    /// path of caixa names traversed from the back-edge target around
7909    /// to itself, in declaration order. Adjacency lists and DFS roots
7910    /// are visited in `BTreeMap` key order so the diagnostic is
7911    /// deterministic across runs.
7912    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
7913        use std::collections::{BTreeMap, BTreeSet};
7914
7915        #[derive(Clone, Copy, PartialEq, Eq)]
7916        enum Mark {
7917            White,
7918            Gray,
7919            Black,
7920        }
7921
7922        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
7923        for m in self.membros() {
7924            adj.entry(m.nome()).or_default();
7925        }
7926        for c in self.contratos() {
7927            // target() was already called by validate(); re-running here
7928            // keeps detect_sync_cycles self-contained for callers that
7929            // reuse it (M4 per-edge policy resolver) without revalidating.
7930            //
7931            // The pub-sub-arm check routes through the lifted
7932            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
7933            // arm-discriminator predicate rather than a raw `matches!(…,
7934            // WitTarget::PubSub { .. })` on the variant so a future
7935            // rebrand on the axis (an M4 per-edge WIT registry split of
7936            // [`WitTarget::PubSub`] into shape-specific peers, a
7937            // per-consumer rename that the accept-set already carries)
7938            // reaches this call site through the derive rather than a
7939            // scattered per-arm `matches!` rewrite — same
7940            // `IsVariant`-derived-arm-discriminator discipline the
7941            // peer closed-set typed enums ([`crate::CaixaKind`] via
7942            // f5bba80, [`PlacementStrategy`] via 766ec63,
7943            // [`crate::supervisor::RestartStrategy`] +
7944            // [`crate::supervisor::RestartPolicy`],
7945            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
7946            // already route through on the substrate's other typed-enum
7947            // arm-discriminator axes.
7948            if c.target()?.is_pubsub() {
7949                continue;
7950            }
7951            adj.entry(c.source()).or_default().insert(c.destination());
7952        }
7953
7954        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
7955        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
7956
7957        // Stable DFS root order — BTreeMap iteration is sorted by key.
7958        let roots: Vec<&str> = adj.keys().copied().collect();
7959
7960        // Frame: (node, sorted-neighbours snapshot, next-edge index).
7961        for root in roots {
7962            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
7963                continue;
7964            }
7965            let root_neighbors: Vec<&str> = adj
7966                .get(root)
7967                .map(|s| s.iter().copied().collect())
7968                .unwrap_or_default();
7969            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
7970            color.insert(root, Mark::Gray);
7971
7972            loop {
7973                // Read+advance the top frame in one borrow scope so we
7974                // can later mutate the stack (push/pop) without holding
7975                // a borrow across.
7976                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
7977                    let node = top.0;
7978                    if top.2 >= top.1.len() {
7979                        (node, None)
7980                    } else {
7981                        let nxt = top.1[top.2];
7982                        top.2 += 1;
7983                        (node, Some(nxt))
7984                    }
7985                });
7986                let Some((node, nxt_opt)) = step else { break };
7987                let Some(nxt) = nxt_opt else {
7988                    color.insert(node, Mark::Black);
7989                    stack.pop();
7990                    continue;
7991                };
7992                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
7993                match nxt_color {
7994                    Mark::Gray => {
7995                        // Reconstruct the cycle from `node` back through
7996                        // the parent chain to `nxt`, then close.
7997                        let mut cycle = Vec::new();
7998                        let mut cur = node;
7999                        cycle.push(cur.to_string());
8000                        while cur != nxt {
8001                            match parent.get(cur).copied() {
8002                                Some(p) => {
8003                                    cur = p;
8004                                    cycle.push(cur.to_string());
8005                                }
8006                                None => break,
8007                            }
8008                        }
8009                        cycle.reverse();
8010                        cycle.push(nxt.to_string());
8011                        return Err(AplicacaoError::ContratoCycle { cycle });
8012                    }
8013                    Mark::White => {
8014                        parent.insert(nxt, node);
8015                        color.insert(nxt, Mark::Gray);
8016                        let nxt_neighbors: Vec<&str> = adj
8017                            .get(nxt)
8018                            .map(|s| s.iter().copied().collect())
8019                            .unwrap_or_default();
8020                        stack.push((nxt, nxt_neighbors, 0));
8021                    }
8022                    Mark::Black => {}
8023                }
8024            }
8025        }
8026        Ok(())
8027    }
8028
8029    /// Substrate-canonical destination-facing TCP port every emitted
8030    /// per-Aplicacao artifact must key `destination`-shaped port axes
8031    /// off. Returns the typed `:entrada :port` scalar when this
8032    /// Aplicacao's `:entrada` block names `destination` under its
8033    /// `:para` axis (the destination Servico *is* the ingress apex, so
8034    /// the substrate honors the author-declared listener port
8035    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8036    /// fallback otherwise (every non-apex destination — the internal
8037    /// mesh Servicos `:contratos` reach across, the future per-edge
8038    /// policy resolver's per-destination probe targets, the
8039    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8040    /// L4 port resolver — reads the same substrate-canonical port floor
8041    /// by construction).
8042    ///
8043    /// Prior to this lift the "if :entrada matches this destination use
8044    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8045    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8046    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8047    /// prior to this lift), with no typed method on the substrate primitive
8048    /// that named the rule. A future per-destination port axis addition
8049    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8050    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8051    /// per-Servico listener ports land, a per-cluster override the operator
8052    /// pins through a future `:placement :default-port` slot — would have
8053    /// to be threaded through every renderer's inline cascade in lockstep
8054    /// or one consumer would silently disagree on which port a given
8055    /// destination Servico's ingress lands at. Lifting the rule to a
8056    /// typed method on the substrate primitive means the M4 CR
8057    /// materializer, the future per-edge policy resolver, and every
8058    /// downstream test-fixture navigator reach for exactly one typed
8059    /// dispatch — the resolver's accept-set moves as a unit on any
8060    /// future axis addition.
8061    ///
8062    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8063    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8064    /// the typed primitive, thin projections at each consumer"
8065    /// discipline lifts on the sibling `:contratos` payload / `:politicas
8066    /// :rate-limit` unit-suffix axes; extends the discipline onto the
8067    /// destination-facing port-resolution axis every per-Aplicacao
8068    /// L4-fallback renderer consumes.
8069    #[must_use]
8070    pub fn port_for_destination(&self, destination: &str) -> u16 {
8071        // Route the per-`:entrada` composite-reference read through
8072        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8073        // the raw `self.entrada.as_ref()` field access — the
8074        // per-destination L4-port fallback resolver's composite-
8075        // projection seed is now the canonical read-side surface
8076        // every per-Aplicacao entrada consumer routes through, peer
8077        // of the sibling `validate` per-`:entrada` shape-and-
8078        // membership gate migration on the same outer-composite
8079        // axis.
8080        // Route the per-`:entrada` apex-destination membership probe
8081        // through the lifted [`Entrada::destination`] accessor rather
8082        // than the raw `e.para == destination` field access — the last
8083        // un-lifted `.para` production-code read site on the per-
8084        // `:entrada` `:para` axis, sibling to the four caixa-core
8085        // consumer sites the peer 15ddd8c converge already routed
8086        // through the accessor (the three
8087        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8088        // membership gate sites: the `validate_entrada_para` DNS-1123
8089        // shape gate, the per-`:membros` membership lookup, and the
8090        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8091        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8092        // `entrada.para`-projection converge at
8093        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8094        // route-name projection site). Prior to this converge the
8095        // `port_for_destination` resolver was the solitary consumer
8096        // bypassing the typed dispatch on the `.para` axis — the two
8097        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8098        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8099        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8100        // reach through the same accessor family compose with this
8101        // resolver at the emit boundary via the apex-identity
8102        // invariant `spec.port_for_destination(entrada.destination())
8103        // == entrada.port` the sibling
8104        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8105        // pin pins across four permutations. A future extension of the
8106        // `:entrada :para` axis to a richer author surface (a per-
8107        // cluster alias overlay the operator pins through a future
8108        // `:placement`-scoped slot, a namespace-qualified rewrite the
8109        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8110        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8111        // §III.2 acknowledges) that lands on the accessor would silently
8112        // disagree between this resolver and the two `caixa-mesh` emit
8113        // sites — an author-declared `:para "cart"` value the accessor
8114        // rewrote to `"cart-v2"` under a future canary arm would leave
8115        // the resolver's membership arm falling through to
8116        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8117        // `.para`) while the peer emit-site consumers landed on the
8118        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8119        // silently disagreed on which destination port a given typed
8120        // `:entrada` resolves to at cluster-apply time. Pinned by the
8121        // drift-detection test
8122        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8123        // below.
8124        self.entrada()
8125            .filter(|e| e.destination() == destination)
8126            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8127    }
8128}
8129
8130/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8131/// entry may name the Aplicacao's own `:nome`.
8132///
8133/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8134/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8135/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8136/// Servicos that compose the app; an Aplicacao is never its own constituent),
8137/// and the lacre pipeline's closure-resolution would otherwise be handed a
8138/// node that is its own parent: a one-node cycle it either rejects far from
8139/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8140/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8141/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8142/// label + lacre closure root), a member whose `:caixa` equals the
8143/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8144/// peer.
8145///
8146/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8147/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8148/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8149/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8150/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8151/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8152/// (the Aplicacao :membros set; the supervision-tree :children list was the
8153/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8154/// every validated Supervisor's children are distinct from its `:nome`,
8155/// every validated Aplicacao's membros are distinct from its `:nome`. The
8156/// transitive consequence is that `:entrada :para` and `:contratos`
8157/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8158/// name the Aplicacao itself, without re-deriving the partition.
8159pub fn validate_no_self_membership(
8160    membros: &[Membro],
8161    parent_nome: &str,
8162) -> Result<(), AplicacaoError> {
8163    for m in membros {
8164        if m.nome() == parent_nome {
8165            return Err(AplicacaoError::MembroIsSelfAplicacao {
8166                caixa: parent_nome.to_string(),
8167            });
8168        }
8169    }
8170    Ok(())
8171}
8172
8173#[derive(Debug, Error, PartialEq, Eq)]
8174pub enum AplicacaoError {
8175    #[error("Aplicacao must declare at least one :membros entry")]
8176    NoMembros,
8177    #[error(
8178        ":membros entry has empty :caixa (every member must name a Servico; \
8179         omit the entry instead of carrying an empty name)"
8180    )]
8181    MembroCaixaEmpty,
8182    #[error(
8183        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8184         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8185         name / label value the member name lands in; use a lowercase \
8186         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8187    )]
8188    MembroCaixaInvalid { caixa: String, reason: String },
8189    #[error(
8190        ":membros entry {caixa:?} has empty :versao (every member must pin a \
8191         semver constraint that resolves through the lacre pipeline)"
8192    )]
8193    MembroVersaoEmpty { caixa: String },
8194    #[error(
8195        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8196         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8197         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8198         carries; the lacre pipeline resolves both through the same parser)"
8199    )]
8200    MembroVersaoInvalid {
8201        caixa: String,
8202        versao: String,
8203        reason: String,
8204    },
8205    #[error(
8206        ":membros entry {caixa:?} appears more than once (the graph node set \
8207         is a set, not a multiset; duplicate members produce duplicate \
8208         programs.yaml entries and ambiguous :contratos membership lookups)"
8209    )]
8210    MembroDuplicate { caixa: String },
8211    #[error(
8212        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8213         never its own constituent Servico (the application graph is a DAG rooted \
8214         at the Aplicacao; :membros names the *other* caixas that compose the \
8215         app, not the app itself). Since every :nome is a globally-unique \
8216         substrate identity, a member naming the Aplicacao's own :nome is a \
8217         one-node lacre-closure recursion, not a coincidentally-named peer; \
8218         drop the self-referential :membros entry or rename it to the actual \
8219         constituent caixa."
8220    )]
8221    MembroIsSelfAplicacao { caixa: String },
8222    #[error(
8223        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8224         caixa declared in :membros; omit the contract or fill the {slot} field with a \
8225         member name)"
8226    )]
8227    ContratoCaixaEmpty { slot: &'static str },
8228    #[error(
8229        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8230         :contratos {slot} value names a member of :membros, which is itself a \
8231         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8232         object the member name lands in — Service, Pod, identity-based Cilium \
8233         selector; use a lowercase alphanumeric + hyphen identifier like \
8234         `\"checkout\"` or `\"cart-v2\"`)"
8235    )]
8236    ContratoCaixaInvalid {
8237        slot: &'static str,
8238        caixa: String,
8239        reason: String,
8240    },
8241    #[error("contrato references caixa {caixa:?} not declared in :membros")]
8242    ContratoMemberMissing { caixa: String },
8243    #[error(
8244        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8245         entry is an inter-Servico contract whose :de and :para must name distinct \
8246         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8247         the contract, or point :para at the member it actually calls)"
8248    )]
8249    ContratoSelfLoop { caixa: String, wit: String },
8250    #[error("contrato {de:?} → {para:?} has empty :wit")]
8251    EmptyWit { de: String, para: String },
8252    #[error(
8253        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8254         {reason} (the substrate dispatches `:wit` values on the canonical \
8255         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8256         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8257         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8258         kebab-case identifier per segment)"
8259    )]
8260    ContratoWitInvalid {
8261        de: String,
8262        para: String,
8263        wit: String,
8264        reason: String,
8265    },
8266    #[error(
8267        ":entrada :para is empty (every :entrada must route to a caixa declared in \
8268         :membros; fill the :para field with a member name)"
8269    )]
8270    EntradaParaEmpty,
8271    #[error(
8272        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8273         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8274         label per the K8s apiserver's `metadata.name` rule on every object the \
8275         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8276         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8277         `\"checkout\"` or `\"cart-v2\"`)"
8278    )]
8279    EntradaParaInvalid { para: String, reason: String },
8280    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8281    EntradaMemberMissing { para: String },
8282    #[error(":entrada must declare a non-empty :host")]
8283    EmptyEntradaHost,
8284    #[error(
8285        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8286         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8287         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8288         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8289    )]
8290    EntradaHostInvalid { host: String, reason: String },
8291    #[error(":entrada :port must be in 1..=65535, got 0")]
8292    EntradaPortZero,
8293    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8294    EntradaPathEmpty,
8295    #[error(
8296        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8297    )]
8298    EntradaPathNotAbsolute { path: String },
8299    #[error(
8300        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8301         value: {reason} (the K8s apiserver enforces the same shape on \
8302         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8303         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8304         requires percent-encoding `%XX` for non-ASCII and whitespace)"
8305    )]
8306    EntradaPathInvalid { path: String, reason: String },
8307    #[error(":entrada :paths entry {path:?} appears more than once")]
8308    EntradaPathDuplicate { path: String },
8309    #[error(
8310        ":placement {estrategia} requires at least one :clusters entry \
8311         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8312    )]
8313    PlacementWithoutClusters { estrategia: PlacementStrategy },
8314    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8315    PlacementClusterEmpty,
8316    #[error(
8317        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8318         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8319         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8320         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8321         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8322         identifier like `\"rio\"` or `\"mar-east\"`)"
8323    )]
8324    PlacementClusterInvalid { cluster: String, reason: String },
8325    #[error(":placement :clusters entry {cluster:?} appears more than once")]
8326    PlacementClusterDuplicate { cluster: String },
8327    #[error(
8328        ":placement :affinity must be non-empty when set (omit :affinity to express \
8329         `no placement hint`)"
8330    )]
8331    PlacementAffinityEmpty,
8332    #[error(
8333        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8334         (placement hints land verbatim in the M3 Adaptive compression overlay's \
8335         `placement.affinity` field and in every future M4 placement-engine routing \
8336         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8337         selector — both enforce the DNS-1123 label rule on admission; use a \
8338         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8339         `\"low-latency\"`, or `\"anti-affinity\"`)"
8340    )]
8341    PlacementAffinityInvalid { affinity: String, reason: String },
8342    #[error(":placement Sharded requires :shard-key")]
8343    ShardedWithoutKey,
8344    #[error(
8345        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8346         hashes every entity onto the same shard, defeating sharding entirely)"
8347    )]
8348    ShardedKeyEmpty,
8349    #[error(
8350        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8351         entity-id extractor expression: {reason} (the future M4 Akka-style \
8352         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8353         as a single-token property reference and hashes the extracted entity ID \
8354         to compute shard placement; use a printable-ASCII extractor expression \
8355         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8356         `\"${{tenant}}\"`)"
8357    )]
8358    ShardKeyInvalid { shard_key: String, reason: String },
8359    #[error(
8360        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8361         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8362         convention); :estrategia Replicated runs every cluster active-active and \
8363         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8364         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8365         to :estrategia Sharded if hash-keyed routing is the intent"
8366    )]
8367    ShardKeyOnNonSharded {
8368        estrategia: PlacementStrategy,
8369        shard_key: String,
8370    },
8371    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8372    ContratoMissingTarget {
8373        de: String,
8374        para: String,
8375        wit: String,
8376        expected: &'static str,
8377    },
8378    #[error(
8379        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8380         expected `:{expected}` only"
8381    )]
8382    ContratoWrongTarget {
8383        de: String,
8384        para: String,
8385        wit: String,
8386        expected: &'static str,
8387    },
8388    #[error(
8389        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8390         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8391         that matches no traffic and silently drops every request)"
8392    )]
8393    ContratoEndpointEmpty { de: String, para: String },
8394    #[error(
8395        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8396         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8397         :entrada :paths)"
8398    )]
8399    ContratoEndpointNotAbsolute {
8400        de: String,
8401        para: String,
8402        endpoint: String,
8403    },
8404    #[error(
8405        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8406         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8407         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8408         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8409         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8410         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8411         and whitespace)"
8412    )]
8413    ContratoEndpointInvalid {
8414        de: String,
8415        para: String,
8416        endpoint: String,
8417        reason: String,
8418    },
8419    #[error(
8420        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8421         subject is a no-op subscribe; omit :subject only if the WIT world is not \
8422         pub-sub-shaped)"
8423    )]
8424    ContratoSubjectEmpty { de: String, para: String },
8425    #[error(
8426        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8427         NATS subject: {reason} (the NATS server's subject parser enforces the \
8428         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8429         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8430         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8431         `\"orders.*.completed\"` — a malformed subject silently drops every \
8432         message at runtime far from the source caixa.lisp)"
8433    )]
8434    ContratoSubjectInvalid {
8435        de: String,
8436        para: String,
8437        subject: String,
8438        reason: String,
8439    },
8440    #[error(
8441        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8442         addresses the bucket root, defeating the per-key isolation the slot exists \
8443         for; omit :slot only if the WIT world is not store-shaped)"
8444    )]
8445    ContratoSlotEmpty { de: String, para: String },
8446    #[error(
8447        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8448         WASI keyvalue store slot template: {reason} (the substrate enforces \
8449         the printable-ASCII intersection-floor every kv backend admits — \
8450         use a single-token path / template expression like `\"checkout/$orderId\"`, \
8451         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8452         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8453         slot either gets rejected on write by strict backends or silently \
8454         corrupts the next read on permissive ones, far from the source caixa.lisp)"
8455    )]
8456    ContratoSlotInvalid {
8457        de: String,
8458        para: String,
8459        slot: String,
8460        reason: String,
8461    },
8462    #[error(
8463        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
8464         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
8465        cycle.join(" → ")
8466    )]
8467    ContratoCycle { cycle: Vec<String> },
8468    #[error(
8469        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
8470         than once (the typed graph edges are a set, not a multiset; duplicate \
8471         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
8472         values that K8s admission rejects far from the source caixa.lisp)"
8473    )]
8474    ContratoDuplicate {
8475        de: String,
8476        para: String,
8477        wit: String,
8478        target: String,
8479    },
8480    #[error(
8481        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
8482         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
8483         express `no per-call deadline on this axis`"
8484    )]
8485    PolicyTimeoutZero,
8486    #[error(
8487        ":politicas :retries must be > 0 when set; omit :retries to express \
8488         `no retries on transient failure`"
8489    )]
8490    PolicyRetriesZero,
8491    #[error(
8492        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
8493         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
8494         retry policy into a thundering-herd amplification vector on transient \
8495         failure (one caller request fans out to `(retries+1)^depth` server-side \
8496         calls across the synchronous-:contratos subgraph), exactly the failure \
8497         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
8498         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
8499         or omit :retries to disable retries entirely"
8500    )]
8501    PolicyRetriesExceedsCap { retries: u32 },
8502    #[error(
8503        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
8504         breaker trips on the first call); omit :circuit-breaker to disable it"
8505    )]
8506    PolicyBreakerZeroFailures,
8507    #[error(
8508        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
8509         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
8510         above this cap turns the typed breaker policy into a no-op: the trip \
8511         threshold is structurally so high that no realistic failures-per-:window \
8512         traffic shape can reach it, so the breaker never trips and every typed-slot \
8513         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
8514         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
8515         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
8516         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
8517         omit :circuit-breaker to disable the breaker entirely"
8518    )]
8519    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
8520    #[error(
8521        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
8522         tracks no failures); omit :circuit-breaker to disable it"
8523    )]
8524    PolicyBreakerZeroWindow,
8525    #[error(
8526        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
8527         request); omit :rate-limit to disable rate limiting"
8528    )]
8529    PolicyRateLimitZero,
8530    #[error(
8531        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
8532         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
8533         rate-limit policy into a no-op limiter: the token-bucket capacity is \
8534         structurally so high that no realistic per-edge traffic shape can drain it, \
8535         so the limiter never trips and every typed-slot consumer (the future \
8536         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8537         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
8538         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
8539         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
8540         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
8541         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
8542         to disable rate limiting entirely"
8543    )]
8544    PolicyRateLimitExceedsCap { rate: u32 },
8545    #[error(
8546        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
8547         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
8548         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
8549         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
8550         three canonical windows)"
8551    )]
8552    PolicyRateLimitWindowNotCanonical { window: Duration },
8553    #[error(
8554        ":politicas :timeout must be an integer number of milliseconds — the canonical \
8555         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
8556         duration codec round-trips losslessly; got {timeout:?} which carries a \
8557         sub-millisecond residue that either truncates to a different `Duration` on \
8558         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
8559         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
8560         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
8561         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
8562    )]
8563    PolicyTimeoutNotCanonical { timeout: Duration },
8564    #[error(
8565        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
8566         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
8567         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
8568         overlays carry a deadline so long no realistic synchronous-:contratos \
8569         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
8570         CSE invariant degenerates to enforcement only at the per-Servico \
8571         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
8572         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
8573         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
8574         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
8575         maxes out at the same `3600s` ceiling) or omit :timeout to express \
8576         `no per-call deadline on this axis` (the synchronous-call deadline then \
8577         relies entirely on the per-Servico `:limits :wall-clock` axis)"
8578    )]
8579    PolicyTimeoutExceedsCap { timeout: Duration },
8580    #[error(
8581        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
8582         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
8583         the shared duration codec round-trips losslessly; got {window:?} which carries a \
8584         sub-millisecond residue that either truncates to a different `Duration` on \
8585         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
8586         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
8587    )]
8588    PolicyBreakerWindowNotCanonical { window: Duration },
8589    #[error(
8590        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
8591         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
8592         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
8593         is structurally so long that transient failures are never forgotten, the breaker \
8594         trips once and stays tripped for the lifetime of the component, and every typed-slot \
8595         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8596         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
8597         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
8598         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
8599         the breaker entirely"
8600    )]
8601    PolicyBreakerWindowExceedsCap { window: Duration },
8602}
8603
8604#[cfg(test)]
8605mod tests {
8606    use super::*;
8607
8608    fn membro(name: &str, ver: &str) -> Membro {
8609        Membro {
8610            caixa: name.into(),
8611            versao: ver.into(),
8612        }
8613    }
8614
8615    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
8616        WitContract {
8617            de: de.into(),
8618            para: para.into(),
8619            wit: "wasi:http/proxy".into(),
8620            endpoint: Some(ep.into()),
8621            subject: None,
8622            slot: None,
8623        }
8624    }
8625
8626    fn three_member_spec() -> AplicacaoSpec {
8627        AplicacaoSpec {
8628            membros: vec![
8629                membro("catalog", "^0.1"),
8630                membro("cart", "^0.1"),
8631                membro("payment", "^0.2"),
8632            ],
8633            contratos: vec![
8634                contract_http("cart", "catalog", "/products/:id"),
8635                contract_http("cart", "payment", "/charge"),
8636            ],
8637            politicas: MeshPolicy {
8638                timeout: Some(Duration::from_secs(30)),
8639                retries: Some(3),
8640                mtls_required: Some(true),
8641                ..Default::default()
8642            },
8643            placement: Placement {
8644                estrategia: PlacementStrategy::Replicated,
8645                clusters: vec!["rio".into(), "mar".into()],
8646                affinity: Some("data-locality".into()),
8647                shard_key: None,
8648            },
8649            entrada: Some(Entrada {
8650                host: "checkout.quero.cloud".into(),
8651                para: "cart".into(),
8652                paths: vec!["/api/cart".into(), "/api/products".into()],
8653                port: 8080,
8654            }),
8655        }
8656    }
8657
8658    #[test]
8659    fn happy_path_validates() {
8660        three_member_spec().validate().unwrap();
8661    }
8662
8663    #[test]
8664    fn rejects_empty_membros() {
8665        let mut s = three_member_spec();
8666        s.membros = vec![];
8667        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
8668    }
8669
8670    #[test]
8671    fn rejects_empty_membro_caixa() {
8672        // A `:caixa ""` entry has no name to render into programs.yaml
8673        // and no caixa.lisp to resolve at lacre time.
8674        let mut s = three_member_spec();
8675        s.membros[1].caixa = String::new();
8676        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
8677    }
8678
8679    #[test]
8680    fn rejects_empty_membro_versao() {
8681        // A `:versao ""` entry can't pin a semver constraint, so the
8682        // lacre pipeline fails far from the source.
8683        let mut s = three_member_spec();
8684        s.membros[2].versao = String::new();
8685        let err = s.validate().unwrap_err();
8686        assert!(
8687            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
8688            "got {err:?}"
8689        );
8690    }
8691
8692    #[test]
8693    fn rejects_duplicate_membro_caixa() {
8694        // Two `:membros` entries with the same `:caixa` collapse to one
8695        // node in the membership HashSet, which masks `:contratos`
8696        // membership errors and produces duplicate programs.yaml entries.
8697        let mut s = three_member_spec();
8698        s.membros.push(membro("cart", "^0.2"));
8699        let err = s.validate().unwrap_err();
8700        assert!(
8701            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8702            "got {err:?}"
8703        );
8704    }
8705
8706    #[test]
8707    fn rejects_invalid_membro_versao_requirement() {
8708        // The fail-before-pass-after pin: a non-empty but malformed
8709        // semver requirement (`"^bad-version"`) silently passed
8710        // `validate()` on every pre-gate codebase because the prior
8711        // shape only refused the empty string. The parse failure
8712        // surfaced far downstream at lacre-resolve time with a
8713        // `semver::Error` that didn't name which `:membros` entry
8714        // carried the typo. The new gate moves the check to caixa-build
8715        // time at the source caixa.lisp.
8716        let mut s = three_member_spec();
8717        s.membros[2].versao = "^bad-version".into();
8718        let err = s.validate().unwrap_err();
8719        assert!(
8720            matches!(
8721                err,
8722                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8723                    if caixa == "payment" && versao == "^bad-version"
8724            ),
8725            "got {err:?}"
8726        );
8727    }
8728
8729    #[test]
8730    fn rejects_membro_versao_with_double_caret_typo() {
8731        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
8732        // Cargo-shaped requirement on first glance but fails the parser
8733        // because semver doesn't accept stacked operators. Pin this
8734        // adjacent-shape footgun explicitly so a future relaxation that
8735        // accepts "looks-canonical-but-isn't" forms surfaces here.
8736        let mut s = three_member_spec();
8737        s.membros[0].versao = "^^0.1".into();
8738        let err = s.validate().unwrap_err();
8739        assert!(
8740            matches!(
8741                err,
8742                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8743                    if caixa == "catalog" && versao == "^^0.1"
8744            ),
8745            "got {err:?}"
8746        );
8747    }
8748
8749    #[test]
8750    fn rejects_membro_versao_with_v_prefixed_tag() {
8751        // `"v0.1"` is the canonical "git-tag-shape leaking into the
8752        // semver requirement slot" typo — an author copies the
8753        // publish-side git-tag string verbatim into `:versao`, but
8754        // Cargo's semver parser rejects the leading `v` (only digits +
8755        // canonical operators are valid in the major-version
8756        // position). The gate's diagnostic names which member entry
8757        // carried the v-prefix so the fix is one edit, not a grep
8758        // through every member's `:versao`. (Note: bare `x`-glob
8759        // shorthands like `^0.1.x` are *accepted* by the semver crate
8760        // as an `*` wildcard on the patch axis — they're a Cargo-side
8761        // valid shape, not a typo, so the gate intentionally lets them
8762        // through.)
8763        let mut s = three_member_spec();
8764        s.membros[1].versao = "v0.1".into();
8765        let err = s.validate().unwrap_err();
8766        assert!(
8767            matches!(
8768                err,
8769                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8770                    if caixa == "cart" && versao == "v0.1"
8771            ),
8772            "got {err:?}"
8773        );
8774    }
8775
8776    #[test]
8777    fn accepts_canonical_membro_versao_forms() {
8778        // The four Cargo-shaped requirement forms `:deps :versao`
8779        // already accepts via `crate::parse_requirement` must pass the
8780        // membros gate without re-validating at the resolver layer.
8781        // Pin every leg so a future tightening of the canonical set
8782        // surfaces here as a test failure.
8783        for form in [
8784            "^0.1",      // caret — minor-range pin (the most common shape)
8785            "~0.1.2",    // tilde — patch-range pin
8786            "0.1.0",     // exact — single-version pin
8787            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
8788            ">=0.1, <2", // multi-range — comma-separated comparators
8789        ] {
8790            let mut s = three_member_spec();
8791            for m in &mut s.membros {
8792                m.versao = form.into();
8793            }
8794            s.validate()
8795                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8796        }
8797    }
8798
8799    #[test]
8800    fn membro_versao_empty_takes_precedence_over_invalid() {
8801        // Order pin: the existing `MembroVersaoEmpty` diagnostic
8802        // (which doesn't try to parse) fires before the new
8803        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
8804        // `:versao` keeps its narrower error message — `parse_requirement`
8805        // would also reject `""`, but the empty-string arm is the more
8806        // self-locating diagnostic for the author.
8807        let mut s = three_member_spec();
8808        s.membros[1].versao = String::new();
8809        let err = s.validate().unwrap_err();
8810        assert!(
8811            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
8812            "got {err:?}"
8813        );
8814    }
8815
8816    #[test]
8817    fn membro_versao_invalid_fires_before_duplicate_check() {
8818        // Order pin: a malformed requirement on a non-duplicate entry
8819        // surfaces *its own* diagnostic (which names the offending
8820        // `:versao` string), even when a later entry would otherwise
8821        // collapse onto an earlier name. The per-entry shape gate runs
8822        // inline before the duplicate-key insert, parallel to
8823        // `membros_validation_runs_before_contratos_membership_check`
8824        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
8825        let mut s = three_member_spec();
8826        s.membros[0].versao = "^bad".into();
8827        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8828        let err = s.validate().unwrap_err();
8829        assert!(
8830            matches!(
8831                err,
8832                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
8833            ),
8834            "got {err:?}"
8835        );
8836    }
8837
8838    #[test]
8839    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
8840        // The diagnostic-shape pin: the error names the offending
8841        // `:versao` value verbatim so the author can grep their
8842        // caixa.lisp without re-running the build, and carries a
8843        // non-empty `reason` from `semver::VersionReq::parse` so the
8844        // parser's own wording flows through to the diagnostic.
8845        let mut s = three_member_spec();
8846        s.membros[2].versao = "not-a-req".into();
8847        let err = s.validate().unwrap_err();
8848        let AplicacaoError::MembroVersaoInvalid {
8849            caixa,
8850            versao,
8851            reason,
8852        } = err
8853        else {
8854            panic!("expected MembroVersaoInvalid, got other variant");
8855        };
8856        assert_eq!(caixa, "payment");
8857        assert_eq!(versao, "not-a-req");
8858        assert!(
8859            !reason.is_empty(),
8860            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
8861        );
8862    }
8863
8864    #[test]
8865    fn membro_versao_invalid_runs_before_contratos_check() {
8866        // A malformed `:versao` on any member must surface its own
8867        // diagnostic (which names *which* member to fix) before any
8868        // `:contratos` membership lookup raises `ContratoMemberMissing`.
8869        // The `:contratos` gate runs after `validate_membros`, so this
8870        // is structurally guaranteed — pin it explicitly so a future
8871        // refactor that reorders the gates surfaces here.
8872        let mut s = three_member_spec();
8873        s.membros[1].versao = "^^0.1".into();
8874        // Add a contrato whose `:para` doesn't exist — would normally
8875        // raise ContratoMemberMissing at the membership lookup, but
8876        // the membros gate must fire first.
8877        s.contratos
8878            .push(contract_http("cart", "phantom", "/never-reached"));
8879        let err = s.validate().unwrap_err();
8880        assert!(
8881            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
8882            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
8883        );
8884    }
8885
8886    #[test]
8887    fn membros_validation_runs_before_contratos_membership_check() {
8888        // If `:membros` carries a duplicate, the membership-collapse
8889        // would silently accept a `:contratos :para "phantom"` so long
8890        // as some entry hashes to "phantom". Pinning order: the
8891        // duplicate-membros error fires first, regardless of whether
8892        // contratos reference real members.
8893        let mut s = three_member_spec();
8894        s.membros = vec![
8895            membro("cart", "^0.1"),
8896            membro("cart", "^0.2"),
8897            membro("catalog", "^0.1"),
8898            membro("payment", "^0.1"),
8899        ];
8900        let err = s.validate().unwrap_err();
8901        assert!(
8902            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8903            "got {err:?}"
8904        );
8905    }
8906
8907    #[test]
8908    fn distinct_membros_validate() {
8909        // Pin the happy-path: every `:membros` entry has a non-empty
8910        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
8911        // The fixture already satisfies this; this test makes the
8912        // invariant explicit so a future refactor of the fixture can't
8913        // silently break the guarantee.
8914        three_member_spec().validate().unwrap();
8915    }
8916
8917    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
8918
8919    #[test]
8920    fn rejects_membro_caixa_with_uppercase() {
8921        // The canonical "I copied the Servico's display name verbatim"
8922        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
8923        // but author tools often round-trip a TitleCase or CamelCase
8924        // identifier from an ADR or a sketch. Pin the diagnostic names
8925        // the offending name and suggests the lower-cased fix in one
8926        // edit, mirroring the `rejects_entrada_host_with_uppercase`
8927        // gate's shape (c7d05ec).
8928        let mut s = three_member_spec();
8929        s.membros[1].caixa = "Cart".into();
8930        let err = s.validate().unwrap_err();
8931        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8932            panic!("expected MembroCaixaInvalid, got other variant");
8933        };
8934        assert_eq!(caixa, "Cart");
8935        assert!(
8936            reason.contains("uppercase"),
8937            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8938        );
8939        assert!(
8940            reason.contains("\"cart\""),
8941            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
8942        );
8943    }
8944
8945    #[test]
8946    fn rejects_membro_caixa_with_underscore() {
8947        // The canonical "I'm thinking of a Python module / Postgres
8948        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
8949        // label schema. K8s rejects `metadata.name: my_cart` at admission
8950        // time with an opaque `field is invalid` (no source-citing
8951        // diagnostic). The gate moves it to caixa-build time.
8952        let mut s = three_member_spec();
8953        s.membros[0].caixa = "my_cart".into();
8954        let err = s.validate().unwrap_err();
8955        assert!(
8956            matches!(
8957                err,
8958                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8959                    if caixa == "my_cart" && reason.contains('_')
8960            ),
8961            "got {err:?}"
8962        );
8963    }
8964
8965    #[test]
8966    fn rejects_membro_caixa_with_dot() {
8967        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
8968        // subdomain — even though K8s `metadata.name` itself accepts
8969        // dots (DNS-1123 subdomain rule), this string also lands as a
8970        // K8s Service name (DNS-1035 label — no dots) and as a label
8971        // value on identity-based Cilium selectors. The strictest floor
8972        // among the use sites wins. The "I want to namespace my member
8973        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
8974        let mut s = three_member_spec();
8975        s.membros[2].caixa = "team.cart".into();
8976        let err = s.validate().unwrap_err();
8977        assert!(
8978            matches!(
8979                err,
8980                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8981                    if caixa == "team.cart" && reason.contains('.')
8982            ),
8983            "got {err:?}"
8984        );
8985    }
8986
8987    #[test]
8988    fn rejects_membro_caixa_with_leading_hyphen() {
8989        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
8990        // with an alphanumeric. The K8s apiserver rejects `-cart`
8991        // outright; the renderer would emit a `metadata.name: "-cart"`
8992        // that fails admission far from the source caixa.lisp.
8993        let mut s = three_member_spec();
8994        s.membros[0].caixa = "-cart".into();
8995        let err = s.validate().unwrap_err();
8996        assert!(
8997            matches!(
8998                err,
8999                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9000                    if caixa == "-cart" && reason.contains("start and end")
9001            ),
9002            "got {err:?}"
9003        );
9004    }
9005
9006    #[test]
9007    fn rejects_membro_caixa_with_trailing_hyphen() {
9008        // The symmetric arm of the boundary rule. Pin separately so
9009        // both ends of the label are covered against a future relaxation
9010        // that only checks one boundary.
9011        let mut s = three_member_spec();
9012        s.membros[1].caixa = "cart-".into();
9013        let err = s.validate().unwrap_err();
9014        assert!(
9015            matches!(
9016                err,
9017                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9018                    if caixa == "cart-"
9019            ),
9020            "got {err:?}"
9021        );
9022    }
9023
9024    #[test]
9025    fn rejects_membro_caixa_with_unicode() {
9026        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9027        // (`xn--…`) by the author before it reaches K8s. The byte-by-
9028        // byte ASCII validity check rejects multi-byte UTF-8 sequences
9029        // by the first byte that fails the `[a-z0-9-]` predicate.
9030        let mut s = three_member_spec();
9031        s.membros[2].caixa = "café".into();
9032        let err = s.validate().unwrap_err();
9033        assert!(
9034            matches!(
9035                err,
9036                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9037                    if caixa == "café"
9038            ),
9039            "got {err:?}"
9040        );
9041    }
9042
9043    #[test]
9044    fn rejects_membro_caixa_with_whitespace() {
9045        // Whitespace is the canonical "I pasted from a sketch / doc"
9046        // footgun. The apiserver rejects every `metadata.name` value
9047        // carrying whitespace; pin the gate fires at the right boundary.
9048        let mut s = three_member_spec();
9049        s.membros[0].caixa = "my cart".into();
9050        let err = s.validate().unwrap_err();
9051        assert!(
9052            matches!(
9053                err,
9054                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9055                    if caixa == "my cart"
9056            ),
9057            "got {err:?}"
9058        );
9059    }
9060
9061    #[test]
9062    fn rejects_membro_caixa_too_long() {
9063        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
9064        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
9065        // exactly. The gate's reason names both the cap and the actual
9066        // length so the author can shorten in one edit.
9067        let mut s = three_member_spec();
9068        let too_long = "a".repeat(64);
9069        s.membros[1].caixa = too_long.clone();
9070        let err = s.validate().unwrap_err();
9071        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9072            panic!("expected MembroCaixaInvalid");
9073        };
9074        assert_eq!(caixa, too_long);
9075        assert!(
9076            reason.contains("63") && reason.contains("64"),
9077            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
9078        );
9079    }
9080
9081    #[test]
9082    fn membro_caixa_max_length_validates() {
9083        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
9084        // so a future tightening (e.g. dropping to 62) surfaces here as
9085        // a regression, mirroring `entrada_host_max_length_validates`
9086        // (c7d05ec).
9087        let mut s = three_member_spec();
9088        s.membros[2].caixa = "a".repeat(63);
9089        s.entrada.as_mut().unwrap().para = "a".repeat(63);
9090        // remove contratos referencing the renamed member; they'd
9091        // raise ContratoMemberMissing otherwise
9092        s.contratos
9093            .retain(|c| c.de != "payment" && c.para != "payment");
9094        s.validate().unwrap();
9095    }
9096
9097    #[test]
9098    fn accepts_canonical_membro_caixa_forms() {
9099        // The DNS-1123 label shapes a caixa author is realistically
9100        // going to write: single-word lowercase, hyphen-joined, ending
9101        // in a digit-suffixed version (`cart-v2`), starting with a
9102        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
9103        // DNS-1035 which requires a letter at position 0), single-
9104        // character (`a` — boundary). Pin every leg so a future
9105        // tightening that bans (e.g.) digit-start identifiers surfaces
9106        // here.
9107        for form in [
9108            "checkout",
9109            "cart",
9110            "cart-v2",
9111            "a",
9112            "c0",
9113            "3rd-party-shim",
9114            "x-1-2-3-4",
9115        ] {
9116            let mut s = three_member_spec();
9117            // Renaming a member also requires updating downstream refs;
9118            // drop everything else and rebuild a minimal spec around
9119            // just the one renamed member.
9120            s.membros = vec![membro(form, "^0.1")];
9121            s.contratos = vec![];
9122            s.entrada = None;
9123            s.validate()
9124                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
9125        }
9126    }
9127
9128    #[test]
9129    fn membro_caixa_empty_takes_precedence_over_invalid() {
9130        // Order pin: the existing `MembroCaixaEmpty` diagnostic
9131        // (which doesn't try to parse) fires before the new
9132        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
9133        // `:caixa` keeps its narrower error message — the new gate
9134        // would also reject `""`, but the empty-string arm is the more
9135        // self-locating diagnostic for the author. Mirrors the
9136        // `entrada_host_empty_takes_precedence_over_invalid` pin
9137        // (c7d05ec).
9138        let mut s = three_member_spec();
9139        s.membros[1].caixa = String::new();
9140        let err = s.validate().unwrap_err();
9141        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
9142    }
9143
9144    #[test]
9145    fn membro_caixa_invalid_fires_before_versao_check() {
9146        // Order pin: an invalid-shape `:caixa` surfaces *its own*
9147        // diagnostic (which names the offending caixa name), even when
9148        // the same entry's `:versao` is also empty/invalid. The shape
9149        // gate runs first because the diagnostic is more self-locating —
9150        // an empty/invalid `:versao` on an invalid-shape caixa name is
9151        // a downstream-fix-after-the-caixa-rename concern.
9152        let mut s = three_member_spec();
9153        s.membros[1].caixa = "Cart".into();
9154        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
9155        let err = s.validate().unwrap_err();
9156        assert!(
9157            matches!(
9158                err,
9159                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
9160            ),
9161            "got {err:?}"
9162        );
9163    }
9164
9165    #[test]
9166    fn membro_caixa_invalid_fires_before_duplicate_check() {
9167        // Order pin: a malformed-shape `:caixa` on an earlier entry
9168        // surfaces *its own* diagnostic, even when a later entry would
9169        // otherwise collapse onto a duplicate name. The per-entry shape
9170        // gate runs inline before the duplicate-key insert, parallel
9171        // to `membro_versao_invalid_fires_before_duplicate_check`.
9172        let mut s = three_member_spec();
9173        s.membros[0].caixa = "Catalog".into();
9174        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
9175        let err = s.validate().unwrap_err();
9176        assert!(
9177            matches!(
9178                err,
9179                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
9180            ),
9181            "got {err:?}"
9182        );
9183    }
9184
9185    #[test]
9186    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
9187        // The diagnostic-shape pin: the error names the offending
9188        // `:caixa` value verbatim so the author can grep their
9189        // caixa.lisp without re-running the build, and carries a
9190        // non-empty `reason` naming the specific violation. Same
9191        // shape every typed-shape gate enshrines (c7d05ec's
9192        // `entrada_host_diagnostic_carries_offending_host`,
9193        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
9194        let mut s = three_member_spec();
9195        s.membros[2].caixa = "BAD_NAME".into();
9196        let err = s.validate().unwrap_err();
9197        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9198            panic!("expected MembroCaixaInvalid");
9199        };
9200        assert_eq!(caixa, "BAD_NAME");
9201        assert!(
9202            !reason.is_empty(),
9203            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
9204        );
9205    }
9206
9207    #[test]
9208    fn rejects_contrato_with_unknown_de() {
9209        let mut s = three_member_spec();
9210        s.contratos.push(contract_http("phantom", "catalog", "/x"));
9211        let err = s.validate().unwrap_err();
9212        assert!(
9213            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9214        );
9215    }
9216
9217    #[test]
9218    fn rejects_contrato_with_unknown_para() {
9219        let mut s = three_member_spec();
9220        s.contratos.push(contract_http("cart", "phantom", "/x"));
9221        let err = s.validate().unwrap_err();
9222        assert!(
9223            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9224        );
9225    }
9226
9227    #[test]
9228    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
9229        // The read-path pin: the phantom-`:de` refusal arm's
9230        // `ContratoMemberMissing.caixa` carrier must be observed through
9231        // the lifted [`WitContract::source`] accessor, not the raw
9232        // `.de.clone()` field-access `String`-carry. Peer of the sibling
9233        // per-`:contratos` self-loop arm's `.source().to_string()` /
9234        // `.world_ref().to_string()` `String`-carry sites the earlier
9235        // convergence lifted onto the same accessor pair. A future
9236        // silent detour that reintroduced the raw `.de.clone()` at the
9237        // wrap envelope while the shape-gate and membership lookup
9238        // routed through the accessor would surface here as a byte-equal
9239        // miss between the fired diagnostic's `caixa:` field and the
9240        // offending edge's `.source()` — pinning the accessor as the
9241        // sole read path across the phantom-name refusal arm's arg +
9242        // wrap-envelope emit surface.
9243        let mut s = three_member_spec();
9244        let phantom = contract_http("phantom", "catalog", "/x");
9245        s.contratos.push(phantom.clone());
9246        let err = s.validate().unwrap_err();
9247        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9248            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
9249        };
9250        assert_eq!(
9251            caixa,
9252            phantom.source(),
9253            "ContratoMemberMissing.caixa on the phantom-:de arm must \
9254             byte-equal WitContract::source — the wrap envelope must \
9255             route through the lifted accessor rather than the raw \
9256             .de.clone() field-access String-carry"
9257        );
9258    }
9259
9260    #[test]
9261    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9262        // The symmetric read-path pin on the `:para` phantom-name
9263        // refusal arm — same shape as the sibling `:de` pin above but
9264        // on the callee-Servico axis. Pins the wrap envelope's
9265        // `caixa:` field is observed through the lifted
9266        // [`WitContract::destination`] accessor, not the raw
9267        // `.para.clone()` field-access `String`-carry.
9268        let mut s = three_member_spec();
9269        let phantom = contract_http("cart", "phantom", "/x");
9270        s.contratos.push(phantom.clone());
9271        let err = s.validate().unwrap_err();
9272        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9273            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
9274        };
9275        assert_eq!(
9276            caixa,
9277            phantom.destination(),
9278            "ContratoMemberMissing.caixa on the phantom-:para arm must \
9279             byte-equal WitContract::destination — the wrap envelope \
9280             must route through the lifted accessor rather than the raw \
9281             .para.clone() field-access String-carry"
9282        );
9283    }
9284
9285    #[test]
9286    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
9287        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
9288        // refusal arm — the `validate_contrato_caixa` arg must be
9289        // observed through the lifted [`WitContract::source`] accessor,
9290        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
9291        // value routes through the shared
9292        // [`crate::render::require_valid_dns_1123_label`] floor with the
9293        // accessor-projected value; the fired
9294        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
9295        // the offending edge's `.source()`, pinning that the arg + the
9296        // downstream `caixa: caixa.to_string()` wrap route through the
9297        // same accessor's read path.
9298        let mut s = three_member_spec();
9299        let malformed = contract_http("BAD_NAME", "catalog", "/x");
9300        s.contratos.push(malformed.clone());
9301        let err = s.validate().unwrap_err();
9302        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9303            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
9304        };
9305        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9306        assert_eq!(
9307            caixa,
9308            malformed.source(),
9309            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
9310             byte-equal WitContract::source — the shape-gate arg + wrap \
9311             envelope must route through the lifted accessor rather \
9312             than the raw &c.de &String-borrow"
9313        );
9314    }
9315
9316    #[test]
9317    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9318        // Symmetric arm to the sibling `:de` malformed-shape pin above,
9319        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
9320        // route through the lifted [`WitContract::destination`]
9321        // accessor. `:para` runs after the `:de` shape gate in the
9322        // canonical edge-direction order, so the `:de` value must be
9323        // well-shaped for the `:para` gate to fire — the `cart` :de is
9324        // canonical.
9325        let mut s = three_member_spec();
9326        let malformed = contract_http("cart", "BAD_NAME", "/x");
9327        s.contratos.push(malformed.clone());
9328        let err = s.validate().unwrap_err();
9329        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9330            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
9331        };
9332        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9333        assert_eq!(
9334            caixa,
9335            malformed.destination(),
9336            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
9337             byte-equal WitContract::destination — the shape-gate arg + \
9338             wrap envelope must route through the lifted accessor \
9339             rather than the raw &c.para &String-borrow"
9340        );
9341    }
9342
9343    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
9344
9345    #[test]
9346    fn rejects_contrato_de_empty() {
9347        // `:de ""` previously fell through to `ContratoMemberMissing`
9348        // (with `caixa: ""`) because the validated `:membros :caixa`
9349        // set never contains the empty string. The narrower
9350        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
9351        // the offending slot.
9352        let mut s = three_member_spec();
9353        s.contratos.push(contract_http("", "catalog", "/x"));
9354        let err = s.validate().unwrap_err();
9355        assert_eq!(
9356            err,
9357            AplicacaoError::ContratoCaixaEmpty {
9358                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9359            },
9360            "got {err:?}"
9361        );
9362    }
9363
9364    #[test]
9365    fn rejects_contrato_para_empty() {
9366        // Symmetric arm to `:de ""` — `:para ""` previously fell
9367        // through to `ContratoMemberMissing { caixa: "" }`.
9368        let mut s = three_member_spec();
9369        s.contratos.push(contract_http("cart", "", "/x"));
9370        let err = s.validate().unwrap_err();
9371        assert_eq!(
9372            err,
9373            AplicacaoError::ContratoCaixaEmpty {
9374                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9375            },
9376            "got {err:?}"
9377        );
9378    }
9379
9380    #[test]
9381    fn rejects_contrato_de_with_uppercase() {
9382        // The canonical "I copied the Servico's TitleCase display
9383        // name from an ADR" typo. Until this gate landed `:de "Cart"`
9384        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
9385        // as "this caixa isn't in `:membros`" when the root cause is
9386        // "this `:de` value's shape can never legitimately match a
9387        // validated member (DNS-1123 labels are lowercase)". The
9388        // narrower diagnostic names the offending slot, the value
9389        // verbatim, and the parser-shaped reason.
9390        let mut s = three_member_spec();
9391        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9392        let err = s.validate().unwrap_err();
9393        let AplicacaoError::ContratoCaixaInvalid {
9394            slot,
9395            caixa,
9396            reason,
9397        } = err
9398        else {
9399            panic!("expected ContratoCaixaInvalid, got other variant");
9400        };
9401        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9402        assert_eq!(caixa, "Cart");
9403        assert!(
9404            reason.contains("uppercase"),
9405            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9406        );
9407    }
9408
9409    #[test]
9410    fn rejects_contrato_para_with_underscore() {
9411        // The canonical "I'm thinking of a Python module" leak —
9412        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9413        // Pin the `:para` axis surfaces the same diagnostic shape as
9414        // the `:de` axis on the underscore violation.
9415        let mut s = three_member_spec();
9416        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
9417        let err = s.validate().unwrap_err();
9418        assert!(
9419            matches!(
9420                err,
9421                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9422                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
9423            ),
9424            "got {err:?}"
9425        );
9426    }
9427
9428    #[test]
9429    fn rejects_contrato_de_with_dot() {
9430        // A `:contratos :de` value is a single DNS-1123 *label*, not
9431        // a subdomain — mirroring the `:membros :caixa` floor. The
9432        // strictest floor among the use sites wins.
9433        let mut s = three_member_spec();
9434        s.contratos
9435            .push(contract_http("team.cart", "catalog", "/x"));
9436        let err = s.validate().unwrap_err();
9437        assert!(
9438            matches!(
9439                err,
9440                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9441                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
9442            ),
9443            "got {err:?}"
9444        );
9445    }
9446
9447    #[test]
9448    fn rejects_contrato_para_with_unicode() {
9449        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9450        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
9451        // validity check rejects multi-byte UTF-8 by the first
9452        // non-`[a-z0-9-]` byte.
9453        let mut s = three_member_spec();
9454        s.contratos.push(contract_http("cart", "café", "/x"));
9455        let err = s.validate().unwrap_err();
9456        assert!(
9457            matches!(
9458                err,
9459                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9460                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
9461            ),
9462            "got {err:?}"
9463        );
9464    }
9465
9466    #[test]
9467    fn rejects_contrato_de_with_leading_hyphen() {
9468        // DNS-1123 boundary rule: labels must start and end with an
9469        // alphanumeric. K8s rejects `-cart` outright; the narrower
9470        // shape diagnostic now names the violation at caixa-build
9471        // time rather than the misframed membership-lookup arm.
9472        let mut s = three_member_spec();
9473        s.contratos.push(contract_http("-cart", "catalog", "/x"));
9474        let err = s.validate().unwrap_err();
9475        assert!(
9476            matches!(
9477                err,
9478                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9479                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
9480            ),
9481            "got {err:?}"
9482        );
9483    }
9484
9485    #[test]
9486    fn contrato_de_empty_takes_precedence_over_invalid() {
9487        // Order pin: the `ContratoCaixaEmpty` arm fires before the
9488        // `ContratoCaixaInvalid` parse-side arm — same empty-first
9489        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9490        // / `validate_entrada_host` already establish on their peer
9491        // name axes. The empty string is a structurally distinct
9492        // authoring footgun (the author left the field blank, vs.
9493        // typed a malformed value), so it gets its own diagnostic.
9494        let mut s = three_member_spec();
9495        s.contratos.push(contract_http("", "catalog", "/x"));
9496        let err = s.validate().unwrap_err();
9497        assert_eq!(
9498            err,
9499            AplicacaoError::ContratoCaixaEmpty {
9500                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9501            }
9502        );
9503    }
9504
9505    #[test]
9506    fn contrato_de_shape_fires_before_para_shape() {
9507        // Per-axis order pin: within one `:contratos` entry, the `:de`
9508        // shape gate fires before the `:para` shape gate — same
9509        // edge-direction order the existing `ContratoMemberMissing` /
9510        // `ContratoSelfLoop` / target-dispatch checks use, so the
9511        // diagnostic for a contract with both `:de` and `:para`
9512        // malformed is stable. Authors fixing the surfaced `:de`
9513        // first will see `:para`'s diagnostic on re-run.
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, .. }
9521                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9522            ),
9523            "got {err:?}"
9524        );
9525    }
9526
9527    #[test]
9528    fn contrato_shape_fires_before_membership_lookup() {
9529        // The load-bearing pin: an invalid-shape `:de` surfaces its
9530        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
9531        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9532        // an invalid-shape `:de` could never legitimately match any
9533        // member — the prior `ContratoMemberMissing` diagnostic was
9534        // a structural impossibility framed as a graph-membership
9535        // failure. The shape gate now routes every such input through
9536        // the narrower self-locating diagnostic.
9537        let mut s = three_member_spec();
9538        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9539        let err = s.validate().unwrap_err();
9540        assert!(
9541            matches!(
9542                err,
9543                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
9544            ),
9545            "got {err:?}"
9546        );
9547        // And the symmetric case: an invalid-shape `:para` surfaces
9548        // its own diagnostic too, even when `:de` is well-shaped.
9549        let mut s = three_member_spec();
9550        s.contratos.push(contract_http("cart", "Catalog", "/x"));
9551        let err = s.validate().unwrap_err();
9552        assert!(
9553            matches!(
9554                err,
9555                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
9556            ),
9557            "got {err:?}"
9558        );
9559    }
9560
9561    #[test]
9562    fn contrato_shape_fires_before_self_edge_check() {
9563        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
9564        // bugs: the shape violation (uppercase) and the self-edge
9565        // violation. The narrower per-axis shape diagnostic surfaces
9566        // first because fixing the shape may reveal that the author
9567        // also meant to point `:para` at a different member — the
9568        // self-edge framing is only useful once both endpoints have
9569        // valid shape.
9570        let mut s = three_member_spec();
9571        s.contratos.push(contract_http("Cart", "Cart", "/x"));
9572        let err = s.validate().unwrap_err();
9573        assert!(
9574            matches!(
9575                err,
9576                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9577                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9578            ),
9579            "got {err:?}"
9580        );
9581    }
9582
9583    #[test]
9584    fn contrato_well_shaped_phantom_still_raises_member_missing() {
9585        // Strict-improvement pin: a well-shaped `:de` that simply
9586        // isn't in `:membros` (a phantom reference — author meant
9587        // to add the member but didn't, or renamed and missed an
9588        // update) still surfaces `ContratoMemberMissing`, unchanged.
9589        // The shape gate only intercepts inputs that could never
9590        // legitimately match a validated member; legitimately-shaped
9591        // phantom references remain on the graph-membership axis.
9592        let mut s = three_member_spec();
9593        s.contratos
9594            .push(contract_http("phantom-shim", "catalog", "/x"));
9595        let err = s.validate().unwrap_err();
9596        assert!(
9597            matches!(
9598                err,
9599                AplicacaoError::ContratoMemberMissing { ref caixa }
9600                    if caixa == "phantom-shim"
9601            ),
9602            "got {err:?}"
9603        );
9604    }
9605
9606    #[test]
9607    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
9608        // The diagnostic-shape pin: the error names the offending
9609        // slot (`:de` or `:para`) verbatim and the offending value
9610        // verbatim plus a non-empty parser-shaped reason, so the
9611        // author can grep their caixa.lisp for `:de "<name>"` /
9612        // `:para "<name>"` and fix it in one edit. Same diagnostic
9613        // shape as `MembroCaixaInvalid` (3f9d7a0) and
9614        // `PlacementClusterInvalid` (6c8c00b).
9615        let mut s = three_member_spec();
9616        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
9617        let err = s.validate().unwrap_err();
9618        let AplicacaoError::ContratoCaixaInvalid {
9619            slot,
9620            caixa,
9621            reason,
9622        } = err
9623        else {
9624            panic!("expected ContratoCaixaInvalid, got {err:?}");
9625        };
9626        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9627        assert_eq!(caixa, "BAD_NAME");
9628        assert!(
9629            !reason.is_empty(),
9630            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
9631        );
9632    }
9633
9634    #[test]
9635    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
9636        // Scalar-value pin: the two author-facing kebab-case labels the
9637        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
9638        // admits on the `:contratos` per-entry endpoint-shape axis,
9639        // one arm per typed sub-slot. Mirrors the peer scalar-value
9640        // pin the sibling top-level M2 / M3 / Supervisor
9641        // author-facing-label consts carry
9642        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
9643        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
9644        // slot itself), so every altitude of the typed-slot algebra
9645        // shares the same "one canonical byte-string per arm"
9646        // discipline. A future rebrand (`:de` → `:from` matching the
9647        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
9648        // sibling, `:para` → `:to` matching the same, or
9649        // `:de`/`:para` → `:source`/`:target` matching the WIT
9650        // world's `import`/`export` half-vocabulary) lands as an
9651        // edit to exactly one const, and every consumer that reaches
9652        // for the label picks it up at build time rather than at
9653        // runtime as a downstream `ContratoCaixaEmpty` /
9654        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
9655        // diagnostic mismatch far from the rename's commit.
9656        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
9657        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
9658    }
9659
9660    #[test]
9661    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
9662        // Production-through-const pin: the two per-axis labels the
9663        // per-`:contratos` entry endpoint-shape gate at
9664        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
9665        // argument to [`validate_contrato_caixa`] route through the
9666        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
9667        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
9668        // future rebrand that reaches the const but not the gate (or
9669        // vice versa) surfaces here at build time rather than at
9670        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
9671        // `slot: <stale-kebab-case>` diagnostic far from the rename's
9672        // commit. Mirror of the peer
9673        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
9674        // pin (882f498) on the sibling M3 top-level slot axis.
9675        let mut s = three_member_spec();
9676        s.contratos.push(contract_http("", "catalog", "/x"));
9677        assert_eq!(
9678            s.validate().unwrap_err(),
9679            AplicacaoError::ContratoCaixaEmpty {
9680                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9681            }
9682        );
9683        let mut s = three_member_spec();
9684        s.contratos.push(contract_http("cart", "", "/x"));
9685        assert_eq!(
9686            s.validate().unwrap_err(),
9687            AplicacaoError::ContratoCaixaEmpty {
9688                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9689            }
9690        );
9691    }
9692
9693    #[test]
9694    fn accepts_canonical_contrato_caixa_forms() {
9695        // The DNS-1123 label shapes a caixa author is realistically
9696        // going to write on a `:contratos :de` / `:para`. Pin every
9697        // leg so a future tightening that bans (e.g.) digit-start
9698        // identifiers surfaces here, mirroring
9699        // `accepts_canonical_membro_caixa_forms` on the peer name
9700        // axis.
9701        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9702            let mut s = three_member_spec();
9703            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
9704            s.contratos = vec![contract_http("checkout", form, "/x")];
9705            s.entrada = None;
9706            s.validate().unwrap_or_else(|e| {
9707                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
9708            });
9709
9710            let mut s = three_member_spec();
9711            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9712            s.contratos = vec![contract_http(form, "catalog", "/x")];
9713            s.entrada = None;
9714            s.validate().unwrap_or_else(|e| {
9715                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
9716            });
9717        }
9718    }
9719
9720    #[test]
9721    fn rejects_empty_wit() {
9722        let mut s = three_member_spec();
9723        s.contratos.push(WitContract {
9724            de: "cart".into(),
9725            para: "catalog".into(),
9726            wit: "".into(),
9727            endpoint: None,
9728            subject: None,
9729            slot: None,
9730        });
9731        let err = s.validate().unwrap_err();
9732        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
9733    }
9734
9735    #[test]
9736    fn rejects_entrada_to_unknown_member() {
9737        let mut s = three_member_spec();
9738        s.entrada.as_mut().unwrap().para = "phantom".into();
9739        assert!(matches!(
9740            s.validate().unwrap_err(),
9741            AplicacaoError::EntradaMemberMissing { .. }
9742        ));
9743    }
9744
9745    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
9746
9747    #[test]
9748    fn rejects_entrada_para_empty() {
9749        // `:para ""` previously fell through to
9750        // `EntradaMemberMissing { para: "" }` because the validated
9751        // `:membros :caixa` set never contains the empty string. The
9752        // narrower `EntradaParaEmpty` diagnostic now names the
9753        // offending slot directly — same empty-first cascade
9754        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
9755        // `ContratoCaixaEmpty` establish on the peer name axes.
9756        let mut s = three_member_spec();
9757        s.entrada.as_mut().unwrap().para = String::new();
9758        let err = s.validate().unwrap_err();
9759        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
9760    }
9761
9762    #[test]
9763    fn rejects_entrada_para_with_uppercase() {
9764        // The canonical "I copied the Servico's TitleCase display
9765        // name from an ADR" typo. Until this gate landed `:para "Cart"`
9766        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
9767        // as "this caixa isn't in `:membros`" when the root cause is
9768        // "this `:para` value's shape can never legitimately match a
9769        // validated member (DNS-1123 labels are lowercase)". The
9770        // narrower diagnostic names the value verbatim plus the
9771        // parser-shaped reason.
9772        let mut s = three_member_spec();
9773        s.entrada.as_mut().unwrap().para = "Cart".into();
9774        let err = s.validate().unwrap_err();
9775        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9776            panic!("expected EntradaParaInvalid, got other variant");
9777        };
9778        assert_eq!(para, "Cart");
9779        assert!(
9780            reason.contains("uppercase"),
9781            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9782        );
9783    }
9784
9785    #[test]
9786    fn rejects_entrada_para_with_underscore() {
9787        // The canonical "I'm thinking of a Python module" leak —
9788        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9789        let mut s = three_member_spec();
9790        s.entrada.as_mut().unwrap().para = "my_cart".into();
9791        let err = s.validate().unwrap_err();
9792        assert!(
9793            matches!(
9794                err,
9795                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9796                    if para == "my_cart" && reason.contains('_')
9797            ),
9798            "got {err:?}"
9799        );
9800    }
9801
9802    #[test]
9803    fn rejects_entrada_para_with_dot() {
9804        // An `:entrada :para` value is a single DNS-1123 *label*, not
9805        // a subdomain — mirroring the `:membros :caixa` floor. The
9806        // strictest floor among the use sites wins.
9807        let mut s = three_member_spec();
9808        s.entrada.as_mut().unwrap().para = "team.cart".into();
9809        let err = s.validate().unwrap_err();
9810        assert!(
9811            matches!(
9812                err,
9813                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9814                    if para == "team.cart" && reason.contains('.')
9815            ),
9816            "got {err:?}"
9817        );
9818    }
9819
9820    #[test]
9821    fn rejects_entrada_para_with_unicode() {
9822        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9823        // (`xn--…`) before it reaches K8s.
9824        let mut s = three_member_spec();
9825        s.entrada.as_mut().unwrap().para = "café".into();
9826        let err = s.validate().unwrap_err();
9827        assert!(
9828            matches!(
9829                err,
9830                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
9831            ),
9832            "got {err:?}"
9833        );
9834    }
9835
9836    #[test]
9837    fn rejects_entrada_para_with_leading_hyphen() {
9838        // DNS-1123 boundary rule: labels must start and end with an
9839        // alphanumeric. K8s rejects `-cart` outright.
9840        let mut s = three_member_spec();
9841        s.entrada.as_mut().unwrap().para = "-cart".into();
9842        let err = s.validate().unwrap_err();
9843        assert!(
9844            matches!(
9845                err,
9846                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9847                    if para == "-cart" && reason.contains("start and end")
9848            ),
9849            "got {err:?}"
9850        );
9851    }
9852
9853    #[test]
9854    fn rejects_entrada_para_with_trailing_hyphen() {
9855        // Symmetric boundary arm.
9856        let mut s = three_member_spec();
9857        s.entrada.as_mut().unwrap().para = "cart-".into();
9858        let err = s.validate().unwrap_err();
9859        assert!(
9860            matches!(
9861                err,
9862                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9863                    if para == "cart-" && reason.contains("start and end")
9864            ),
9865            "got {err:?}"
9866        );
9867    }
9868
9869    #[test]
9870    fn rejects_entrada_para_too_long() {
9871        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
9872        // bytes per label. K8s rejects longer names at admission on
9873        // every `metadata.name` axis.
9874        let mut s = three_member_spec();
9875        s.entrada.as_mut().unwrap().para = "a".repeat(64);
9876        let err = s.validate().unwrap_err();
9877        assert!(
9878            matches!(
9879                err,
9880                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9881                    if para.len() == 64 && reason.contains("max length")
9882            ),
9883            "got {err:?}"
9884        );
9885    }
9886
9887    #[test]
9888    fn entrada_para_empty_takes_precedence_over_invalid() {
9889        // Order pin: the `EntradaParaEmpty` arm fires before the
9890        // `EntradaParaInvalid` parse-side arm — same empty-first
9891        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9892        // / `validate_contrato_caixa` already establish.
9893        let mut s = three_member_spec();
9894        s.entrada.as_mut().unwrap().para = String::new();
9895        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
9896    }
9897
9898    #[test]
9899    fn entrada_para_shape_fires_before_membership_lookup() {
9900        // The load-bearing pin: an invalid-shape `:para` surfaces its
9901        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
9902        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9903        // an invalid-shape `:para` could never legitimately match any
9904        // member — the prior `EntradaMemberMissing` diagnostic framed
9905        // a structural impossibility as a graph-membership failure.
9906        let mut s = three_member_spec();
9907        s.entrada.as_mut().unwrap().para = "Cart".into();
9908        let err = s.validate().unwrap_err();
9909        assert!(
9910            matches!(
9911                err,
9912                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9913            ),
9914            "got {err:?}"
9915        );
9916    }
9917
9918    #[test]
9919    fn entrada_para_shape_fires_before_host_gate() {
9920        // Per-`:entrada` order pin: the `:para` shape gate fires
9921        // before the `:host` gate, mirroring the existing
9922        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
9923        // ordering where the member-lookup arm preceded the host gate.
9924        // The shape gate slots ahead of that, so a malformed `:para`
9925        // surfaces its own diagnostic even when `:host` is also wrong.
9926        let mut s = three_member_spec();
9927        let e = s.entrada.as_mut().unwrap();
9928        e.para = "Cart".into();
9929        e.host = "BAD HOST".into();
9930        let err = s.validate().unwrap_err();
9931        assert!(
9932            matches!(
9933                err,
9934                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9935            ),
9936            "got {err:?}"
9937        );
9938    }
9939
9940    #[test]
9941    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
9942        // Strict-improvement pin: a well-shaped `:para` that simply
9943        // isn't in `:membros` (a phantom reference — author meant to
9944        // add the member but didn't, or renamed and missed an
9945        // update) still surfaces `EntradaMemberMissing`, unchanged.
9946        // The shape gate only intercepts inputs that could never
9947        // legitimately match a validated member.
9948        let mut s = three_member_spec();
9949        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
9950        let err = s.validate().unwrap_err();
9951        assert!(
9952            matches!(
9953                err,
9954                AplicacaoError::EntradaMemberMissing { ref para }
9955                    if para == "phantom-shim"
9956            ),
9957            "got {err:?}"
9958        );
9959    }
9960
9961    #[test]
9962    fn entrada_para_invalid_diagnostic_carries_offending_para() {
9963        // The diagnostic-shape pin: the error names the offending
9964        // `:para` value verbatim plus a non-empty parser-shaped
9965        // reason, so the author can grep their caixa.lisp for
9966        // `:para "<name>"` and fix it in one edit. Same diagnostic
9967        // shape as `MembroCaixaInvalid` (3f9d7a0),
9968        // `PlacementClusterInvalid` (6c8c00b), and
9969        // `ContratoCaixaInvalid` (8d5af6b).
9970        let mut s = three_member_spec();
9971        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
9972        let err = s.validate().unwrap_err();
9973        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9974            panic!("expected EntradaParaInvalid, got {err:?}");
9975        };
9976        assert_eq!(para, "BAD_NAME");
9977        assert!(
9978            !reason.is_empty(),
9979            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
9980        );
9981    }
9982
9983    #[test]
9984    fn accepts_canonical_entrada_para_forms() {
9985        // Positive-control sweep covering the DNS-1123 label shapes a
9986        // caixa author is realistically going to write on `:entrada
9987        // :para`. Pin every leg so a future tightening that bans
9988        // (e.g.) digit-start identifiers surfaces here, mirroring
9989        // `accepts_canonical_membro_caixa_forms` and
9990        // `accepts_canonical_contrato_caixa_forms` on the peer name
9991        // axes.
9992        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9993            let mut s = three_member_spec();
9994            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9995            s.contratos = vec![contract_http(form, "catalog", "/x")];
9996            s.entrada = Some(Entrada {
9997                host: "checkout.quero.cloud".into(),
9998                para: form.into(),
9999                paths: vec!["/api".into()],
10000                port: 8080,
10001            });
10002            s.validate().unwrap_or_else(|e| {
10003                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
10004            });
10005        }
10006    }
10007
10008    #[test]
10009    fn rejects_replicated_without_clusters() {
10010        let mut s = three_member_spec();
10011        s.placement.clusters = vec![];
10012        assert!(matches!(
10013            s.validate().unwrap_err(),
10014            AplicacaoError::PlacementWithoutClusters { .. }
10015        ));
10016    }
10017
10018    #[test]
10019    fn rejects_sharded_without_key() {
10020        let mut s = three_member_spec();
10021        s.placement.estrategia = PlacementStrategy::Sharded;
10022        s.placement.shard_key = None;
10023        s.placement.clusters = vec!["rio".into()];
10024        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
10025    }
10026
10027    #[test]
10028    fn sharded_with_key_validates() {
10029        let mut s = three_member_spec();
10030        s.placement.estrategia = PlacementStrategy::Sharded;
10031        s.placement.shard_key = Some("$tenantId".into());
10032        s.validate().unwrap();
10033    }
10034
10035    #[test]
10036    fn round_trip_via_json_preserves_shape() {
10037        let s = three_member_spec();
10038        let json = serde_json::to_string(&s.membros).unwrap();
10039        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
10040        assert_eq!(back, s.membros);
10041
10042        let json = serde_json::to_string(&s.contratos).unwrap();
10043        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
10044        assert_eq!(back, s.contratos);
10045
10046        let json = serde_json::to_string(&s.placement).unwrap();
10047        let back: Placement = serde_json::from_str(&json).unwrap();
10048        assert_eq!(back, s.placement);
10049
10050        let json = serde_json::to_string(&s.entrada).unwrap();
10051        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
10052        assert_eq!(back, s.entrada);
10053    }
10054
10055    #[test]
10056    fn rate_limit_round_trip_seconds() {
10057        let policy = MeshPolicy {
10058            rate_limit: Some(RateLimit {
10059                rate: 100,
10060                window: Duration::from_secs(1),
10061            }),
10062            ..Default::default()
10063        };
10064        let json = serde_json::to_string(&policy).unwrap();
10065        assert!(json.contains("\"100/s\""));
10066        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10067        assert_eq!(back.rate_limit.unwrap().rate, 100);
10068        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
10069    }
10070
10071    #[test]
10072    fn rate_limit_round_trip_minutes() {
10073        let policy = MeshPolicy {
10074            rate_limit: Some(RateLimit {
10075                rate: 5000,
10076                window: Duration::from_secs(60),
10077            }),
10078            ..Default::default()
10079        };
10080        let json = serde_json::to_string(&policy).unwrap();
10081        assert!(json.contains("\"5000/m\""));
10082    }
10083
10084    #[test]
10085    fn circuit_breaker_round_trip() {
10086        let policy = MeshPolicy {
10087            circuit_breaker: Some(CircuitBreaker {
10088                max_failures: 5,
10089                window: Duration::from_secs(60),
10090            }),
10091            ..Default::default()
10092        };
10093        let json = serde_json::to_string(&policy).unwrap();
10094        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10095        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
10096        assert_eq!(
10097            back.circuit_breaker.unwrap().window,
10098            Duration::from_secs(60)
10099        );
10100    }
10101
10102    #[test]
10103    fn rejects_http_contrato_without_endpoint() {
10104        let mut s = three_member_spec();
10105        s.contratos.push(WitContract {
10106            de: "cart".into(),
10107            para: "catalog".into(),
10108            wit: "wasi:http/proxy".into(),
10109            endpoint: None,
10110            subject: None,
10111            slot: None,
10112        });
10113        let err = s.validate().unwrap_err();
10114        assert!(matches!(
10115            err,
10116            AplicacaoError::ContratoMissingTarget {
10117                expected: WitTarget::HTTP_FIELD_NAME,
10118                ..
10119            }
10120        ));
10121    }
10122
10123    #[test]
10124    fn rejects_http_contrato_with_subject() {
10125        let mut s = three_member_spec();
10126        s.contratos.push(WitContract {
10127            de: "cart".into(),
10128            para: "catalog".into(),
10129            wit: "wasi:http/proxy".into(),
10130            endpoint: Some("/x".into()),
10131            subject: Some("not.allowed.here".into()),
10132            slot: None,
10133        });
10134        let err = s.validate().unwrap_err();
10135        assert!(matches!(
10136            err,
10137            AplicacaoError::ContratoWrongTarget {
10138                expected: WitTarget::HTTP_FIELD_NAME,
10139                ..
10140            }
10141        ));
10142    }
10143
10144    #[test]
10145    fn rejects_pubsub_contrato_without_subject() {
10146        let mut s = three_member_spec();
10147        s.contratos.push(WitContract {
10148            de: "cart".into(),
10149            para: "catalog".into(),
10150            wit: "nats:pub-sub".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::PUBSUB_FIELD_NAME,
10160                ..
10161            }
10162        ));
10163    }
10164
10165    #[test]
10166    fn rejects_pubsub_contrato_with_endpoint() {
10167        let mut s = three_member_spec();
10168        s.contratos.push(WitContract {
10169            de: "cart".into(),
10170            para: "catalog".into(),
10171            wit: "kafka:topic".into(),
10172            endpoint: Some("/wrong".into()),
10173            subject: Some("topic.x".into()),
10174            slot: None,
10175        });
10176        let err = s.validate().unwrap_err();
10177        assert!(matches!(
10178            err,
10179            AplicacaoError::ContratoWrongTarget {
10180                expected: WitTarget::PUBSUB_FIELD_NAME,
10181                ..
10182            }
10183        ));
10184    }
10185
10186    #[test]
10187    fn rejects_store_contrato_without_slot() {
10188        let mut s = three_member_spec();
10189        s.contratos.push(WitContract {
10190            de: "cart".into(),
10191            para: "catalog".into(),
10192            wit: "wasi:keyvalue/store".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::STORE_FIELD_NAME,
10202                ..
10203            }
10204        ));
10205    }
10206
10207    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
10208
10209    #[test]
10210    fn rejects_http_contrato_with_empty_endpoint() {
10211        // `Some("")` for an HTTP endpoint passes the presence check
10212        // (target() previously returned WitTarget::Http { endpoint: "" })
10213        // but renders as a `path: ""` Cilium L7 rule that matches no
10214        // traffic. Same value-shape footgun closed for :entrada :paths
10215        // entries (eb3456d).
10216        let mut s = three_member_spec();
10217        s.contratos.push(WitContract {
10218            de: "cart".into(),
10219            para: "catalog".into(),
10220            wit: "wasi:http/proxy".into(),
10221            endpoint: Some(String::new()),
10222            subject: None,
10223            slot: None,
10224        });
10225        let err = s.validate().unwrap_err();
10226        assert!(
10227            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
10228                if de == "cart" && para == "catalog"),
10229            "got {err:?}"
10230        );
10231    }
10232
10233    #[test]
10234    fn rejects_http_contrato_with_relative_endpoint() {
10235        // Cilium L7 :path + Gateway API PathPrefix both require a
10236        // leading `/`. Same shape required of :entrada :paths
10237        // (eb3456d). Lifted into target() so every consumer of the
10238        // typed WitTarget view inherits the guarantee.
10239        let mut s = three_member_spec();
10240        s.contratos.push(WitContract {
10241            de: "cart".into(),
10242            para: "catalog".into(),
10243            wit: "wasi:http/proxy".into(),
10244            endpoint: Some("products/:id".into()),
10245            subject: None,
10246            slot: None,
10247        });
10248        let err = s.validate().unwrap_err();
10249        assert!(
10250            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10251                if endpoint == "products/:id"),
10252            "got {err:?}"
10253        );
10254    }
10255
10256    #[test]
10257    fn rejects_pubsub_contrato_with_empty_subject() {
10258        // NATS / Kafka publish without a subject is a no-op subscribe;
10259        // never the author's intent. Same empty-string rejection as
10260        // :membros :caixa, :placement :clusters entries, :entrada
10261        // :paths entries — every value carried by every typed slot is
10262        // value-shape-checked at validate().
10263        let mut s = three_member_spec();
10264        s.contratos.push(WitContract {
10265            de: "cart".into(),
10266            para: "catalog".into(),
10267            wit: "nats:pub-sub".into(),
10268            endpoint: None,
10269            subject: Some(String::new()),
10270            slot: None,
10271        });
10272        let err = s.validate().unwrap_err();
10273        assert!(
10274            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
10275                if de == "cart" && para == "catalog"),
10276            "got {err:?}"
10277        );
10278    }
10279
10280    #[test]
10281    fn rejects_store_contrato_with_empty_slot() {
10282        // An empty slot template addresses the bucket root, defeating
10283        // the per-key isolation the slot exists for — a footgun on
10284        // `wasi:keyvalue/store` whose closest analog is the empty
10285        // shard-key rejected on :placement Sharded (c7c7799).
10286        let mut s = three_member_spec();
10287        s.contratos.push(WitContract {
10288            de: "cart".into(),
10289            para: "catalog".into(),
10290            wit: "wasi:keyvalue/store".into(),
10291            endpoint: None,
10292            subject: None,
10293            slot: Some(String::new()),
10294        });
10295        let err = s.validate().unwrap_err();
10296        assert!(
10297            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
10298                if de == "cart" && para == "catalog"),
10299            "got {err:?}"
10300        );
10301    }
10302
10303    #[test]
10304    fn http_contrato_root_endpoint_validates() {
10305        // Pin the boundary case: a single-`/` endpoint is the catch-all
10306        // form the Gateway HTTPRoute renderer falls back to when
10307        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
10308        // must remain a valid contrato endpoint too.
10309        let mut s = three_member_spec();
10310        s.contratos.push(contract_http("cart", "catalog", "/"));
10311        s.validate().unwrap();
10312    }
10313
10314    // ── :contratos :endpoint value-shape gate ────────────────────────────
10315    //
10316    // Mirrors the `:entrada :paths` value-shape suite on the peer
10317    // HTTP-path axis. Until this gate landed `WitContract::target()`
10318    // only refused the empty string + the missing-leading-`/` form
10319    // (c4213a4); a structurally invalid endpoint passed validate and
10320    // landed verbatim as a Cilium L7 `path:` rule
10321    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
10322    // traffic or was rejected at apply time by Cilium policy admission.
10323    // Every authoring footgun the K8s Gateway API webhook / Cilium
10324    // policy validator would catch on admission now becomes a caixa-
10325    // build-time `ContratoEndpointInvalid` with the offending
10326    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
10327    // shape as `EntradaPathInvalid` on the sibling axis; same shared
10328    // predicate (`crate::render::is_gateway_api_http_path`) ensures
10329    // drift between the two axes' rule enforcement is a build error
10330    // at the predicate.
10331
10332    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
10333        // Fresh spec per call so the would-be-duplicate edge
10334        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
10335        // `three_member_spec`'s pre-existing
10336        // `(cart, catalog, …, /products/:id)` entry — only the
10337        // endpoint payload differs.
10338        let mut s = three_member_spec();
10339        s.contratos.push(contract_http("cart", "catalog", ep));
10340        s.validate().unwrap_err()
10341    }
10342
10343    #[test]
10344    fn rejects_http_contrato_endpoint_with_query() {
10345        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
10346        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
10347        // rule the L7 matcher would never satisfy.
10348        let err = contrato_endpoint_err("/charge?token=X");
10349        assert!(
10350            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10351                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
10352            "got {err:?}"
10353        );
10354    }
10355
10356    #[test]
10357    fn rejects_http_contrato_endpoint_with_fragment() {
10358        let err = contrato_endpoint_err("/charge#frag");
10359        assert!(
10360            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10361                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
10362            "got {err:?}"
10363        );
10364    }
10365
10366    #[test]
10367    fn rejects_http_contrato_endpoint_with_whitespace() {
10368        let err = contrato_endpoint_err("/foo bar");
10369        assert!(
10370            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10371                if endpoint == "/foo bar" && reason.contains("whitespace")),
10372            "got {err:?}"
10373        );
10374    }
10375
10376    #[test]
10377    fn rejects_http_contrato_endpoint_with_control_char() {
10378        let err = contrato_endpoint_err("/api/\x01bar");
10379        assert!(
10380            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10381                if endpoint == "/api/\x01bar" && reason.contains("control character")),
10382            "got {err:?}"
10383        );
10384    }
10385
10386    #[test]
10387    fn rejects_http_contrato_endpoint_with_non_ascii() {
10388        let err = contrato_endpoint_err("/api/café");
10389        assert!(
10390            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10391                if endpoint == "/api/café" && reason.contains("non-ASCII")),
10392            "got {err:?}"
10393        );
10394    }
10395
10396    #[test]
10397    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
10398        let err = contrato_endpoint_err("/api//cart");
10399        assert!(
10400            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10401                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
10402            "got {err:?}"
10403        );
10404    }
10405
10406    #[test]
10407    fn rejects_http_contrato_endpoint_with_dot_segment() {
10408        let err = contrato_endpoint_err("/api/./cart");
10409        assert!(
10410            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10411                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
10412            "got {err:?}"
10413        );
10414    }
10415
10416    #[test]
10417    fn rejects_http_contrato_endpoint_with_parent_segment() {
10418        // Path-traversal in a contrato endpoint is the canonical
10419        // "L7 rule that the workload's HTTP server's path-resolution
10420        // logic interprets differently than the policy enforcer"
10421        // footgun. Rejected outright at validate time.
10422        let err = contrato_endpoint_err("/api/../etc");
10423        assert!(
10424            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10425                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
10426            "got {err:?}"
10427        );
10428    }
10429
10430    #[test]
10431    fn rejects_http_contrato_endpoint_too_long() {
10432        // 1025-byte endpoint — one over the Gateway API
10433        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
10434        // path matcher has no inherent length limit but the policy
10435        // CR itself rides through the K8s apiserver, which enforces
10436        // ConfigMap-shaped limits; sharing the Gateway API cap is the
10437        // conservative floor.
10438        let big = format!("/api/{}", "a".repeat(1020));
10439        assert_eq!(big.len(), 1025);
10440        let err = contrato_endpoint_err(&big);
10441        assert!(
10442            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10443                if endpoint == &big && reason.contains("max length of 1024")),
10444            "got {err:?}"
10445        );
10446    }
10447
10448    #[test]
10449    fn http_contrato_endpoint_max_length_validates() {
10450        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
10451        // in the cap surfaces here and at
10452        // `rejects_http_contrato_endpoint_too_long` simultaneously,
10453        // mirroring `entrada_path_max_length_validates` on the peer
10454        // axis.
10455        let big = format!("/api/{}", "a".repeat(1019));
10456        assert_eq!(big.len(), 1024);
10457        let mut s = three_member_spec();
10458        s.contratos.push(contract_http("cart", "catalog", &big));
10459        s.validate().unwrap();
10460    }
10461
10462    #[test]
10463    fn http_contrato_endpoint_accepts_canonical_forms() {
10464        // Positive-set sweep: every canonical HTTP-path shape the
10465        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
10466        // plain paths, hidden-file-style `.config` segments distinct
10467        // from the `.` segment, digit-bearing segments, the canonical
10468        // route-template `:param` form, trailing-slash form,
10469        // percent-encoded segments, the `/foo..bar` interior-`..`-
10470        // substring forms that are NOT `..` segments) must remain a
10471        // valid contrato endpoint too. Drift between this list and
10472        // the entrada path positive sweep surfaces at the shared
10473        // `is_gateway_api_http_path` substrate-side suite — one
10474        // source of truth. Uses a fresh `(payment, catalog)` edge so
10475        // none of the swept endpoints collide with the pre-existing
10476        // `(cart, catalog, /products/:id)` / `(cart, payment,
10477        // /charge)` entries in `three_member_spec`.
10478        for ep in [
10479            "/",
10480            "/charge",
10481            "/v1/charge",
10482            "/api/.config",
10483            "/products/:id",
10484            "/api/cart/",
10485            "/api/caf%C3%A9",
10486            "/foo..bar",
10487            "/...",
10488        ] {
10489            let mut s = three_member_spec();
10490            s.contratos.push(contract_http("payment", "catalog", ep));
10491            s.validate()
10492                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
10493        }
10494    }
10495
10496    #[test]
10497    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
10498        // Ordering pin: `ContratoEndpointEmpty` is the more self-
10499        // locating diagnostic on `""` and must lead — the value-
10500        // shape gate is only reached after the empty-check fires.
10501        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
10502        // on the peer axis.
10503        let mut s = three_member_spec();
10504        s.contratos.push(WitContract {
10505            de: "cart".into(),
10506            para: "catalog".into(),
10507            wit: "wasi:http/proxy".into(),
10508            endpoint: Some(String::new()),
10509            subject: None,
10510            slot: None,
10511        });
10512        let err = s.validate().unwrap_err();
10513        assert!(
10514            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
10515            "got {err:?}"
10516        );
10517    }
10518
10519    #[test]
10520    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
10521        // Ordering pin: an endpoint without a leading `/` surfaces the
10522        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
10523        // value-shape gate is only consulted on endpoints that already
10524        // satisfy the absolute-prefix invariant. Mirrors
10525        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
10526        let err = contrato_endpoint_err("bad path");
10527        assert!(
10528            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10529                if endpoint == "bad path"),
10530            "got {err:?}"
10531        );
10532    }
10533
10534    #[test]
10535    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
10536        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
10537        // `:para` + a non-empty reason flow through verbatim so the
10538        // author can grep their caixa.lisp for the offending contrato
10539        // block and fix it in one edit. Same shape as
10540        // `entrada_path_diagnostic_carries_offending_path`.
10541        let err = contrato_endpoint_err("/api?q=1");
10542        match err {
10543            AplicacaoError::ContratoEndpointInvalid {
10544                de,
10545                para,
10546                endpoint,
10547                reason,
10548            } => {
10549                assert_eq!(de, "cart");
10550                assert_eq!(para, "catalog");
10551                assert_eq!(endpoint, "/api?q=1");
10552                assert!(!reason.is_empty(), "reason field must be non-empty");
10553            }
10554            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
10555        }
10556    }
10557
10558    #[test]
10559    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
10560        // The compounding theorem: every &str inside a WitTarget
10561        // returned by target() is non-empty (and absolute, for Http).
10562        // Renderers downstream of typed_view() can rely on this
10563        // without re-checking — the type system carries the proof.
10564        let http = contract_http("cart", "catalog", "/x");
10565        match http.target().unwrap() {
10566            WitTarget::Http { endpoint } => {
10567                assert!(!endpoint.is_empty());
10568                assert!(endpoint.starts_with('/'));
10569            }
10570            other => panic!("expected Http, got {other:?}"),
10571        }
10572        let nats = WitContract {
10573            de: "a".into(),
10574            para: "b".into(),
10575            wit: "nats:pub-sub".into(),
10576            endpoint: None,
10577            subject: Some("topic.x".into()),
10578            slot: None,
10579        };
10580        match nats.target().unwrap() {
10581            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
10582            other => panic!("expected PubSub, got {other:?}"),
10583        }
10584        let kv = WitContract {
10585            de: "a".into(),
10586            para: "b".into(),
10587            wit: "wasi:keyvalue/store".into(),
10588            endpoint: None,
10589            subject: None,
10590            slot: Some("checkout/$orderId".into()),
10591        };
10592        match kv.target().unwrap() {
10593            WitTarget::Store { slot } => assert!(!slot.is_empty()),
10594            other => panic!("expected Store, got {other:?}"),
10595        }
10596    }
10597
10598    #[test]
10599    fn target_diagnostic_names_offending_endpoint_value() {
10600        // When the malformed endpoint string is non-trivial, the
10601        // diagnostic carries the actual value back to the author —
10602        // not a generic "endpoint malformed" error.
10603        let bad = WitContract {
10604            de: "src".into(),
10605            para: "dst".into(),
10606            wit: "wasi:http/proxy".into(),
10607            endpoint: Some("api/v1/charge".into()),
10608            subject: None,
10609            slot: None,
10610        };
10611        match bad.target().unwrap_err() {
10612            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
10613                assert_eq!(de, "src");
10614                assert_eq!(para, "dst");
10615                assert_eq!(endpoint, "api/v1/charge");
10616            }
10617            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
10618        }
10619    }
10620
10621    #[test]
10622    fn rejects_unknown_wit_with_target_set() {
10623        let mut s = three_member_spec();
10624        s.contratos.push(WitContract {
10625            de: "cart".into(),
10626            para: "catalog".into(),
10627            wit: "custom:exchange".into(),
10628            endpoint: Some("/leaked".into()),
10629            subject: None,
10630            slot: None,
10631        });
10632        let err = s.validate().unwrap_err();
10633        assert!(matches!(
10634            err,
10635            AplicacaoError::ContratoWrongTarget {
10636                expected: WitTarget::CAPABILITY_EXPECTED,
10637                ..
10638            }
10639        ));
10640    }
10641
10642    #[test]
10643    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
10644        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
10645        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
10646        // fourth arm of the same "which payload field name goes in the
10647        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
10648        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10649        // consts cover on the peer HTTP / PubSub / Store arms
10650        // (`wit_target_field_name_pins_per_variant`). Until this lift
10651        // landed the byte-string sat twice — once inline in the
10652        // [`WitContract::target`] Capability-arm rejection at the
10653        // production dispatch, once in `rejects_unknown_wit_with_target_set`
10654        // pinning against the same literal — with no compile-time link
10655        // between them. Same "one canonical declaration, next to the
10656        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
10657        // lift established for the payload-less arm's human-readable
10658        // label axis; this test is the shape peer of
10659        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
10660        // pair (routes-through-const + scalar-value pin) on the
10661        // wrong-target diagnostic-scalar axis.
10662        //
10663        // Fail-before-pass-after was verified locally by mutating the
10664        // const declaration to `"capability"` — the scalar-value pin
10665        // below fires (`"capability" != "none"`) and the routes-through
10666        // assertion below still holds (production and const walk in
10667        // lockstep), which is the correct behavior: a rename on the
10668        // const drifts here first, not at a downstream consumer.
10669        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
10670
10671        let mut s = three_member_spec();
10672        s.contratos.push(WitContract {
10673            de: "cart".into(),
10674            para: "catalog".into(),
10675            wit: "custom:exchange".into(),
10676            endpoint: Some("/leaked".into()),
10677            subject: None,
10678            slot: None,
10679        });
10680        match s.validate().unwrap_err() {
10681            AplicacaoError::ContratoWrongTarget { expected, .. } => {
10682                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
10683            }
10684            other => panic!("expected ContratoWrongTarget, got {other:?}"),
10685        }
10686    }
10687
10688    #[test]
10689    fn unknown_wit_capability_only_validates() {
10690        let mut s = three_member_spec();
10691        s.contratos.push(WitContract {
10692            de: "cart".into(),
10693            para: "catalog".into(),
10694            // A WIT world we haven't yet shaped — accept it as a typed
10695            // capability edge so authors aren't blocked while the WIT
10696            // registry catches up. No payload field may be carried.
10697            wit: "custom:exchange".into(),
10698            endpoint: None,
10699            subject: None,
10700            slot: None,
10701        });
10702        s.validate().unwrap();
10703        let added = s.contratos.last().unwrap();
10704        assert_eq!(added.target().unwrap(), WitTarget::Capability);
10705    }
10706
10707    #[test]
10708    fn target_typed_view_round_trips_each_shape() {
10709        let http = contract_http("cart", "catalog", "/products/:id");
10710        assert_eq!(
10711            http.target().unwrap(),
10712            WitTarget::Http {
10713                endpoint: "/products/:id"
10714            }
10715        );
10716        let nats = WitContract {
10717            de: "a".into(),
10718            para: "b".into(),
10719            wit: "nats:pub-sub".into(),
10720            endpoint: None,
10721            subject: Some("topic.x".into()),
10722            slot: None,
10723        };
10724        assert_eq!(
10725            nats.target().unwrap(),
10726            WitTarget::PubSub { subject: "topic.x" }
10727        );
10728        let kv = WitContract {
10729            de: "a".into(),
10730            para: "b".into(),
10731            wit: "wasi:keyvalue/store".into(),
10732            endpoint: None,
10733            subject: None,
10734            slot: Some("checkout/$orderId".into()),
10735        };
10736        assert_eq!(
10737            kv.target().unwrap(),
10738            WitTarget::Store {
10739                slot: "checkout/$orderId"
10740            }
10741        );
10742    }
10743
10744    #[test]
10745    fn wit_contract_kind_predicates() {
10746        let http = contract_http("a", "b", "/x");
10747        assert!(http.is_http());
10748        assert!(!http.is_pubsub());
10749        assert!(!http.is_store());
10750        assert!(!http.is_capability());
10751
10752        let nats = WitContract {
10753            de: "a".into(),
10754            para: "b".into(),
10755            wit: "nats:pub-sub".into(),
10756            endpoint: None,
10757            subject: Some("topic.x".into()),
10758            slot: None,
10759        };
10760        assert!(nats.is_pubsub());
10761        assert!(!nats.is_http());
10762        assert!(!nats.is_capability());
10763
10764        let kv = WitContract {
10765            de: "a".into(),
10766            para: "b".into(),
10767            wit: "wasi:keyvalue/store".into(),
10768            endpoint: None,
10769            subject: None,
10770            slot: Some("checkout/$orderId".into()),
10771        };
10772        assert!(kv.is_store());
10773        assert!(!kv.is_http());
10774        assert!(!kv.is_capability());
10775
10776        // Fourth arm on the paired closed-set predicate family: the
10777        // payload-less capability edge that projects to the payload-
10778        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
10779        // Extends the 3-arm predicate sweep this test opened to cover
10780        // the closed 4-way partition [`WitContract::is_capability`]
10781        // closes on the pre-projection WIT-shape axis, matched with the
10782        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
10783        // 4-arm predicate set.
10784        let cap = WitContract {
10785            de: "a".into(),
10786            para: "b".into(),
10787            wit: "custom:capability-only".into(),
10788            endpoint: None,
10789            subject: None,
10790            slot: None,
10791        };
10792        assert!(cap.is_capability());
10793        assert!(!cap.is_http());
10794        assert!(!cap.is_pubsub());
10795        assert!(!cap.is_store());
10796    }
10797
10798    // ── :contratos :wit value-shape gate ─────────────────────────────────
10799    //
10800    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
10801    // dispatch-discriminator axis. Until this gate landed
10802    // `WitContract::target()` accepted any non-empty string and
10803    // silently demoted unrecognized shapes to a capability-only L4
10804    // edge — the canonical "I thought I had L7 HTTP routing, got
10805    // L4-only" footgun. Every authoring footgun the WIT registry's
10806    // own grammar rejects (uppercase, hyphen-for-colon typo,
10807    // whitespace, empty package, doubled `@`, …) now becomes a
10808    // caixa-build-time `ContratoWitInvalid` with the offending
10809    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
10810    // as `ContratoEndpointInvalid` on the sibling axis; same shared
10811    // predicate (`crate::render::is_wit_world_ref`) ensures drift
10812    // between any two axes' rule enforcement is a build error at the
10813    // predicate, not piecemeal across renderers.
10814
10815    fn contrato_wit_err(wit: &str) -> AplicacaoError {
10816        // Fresh spec per call so the new contract doesn't collide on
10817        // identity with `three_member_spec`'s pre-existing entries.
10818        // The new edge uses `(payment, catalog)` — a pair the fixture
10819        // doesn't already declare — with no payload field set, so the
10820        // wit-shape gate fires before any payload-shape arm.
10821        let mut s = three_member_spec();
10822        s.contratos.push(WitContract {
10823            de: "payment".into(),
10824            para: "catalog".into(),
10825            wit: wit.into(),
10826            endpoint: None,
10827            subject: None,
10828            slot: None,
10829        });
10830        s.validate().unwrap_err()
10831    }
10832
10833    #[test]
10834    fn rejects_wit_with_uppercase_namespace() {
10835        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
10836        // didn't match the lowercase `wasi:http/` prefix is_http() keys
10837        // off, so the dispatch fell through to the capability arm and
10838        // the contract silently rendered as an L4-only Cilium edge.
10839        // The new gate surfaces the uppercase typo at validate time
10840        // with the offending `:wit` named.
10841        let err = contrato_wit_err("WASI:http/proxy");
10842        assert!(
10843            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10844                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
10845            "got {err:?}"
10846        );
10847    }
10848
10849    #[test]
10850    fn rejects_wit_with_hyphen_for_colon_typo() {
10851        // The canonical "I forgot the `:` separator" typo — pre-gate
10852        // this passed as Capability silently, so the renderer emitted
10853        // an L4-only policy where the author expected L7 HTTP rules.
10854        let err = contrato_wit_err("wasi-http/proxy");
10855        assert!(
10856            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10857                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
10858            "got {err:?}"
10859        );
10860    }
10861
10862    #[test]
10863    fn rejects_wit_with_multiple_colons() {
10864        // Doubled `:` — the namespace/package split has nowhere to
10865        // anchor, so the dispatch silently demotes to Capability.
10866        let err = contrato_wit_err("wasi:http:proxy");
10867        assert!(
10868            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10869                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
10870            "got {err:?}"
10871        );
10872    }
10873
10874    #[test]
10875    fn rejects_wit_with_empty_package() {
10876        // `wasi:` — namespace alone with no package. Pre-gate this
10877        // failed neither the is_http nor is_pubsub nor is_store
10878        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
10879        // a bare `wasi:`), so it silently demoted to Capability.
10880        let err = contrato_wit_err("wasi:");
10881        assert!(
10882            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10883                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
10884            "got {err:?}"
10885        );
10886    }
10887
10888    #[test]
10889    fn rejects_wit_with_underscore() {
10890        // Underscore — WIT identifiers are kebab-case, same rule
10891        // DNS-1123 enforces on its peer axes. The diagnostic carries
10892        // the explicit "use `-` instead" remediation.
10893        let err = contrato_wit_err("wasi:http_proxy");
10894        assert!(
10895            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10896                if wit == "wasi:http_proxy" && reason.contains('_')),
10897            "got {err:?}"
10898        );
10899    }
10900
10901    #[test]
10902    fn rejects_wit_with_whitespace() {
10903        // Whitespace mid-token — the prefix check matches but the
10904        // package-and-onward parse silently demoted to Capability.
10905        let err = contrato_wit_err("wasi:http proxy");
10906        assert!(
10907            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10908                if wit == "wasi:http proxy" && reason.contains("whitespace")),
10909            "got {err:?}"
10910        );
10911    }
10912
10913    #[test]
10914    fn rejects_wit_with_non_ascii() {
10915        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10916        // the package name from a doc with smart quotes / accented
10917        // characters" footgun.
10918        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
10919        assert!(
10920            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10921                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
10922            "got {err:?}"
10923        );
10924    }
10925
10926    #[test]
10927    fn rejects_wit_with_consecutive_hyphens() {
10928        // `pub--sub` — WIT identifiers join words with single hyphens.
10929        let err = contrato_wit_err("nats:pub--sub");
10930        assert!(
10931            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10932                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
10933            "got {err:?}"
10934        );
10935    }
10936
10937    #[test]
10938    fn rejects_wit_with_trailing_at_no_version() {
10939        // `wasi:http/proxy@` — the version-suffix author started to
10940        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
10941        // parser would reject this; surface it at validate time.
10942        let err = contrato_wit_err("wasi:http/proxy@");
10943        assert!(
10944            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10945                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
10946            "got {err:?}"
10947        );
10948    }
10949
10950    #[test]
10951    fn rejects_wit_too_long() {
10952        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
10953        // The legitimate-shape arms all pass (lowercase, single `:`,
10954        // kebab-case identifiers); only the cap arm fires. Surfaces
10955        // the paste-from-binary / accidental-multi-line-blob landing
10956        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10957        // on the peer axis.
10958        let big = format!("wasi:{}", "a".repeat(124));
10959        assert_eq!(big.len(), 129);
10960        let err = contrato_wit_err(&big);
10961        assert!(
10962            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10963                if wit == &big && reason.contains("max length of 128")),
10964            "got {err:?}"
10965        );
10966    }
10967
10968    #[test]
10969    fn wit_max_length_validates() {
10970        // 128-byte WIT reference — exactly the cap. Boundary pin:
10971        // drift in the cap surfaces here and at `rejects_wit_too_long`
10972        // simultaneously, mirroring
10973        // `http_contrato_endpoint_max_length_validates` on the peer
10974        // axis.
10975        let big = format!("wasi:{}", "a".repeat(123));
10976        assert_eq!(big.len(), 128);
10977        let mut s = three_member_spec();
10978        s.contratos.push(WitContract {
10979            de: "payment".into(),
10980            para: "catalog".into(),
10981            wit: big,
10982            endpoint: None,
10983            subject: None,
10984            slot: None,
10985        });
10986        s.validate().unwrap();
10987    }
10988
10989    #[test]
10990    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
10991        // Positive-set sweep through the AplicacaoSpec::validate
10992        // surface (rather than the substrate-side predicate directly)
10993        // — pins every shape the existing test fixtures + the
10994        // checkout-aplicacao example carry, so the gate's accept-set
10995        // matches the substrate's emit-set. Drift between this list
10996        // and `render::tests::wit_world_ref_accepts_canonical_forms`
10997        // surfaces at the substrate layer's positive sweep — one
10998        // source of truth for the rule.
10999        for wit in [
11000            "wasi:http/proxy",
11001            "wasi:keyvalue/store",
11002            "nats:pub-sub",
11003            "kafka:topic",
11004            "custom:exchange",
11005            "pleme:cap/audit",
11006            "wasi:http/proxy@0.2.0",
11007        ] {
11008            // Payload field paired to the dispatched WIT shape so the
11009            // shape-↔-target arm doesn't fire instead of the wit-shape
11010            // arm we're exercising. Routes off the same
11011            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
11012            // `wit_shape_is_store` free functions the production
11013            // `WitContract::is_http` / `is_pubsub` / `is_store`
11014            // methods delegate to (both consult the lifted
11015            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
11016            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
11017            // future prefix addition to the routing accept-set
11018            // reaches this test's payload-dispatch arm by
11019            // construction — no per-test-site drift can hide a
11020            // shape-→-target-slot mismatch that would silently
11021            // demote a canonical `:wit` value to the
11022            // `(None, None, None)` capability-only arm and let the
11023            // `AplicacaoSpec::validate` positive sweep pass on a
11024            // shape it should exercise as HTTP / pub-sub / store.
11025            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
11026                (Some("/x".into()), None, None)
11027            } else if wit_shape_is_pubsub(wit) {
11028                (None, Some("topic.x".into()), None)
11029            } else if wit_shape_is_store(wit) {
11030                (None, None, Some("bucket/$key".into()))
11031            } else {
11032                (None, None, None)
11033            };
11034            let mut s = three_member_spec();
11035            s.contratos.push(WitContract {
11036                de: "payment".into(),
11037                para: "catalog".into(),
11038                wit: wit.into(),
11039                endpoint,
11040                subject,
11041                slot,
11042            });
11043            s.validate()
11044                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
11045        }
11046    }
11047
11048    #[test]
11049    fn wit_shape_predicates_accept_canonical_prefix_set() {
11050        // Positive-set sweep pinning every prefix in
11051        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
11052        // WIT_STORE_SHAPE_PREFIXES against the three free-function
11053        // dispatch predicates. The six prefixes are the load-bearing
11054        // routing keys the substrate's WIT-shape dispatch consults
11055        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
11056        // key/value-store-slot admission); any drift between the
11057        // free-function accept-set and this list surfaces here
11058        // rather than at apply time as a silent
11059        // shape-→-capability-only demotion.
11060        assert!(wit_shape_is_http("wasi:http/proxy"));
11061        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
11062        assert!(wit_shape_is_http("http:incoming"));
11063
11064        assert!(wit_shape_is_pubsub("nats:pub-sub"));
11065        assert!(wit_shape_is_pubsub("kafka:topic"));
11066
11067        assert!(wit_shape_is_store("wasi:keyvalue/store"));
11068        assert!(wit_shape_is_store("kv:cache/session"));
11069    }
11070
11071    #[test]
11072    fn wit_shape_predicates_reject_uncanonical_forms() {
11073        // Negative-set pin: the six canonical prefixes are
11074        // lowercase-only (mirrors the `is_wit_world_ref` substrate
11075        // predicate's lowercase invariant — see its docstring on the
11076        // "I thought I had L7 HTTP routing, got L4-only" footgun).
11077        // The empty string, an uppercase-prefixed form, a hyphen-
11078        // instead-of-colon typo, and a bare kebab identifier all miss
11079        // every shape arm — reachable-by-construction only via the
11080        // `is_wit_world_ref` gate that admission-checks the `:wit`
11081        // value first, but pinned here so any future
11082        // free-function change (e.g. a case-insensitive
11083        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
11084        // this unit level.
11085        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
11086            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
11087            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
11088            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
11089        }
11090    }
11091
11092    #[test]
11093    fn wit_shape_predicates_partition_canonical_set() {
11094        // Every canonical prefix routes to exactly one shape arm —
11095        // the three prefix sets are pairwise disjoint. Pins the
11096        // routing property [`WitContract::target`] relies on: an
11097        // `is_http()` return of `true` guarantees `is_pubsub()` and
11098        // `is_store()` return `false`, so the shape-→-target-slot
11099        // dispatch (endpoint vs subject vs slot) is unambiguous.
11100        // Drift (e.g. a future `"kv:"` moved into the HTTP set
11101        // without removal from the store set) would silently route
11102        // one prefix to two arms and the first-matching-arm order
11103        // becomes load-bearing — this pin surfaces it as a build
11104        // error instead.
11105        for prefix in WIT_HTTP_SHAPE_PREFIXES {
11106            let sample = format!("{prefix}x");
11107            assert!(wit_shape_is_http(&sample));
11108            assert!(!wit_shape_is_pubsub(&sample));
11109            assert!(!wit_shape_is_store(&sample));
11110        }
11111        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
11112            let sample = format!("{prefix}x");
11113            assert!(!wit_shape_is_http(&sample));
11114            assert!(wit_shape_is_pubsub(&sample));
11115            assert!(!wit_shape_is_store(&sample));
11116        }
11117        for prefix in WIT_STORE_SHAPE_PREFIXES {
11118            let sample = format!("{prefix}x");
11119            assert!(!wit_shape_is_http(&sample));
11120            assert!(!wit_shape_is_pubsub(&sample));
11121            assert!(wit_shape_is_store(&sample));
11122        }
11123    }
11124
11125    #[test]
11126    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
11127        // Positive pin: [`wit_shape_matches`] is exactly the
11128        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
11129        // parameterized on the accept-set. Two-prefix accept-set,
11130        // one-prefix accept-set, and empty accept-set (which must
11131        // reject everything, including the empty string — an empty
11132        // `any()` fold returns `false`) all pinned so a future
11133        // reimplementation that swaps `starts_with` for `contains`,
11134        // `==`, or a case-folded comparator surfaces at unit-test
11135        // time.
11136        let two = &["wasi:http/", "http:"];
11137        assert!(wit_shape_matches("wasi:http/proxy", two));
11138        assert!(wit_shape_matches("http:incoming", two));
11139        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
11140
11141        let one = &["nats:"];
11142        assert!(wit_shape_matches("nats:pub-sub", one));
11143        assert!(!wit_shape_matches("kafka:topic", one));
11144
11145        // Empty accept-set matches nothing — the identity element
11146        // for the disjunctive `any()` fold across the prefix set.
11147        // Reachable via a future `wit_shape_is_<name>` const paired
11148        // to a still-empty prefix table on a nascent shape-arm draft.
11149        let empty: &[&str] = &[];
11150        assert!(!wit_shape_matches("wasi:http/proxy", empty));
11151        assert!(!wit_shape_matches("", empty));
11152
11153        // starts_with, not contains: a prefix embedded mid-string
11154        // never matches. Pins the routing invariant [`WitContract::target`]
11155        // relies on (an authored `:wit "custom:wasi:http/"` string
11156        // does not silently route through the HTTP arm just because
11157        // it happens to contain the canonical HTTP prefix).
11158        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
11159    }
11160
11161    #[test]
11162    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
11163        // Equivalence pin: each per-shape predicate is exactly
11164        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
11165        // every canonical prefix + the empty string + one negative
11166        // sample against every peer so a future predicate that grew
11167        // its own inline `iter().any(starts_with)` (rather than
11168        // delegating through the lifted combinator) drifts loudly here
11169        // — the peer-const table's contents must agree with the
11170        // predicate's accept-set by construction.
11171        let samples = [
11172            String::new(),
11173            "wasi:http/proxy".to_string(),
11174            "http:incoming".to_string(),
11175            "nats:pub-sub".to_string(),
11176            "kafka:topic".to_string(),
11177            "wasi:keyvalue/store".to_string(),
11178            "kv:cache/session".to_string(),
11179            "custom-shape".to_string(),
11180            "WASI:HTTP/proxy".to_string(),
11181        ];
11182        for wit in &samples {
11183            assert_eq!(
11184                wit_shape_is_http(wit),
11185                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11186                "wit_shape_is_http drifted from combinator on {wit:?}",
11187            );
11188            assert_eq!(
11189                wit_shape_is_pubsub(wit),
11190                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
11191                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
11192            );
11193            assert_eq!(
11194                wit_shape_is_store(wit),
11195                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
11196                "wit_shape_is_store drifted from combinator on {wit:?}",
11197            );
11198        }
11199    }
11200
11201    #[test]
11202    fn wit_contract_shape_methods_delegate_to_free_functions() {
11203        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
11204        // `is_store` are `&self` conveniences on top of the free
11205        // functions — for every canonical prefix the method's return
11206        // matches its free-function peer. Sweeps the union of the
11207        // three prefix sets so a future method that grew its own
11208        // inline prefix logic (rather than delegating) drifts loudly
11209        // here on the first prefix the free function accepts and the
11210        // method doesn't.
11211        for shape_set in [
11212            WIT_HTTP_SHAPE_PREFIXES,
11213            WIT_PUBSUB_SHAPE_PREFIXES,
11214            WIT_STORE_SHAPE_PREFIXES,
11215        ] {
11216            for prefix in shape_set {
11217                let c = WitContract {
11218                    de: "cart".into(),
11219                    para: "catalog".into(),
11220                    wit: format!("{prefix}x"),
11221                    endpoint: None,
11222                    subject: None,
11223                    slot: None,
11224                };
11225                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
11226                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
11227                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
11228                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11229            }
11230        }
11231        // Capability-arm delegation sweep: two representative
11232        // Capability-shaped `:wit` values (a bare non-prefix-matching
11233        // WIT world, the deliberately-shaped empty string
11234        // [`WitContract::is_capability`]'s docstring calls out as
11235        // syntactically Capability). Extends the free-function
11236        // delegation pin onto the fourth arm so a future
11237        // [`WitContract::is_capability`] rewrite that grew an inline
11238        // prefix-set scan (rather than delegating through
11239        // [`wit_shape_is_capability`]) drifts loudly here on the first
11240        // Capability-shaped sample.
11241        for wit in ["custom:capability-only", ""] {
11242            let c = WitContract {
11243                de: "cart".into(),
11244                para: "catalog".into(),
11245                wit: wit.into(),
11246                endpoint: None,
11247                subject: None,
11248                slot: None,
11249            };
11250            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11251        }
11252    }
11253
11254    #[test]
11255    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
11256        // 4-way partition-witness pin on the raw `&str` axis: for every
11257        // canonical prefix in the three payload-arm accept-sets,
11258        // exactly one of the four [`wit_shape_is_http`] /
11259        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11260        // [`wit_shape_is_capability`] free functions returns `true` and
11261        // the other three return `false` — the four-arm partition
11262        // witness that locks the free-function WIT-shape-classifier
11263        // family into a partition of the `:contratos :wit` axis
11264        // load-bearing. Peer of the sibling [`WitContract`]-surface
11265        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
11266        // partition pin — extends the discipline onto the raw `&str`
11267        // axis so any future arm addition (a hypothetical
11268        // `wasi:sockets/*` transport-layer shape, an `oci:*`
11269        // capability-import carrier per the sibling
11270        // [`wit_shape_matches`] docstring's trajectory bullet) that
11271        // landed on one of the payload-arm free functions without
11272        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
11273        // here as two arms returning `true` simultaneously at
11274        // caixa-core build time rather than a silent per-consumer
11275        // misclassification at renderer emit time.
11276        for shape_set in [
11277            WIT_HTTP_SHAPE_PREFIXES,
11278            WIT_PUBSUB_SHAPE_PREFIXES,
11279            WIT_STORE_SHAPE_PREFIXES,
11280        ] {
11281            for prefix in shape_set {
11282                let wit = format!("{prefix}x");
11283                let hits = [
11284                    wit_shape_is_http(&wit),
11285                    wit_shape_is_pubsub(&wit),
11286                    wit_shape_is_store(&wit),
11287                    wit_shape_is_capability(&wit),
11288                ]
11289                .iter()
11290                .filter(|&&b| b)
11291                .count();
11292                assert_eq!(
11293                    hits,
11294                    1,
11295                    "raw-&str WIT-shape 4-way predicate partition must \
11296                     admit exactly one arm per canonical prefix; got {hits} \
11297                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
11298                     is_capability={})",
11299                    wit_shape_is_http(&wit),
11300                    wit_shape_is_pubsub(&wit),
11301                    wit_shape_is_store(&wit),
11302                    wit_shape_is_capability(&wit),
11303                );
11304            }
11305        }
11306        // Capability-arm sweep on the raw `&str` axis: two
11307        // representative Capability-shaped `:wit` values (a bare non-
11308        // prefix-matching WIT world, the deliberately-shaped empty
11309        // string the pure classifier still admits per
11310        // [`wit_shape_is_capability`]'s docstring). Both must land on
11311        // the fourth arm exclusively so the partition witness holds
11312        // across the full 4-arm closure on the raw `&str` axis.
11313        for wit in ["custom:capability-only", ""] {
11314            let hits = [
11315                wit_shape_is_http(wit),
11316                wit_shape_is_pubsub(wit),
11317                wit_shape_is_store(wit),
11318                wit_shape_is_capability(wit),
11319            ]
11320            .iter()
11321            .filter(|&&b| b)
11322            .count();
11323            assert_eq!(
11324                hits, 1,
11325                "raw-&str WIT-shape 4-way predicate partition must \
11326                 admit exactly one arm on Capability-shaped wit={wit:?}"
11327            );
11328            assert!(
11329                wit_shape_is_capability(wit),
11330                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
11331            );
11332        }
11333    }
11334
11335    #[test]
11336    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
11337        // Composition-witness pin: [`wit_shape_is_capability`] is the
11338        // exact-inverse disjunction of the sibling payload-arm free-
11339        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
11340        // / [`wit_shape_is_store`]. A future reimplementation that
11341        // grew its own prefix-set scan (e.g. inlining a fourth
11342        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
11343        // not own today) rather than delegating to the sibling trio
11344        // would drift loudly here — the composition contract binds the
11345        // fourth-arm free-function predicate to the exact-inverse of
11346        // the three payload-arm free-function predicates, so any
11347        // rebrand of any prefix-set const flows through
11348        // [`wit_shape_is_capability`] by construction without a
11349        // coordinated per-consumer rewrite. Peer of the sibling
11350        // [`WitContract`]-surface
11351        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
11352        // composition pin — extends the discipline onto the raw
11353        // `&str` axis.
11354        let mut cases: Vec<String> = Vec::new();
11355        for shape_set in [
11356            WIT_HTTP_SHAPE_PREFIXES,
11357            WIT_PUBSUB_SHAPE_PREFIXES,
11358            WIT_STORE_SHAPE_PREFIXES,
11359        ] {
11360            for prefix in shape_set {
11361                cases.push(format!("{prefix}x"));
11362            }
11363        }
11364        cases.push("custom:capability-only".to_string());
11365        cases.push(String::new());
11366        for wit in cases {
11367            assert_eq!(
11368                wit_shape_is_capability(&wit),
11369                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
11370                "wit_shape_is_capability must equal \
11371                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
11372                 at wit={wit:?}"
11373            );
11374        }
11375    }
11376
11377    #[test]
11378    fn wit_shape_classifier_family_is_const_fn() {
11379        // Fail-before-pass-after pin on the 4-arm free-function WIT-
11380        // shape classifier family's `const`-eval posture. Each of the
11381        // four peer classifiers ([`wit_shape_is_http`] /
11382        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11383        // [`wit_shape_is_capability`]) and the underlying combinator
11384        // [`wit_shape_matches`] must be `pub const fn` — any future
11385        // accidental downgrade to non-`const` fails the `const fn`
11386        // wrappers below at caixa-core build time with E0015
11387        // (`cannot call non-const function`), strictly stronger than
11388        // a runtime `assert!` and strictly stronger than the module-
11389        // scope `const _: () = assert!(…)` pins immediately after the
11390        // classifier declarations (those anchor specific accept-set
11391        // truth-table entries; this pin anchors the `const` posture
11392        // itself via `const fn` wrappers that are only well-formed
11393        // when the callee is itself `const fn`).
11394        //
11395        // Verified fail-before-pass-after by locally reverting
11396        // `pub const fn` → `pub fn` on each classifier and observing
11397        // E0015 at every corresponding wrapper call site (build
11398        // error, no test-time surface), then restoring `pub const fn`
11399        // and observing the pin pass at test time. Peer of the
11400        // sibling M3
11401        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11402        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11403        // M2
11404        // [`child_spec_restart_accessor_is_const_fn`] /
11405        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11406        // and M3
11407        // [`placement_estrategia_accessor_is_const_fn`] /
11408        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11409        // sibling `const`-eval-surface-pass axes.
11410        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
11411            wit_shape_matches(wit, prefixes)
11412        }
11413        const fn http_via_const_fn(wit: &str) -> bool {
11414            wit_shape_is_http(wit)
11415        }
11416        const fn pubsub_via_const_fn(wit: &str) -> bool {
11417            wit_shape_is_pubsub(wit)
11418        }
11419        const fn store_via_const_fn(wit: &str) -> bool {
11420            wit_shape_is_store(wit)
11421        }
11422        const fn capability_via_const_fn(wit: &str) -> bool {
11423            wit_shape_is_capability(wit)
11424        }
11425        // Sweep one canonical accept-set sample per arm plus the
11426        // payload-less/empty capability samples, asserting the
11427        // wrapper and direct dispatches agree byte-for-byte across
11428        // the closed 4-arm partition.
11429        let cases: [(&str, bool, bool, bool, bool); 6] = [
11430            ("wasi:http/proxy", true, false, false, false),
11431            ("http:incoming", true, false, false, false),
11432            ("nats:events", false, true, false, false),
11433            ("kafka:topic", false, true, false, false),
11434            ("wasi:keyvalue/store", false, false, true, false),
11435            ("kv:cache", false, false, true, false),
11436        ];
11437        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
11438            assert_eq!(
11439                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
11440                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11441                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
11442            );
11443            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
11444            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
11445            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
11446            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11447            assert_eq!(wit_shape_is_http(wit), is_http);
11448            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
11449            assert_eq!(wit_shape_is_store(wit), is_store);
11450        }
11451        // Payload-less capability arm (the 4th partition arm).
11452        let capability_samples: [&str; 3] =
11453            ["wasi:filesystem/preopens", "custom:capability-only", ""];
11454        for wit in capability_samples {
11455            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11456            assert!(wit_shape_is_capability(wit));
11457            assert!(!wit_shape_is_http(wit));
11458            assert!(!wit_shape_is_pubsub(wit));
11459            assert!(!wit_shape_is_store(wit));
11460        }
11461    }
11462
11463    #[test]
11464    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
11465        // Composition-witness pin: [`wit_shape_matches`] agrees with
11466        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
11467        // dispatch (the prior non-`const` implementation) across
11468        // boundary lengths — empty `wit`, empty prefix, one-byte
11469        // slack, prefix longer than `wit`, one-byte trailing slack.
11470        // The rewrite to a byte-level manual starts_with loop (the
11471        // enabler for the `pub const fn` posture) must not change any
11472        // truth-table entry on the canonical accept-set — this pin
11473        // sweeps a targeted boundary corpus and asserts byte-for-byte
11474        // agreement, locking the const-fn rewrite's semantics against
11475        // the prior iterator body by construction.
11476        let prefixes = &["wasi:http/", "http:"][..];
11477        let cases: [(&str, bool); 12] = [
11478            ("wasi:http/proxy", true),
11479            ("wasi:http/", true), // exact-length match on prefix
11480            ("wasi:http", false), // one byte short
11481            ("http:", true),
11482            ("http:incoming", true),
11483            ("http", false), // one byte short
11484            ("", false),
11485            ("wasi:https/proxy", false),
11486            ("nats:events", false),
11487            ("HTTPS:", false), // uppercase — no case-fold in classifier
11488            ("wasi:HTTP/proxy", false),
11489            ("wasi:http", false),
11490        ];
11491        for (wit, expected) in cases {
11492            assert_eq!(
11493                wit_shape_matches(wit, prefixes),
11494                expected,
11495                "wit_shape_matches disagrees with reference at wit={wit:?}",
11496            );
11497            // Byte-equal to the iterator body it replaced.
11498            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
11499            assert_eq!(
11500                wit_shape_matches(wit, prefixes),
11501                via_iter,
11502                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
11503            );
11504        }
11505        // Empty prefix set → always false regardless of `wit`.
11506        let empty: &[&str] = &[];
11507        assert!(!wit_shape_matches("", empty));
11508        assert!(!wit_shape_matches("wasi:http/proxy", empty));
11509        // Empty prefix inside a non-empty set → always true (every
11510        // string starts with the empty string, matching the
11511        // iterator body's semantics on `str::starts_with("")`).
11512        let contains_empty: &[&str] = &["nats:", ""];
11513        assert!(wit_shape_matches("", contains_empty));
11514        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
11515    }
11516
11517    #[test]
11518    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
11519        // 4-way partition-witness pin: for every canonical prefix in
11520        // the payload-arm accept-sets, exactly one of the four
11521        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11522        // [`WitContract::is_store`] / [`WitContract::is_capability`]
11523        // predicates returns `true` and the other three return `false`
11524        // — the four-arm partition witness that locks the substrate's
11525        // WIT-shape-space closure on the pre-projection axis load-
11526        // bearing. A future arm addition (a hypothetical fourth
11527        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
11528        // shape) that landed on one of the payload-arm predicates
11529        // without shrinking [`WitContract::is_capability`]'s accept-set
11530        // would surface here as two arms returning `true` simultaneously
11531        // — a partition-witness break the pin catches at caixa-core
11532        // build time rather than a silent per-consumer misclassification
11533        // at renderer emit time. Peer of the sibling `WitTarget`-side
11534        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
11535        // partition-witness pin on the post-projection payload-scalar
11536        // arm-set — extends the discipline onto the pre-projection
11537        // 4-arm shape-space.
11538        for shape_set in [
11539            WIT_HTTP_SHAPE_PREFIXES,
11540            WIT_PUBSUB_SHAPE_PREFIXES,
11541            WIT_STORE_SHAPE_PREFIXES,
11542        ] {
11543            for prefix in shape_set {
11544                let c = WitContract {
11545                    de: "cart".into(),
11546                    para: "catalog".into(),
11547                    wit: format!("{prefix}x"),
11548                    endpoint: None,
11549                    subject: None,
11550                    slot: None,
11551                };
11552                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11553                    .iter()
11554                    .filter(|&&b| b)
11555                    .count();
11556                assert_eq!(
11557                    hits,
11558                    1,
11559                    "WitContract WIT-shape 4-way predicate partition must \
11560                     admit exactly one arm per canonical prefix; got {hits} \
11561                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
11562                     is_capability={})",
11563                    c.wit,
11564                    c.is_http(),
11565                    c.is_pubsub(),
11566                    c.is_store(),
11567                    c.is_capability(),
11568                );
11569            }
11570        }
11571        // Capability-arm sweep: two representative capability shapes
11572        // (a bare WIT world outside the three payload-arm prefix sets,
11573        // and the deliberately-shaped empty string that
11574        // [`crate::render::is_wit_world_ref`] rejects at
11575        // [`WitContract::target`] time but which the pure classifier
11576        // still admits — see the method docstring's "purely syntactic
11577        // classification" note). Both must land on the fourth arm
11578        // exclusively, so the partition witness holds across the full
11579        // 4-arm closure.
11580        for wit in ["custom:capability-only", ""] {
11581            let c = WitContract {
11582                de: "cart".into(),
11583                para: "catalog".into(),
11584                wit: wit.into(),
11585                endpoint: None,
11586                subject: None,
11587                slot: None,
11588            };
11589            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11590                .iter()
11591                .filter(|&&b| b)
11592                .count();
11593            assert_eq!(
11594                hits, 1,
11595                "WitContract WIT-shape 4-way predicate partition must \
11596                 admit exactly one arm on Capability-shaped wit={wit:?}"
11597            );
11598            assert!(
11599                c.is_capability(),
11600                "wit={wit:?} must project onto the Capability arm"
11601            );
11602        }
11603    }
11604
11605    #[test]
11606    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
11607        // Composition-witness pin: [`WitContract::is_capability`] is the
11608        // exact-inverse disjunction of the sibling payload-arm predicate
11609        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11610        // [`WitContract::is_store`]. A future reimplementation that
11611        // grew its own prefix-set scan (e.g. inlining a fourth
11612        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
11613        // own today) rather than delegating to the sibling trio would
11614        // drift loudly here — the composition contract binds the
11615        // fourth-arm predicate to the exact-inverse of the three
11616        // payload-arm predicates, so any rebrand of any prefix-set const
11617        // flows through this method by construction without a
11618        // coordinated per-consumer rewrite. Sweeps the union of the
11619        // three payload-arm prefix sets plus two Capability-shaped
11620        // shapes (a bare non-prefix-matching WIT world, the deliberately-
11621        // empty string the pure classifier still admits per the method
11622        // docstring's "purely syntactic classification" note).
11623        let mut cases: Vec<String> = Vec::new();
11624        for shape_set in [
11625            WIT_HTTP_SHAPE_PREFIXES,
11626            WIT_PUBSUB_SHAPE_PREFIXES,
11627            WIT_STORE_SHAPE_PREFIXES,
11628        ] {
11629            for prefix in shape_set {
11630                cases.push(format!("{prefix}x"));
11631            }
11632        }
11633        cases.push("custom:capability-only".to_string());
11634        cases.push(String::new());
11635        for wit in cases {
11636            let c = WitContract {
11637                de: "cart".into(),
11638                para: "catalog".into(),
11639                wit: wit.clone(),
11640                endpoint: None,
11641                subject: None,
11642                slot: None,
11643            };
11644            assert_eq!(
11645                c.is_capability(),
11646                !c.is_http() && !c.is_pubsub() && !c.is_store(),
11647                "WitContract::is_capability must equal \
11648                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
11649            );
11650        }
11651    }
11652
11653    #[test]
11654    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
11655        // Cross-projection-witness pin: whenever [`WitContract::target`]
11656        // succeeds, the pre-projection [`WitContract::is_capability`]
11657        // classification agrees with the post-projection
11658        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
11659        // predicate — the 4-arm typed partition on the substrate's
11660        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
11661        // partition on the pre-projection axis line up by construction.
11662        // A future divergence between the two axes (a peer
11663        // [`WitTarget`] variant addition that landed on the typed-view
11664        // surface without a peer prefix-set + [`WitContract`] predicate
11665        // extension, or vice versa) would surface here at caixa-core
11666        // build time rather than a silent per-consumer split at renderer
11667        // emit time. Peer of the sibling pre-/post-projection
11668        // agreement pins the payload-carrier trio
11669        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
11670        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
11671        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
11672        // post-projection — b11bb49 trio lift) already carry across the
11673        // three payload arms — this pin closes the pair on the fourth
11674        // payload-less arm.
11675        let http = WitContract {
11676            de: "cart".into(),
11677            para: "catalog".into(),
11678            wit: "wasi:http/proxy".into(),
11679            endpoint: Some("/x".into()),
11680            subject: None,
11681            slot: None,
11682        };
11683        assert!(!http.is_capability());
11684        assert!(!http.target().unwrap().is_capability());
11685
11686        let nats = WitContract {
11687            de: "cart".into(),
11688            para: "catalog".into(),
11689            wit: "nats:pub-sub".into(),
11690            endpoint: None,
11691            subject: Some("events.x".into()),
11692            slot: None,
11693        };
11694        assert!(!nats.is_capability());
11695        assert!(!nats.target().unwrap().is_capability());
11696
11697        let kv = WitContract {
11698            de: "cart".into(),
11699            para: "catalog".into(),
11700            wit: "wasi:keyvalue/store".into(),
11701            endpoint: None,
11702            subject: None,
11703            slot: Some("checkout/$orderId".into()),
11704        };
11705        assert!(!kv.is_capability());
11706        assert!(!kv.target().unwrap().is_capability());
11707
11708        let cap = WitContract {
11709            de: "cart".into(),
11710            para: "catalog".into(),
11711            wit: "custom:capability-only".into(),
11712            endpoint: None,
11713            subject: None,
11714            slot: None,
11715        };
11716        assert!(cap.is_capability());
11717        assert!(cap.target().unwrap().is_capability());
11718    }
11719
11720    #[test]
11721    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
11722        // Fail-before-pass-after pin on the [`WitContract`] pre-
11723        // projection accessor family's `const`-eval-surface posture.
11724        // Each of the three per-`:contratos` byte-string scalar
11725        // accessors ([`WitContract::source`] / [`WitContract::destination`]
11726        // / [`WitContract::world_ref`], each projecting through
11727        // `String::as_str` — const-stable since Rust 1.87, well within
11728        // the workspace MSRV) and each of the four peer WIT-shape
11729        // predicates ([`WitContract::is_http`] /
11730        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
11731        // [`WitContract::is_capability`], each composing
11732        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
11733        // free-function classifier family the sibling
11734        // [`wit_shape_classifier_family_is_const_fn`] pin already
11735        // anchors on the raw `&str → bool` axis) must be `pub const fn`
11736        // — any future accidental downgrade to non-`const` fails the
11737        // `const fn` wrappers below at caixa-core build time with E0015
11738        // (`cannot call non-const function`), strictly stronger than a
11739        // runtime `assert!` and strictly stronger than a
11740        // module-scope `const _: () = assert!(…)` pin (which cannot be
11741        // formed on a `&WitContract` fixture because the type's
11742        // `String` / `Option<String>` carriers rule out `const`-context
11743        // construction; the `const fn` wrapper is the load-bearing
11744        // shape that side-steps the destructor-in-const restriction on
11745        // the value axis while still pinning the `const`-fn posture on
11746        // the callee).
11747        //
11748        // Peer of the sibling free-function classifier pin
11749        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
11750        // raw `&str → bool` axis — this pin extends the same
11751        // `const`-eval-surface discipline onto the peer method surface
11752        // that composes through those free-function classifiers, and
11753        // simultaneously onto the underlying per-`:contratos`
11754        // byte-string scalar-accessor trio each predicate reads
11755        // through. Sibling of the peer M3
11756        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11757        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11758        // M2
11759        // [`child_spec_restart_accessor_is_const_fn`] /
11760        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11761        // and M3
11762        // [`placement_estrategia_accessor_is_const_fn`] /
11763        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11764        // sibling `const`-eval-surface-pass axes.
11765        const fn source_via_const_fn(c: &WitContract) -> &str {
11766            c.source()
11767        }
11768        const fn destination_via_const_fn(c: &WitContract) -> &str {
11769            c.destination()
11770        }
11771        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
11772            c.world_ref()
11773        }
11774        const fn is_http_via_const_fn(c: &WitContract) -> bool {
11775            c.is_http()
11776        }
11777        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
11778            c.is_pubsub()
11779        }
11780        const fn is_store_via_const_fn(c: &WitContract) -> bool {
11781            c.is_store()
11782        }
11783        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
11784            c.is_capability()
11785        }
11786        // Sweep one canonical accept-set sample per WIT-shape arm plus
11787        // a payload-less capability sample, asserting the wrapper and
11788        // direct dispatches agree byte-for-byte across the closed
11789        // 4-arm partition on both the scalar-accessor trio and the
11790        // WIT-shape-predicate family.
11791        for (wit, is_http, is_pubsub, is_store, is_capability) in [
11792            ("wasi:http/proxy", true, false, false, false),
11793            ("http:incoming", true, false, false, false),
11794            ("nats:events", false, true, false, false),
11795            ("kafka:topic", false, true, false, false),
11796            ("wasi:keyvalue/store", false, false, true, false),
11797            ("kv:cache", false, false, true, false),
11798            ("custom:capability-only", false, false, false, true),
11799            ("", false, false, false, true),
11800        ] {
11801            let c = WitContract {
11802                de: "cart".into(),
11803                para: "catalog".into(),
11804                wit: wit.into(),
11805                endpoint: None,
11806                subject: None,
11807                slot: None,
11808            };
11809            assert_eq!(source_via_const_fn(&c), c.source());
11810            assert_eq!(destination_via_const_fn(&c), c.destination());
11811            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
11812            assert_eq!(is_http_via_const_fn(&c), c.is_http());
11813            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
11814            assert_eq!(is_store_via_const_fn(&c), c.is_store());
11815            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
11816            assert_eq!(c.source(), "cart");
11817            assert_eq!(c.destination(), "catalog");
11818            assert_eq!(c.world_ref(), wit);
11819            assert_eq!(c.is_http(), is_http);
11820            assert_eq!(c.is_pubsub(), is_pubsub);
11821            assert_eq!(c.is_store(), is_store);
11822            assert_eq!(c.is_capability(), is_capability);
11823        }
11824    }
11825
11826    #[test]
11827    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
11828        // Fail-before-pass-after pin on the four M3 mesh-slot
11829        // `String → &str` scalar accessors ([`Membro::nome`] /
11830        // [`Membro::versao_requirement`] on the per-`:membros` axis,
11831        // [`Entrada::hostname`] / [`Entrada::destination`] on the
11832        // per-`:entrada` axis) — each projects the typed slot's
11833        // [`String`] storage through the `pub const fn`
11834        // [`String::as_str`] (const-stable since Rust 1.87, well
11835        // within the workspace MSRV) and any future accidental
11836        // downgrade to non-`const` fails the corresponding
11837        // `<name>_via_const_fn` wrapper at caixa-core build time with
11838        // E0015 (`cannot call non-const method`), strictly stronger
11839        // than a runtime `assert!` and strictly stronger than a
11840        // module-scope `const _: () = assert!(…)` pin (which cannot
11841        // be formed on `&Membro` / `&Entrada` fixtures because the
11842        // types' `String` carriers rule out `const`-context value
11843        // construction; the `const fn` wrapper is the load-bearing
11844        // shape that side-steps the destructor-in-const restriction
11845        // on the value axis while still pinning the `const`-fn
11846        // posture on the callee — mirror of the sibling
11847        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
11848        // (279823b) pin on the per-`:contratos` axis). Peer of the
11849        // sibling per-M2/M3/universal-axis `String → &str` accessor
11850        // family pins on the sibling `const`-eval-surface passes
11851        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
11852        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
11853        // typed-newtype wrapper,
11854        // [`crate::supervisor::ChildSpec::nome`] /
11855        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
11856        // M2 supervisor-tree axis,
11857        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
11858        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
11859        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
11860        // axis, and the sibling per-`:contratos`
11861        // [`WitContract::source`] / [`WitContract::destination`] /
11862        // [`WitContract::world_ref`] trio at 279823b).
11863        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
11864            m.nome()
11865        }
11866        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
11867            m.versao_requirement()
11868        }
11869        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
11870            e.hostname()
11871        }
11872        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
11873            e.destination()
11874        }
11875        for (caixa, versao) in [
11876            ("cart", "^0.1"),
11877            ("catalog-v2", "~0.2.3"),
11878            ("checkout", "*"),
11879        ] {
11880            let m = Membro {
11881                caixa: caixa.into(),
11882                versao: versao.into(),
11883            };
11884            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
11885            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
11886            assert_eq!(m.nome(), caixa);
11887            assert_eq!(m.versao_requirement(), versao);
11888        }
11889        for (host, para) in [
11890            ("cart.example.com", "cart"),
11891            ("api.checkout.io", "checkout"),
11892        ] {
11893            let e = Entrada {
11894                host: host.into(),
11895                para: para.into(),
11896                paths: vec![],
11897                port: DEFAULT_SERVICO_PORT,
11898            };
11899            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
11900            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
11901            assert_eq!(e.hostname(), host);
11902            assert_eq!(e.destination(), para);
11903        }
11904    }
11905
11906    #[test]
11907    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
11908        // Load-bearing contract pin: on every canonical
11909        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
11910        // [`WitContract::target_projected`] returns byte-equal to
11911        // [`WitContract::target`]`().unwrap()` — the post-validation
11912        // projection accessor is a thin panicking wrapper over the
11913        // pre-validation validator, no extra work in the projection
11914        // path. Any future divergence (a validator-side normalization
11915        // the projection doesn't route through, an accessor-side
11916        // caching layer the validator doesn't populate) would surface
11917        // here at caixa-core build time rather than a silent per-consumer
11918        // split at renderer emit time. Sweeps the closed 4-arm
11919        // [`WitTarget`] partition ([`WitTarget::Http`] /
11920        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
11921        // [`WitTarget::Capability`]) so every arm carries a byte-equality
11922        // pin on the two-accessor pair.
11923        for (wit, endpoint, subject, slot) in [
11924            ("wasi:http/proxy", Some("/x"), None, None),
11925            ("nats:pub-sub", None, Some("events.x"), None),
11926            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
11927            ("custom:capability-only", None, None, None),
11928        ] {
11929            let c = WitContract {
11930                de: "cart".into(),
11931                para: "catalog".into(),
11932                wit: wit.into(),
11933                endpoint: endpoint.map(str::to_string),
11934                subject: subject.map(str::to_string),
11935                slot: slot.map(str::to_string),
11936            };
11937            assert_eq!(
11938                c.target_projected(),
11939                c.target().unwrap(),
11940                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
11941            );
11942        }
11943    }
11944
11945    #[test]
11946    #[should_panic(expected = "validated by typed_view")]
11947    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
11948        // Panic-path pin: [`WitContract::target_projected`] threads the
11949        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
11950        // through its expect-panic when called on a contract whose
11951        // (`:wit`, payload) shape has not been crossed by
11952        // [`AplicacaoSpec::validate`] — a contract with a structurally-
11953        // invalid `:wit` (hyphen-for-colon typo) that would surface
11954        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
11955        // A future rebrand on the panic-message axis would land at one
11956        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
11957        // and this pin's [`should_panic(expected = …)`] literal would
11958        // migrate alongside — the pin catches drift between the const
11959        // and the accessor's `expect(…)` call by construction.
11960        let c = WitContract {
11961            de: "cart".into(),
11962            para: "catalog".into(),
11963            // Hyphen-for-colon typo: `WitContract::target` returns
11964            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
11965            // driving the [`WitContract::target_projected`] expect-panic.
11966            wit: "wasi-http/proxy".into(),
11967            endpoint: Some("/x".into()),
11968            subject: None,
11969            slot: None,
11970        };
11971        let _ = c.target_projected();
11972    }
11973
11974    #[test]
11975    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
11976        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
11977        // carries the exact byte-string the two prior open-coded
11978        // `.target().expect("validated by typed_view")` production
11979        // consumers threaded through inline before this lift converged
11980        // them onto [`WitContract::target_projected`] — the caixa-mesh
11981        // per-`(:de, :para)` CNP L7 introspection branch at
11982        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
11983        // graph` per-`:contratos` payload-column printer at
11984        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
11985        // byte-string load-bearing so a well-meaning const-side rebrand
11986        // that didn't carry a matched pin migration would surface here
11987        // at caixa-core build time rather than a silent per-consumer
11988        // panic-message drift at cluster-apply time. Peer of the
11989        // sibling [`WitTarget::CAPABILITY_LABEL`] /
11990        // [`WitTarget::CAPABILITY_EXPECTED`] /
11991        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
11992        // the paired payload-less-arm scalar-const family.
11993        assert_eq!(
11994            WitContract::PROJECTED_INVARIANT_MSG,
11995            "validated by typed_view"
11996        );
11997    }
11998
11999    #[test]
12000    fn empty_wit_takes_precedence_over_invalid() {
12001        // Ordering pin: `EmptyWit` is the more self-locating
12002        // diagnostic on `""` and must lead — the value-shape gate is
12003        // only reached after the empty-check fires. Mirrors
12004        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12005        // the peer payload axis.
12006        let mut s = three_member_spec();
12007        s.contratos.push(WitContract {
12008            de: "payment".into(),
12009            para: "catalog".into(),
12010            wit: String::new(),
12011            endpoint: None,
12012            subject: None,
12013            slot: None,
12014        });
12015        let err = s.validate().unwrap_err();
12016        assert!(
12017            matches!(err, AplicacaoError::EmptyWit { .. }),
12018            "got {err:?}"
12019        );
12020    }
12021
12022    #[test]
12023    fn wit_invalid_fires_before_payload_shape_arm() {
12024        // Ordering pin: a malformed `:wit` surfaces *its own*
12025        // diagnostic (which names the offending wit verbatim) before
12026        // any payload-field check — a contrato whose wit is
12027        // structurally invalid AND carries a wrong target field
12028        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
12029        // because the dispatch on the wit is what decides which
12030        // payload field is "right" in the first place. Without this
12031        // ordering, the author would see "wrong target field" for a
12032        // wit that hasn't even been parsed, which doesn't name the
12033        // root cause.
12034        let mut s = three_member_spec();
12035        s.contratos.push(WitContract {
12036            de: "payment".into(),
12037            para: "catalog".into(),
12038            // Hyphen-for-colon typo + endpoint set: pre-gate this
12039            // raised `ContratoWrongTarget { expected: "none" }` (the
12040            // Capability arm rejecting the endpoint), masking the
12041            // real authoring mistake (the wit isn't `wasi:http/proxy`).
12042            wit: "wasi-http/proxy".into(),
12043            endpoint: Some("/x".into()),
12044            subject: None,
12045            slot: None,
12046        });
12047        let err = s.validate().unwrap_err();
12048        assert!(
12049            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
12050                if wit == "wasi-http/proxy"),
12051            "got {err:?}"
12052        );
12053    }
12054
12055    #[test]
12056    fn wit_invalid_diagnostic_carries_offending_wit() {
12057        // Diagnostic-shape pin — the offending `:wit` + `:de` +
12058        // `:para` + a non-empty reason flow through verbatim so the
12059        // author can grep their caixa.lisp for the offending contrato
12060        // block and fix it in one edit. Same shape as
12061        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
12062        let err = contrato_wit_err("WASI:HTTP/proxy");
12063        match err {
12064            AplicacaoError::ContratoWitInvalid {
12065                de,
12066                para,
12067                wit,
12068                reason,
12069            } => {
12070                assert_eq!(de, "payment");
12071                assert_eq!(para, "catalog");
12072                assert_eq!(wit, "WASI:HTTP/proxy");
12073                assert!(!reason.is_empty(), "reason field must be non-empty");
12074            }
12075            other => panic!("expected ContratoWitInvalid, got {other:?}"),
12076        }
12077    }
12078
12079    // ── :contratos :subject value-shape gate ─────────────────────────────
12080    //
12081    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
12082    // suites on the peer payload axes. Until this gate landed
12083    // `WitContract::target()` only refused the empty string; a
12084    // structurally invalid subject silently passed validate and the
12085    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
12086    // Subject'` on publish / subscribe, or as a silent message drop,
12087    // far from the source caixa.lisp. Every authoring footgun the
12088    // NATS server's subject parser would catch on admission now
12089    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
12090    // offending `:subject` + `:de` + `:para` named verbatim. Same
12091    // diagnostic shape as `ContratoEndpointInvalid` /
12092    // `ContratoWitInvalid` on the peer payload axes; same shared
12093    // predicate (`crate::render::is_nats_subject`) ensures drift
12094    // between any two axes' rule enforcement is a build error at the
12095    // predicate, not piecemeal across renderers.
12096
12097    fn contrato_subject_err(subject: &str) -> AplicacaoError {
12098        // Fresh spec per call so the new contract doesn't collide on
12099        // identity with `three_member_spec`'s pre-existing entries.
12100        // The new edge uses `(payment, catalog)` — a pair the fixture
12101        // doesn't already declare — with `:wit "nats:pub-sub"` and the
12102        // varying `:subject`, so the subject-shape gate fires cleanly
12103        // after the wit-shape gate (which `"nats:pub-sub"` passes).
12104        let mut s = three_member_spec();
12105        s.contratos.push(WitContract {
12106            de: "payment".into(),
12107            para: "catalog".into(),
12108            wit: "nats:pub-sub".into(),
12109            endpoint: None,
12110            subject: Some(subject.into()),
12111            slot: None,
12112        });
12113        s.validate().unwrap_err()
12114    }
12115
12116    #[test]
12117    fn rejects_pubsub_contrato_subject_with_whitespace() {
12118        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
12119        // landed at the NATS server as a malformed subject the parser
12120        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
12121        // source caixa.lisp.
12122        let err = contrato_subject_err("foo bar");
12123        assert!(
12124            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12125                if subject == "foo bar" && reason.contains("whitespace")),
12126            "got {err:?}"
12127        );
12128    }
12129
12130    #[test]
12131    fn rejects_pubsub_contrato_subject_with_control_char() {
12132        let err = contrato_subject_err("foo\x01bar");
12133        assert!(
12134            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12135                if subject == "foo\x01bar" && reason.contains("control character")),
12136            "got {err:?}"
12137        );
12138    }
12139
12140    #[test]
12141    fn rejects_pubsub_contrato_subject_with_non_ascii() {
12142        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12143        // the subject from a doc with smart quotes / accented
12144        // characters" footgun.
12145        let err = contrato_subject_err("foo.caf\u{e9}");
12146        assert!(
12147            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12148                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
12149            "got {err:?}"
12150        );
12151    }
12152
12153    #[test]
12154    fn rejects_pubsub_contrato_subject_with_leading_dot() {
12155        // Empty leading token — NATS rejects.
12156        let err = contrato_subject_err(".foo");
12157        assert!(
12158            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12159                if subject == ".foo" && reason.contains("must not start with `.`")),
12160            "got {err:?}"
12161        );
12162    }
12163
12164    #[test]
12165    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
12166        // Empty trailing token — NATS rejects. The remediation
12167        // (use `>` instead) is in the reason string.
12168        let err = contrato_subject_err("foo.");
12169        assert!(
12170            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12171                if subject == "foo." && reason.contains("must not end with `.`")),
12172            "got {err:?}"
12173        );
12174    }
12175
12176    #[test]
12177    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
12178        // The canonical "I forgot to fill in the middle segment"
12179        // typo — `"foo..bar"`. NATS rejects empty tokens.
12180        let err = contrato_subject_err("foo..bar");
12181        assert!(
12182            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12183                if subject == "foo..bar" && reason.contains("consecutive `.`")),
12184            "got {err:?}"
12185        );
12186    }
12187
12188    #[test]
12189    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
12190        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
12191        // as the final segment. Pre-gate this passed as a typed edge
12192        // and surfaced at runtime as a NATS subscribe rejection.
12193        let err = contrato_subject_err("foo.>.bar");
12194        assert!(
12195            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12196                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
12197            "got {err:?}"
12198        );
12199    }
12200
12201    #[test]
12202    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
12203        // `foo*.bar` — NATS wildcards are standalone tokens. The
12204        // remediation is in the reason string.
12205        let err = contrato_subject_err("foo*.bar");
12206        assert!(
12207            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12208                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
12209            "got {err:?}"
12210        );
12211    }
12212
12213    #[test]
12214    fn rejects_pubsub_contrato_subject_with_invalid_char() {
12215        // `foo,bar` — comma is not a valid NATS subject character.
12216        // Pinned separately from the wildcard arms so the invalid-
12217        // character diagnostic is in force.
12218        let err = contrato_subject_err("foo,bar");
12219        assert!(
12220            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12221                if subject == "foo,bar" && reason.contains("invalid character")),
12222            "got {err:?}"
12223        );
12224    }
12225
12226    #[test]
12227    fn rejects_pubsub_contrato_subject_too_long() {
12228        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
12229        // The legitimate-shape arms all pass (one all-`a` token, no
12230        // `.`, no wildcards); only the cap arm fires. Surfaces the
12231        // paste-from-binary / accidental-multi-line-blob landing
12232        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
12233        // on the peer axis.
12234        let big = "a".repeat(257);
12235        assert_eq!(big.len(), 257);
12236        let err = contrato_subject_err(&big);
12237        assert!(
12238            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12239                if subject == &big && reason.contains("max length of 256")),
12240            "got {err:?}"
12241        );
12242    }
12243
12244    #[test]
12245    fn pubsub_contrato_subject_max_length_validates() {
12246        // 256-byte subject — exactly the cap. Boundary pin: drift in
12247        // the cap surfaces here and at
12248        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
12249        // mirroring `http_contrato_endpoint_max_length_validates` and
12250        // `wit_max_length_validates` on the peer axes.
12251        let big = "a".repeat(256);
12252        assert_eq!(big.len(), 256);
12253        let mut s = three_member_spec();
12254        s.contratos.push(WitContract {
12255            de: "payment".into(),
12256            para: "catalog".into(),
12257            wit: "nats:pub-sub".into(),
12258            endpoint: None,
12259            subject: Some(big),
12260            slot: None,
12261        });
12262        s.validate().unwrap();
12263    }
12264
12265    #[test]
12266    fn pubsub_contrato_subject_accepts_canonical_forms() {
12267        // Positive-set sweep: every canonical NATS subject shape the
12268        // substrate-side `is_nats_subject` predicate accepts (the
12269        // multi-dot `events.order.charged`, the snake_case / kebab-
12270        // case / mixed-case tokens, the digit-bearing tokens, the
12271        // single-token wildcard `*` at every segment position, and
12272        // the trailing `>` multi-token wildcard) must remain a valid
12273        // contrato subject too. Drift between this list and the
12274        // substrate-side `nats_subject_accepts_canonical_forms` sweep
12275        // surfaces at the shared predicate — one source of truth.
12276        // Uses a fresh `(payment, catalog)` edge so none of the swept
12277        // subjects collide with the pre-existing entries in
12278        // `three_member_spec`.
12279        for subject in [
12280            "checkout.events.charge.failed",
12281            "rio.events.order.charged",
12282            "orders",
12283            "orders.123",
12284            "snake_case.token",
12285            "kebab-case.token",
12286            "MixedCase.Token",
12287            "orders.*.charged",
12288            "*.events.*",
12289            "orders.>",
12290        ] {
12291            let mut s = three_member_spec();
12292            s.contratos.push(WitContract {
12293                de: "payment".into(),
12294                para: "catalog".into(),
12295                wit: "nats:pub-sub".into(),
12296                endpoint: None,
12297                subject: Some(subject.into()),
12298                slot: None,
12299            });
12300            s.validate()
12301                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
12302        }
12303    }
12304
12305    #[test]
12306    fn contrato_subject_empty_takes_precedence_over_invalid() {
12307        // Ordering pin: `ContratoSubjectEmpty` is the more self-
12308        // locating diagnostic on `""` and must lead — the value-shape
12309        // gate is only reached after the empty-check fires. Mirrors
12310        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12311        // the peer payload axis.
12312        let mut s = three_member_spec();
12313        s.contratos.push(WitContract {
12314            de: "payment".into(),
12315            para: "catalog".into(),
12316            wit: "nats:pub-sub".into(),
12317            endpoint: None,
12318            subject: Some(String::new()),
12319            slot: None,
12320        });
12321        let err = s.validate().unwrap_err();
12322        assert!(
12323            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
12324            "got {err:?}"
12325        );
12326    }
12327
12328    #[test]
12329    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
12330        // Diagnostic-shape pin — the offending `:subject` + `:de` +
12331        // `:para` + a non-empty reason flow through verbatim so the
12332        // author can grep their caixa.lisp for the offending contrato
12333        // block and fix it in one edit. Same shape as
12334        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12335        // and `wit_invalid_diagnostic_carries_offending_wit`.
12336        let err = contrato_subject_err("foo..bar");
12337        match err {
12338            AplicacaoError::ContratoSubjectInvalid {
12339                de,
12340                para,
12341                subject,
12342                reason,
12343            } => {
12344                assert_eq!(de, "payment");
12345                assert_eq!(para, "catalog");
12346                assert_eq!(subject, "foo..bar");
12347                assert!(!reason.is_empty(), "reason field must be non-empty");
12348            }
12349            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
12350        }
12351    }
12352
12353    #[test]
12354    fn target_view_pubsub_subject_passes_through_to_typed_view() {
12355        // The compounding theorem on the pub-sub axis: every
12356        // `WitTarget::PubSub { subject }` returned by `target()` carries
12357        // a NATS-server-accepted subject. Renderers downstream of
12358        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
12359        // NATS Stream/Consumer CR emitter, the future `feira app graph`
12360        // view's subject labeller) can rely on this without re-checking
12361        // — the type system carries the proof. Mirrors
12362        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
12363        // on the peer axes.
12364        let nats = WitContract {
12365            de: "a".into(),
12366            para: "b".into(),
12367            wit: "nats:pub-sub".into(),
12368            endpoint: None,
12369            subject: Some("orders.events.*.charged".into()),
12370            slot: None,
12371        };
12372        match nats.target().unwrap() {
12373            WitTarget::PubSub { subject } => {
12374                assert_eq!(subject, "orders.events.*.charged");
12375            }
12376            other => panic!("expected PubSub, got {other:?}"),
12377        }
12378    }
12379
12380    // ── :contratos :slot value-shape gate ────────────────────────────────
12381    //
12382    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
12383    // (63e18a0) value-shape suites on the peer payload axes. Until this
12384    // gate landed `WitContract::target()` only refused the empty string
12385    // for the Store arm; a structurally invalid slot (raw whitespace,
12386    // control character, non-ASCII byte, paste-from-binary multi-line
12387    // blob) silently passed validate and surfaced at runtime as a
12388    // per-backend kv write rejection or a silent next-read corruption,
12389    // far from the source caixa.lisp with no field naming which
12390    // `:contratos` edge carried the typo. Every authoring footgun the
12391    // kv backend intersection-floor would catch on write now becomes a
12392    // caixa-build-time `ContratoSlotInvalid` with the offending
12393    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
12394    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
12395    // peer payload axes; same shared predicate
12396    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
12397    // any two axes' rule enforcement is a build error at the
12398    // predicate, not piecemeal across renderers. Closes the typed
12399    // payload-axis value-shape trajectory across all three legs of the
12400    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
12401
12402    fn contrato_slot_err(slot: &str) -> AplicacaoError {
12403        // Fresh spec per call so the new contract doesn't collide on
12404        // identity with `three_member_spec`'s pre-existing entries
12405        // and doesn't close a synchronous cycle the cycle detector
12406        // would reject before the slot-shape gate fires. The new edge
12407        // uses `(payment, catalog)` — a pair the fixture doesn't
12408        // already declare in either direction (the fixture carries
12409        // `cart -> catalog` and `cart -> payment`, so `payment ->
12410        // catalog` doesn't form a cycle on the sync subgraph) — with
12411        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
12412        // slot-shape gate fires cleanly after the wit-shape gate
12413        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
12414        // peer `contrato_subject_err` helper uses (63e18a0).
12415        let mut s = three_member_spec();
12416        s.contratos.push(WitContract {
12417            de: "payment".into(),
12418            para: "catalog".into(),
12419            wit: "wasi:keyvalue/store".into(),
12420            endpoint: None,
12421            subject: None,
12422            slot: Some(slot.into()),
12423        });
12424        s.validate().unwrap_err()
12425    }
12426
12427    #[test]
12428    fn rejects_store_contrato_slot_with_whitespace() {
12429        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
12430        // silently landed at the kv backend with whitespace whose
12431        // runtime behavior varies unpredictably across backends (etcd
12432        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
12433        // rejects on write). Now caught at the source caixa.lisp.
12434        let err = contrato_slot_err("check out/$order");
12435        assert!(
12436            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12437                if slot == "check out/$order" && reason.contains("whitespace")),
12438            "got {err:?}"
12439        );
12440    }
12441
12442    #[test]
12443    fn rejects_store_contrato_slot_with_tab() {
12444        // Tab byte arm-pinned separately from the space arm so a
12445        // future relaxation that admits one but not the other surfaces
12446        // here.
12447        let err = contrato_slot_err("check\tout");
12448        assert!(
12449            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12450                if slot == "check\tout" && reason.contains("whitespace")),
12451            "got {err:?}"
12452        );
12453    }
12454
12455    #[test]
12456    fn rejects_store_contrato_slot_with_control_char() {
12457        // SOH (0x01) — distinct from the whitespace arm. Redis admits
12458        // and corrupts on RESP protocol framing; DynamoDB rejects on
12459        // write.
12460        let err = contrato_slot_err("checkout/\x01order");
12461        assert!(
12462            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12463                if slot == "checkout/\x01order" && reason.contains("control character")),
12464            "got {err:?}"
12465        );
12466    }
12467
12468    #[test]
12469    fn rejects_store_contrato_slot_with_newline() {
12470        // Embedded newline — the canonical "the paste-from-binary slug
12471        // spans multiple lines" footgun. Distinct from the whitespace
12472        // arm because `\n` is a control character (0x0A).
12473        let err = contrato_slot_err("checkout\norder");
12474        assert!(
12475            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12476                if slot == "checkout\norder" && reason.contains("control character")),
12477            "got {err:?}"
12478        );
12479    }
12480
12481    #[test]
12482    fn rejects_store_contrato_slot_with_non_ascii() {
12483        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12484        // the slot from a doc with accented characters" footgun. Each
12485        // kv backend re-encodes non-ASCII differently (etcd preserves
12486        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
12487        // rejects), so the typed slot's value set is the intersection-
12488        // floor every backend admits identically (printable ASCII).
12489        let err = contrato_slot_err("ch\u{e9}ckout/$order");
12490        assert!(
12491            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12492                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
12493            "got {err:?}"
12494        );
12495    }
12496
12497    #[test]
12498    fn rejects_store_contrato_slot_too_long() {
12499        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
12500        // legitimate-shape arms all pass (a single all-`a` token, no
12501        // separators); only the cap arm fires. Surfaces the paste-
12502        // from-binary / accidental-multi-line-blob landing footgun.
12503        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
12504        // `rejects_http_contrato_endpoint_too_long` on the peer
12505        // payload axes.
12506        let big = "a".repeat(513);
12507        assert_eq!(big.len(), 513);
12508        let err = contrato_slot_err(&big);
12509        assert!(
12510            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12511                if slot == &big && reason.contains("max length of 512")),
12512            "got {err:?}"
12513        );
12514    }
12515
12516    #[test]
12517    fn store_contrato_slot_max_length_validates() {
12518        // 512-byte slot — exactly the cap. Boundary pin: drift in the
12519        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
12520        // simultaneously, mirroring
12521        // `pubsub_contrato_subject_max_length_validates` and
12522        // `http_contrato_endpoint_max_length_validates` on the peer
12523        // payload axes.
12524        let big = "a".repeat(512);
12525        assert_eq!(big.len(), 512);
12526        let mut s = three_member_spec();
12527        s.contratos.push(WitContract {
12528            de: "payment".into(),
12529            para: "catalog".into(),
12530            wit: "wasi:keyvalue/store".into(),
12531            endpoint: None,
12532            subject: None,
12533            slot: Some(big),
12534        });
12535        s.validate().unwrap();
12536    }
12537
12538    #[test]
12539    fn store_contrato_slot_accepts_canonical_forms() {
12540        // Positive-set sweep: every canonical kv slot template the
12541        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
12542        // (single-token identifiers, path-namespaced `$`-templates,
12543        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
12544        // snake_case / kebab-case / MixedCase tokens, digit-bearing
12545        // tokens, percent-encoded fragments) must remain valid
12546        // contrato slots too. Drift between this list and the
12547        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
12548        // surfaces at the shared predicate — one source of truth.
12549        // Uses a fresh `(payment, catalog)` edge so none of the swept
12550        // slots collide with the pre-existing entries in
12551        // `three_member_spec`.
12552        for slot in [
12553            "checkout",
12554            "checkout/$orderId",
12555            "users:{tenant}/{id}",
12556            "session.<sid>",
12557            "session.tokens.<sid>",
12558            "snake_case_key",
12559            "kebab-case-key",
12560            "MixedCase",
12561            "shard0",
12562            "v2/key",
12563            "users/caf%C3%A9",
12564        ] {
12565            let mut s = three_member_spec();
12566            s.contratos.push(WitContract {
12567                de: "payment".into(),
12568                para: "catalog".into(),
12569                wit: "wasi:keyvalue/store".into(),
12570                endpoint: None,
12571                subject: None,
12572                slot: Some(slot.into()),
12573            });
12574            s.validate()
12575                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
12576        }
12577    }
12578
12579    #[test]
12580    fn contrato_slot_empty_takes_precedence_over_invalid() {
12581        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
12582        // diagnostic on `""` and must lead — the value-shape gate is
12583        // only reached after the empty-check fires. Mirrors
12584        // `contrato_subject_empty_takes_precedence_over_invalid` and
12585        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12586        // the peer payload axes.
12587        let mut s = three_member_spec();
12588        s.contratos.push(WitContract {
12589            de: "payment".into(),
12590            para: "catalog".into(),
12591            wit: "wasi:keyvalue/store".into(),
12592            endpoint: None,
12593            subject: None,
12594            slot: Some(String::new()),
12595        });
12596        let err = s.validate().unwrap_err();
12597        assert!(
12598            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
12599            "got {err:?}"
12600        );
12601    }
12602
12603    #[test]
12604    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
12605        // Diagnostic-shape pin — the offending `:slot` + `:de` +
12606        // `:para` + a non-empty reason flow through verbatim so the
12607        // author can grep their caixa.lisp for the offending contrato
12608        // block and fix it in one edit. Same shape as
12609        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
12610        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12611        // on the peer payload axes.
12612        let err = contrato_slot_err("check out/$order");
12613        match err {
12614            AplicacaoError::ContratoSlotInvalid {
12615                de,
12616                para,
12617                slot,
12618                reason,
12619            } => {
12620                assert_eq!(de, "payment");
12621                assert_eq!(para, "catalog");
12622                assert_eq!(slot, "check out/$order");
12623                assert!(!reason.is_empty(), "reason field must be non-empty");
12624            }
12625            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
12626        }
12627    }
12628
12629    #[test]
12630    fn target_view_store_slot_passes_through_to_typed_view() {
12631        // The compounding theorem on the store axis: every
12632        // `WitTarget::Store { slot }` returned by `target()` carries a
12633        // kv-backend-accepted slot template. Renderers downstream of
12634        // `typed_view()` (the future per-Servico `:capabilities
12635        // wasi:keyvalue/store` axis emitter, the future `feira app
12636        // graph` view's slot labeller, the future kv-provider CR
12637        // materializer) can rely on this without re-checking — the
12638        // type system carries the proof. Mirrors
12639        // `target_view_pubsub_subject_passes_through_to_typed_view` on
12640        // the peer payload axis.
12641        let store = WitContract {
12642            de: "a".into(),
12643            para: "b".into(),
12644            wit: "wasi:keyvalue/store".into(),
12645            endpoint: None,
12646            subject: None,
12647            slot: Some("checkout/$orderId".into()),
12648        };
12649        match store.target().unwrap() {
12650            WitTarget::Store { slot } => {
12651                assert_eq!(slot, "checkout/$orderId");
12652            }
12653            other => panic!("expected Store, got {other:?}"),
12654        }
12655    }
12656
12657    #[test]
12658    fn rejects_self_loop_in_synchronous_contratos() {
12659        // A synchronous self-edge (`cart → cart` over HTTP) is now
12660        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
12661        // "this edge is degenerate" diagnostic — rather than incidentally
12662        // by the cycle detector framing it as a `["cart", "cart"]`
12663        // multi-node deadlock.
12664        let mut s = three_member_spec();
12665        s.contratos.push(contract_http("cart", "cart", "/loop"));
12666        let err = s.validate().unwrap_err();
12667        match err {
12668            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
12669                assert_eq!(caixa, "cart");
12670                assert_eq!(wit, "wasi:http/proxy");
12671            }
12672            other => panic!("expected ContratoSelfLoop, got {other:?}"),
12673        }
12674    }
12675
12676    #[test]
12677    fn rejects_self_loop_in_pubsub_contratos() {
12678        // The cycle detector excludes pub-sub edges (acyclic by
12679        // construction), so before the explicit gate a `nats:pub-sub`
12680        // self-edge silently validated and rendered a self-allow CNP.
12681        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
12682        let mut s = three_member_spec();
12683        s.contratos.push(WitContract {
12684            de: "payment".into(),
12685            para: "payment".into(),
12686            wit: "nats:pub-sub".into(),
12687            endpoint: None,
12688            subject: Some("rio.events.payment".into()),
12689            slot: None,
12690        });
12691        let err = s.validate().unwrap_err();
12692        match err {
12693            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
12694                assert_eq!(caixa, "payment");
12695                assert_eq!(wit, "nats:pub-sub");
12696            }
12697            other => panic!("expected ContratoSelfLoop, got {other:?}"),
12698        }
12699    }
12700
12701    #[test]
12702    fn self_loop_fires_before_payload_shape_check() {
12703        // The structural "this edge can't exist" error precedes the
12704        // narrower payload-shape diagnostics: a self-edge carrying an
12705        // otherwise-malformed endpoint still reports ContratoSelfLoop,
12706        // not ContratoEndpointInvalid.
12707        let mut s = three_member_spec();
12708        s.contratos.push(WitContract {
12709            de: "cart".into(),
12710            para: "cart".into(),
12711            wit: "wasi:http/proxy".into(),
12712            endpoint: Some("not-absolute".into()),
12713            subject: None,
12714            slot: None,
12715        });
12716        match s.validate().unwrap_err() {
12717            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
12718            other => panic!("expected ContratoSelfLoop, got {other:?}"),
12719        }
12720    }
12721
12722    #[test]
12723    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
12724        // A self-edge naming a non-member reports the more fundamental
12725        // ContratoMemberMissing first (the member doesn't exist), so the
12726        // self-loop gate is reached only once both endpoints resolve.
12727        let mut s = three_member_spec();
12728        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
12729        match s.validate().unwrap_err() {
12730            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
12731            other => panic!("expected ContratoMemberMissing, got {other:?}"),
12732        }
12733    }
12734
12735    #[test]
12736    fn rejects_two_node_synchronous_cycle() {
12737        let mut s = three_member_spec();
12738        // existing edges: cart → catalog, cart → payment
12739        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
12740        s.contratos
12741            .push(contract_http("catalog", "cart", "/refresh"));
12742        let err = s.validate().unwrap_err();
12743        match err {
12744            AplicacaoError::ContratoCycle { cycle } => {
12745                // Cycle traversal should mention both endpoints, with
12746                // the back-edge target appearing as both first and last
12747                // element to close the loop.
12748                assert!(cycle.len() >= 3);
12749                assert_eq!(cycle.first(), cycle.last());
12750                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
12751                assert!(body.contains("cart"));
12752                assert!(body.contains("catalog"));
12753            }
12754            other => panic!("expected ContratoCycle, got {other:?}"),
12755        }
12756    }
12757
12758    #[test]
12759    fn rejects_three_node_synchronous_cycle() {
12760        let mut s = three_member_spec();
12761        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
12762        s.contratos = vec![
12763            contract_http("catalog", "cart", "/x"),
12764            contract_http("cart", "payment", "/y"),
12765            contract_http("payment", "catalog", "/z"),
12766        ];
12767        let err = s.validate().unwrap_err();
12768        match err {
12769            AplicacaoError::ContratoCycle { cycle } => {
12770                assert_eq!(cycle.first(), cycle.last());
12771                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
12772                assert_eq!(body.len(), 3);
12773                assert!(body.contains("cart"));
12774                assert!(body.contains("catalog"));
12775                assert!(body.contains("payment"));
12776            }
12777            other => panic!("expected ContratoCycle, got {other:?}"),
12778        }
12779    }
12780
12781    #[test]
12782    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
12783        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
12784        // "acyclic by construction" — so a cycle whose closing edge
12785        // is pub-sub should NOT raise ContratoCycle.
12786        let mut s = three_member_spec();
12787        s.contratos = vec![
12788            contract_http("catalog", "cart", "/x"),
12789            contract_http("cart", "payment", "/y"),
12790            // Closing edge is pub-sub — async; not a sync deadlock.
12791            WitContract {
12792                de: "payment".into(),
12793                para: "catalog".into(),
12794                wit: "nats:pub-sub".into(),
12795                endpoint: None,
12796                subject: Some("checkout.events.charge.completed".into()),
12797                slot: None,
12798            },
12799        ];
12800        s.validate().expect("pub-sub edge breaks the sync cycle");
12801    }
12802
12803    #[test]
12804    fn store_edge_counts_as_synchronous_for_cycle_detection() {
12805        // wasi:keyvalue/store is request/response; a cycle through one
12806        // *is* a sync deadlock, just like HTTP.
12807        let mut s = three_member_spec();
12808        s.contratos = vec![
12809            contract_http("catalog", "cart", "/x"),
12810            WitContract {
12811                de: "cart".into(),
12812                para: "catalog".into(),
12813                wit: "wasi:keyvalue/store".into(),
12814                endpoint: None,
12815                subject: None,
12816                slot: Some("session/$id".into()),
12817            },
12818        ];
12819        let err = s.validate().unwrap_err();
12820        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
12821    }
12822
12823    #[test]
12824    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
12825        // Capability-only edges (unknown WIT shape, no payload) default
12826        // to synchronous — safer; authors with truly async capability
12827        // semantics can model them as pub-sub explicitly.
12828        let mut s = three_member_spec();
12829        s.contratos = vec![
12830            contract_http("catalog", "cart", "/x"),
12831            WitContract {
12832                de: "cart".into(),
12833                para: "catalog".into(),
12834                wit: "custom:exchange".into(),
12835                endpoint: None,
12836                subject: None,
12837                slot: None,
12838            },
12839        ];
12840        let err = s.validate().unwrap_err();
12841        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
12842    }
12843
12844    #[test]
12845    fn long_acyclic_chain_validates() {
12846        // A long sync chain (no back-edges) must validate even when
12847        // every node is reachable from the first.
12848        let mut s = three_member_spec();
12849        s.membros = vec![
12850            membro("a", "^0.1"),
12851            membro("b", "^0.1"),
12852            membro("c", "^0.1"),
12853            membro("d", "^0.1"),
12854            membro("e", "^0.1"),
12855        ];
12856        s.contratos = vec![
12857            contract_http("a", "b", "/1"),
12858            contract_http("b", "c", "/2"),
12859            contract_http("c", "d", "/3"),
12860            contract_http("d", "e", "/4"),
12861        ];
12862        s.entrada.as_mut().unwrap().para = "a".into();
12863        s.validate().unwrap();
12864    }
12865
12866    #[test]
12867    fn diamond_acyclic_validates() {
12868        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
12869        let mut s = three_member_spec();
12870        s.membros = vec![
12871            membro("a", "^0.1"),
12872            membro("b", "^0.1"),
12873            membro("c", "^0.1"),
12874            membro("d", "^0.1"),
12875        ];
12876        s.contratos = vec![
12877            contract_http("a", "b", "/1"),
12878            contract_http("a", "c", "/2"),
12879            contract_http("b", "d", "/3"),
12880            contract_http("c", "d", "/4"),
12881        ];
12882        s.entrada.as_mut().unwrap().para = "a".into();
12883        s.validate().unwrap();
12884    }
12885
12886    // ── duplicate-`:contratos` build-error gate ──────────────────────────
12887
12888    #[test]
12889    fn rejects_duplicate_http_contrato() {
12890        // Fail-before-pass-after pin: the fixture's `cart → catalog`
12891        // HTTP edge appears once. Push an identical entry — same
12892        // (de, para, wit, endpoint) — and validate() must reject it.
12893        // Until this gate landed the typed surface accepted the
12894        // duplicate silently and caixa-mesh's `cilium_network_policies`
12895        // emitted two ``CiliumNetworkPolicy`` objects with identical
12896        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
12897        // admission rejects on `kubectl apply` far from the source.
12898        let mut s = three_member_spec();
12899        s.contratos
12900            .push(contract_http("cart", "catalog", "/products/:id"));
12901        let err = s.validate().unwrap_err();
12902        assert!(
12903            matches!(
12904                err,
12905                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12906                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
12907            ),
12908            "got {err:?}"
12909        );
12910    }
12911
12912    #[test]
12913    fn rejects_duplicate_pubsub_contrato() {
12914        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
12915        // edges with identical (de, para, subject) are degenerate;
12916        // pin that the typed surface refuses both at validate time.
12917        let mut s = three_member_spec();
12918        let pubsub = WitContract {
12919            de: "payment".into(),
12920            para: "cart".into(),
12921            wit: "nats:pub-sub".into(),
12922            endpoint: None,
12923            subject: Some("checkout.events.charge.failed".into()),
12924            slot: None,
12925        };
12926        s.contratos.push(pubsub.clone());
12927        s.contratos.push(pubsub);
12928        let err = s.validate().unwrap_err();
12929        assert!(
12930            matches!(
12931                err,
12932                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12933                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
12934            ),
12935            "got {err:?}"
12936        );
12937    }
12938
12939    #[test]
12940    fn rejects_duplicate_store_contrato() {
12941        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
12942        // edges with identical (de, para, slot) collapse to one mesh-
12943        // policy edge; pin the build error.
12944        let mut s = three_member_spec();
12945        let store = WitContract {
12946            de: "cart".into(),
12947            para: "payment".into(),
12948            wit: "wasi:keyvalue/store".into(),
12949            endpoint: None,
12950            subject: None,
12951            slot: Some("checkout/$orderId".into()),
12952        };
12953        // Drop the conflicting HTTP `cart → payment` edge from the
12954        // fixture so the duplicate-store pair is the only one
12955        // distinguishable on this pair.
12956        s.contratos
12957            .retain(|c| !(c.de == "cart" && c.para == "payment"));
12958        s.contratos.push(store.clone());
12959        s.contratos.push(store);
12960        let err = s.validate().unwrap_err();
12961        assert!(
12962            matches!(
12963                err,
12964                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12965                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
12966            ),
12967            "got {err:?}"
12968        );
12969    }
12970
12971    #[test]
12972    fn rejects_duplicate_capability_contrato() {
12973        // Same gate on the pure-capability axis (no payload selector).
12974        // Two contracts with identical (de, para, wit) and no
12975        // endpoint/subject/slot are duplicate edges; pin so a future
12976        // `target_label` change can't accidentally collapse the
12977        // capability arm into a None-shaped key that compares equal
12978        // to a populated one.
12979        let mut s = three_member_spec();
12980        let capability = WitContract {
12981            de: "cart".into(),
12982            para: "catalog".into(),
12983            wit: "pleme:cap/audit".into(),
12984            endpoint: None,
12985            subject: None,
12986            slot: None,
12987        };
12988        s.contratos.push(capability.clone());
12989        s.contratos.push(capability);
12990        let err = s.validate().unwrap_err();
12991        match err {
12992            AplicacaoError::ContratoDuplicate {
12993                de,
12994                para,
12995                wit,
12996                target,
12997            } => {
12998                assert_eq!(de, "cart");
12999                assert_eq!(para, "catalog");
13000                assert_eq!(wit, "pleme:cap/audit");
13001                assert!(
13002                    target.contains("capability"),
13003                    "capability-edge duplicate diagnostic must surface the \
13004                     no-payload shape (got target = {target:?})"
13005                );
13006            }
13007            other => panic!("expected ContratoDuplicate, got {other:?}"),
13008        }
13009    }
13010
13011    #[test]
13012    fn accepts_distinct_http_paths_between_same_pair() {
13013        // Negative pin: two HTTP contracts cart → catalog at distinct
13014        // endpoints (`/products/:id` and `/search`) are *not*
13015        // duplicates — they're distinct typed edges differing on the
13016        // payload axis. The duplicate-gate must not over-match here,
13017        // since the cart-calls-catalog-on-multiple-paths shape is the
13018        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
13019        // example: cart calls catalog at /products/:id, payment at
13020        // /charge — same shape extends to two paths on one para).
13021        let mut s = three_member_spec();
13022        s.contratos
13023            .push(contract_http("cart", "catalog", "/search"));
13024        s.validate()
13025            .expect("distinct endpoints between same (de, para) must validate");
13026    }
13027
13028    #[test]
13029    fn accepts_same_endpoint_on_different_pairs() {
13030        // Negative pin: the same `/charge` endpoint reused on two
13031        // different (de, para) pairs is two distinct edges, not a
13032        // duplicate. Pinning this shape so the gate's identity key
13033        // includes both `de` and `para` (not just `(wit, endpoint)`).
13034        let mut s = three_member_spec();
13035        s.contratos
13036            .push(contract_http("payment", "catalog", "/charge"));
13037        s.validate()
13038            .expect("same endpoint reused on distinct (de, para) must validate");
13039    }
13040
13041    #[test]
13042    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
13043        // Pin the diagnostic shape: the duplicate-edge error names
13044        // *which* target field carried the conflict, so the author
13045        // doesn't have to re-grep the source caixa.lisp to find it.
13046        // Same self-locating diagnostic discipline as
13047        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
13048        let mut s = three_member_spec();
13049        s.contratos
13050            .push(contract_http("cart", "catalog", "/products/:id"));
13051        let err = s.validate().unwrap_err();
13052        let msg = format!("{err}");
13053        assert!(
13054            msg.contains("\"/products/:id\""),
13055            "duplicate-contrato diagnostic must name the offending \
13056             :endpoint payload (got: {msg:?})"
13057        );
13058        assert!(
13059            msg.contains("cart") && msg.contains("catalog"),
13060            "diagnostic must name both endpoints of the duplicate edge \
13061             (got: {msg:?})"
13062        );
13063    }
13064
13065    #[test]
13066    fn duplicate_contrato_gate_runs_after_membership_check() {
13067        // Order pin: a duplicate contract whose `:de` is *also* not in
13068        // `:membros` surfaces the membership error first — the
13069        // missing-member diagnostic is more locating than the
13070        // duplicate-edge one (the author has to fix the membership
13071        // before the duplicate is meaningful). Same ordering
13072        // discipline as `membros_validation_runs_before_contratos_membership_check`.
13073        let mut s = three_member_spec();
13074        s.contratos.push(contract_http("phantom", "catalog", "/x"));
13075        s.contratos.push(contract_http("phantom", "catalog", "/x"));
13076        let err = s.validate().unwrap_err();
13077        assert!(
13078            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
13079            "membership-missing must fire before duplicate-edge (got {err:?})"
13080        );
13081    }
13082
13083    #[test]
13084    fn duplicate_contrato_gate_runs_after_target_shape_check() {
13085        // Order pin: a contract with a malformed target (e.g. an HTTP
13086        // wit world with an empty :endpoint) surfaces the target-shape
13087        // error first, not the duplicate one. Even when two such
13088        // malformed entries are identical, the per-contract `target()`
13089        // check fires inside the loop *before* the duplicate-key
13090        // insert, so the diagnostic remains the most-locating one.
13091        let mut s = three_member_spec();
13092        let malformed = WitContract {
13093            de: "cart".into(),
13094            para: "catalog".into(),
13095            wit: "wasi:http/proxy".into(),
13096            endpoint: Some(String::new()),
13097            subject: None,
13098            slot: None,
13099        };
13100        s.contratos.push(malformed.clone());
13101        s.contratos.push(malformed);
13102        let err = s.validate().unwrap_err();
13103        assert!(
13104            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
13105            "endpoint-empty must fire before duplicate-edge (got {err:?})"
13106        );
13107    }
13108
13109    #[test]
13110    fn wit_target_label_pins_per_variant_format() {
13111        // Label format is the single source of truth every duplicate-
13112        // `:contratos` diagnostic + every future `feira app graph`
13113        // consumer routes through. Pin the shape per variant so a
13114        // future edit to `WitTarget::label` (e.g. a JSON emitter that
13115        // strips the leading `:`, or a rename from `endpoint` →
13116        // `path`) surfaces as a red-red test rather than as a silent
13117        // downstream diagnostic drift. Together with the exhaustive
13118        // `match` on `WitTarget` inside `label()`, adding a future
13119        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
13120        // peer, per-edge WIT registry variants) is a compile error at
13121        // the label site — not a fall-through into the `Capability`
13122        // "no payload" default the prior raw-field-probe helper
13123        // silently landed on.
13124        assert_eq!(
13125            WitTarget::Http {
13126                endpoint: "/charge",
13127            }
13128            .label(),
13129            "\
13130:endpoint \"/charge\""
13131        );
13132        assert_eq!(
13133            WitTarget::PubSub {
13134                subject: "events.checkout.paid",
13135            }
13136            .label(),
13137            "\
13138:subject \"events.checkout.paid\""
13139        );
13140        assert_eq!(
13141            WitTarget::Store {
13142                slot: "checkout/$order",
13143            }
13144            .label(),
13145            "\
13146:slot \"checkout/$order\""
13147        );
13148        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
13149        // Capability-arm label routes through the lifted
13150        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
13151        // declaration per arm, next to the variant" discipline the
13152        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
13153        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13154        // consts already carry extends to the payload-less arm; the
13155        // byte-string equality pin below plus this label-routes-
13156        // through-the-const pin make a future rebrand on either the
13157        // const declaration or the `label()` template a build error
13158        // here rather than a downstream consumer surprise.
13159        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
13160        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
13161    }
13162
13163    #[test]
13164    fn wit_target_display_routes_through_label_helper() {
13165        // Fail-before-pass-after pin on the fourth (and only remaining)
13166        // typed-shape-discriminator axis to converge onto the
13167        // three-path-convergence discipline the sibling M3
13168        // [`PlacementStrategy`] (0a2f653) and M2
13169        // [`crate::supervisor::RestartStrategy`] /
13170        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
13171        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
13172        // through [`WitTarget::label`], so every consumer reaching for
13173        // `format!("{v}")` on a typed payload target lands on the same
13174        // stable author-facing byte-string [`WitTarget::label`] returns
13175        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
13176        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
13177        // `:contratos` gate seeds via [`WitTarget::label`] at
13178        // aplicacao.rs:5491 already threads through.
13179        //
13180        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
13181        // through to the `Debug` derive's structural output
13182        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
13183        // rather than the [`WitTarget::label`] helper's stable byte-
13184        // string (`:endpoint "/charge"` — the author-facing `:contratos`
13185        // keyword form). Every future consumer that reaches for
13186        // `format!("{target}")` — the canonical shape every user-facing
13187        // pretty-print site on the sibling typed-enum axes
13188        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
13189        // [`crate::supervisor::RestartPolicy`]) already uses — would
13190        // silently land under a different byte-string than the
13191        // [`WitTarget::label`] callers that the duplicate-`:contratos`
13192        // diagnostic already threads through, with the mismatch
13193        // surfacing as a downstream diagnostic / graph / audit line
13194        // reading one spelling while the substrate's own gate emitted
13195        // another.
13196        //
13197        // Pin the routing here so a future
13198        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
13199        // that hand-rolls the per-arm formatting instead of delegating
13200        // to [`WitTarget::label`] fails at caixa-core build time.
13201        for variant in [
13202            WitTarget::Http {
13203                endpoint: "/charge",
13204            },
13205            WitTarget::PubSub {
13206                subject: "events.checkout.paid",
13207            },
13208            WitTarget::Store {
13209                slot: "checkout/$order",
13210            },
13211            WitTarget::Capability,
13212        ] {
13213            assert_eq!(
13214                variant.to_string(),
13215                variant.label(),
13216                "WitTarget::{variant:?} Display must route through \
13217                 WitTarget::label (single source of truth: the lifted \
13218                 payload_pair 4-arm dispatch the label helper already \
13219                 threads through)"
13220            );
13221        }
13222    }
13223
13224    #[test]
13225    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
13226        // Consumer-side pin on the three-path convergence:
13227        // [`std::fmt::Display`] agrees byte-for-byte with the
13228        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
13229        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
13230        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
13231        // Pre-lift the two paths were structurally independent — the
13232        // substrate-side gate reached for `target_view.label()` while a
13233        // future downstream diagnostic / graph / audit line reaching
13234        // for `format!("{target}")` would silently land on the `Debug`
13235        // derive's structural output. Pin the two paths byte-for-byte
13236        // here so any future variant addition (M4 `Rest`/`Grpc` split
13237        // of [`WitTarget::Http`], `Queue`-shaped peer of
13238        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
13239        // match error at [`WitTarget::payload_pair`] rather than a
13240        // silent per-consumer dispatch miss.
13241        for variant in [
13242            WitTarget::Http {
13243                endpoint: "/charge",
13244            },
13245            WitTarget::PubSub {
13246                subject: "events.checkout.paid",
13247            },
13248            WitTarget::Store {
13249                slot: "checkout/$order",
13250            },
13251            WitTarget::Capability,
13252        ] {
13253            assert_eq!(
13254                format!("{variant}"),
13255                variant.label(),
13256                "WitTarget::{variant:?} Display byte-string must match \
13257                 the AplicacaoError::ContratoDuplicate `target:` carrier \
13258                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
13259                 seeds via WitTarget::label — three-path convergence: \
13260                 Display + label + payload_pair all resolve to the same \
13261                 per-arm byte-string"
13262            );
13263        }
13264    }
13265
13266    #[test]
13267    fn wit_target_payload_pair_pins_per_variant() {
13268        // Pin the per-arm `(field-name, payload)` pair single-sourced
13269        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
13270        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
13271        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
13272        // and [`WitTarget::field_name`] (returns the first component)
13273        // route through. Until this lift landed [`WitTarget::label`]
13274        // dispatched on the same three arms with a per-arm
13275        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
13276        // paired [`WitTarget::HTTP_FIELD_NAME`] /
13277        // [`WitTarget::PUBSUB_FIELD_NAME`] /
13278        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
13279        // canonical "same shape, written N times" duplication
13280        // THEORY.md §I.3.5 promotes to a build-time concern. A future
13281        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
13282        // [`WitTarget::Http`], `Queue`-shaped peer of
13283        // [`WitTarget::Store`]) is one match-arm edit at
13284        // [`WitTarget::payload_pair`], visible here as a compile-time
13285        // exhaustiveness error on both this pin and the label-format
13286        // pin above.
13287        assert_eq!(
13288            WitTarget::Http {
13289                endpoint: "/charge"
13290            }
13291            .payload_pair(),
13292            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
13293        );
13294        assert_eq!(
13295            WitTarget::PubSub {
13296                subject: "events.x",
13297            }
13298            .payload_pair(),
13299            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
13300        );
13301        assert_eq!(
13302            WitTarget::Store {
13303                slot: "checkout/$order",
13304            }
13305            .payload_pair(),
13306            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
13307        );
13308        assert_eq!(WitTarget::Capability.payload_pair(), None);
13309    }
13310
13311    #[test]
13312    fn wit_target_field_name_pins_per_variant() {
13313        // Pin the per-arm author-facing `:contratos` payload field
13314        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
13315        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13316        // + returned by [`WitTarget::field_name`]. Every downstream
13317        // consumer (the [`WitContract::target`] gate's `expected:`
13318        // scalar, the [`WitTarget::label`] template's keyword prefix,
13319        // the `feira app graph` verb's `endpoint=…` prefix) routes
13320        // through the same three peer consts, so a rename on the
13321        // author-surface `(defcaixa … :contratos ((:de … :para …
13322        // :wit … :endpoint …)))` field lands in exactly one place.
13323        assert_eq!(
13324            WitTarget::Http {
13325                endpoint: "/charge"
13326            }
13327            .field_name(),
13328            Some(WitTarget::HTTP_FIELD_NAME),
13329        );
13330        assert_eq!(
13331            WitTarget::PubSub {
13332                subject: "events.x",
13333            }
13334            .field_name(),
13335            Some(WitTarget::PUBSUB_FIELD_NAME),
13336        );
13337        assert_eq!(
13338            WitTarget::Store {
13339                slot: "checkout/$order",
13340            }
13341            .field_name(),
13342            Some(WitTarget::STORE_FIELD_NAME),
13343        );
13344        // Capability arm carries no payload field — the diagnostic
13345        // never reports `expected: "capability"` because the gate's
13346        // Capability arm accepts no payload at all (it fires the
13347        // "expected: none" WrongTarget error instead), so the field-
13348        // name method returns None here rather than a placeholder.
13349        assert_eq!(WitTarget::Capability.field_name(), None);
13350
13351        // Peer const scalar values pinned so a rename on either side
13352        // (author-surface field name in the `(defcaixa …)` DSL, or
13353        // the diagnostic's `expected:` scalar) can't drift without
13354        // failing here first.
13355        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
13356        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
13357        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
13358    }
13359
13360    #[test]
13361    fn wit_target_payload_pins_per_variant() {
13362        // Pin the per-arm payload scalar single-sourced onto the
13363        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
13364        // [`WitTarget::payload`] — the peer per-half projection to
13365        // [`WitTarget::field_name`] on the paired sub-selector axis. The
13366        // three payload-carrying arms round-trip their author-declared
13367        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
13368        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
13369        // the payload-less [`WitTarget::Capability`] arm returns `None`.
13370        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
13371        // (c6ec2af) pin on the Component-0 projection axis, extended
13372        // onto the Component-1 projection axis so both per-half readers
13373        // on the paired dispatch carry their own byte-shape pin.
13374        assert_eq!(
13375            WitTarget::Http {
13376                endpoint: "/charge",
13377            }
13378            .payload(),
13379            Some("/charge"),
13380        );
13381        assert_eq!(
13382            WitTarget::PubSub {
13383                subject: "events.x",
13384            }
13385            .payload(),
13386            Some("events.x"),
13387        );
13388        assert_eq!(
13389            WitTarget::Store {
13390                slot: "checkout/$order",
13391            }
13392            .payload(),
13393            Some("checkout/$order"),
13394        );
13395        assert_eq!(WitTarget::Capability.payload(), None);
13396    }
13397
13398    #[test]
13399    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
13400        // Per-variant equivalence pin: for every arm of [`WitTarget`],
13401        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
13402        // byte-for-byte. Guards the drift surface where a future refactor
13403        // that split one accessor off the shared match onto its own
13404        // dispatch — a well-meaning "inline the pair back into per-half
13405        // fields for one crate-internal caller who only wanted one half"
13406        // or a scratch `impl` shadowing the derived projection — would
13407        // silently desynchronize [`WitTarget::payload`] from the
13408        // authoritative [`WitTarget::payload_pair`] dispatch, and every
13409        // downstream consumer that thinks "the payload half of the pair"
13410        // would drift from the diagnostic / graph consumers reading the
13411        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
13412        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
13413        // per-half projection pin (`gitrefspec_ref_pair_projects_
13414        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
13415        // FluxCD source-controller `spec.ref.<field>` axis — same "one
13416        // paired dispatch, both per-half projections agree byte-for-
13417        // byte" discipline extended onto the M3 `:contratos` payload-
13418        // arm surface.
13419        for variant in [
13420            WitTarget::Http {
13421                endpoint: "/charge",
13422            },
13423            WitTarget::PubSub {
13424                subject: "events.checkout.paid",
13425            },
13426            WitTarget::Store {
13427                slot: "checkout/$order",
13428            },
13429            WitTarget::Capability,
13430        ] {
13431            let via_projection = variant.payload();
13432            let via_pair = variant.payload_pair().map(|(_, p)| p);
13433            assert_eq!(
13434                via_projection, via_pair,
13435                "WitTarget::{variant:?} payload() must equal \
13436                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
13437                 regression that splits the two per-half projections off \
13438                 their shared match would silently desynchronize the \
13439                 payload accessor from the paired dispatch every \
13440                 diagnostic / graph consumer reads through",
13441            );
13442        }
13443    }
13444
13445    #[test]
13446    fn wit_target_http_endpoint_pins_per_variant() {
13447        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
13448        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
13449        // substrate-primitive per-arm post-projection accessor every
13450        // L7-HTTP-facing consumer routes through, sibling to the peer
13451        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
13452        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
13453        // arm round-trips its author-declared endpoint verbatim as
13454        // `Some("/charge")`; the three sibling arms
13455        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
13456        // [`WitTarget::Capability`]) each return `None` because they
13457        // carry no HTTP endpoint by definition. Same fail-before-pass-
13458        // after per-variant discipline as the sibling
13459        // `wit_target_payload_pins_per_variant` (5d6dc92) /
13460        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
13461        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
13462        // the peer pan-arm / per-half projection axes — extended onto
13463        // the per-arm HTTP-shape post-projection axis so a future
13464        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
13465        // [`WitTarget::Http`], a `Queue`-shaped peer of
13466        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
13467        // error on the sibling [`WitTarget::http_endpoint`] match arms
13468        // whose payload the L7-HTTP-shape accept-set is meant to bound.
13469        assert_eq!(
13470            WitTarget::Http {
13471                endpoint: "/charge",
13472            }
13473            .http_endpoint(),
13474            Some("/charge"),
13475        );
13476        assert_eq!(
13477            WitTarget::PubSub {
13478                subject: "events.checkout.paid",
13479            }
13480            .http_endpoint(),
13481            None,
13482        );
13483        assert_eq!(
13484            WitTarget::Store {
13485                slot: "checkout/$order",
13486            }
13487            .http_endpoint(),
13488            None,
13489        );
13490        assert_eq!(WitTarget::Capability.http_endpoint(), None);
13491    }
13492
13493    #[test]
13494    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
13495        // Per-variant coherence pin: for every arm of [`WitTarget`],
13496        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
13497        // arm (both project the same author-declared request-path
13498        // scalar), and returns `None` on every sibling arm regardless of
13499        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
13500        // Store carry their own payload the pan-arm accessor surfaces,
13501        // but that payload is not an HTTP endpoint — the per-arm
13502        // accessor must not leak it through the HTTP-shape channel).
13503        // Guards the drift surface where a future refactor that
13504        // conflated the per-arm HTTP projection with the pan-arm
13505        // [`WitTarget::payload`] projection — a well-meaning "one
13506        // accessor for the L7 branch, one for the graph" collapse that
13507        // routes both through the same 4-arm dispatch — would silently
13508        // widen the L7-HTTP-shape accept-set onto pub-sub / store
13509        // payloads at the caixa-mesh L7 emit branch, admitting a
13510        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
13511        // rule with the operator-side apply-time symptom (Cilium's
13512        // eBPF data-plane rejects every ingress edge whose L7 filter
13513        // doesn't match the wire-format HTTP request line) far from
13514        // the source refactor. Sibling to the peer
13515        // `wit_target_payload_matches_payload_pair_second_component_
13516        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
13517        // extended onto the per-arm HTTP specialization axis so both
13518        // the pan-arm and the per-arm projections carry their own
13519        // byte-shape coherence witness against the substrate's typed
13520        // arm-family accept-set.
13521        for variant in [
13522            WitTarget::Http {
13523                endpoint: "/charge",
13524            },
13525            WitTarget::PubSub {
13526                subject: "events.checkout.paid",
13527            },
13528            WitTarget::Store {
13529                slot: "checkout/$order",
13530            },
13531            WitTarget::Capability,
13532        ] {
13533            let per_arm = variant.http_endpoint();
13534            let pan_arm = variant.payload();
13535            if variant.is_http() {
13536                assert_eq!(
13537                    per_arm, pan_arm,
13538                    "WitTarget::{variant:?} http_endpoint() must equal \
13539                     payload() on the Http arm — a per-arm-vs-pan-arm \
13540                     split would silently drift the L7 emit branch's \
13541                     path-scalar source from the graph verb's payload \
13542                     scalar source",
13543                );
13544            } else {
13545                assert_eq!(
13546                    per_arm, None,
13547                    "WitTarget::{variant:?} http_endpoint() must return \
13548                     None on non-Http arms — a leak that surfaced a \
13549                     pub-sub :subject or a key/value :slot through the \
13550                     HTTP-endpoint accessor would silently widen the \
13551                     Cilium L7 HTTP `path:` rule accept-set onto \
13552                     protocol shapes Cilium's eBPF data-plane can't \
13553                     introspect",
13554                );
13555            }
13556        }
13557    }
13558
13559    #[test]
13560    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
13561        // Per-variant coherence pin: for every arm of [`WitTarget`],
13562        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
13563        // drift surface where a future extension of the
13564        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
13565        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
13566        // accessor to cover both peers) landed without a paired
13567        // extension of the [`gen_platform::IsVariant`]-derived
13568        // `is_http()` predicate's accept-set, or vice versa — a
13569        // regression that split the "which arms count as HTTP-shaped
13570        // for L7-path emission?" answer between two dispatch surfaces
13571        // the substrate ships. Sibling to the peer
13572        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
13573        // on the paired dispatch axis — extended onto the per-arm
13574        // predicate-vs-accessor coherence axis so the gen-platform
13575        // IsVariant predicate and the substrate-lifted per-arm
13576        // accessor carry one shared answer to "is this the HTTP arm?".
13577        for variant in [
13578            WitTarget::Http {
13579                endpoint: "/charge",
13580            },
13581            WitTarget::PubSub {
13582                subject: "events.checkout.paid",
13583            },
13584            WitTarget::Store {
13585                slot: "checkout/$order",
13586            },
13587            WitTarget::Capability,
13588        ] {
13589            assert_eq!(
13590                variant.http_endpoint().is_some(),
13591                variant.is_http(),
13592                "WitTarget::{variant:?} http_endpoint().is_some() must \
13593                 equal is_http() — a drift would split the L7 emit \
13594                 branch's arm-set gate from the substrate-derived \
13595                 shape-discrimination predicate on the same axis",
13596            );
13597        }
13598    }
13599
13600    #[test]
13601    fn wit_target_pubsub_subject_pins_per_variant() {
13602        // Fail-before-pass-after pin: the substrate-canonical per-arm
13603        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
13604        // is the single dispatch every future pub-sub-facing consumer
13605        // routes through, sibling to the peer [`WitContract::subject`]
13606        // (63e18a0) pre-projection scalar accessor on the raw-field
13607        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
13608        // post-projection per-arm accessor on the sibling HTTP-shape
13609        // axis. The [`WitTarget::PubSub`] arm round-trips its
13610        // author-declared subject verbatim as
13611        // `Some("events.checkout.paid")`; the three sibling arms each
13612        // return `None` because they carry no NATS-shaped subject by
13613        // definition. Same fail-before-pass-after per-variant discipline
13614        // as the sibling `wit_target_http_endpoint_pins_per_variant`
13615        // pin on the peer per-arm axis — extended onto the per-arm
13616        // pub-sub-shape post-projection axis so a future [`WitTarget`]
13617        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
13618        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
13619        // compile-time exhaustiveness error on the sibling
13620        // [`WitTarget::pubsub_subject`] match arms whose payload the
13621        // pub-sub-shape accept-set is meant to bound.
13622        assert_eq!(
13623            WitTarget::PubSub {
13624                subject: "events.checkout.paid",
13625            }
13626            .pubsub_subject(),
13627            Some("events.checkout.paid"),
13628        );
13629        assert_eq!(
13630            WitTarget::Http {
13631                endpoint: "/charge",
13632            }
13633            .pubsub_subject(),
13634            None,
13635        );
13636        assert_eq!(
13637            WitTarget::Store {
13638                slot: "checkout/$order",
13639            }
13640            .pubsub_subject(),
13641            None,
13642        );
13643        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
13644    }
13645
13646    #[test]
13647    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
13648        // Per-variant coherence pin: for every arm of [`WitTarget`],
13649        // `.pubsub_subject()` equals `.payload()` on the
13650        // [`WitTarget::PubSub`] arm (both project the same
13651        // author-declared subject scalar), and returns `None` on every
13652        // sibling arm regardless of whether [`WitTarget::payload`]
13653        // itself returns `Some` (Http / Store carry their own payload
13654        // the pan-arm accessor surfaces, but that payload is not a
13655        // pub-sub subject — the per-arm accessor must not leak it
13656        // through the pub-sub-shape channel). Sibling to the peer
13657        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
13658        // coherence pin on the per-arm HTTP-shape axis — extended onto
13659        // the per-arm pub-sub specialization axis so both per-arm
13660        // projections carry their own byte-shape coherence witness
13661        // against the substrate's typed arm-family accept-set.
13662        for variant in [
13663            WitTarget::Http {
13664                endpoint: "/charge",
13665            },
13666            WitTarget::PubSub {
13667                subject: "events.checkout.paid",
13668            },
13669            WitTarget::Store {
13670                slot: "checkout/$order",
13671            },
13672            WitTarget::Capability,
13673        ] {
13674            let per_arm = variant.pubsub_subject();
13675            let pan_arm = variant.payload();
13676            if variant.is_pubsub() {
13677                assert_eq!(
13678                    per_arm, pan_arm,
13679                    "WitTarget::{variant:?} pubsub_subject() must equal \
13680                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
13681                     split would silently drift the pub-sub-shape emit \
13682                     branch's subject-scalar source from the graph verb's \
13683                     payload scalar source",
13684                );
13685            } else {
13686                assert_eq!(
13687                    per_arm, None,
13688                    "WitTarget::{variant:?} pubsub_subject() must return \
13689                     None on non-PubSub arms — a leak that surfaced an \
13690                     HTTP :endpoint or a key/value :slot through the \
13691                     pub-sub-subject accessor would silently widen the \
13692                     downstream NATS-shape accept-set onto protocol \
13693                     shapes NATS servers can't route",
13694                );
13695            }
13696        }
13697    }
13698
13699    #[test]
13700    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
13701        // Per-variant coherence pin: for every arm of [`WitTarget`],
13702        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
13703        // drift surface where a future extension of the
13704        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
13705        // without a paired extension of the [`gen_platform::IsVariant`]-
13706        // derived `is_pubsub()` predicate's accept-set, or vice versa
13707        // — a regression that split the "which arms count as pub-sub-
13708        // shaped for subject emission?" answer between two dispatch
13709        // surfaces the substrate ships. Sibling to the peer
13710        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
13711        // pin on the per-arm HTTP-shape axis — extended onto the
13712        // per-arm pub-sub predicate-vs-accessor coherence axis so the
13713        // gen-platform IsVariant predicate and the substrate-lifted
13714        // per-arm accessor carry one shared answer to "is this the
13715        // PubSub arm?".
13716        for variant in [
13717            WitTarget::Http {
13718                endpoint: "/charge",
13719            },
13720            WitTarget::PubSub {
13721                subject: "events.checkout.paid",
13722            },
13723            WitTarget::Store {
13724                slot: "checkout/$order",
13725            },
13726            WitTarget::Capability,
13727        ] {
13728            assert_eq!(
13729                variant.pubsub_subject().is_some(),
13730                variant.is_pubsub(),
13731                "WitTarget::{variant:?} pubsub_subject().is_some() must \
13732                 equal is_pubsub() — a drift would split the pub-sub \
13733                 emit branch's arm-set gate from the substrate-derived \
13734                 shape-discrimination predicate on the same axis",
13735            );
13736        }
13737    }
13738
13739    #[test]
13740    fn wit_target_store_slot_pins_per_variant() {
13741        // Fail-before-pass-after pin: the substrate-canonical per-arm
13742        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
13743        // is the single dispatch every future store-facing consumer
13744        // routes through, sibling to the peer [`WitContract::slot`]
13745        // pre-projection scalar accessor on the raw-field axis and to
13746        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
13747        // [`WitTarget::pubsub_subject`] post-projection per-arm
13748        // accessors on the sibling per-payload-arm axes. The
13749        // [`WitTarget::Store`] arm round-trips its author-declared
13750        // slot verbatim as `Some("checkout/$order")`; the three
13751        // sibling arms each return `None` because they carry no
13752        // WASI-key/value slot by definition. Same fail-before-pass-
13753        // after per-variant discipline as the sibling
13754        // `wit_target_http_endpoint_pins_per_variant` +
13755        // `wit_target_pubsub_subject_pins_per_variant` pins on the
13756        // peer per-arm axes — extended onto the per-arm store-shape
13757        // post-projection axis so a future [`WitTarget`] variant
13758        // addition trips a compile-time exhaustiveness error on the
13759        // sibling [`WitTarget::store_slot`] match arms whose payload
13760        // the store-shape accept-set is meant to bound.
13761        assert_eq!(
13762            WitTarget::Store {
13763                slot: "checkout/$order",
13764            }
13765            .store_slot(),
13766            Some("checkout/$order"),
13767        );
13768        assert_eq!(
13769            WitTarget::Http {
13770                endpoint: "/charge",
13771            }
13772            .store_slot(),
13773            None,
13774        );
13775        assert_eq!(
13776            WitTarget::PubSub {
13777                subject: "events.checkout.paid",
13778            }
13779            .store_slot(),
13780            None,
13781        );
13782        assert_eq!(WitTarget::Capability.store_slot(), None);
13783    }
13784
13785    #[test]
13786    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
13787        // Per-variant coherence pin: for every arm of [`WitTarget`],
13788        // `.store_slot()` equals `.payload()` on the
13789        // [`WitTarget::Store`] arm (both project the same
13790        // author-declared slot scalar), and returns `None` on every
13791        // sibling arm regardless of whether [`WitTarget::payload`]
13792        // itself returns `Some`. Sibling to the peer
13793        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
13794        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
13795        // pins on the per-arm HTTP and PubSub axes — closes the
13796        // per-arm-vs-pan-arm byte-shape coherence trio across all
13797        // three payload arms.
13798        for variant in [
13799            WitTarget::Http {
13800                endpoint: "/charge",
13801            },
13802            WitTarget::PubSub {
13803                subject: "events.checkout.paid",
13804            },
13805            WitTarget::Store {
13806                slot: "checkout/$order",
13807            },
13808            WitTarget::Capability,
13809        ] {
13810            let per_arm = variant.store_slot();
13811            let pan_arm = variant.payload();
13812            if variant.is_store() {
13813                assert_eq!(
13814                    per_arm, pan_arm,
13815                    "WitTarget::{variant:?} store_slot() must equal \
13816                     payload() on the Store arm — a per-arm-vs-pan-arm \
13817                     split would silently drift the store-shape emit \
13818                     branch's slot-scalar source from the graph verb's \
13819                     payload scalar source",
13820                );
13821            } else {
13822                assert_eq!(
13823                    per_arm, None,
13824                    "WitTarget::{variant:?} store_slot() must return \
13825                     None on non-Store arms — a leak that surfaced an \
13826                     HTTP :endpoint or a NATS :subject through the \
13827                     key/value-slot accessor would silently widen the \
13828                     downstream WASI-key/value slot accept-set onto \
13829                     protocol shapes the kv backends can't route",
13830                );
13831            }
13832        }
13833    }
13834
13835    #[test]
13836    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
13837        // Per-variant coherence pin: for every arm of [`WitTarget`],
13838        // `.store_slot().is_some()` iff `.is_store()`. Guards the
13839        // drift surface where a future extension of the
13840        // [`WitTarget::store_slot`] accessor's accept-set landed
13841        // without a paired extension of the [`gen_platform::IsVariant`]-
13842        // derived `is_store()` predicate's accept-set. Sibling to the
13843        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
13844        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
13845        // pins — closes the per-arm predicate-vs-accessor coherence
13846        // trio across all three payload arms so the gen-platform
13847        // IsVariant predicate and the substrate-lifted per-arm
13848        // accessor carry one shared answer to "is this the Store arm?".
13849        for variant in [
13850            WitTarget::Http {
13851                endpoint: "/charge",
13852            },
13853            WitTarget::PubSub {
13854                subject: "events.checkout.paid",
13855            },
13856            WitTarget::Store {
13857                slot: "checkout/$order",
13858            },
13859            WitTarget::Capability,
13860        ] {
13861            assert_eq!(
13862                variant.store_slot().is_some(),
13863                variant.is_store(),
13864                "WitTarget::{variant:?} store_slot().is_some() must \
13865                 equal is_store() — a drift would split the store-shape \
13866                 emit branch's arm-set gate from the substrate-derived \
13867                 shape-discrimination predicate on the same axis",
13868            );
13869        }
13870    }
13871
13872    #[test]
13873    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
13874        // Fail-before-pass-after cross-axis pin on the trio
13875        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
13876        // payload-carrying arm of [`WitTarget`], exactly one per-arm
13877        // accessor returns `Some(payload)` and the two peers return
13878        // `None`; and on the payload-less [`WitTarget::Capability`]
13879        // arm, all three return `None`. Guards the drift surface where
13880        // a future extension of one per-arm accessor's accept-set (e.g.
13881        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
13882        // that widened `http_endpoint` to cover both peers without
13883        // narrowing the peer `pubsub_subject` / `store_slot` accept-
13884        // sets to keep the partition mutually exclusive) landed without
13885        // threading through the peer per-arm accessors — the resulting
13886        // silent overlap would land the same edge's payload on two
13887        // downstream per-shape emit branches at once, or leak a
13888        // pub-sub subject through the store-slot channel, at renderer
13889        // emit time far from the substrate primitive's arm-widening
13890        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
13891        // 3-way pin on the payload-field-name axis — extended onto the
13892        // per-arm-accessor payload-projection axis so the substrate-
13893        // owned partition invariant is load-bearing at every per-arm
13894        // consumer's read site.
13895        let payload_variants = [
13896            (
13897                WitTarget::Http {
13898                    endpoint: "/charge",
13899                },
13900                "http",
13901            ),
13902            (
13903                WitTarget::PubSub {
13904                    subject: "events.checkout.paid",
13905                },
13906                "pubsub",
13907            ),
13908            (
13909                WitTarget::Store {
13910                    slot: "checkout/$order",
13911                },
13912                "store",
13913            ),
13914        ];
13915        for (variant, own_arm_label) in payload_variants {
13916            let own_arm_hit = match own_arm_label {
13917                "http" => variant.is_http(),
13918                "pubsub" => variant.is_pubsub(),
13919                "store" => variant.is_store(),
13920                other => panic!("unknown own-arm label {other:?}"),
13921            };
13922            let per_arm_results = [
13923                ("http_endpoint", variant.http_endpoint()),
13924                ("pubsub_subject", variant.pubsub_subject()),
13925                ("store_slot", variant.store_slot()),
13926            ];
13927            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
13928            assert_eq!(
13929                some_count, 1,
13930                "WitTarget::{variant:?} must land exactly one per-arm \
13931                 post-projection accessor's Some result — the trio \
13932                 (http_endpoint, pubsub_subject, store_slot) must \
13933                 partition the payload arm-set; got {per_arm_results:?}",
13934            );
13935            assert!(
13936                own_arm_hit,
13937                "WitTarget::{variant:?} own-arm gen-platform predicate \
13938                 must return true on its own arm — a partition failure \
13939                 upstream of this pin",
13940            );
13941            assert!(
13942                variant.payload().is_some(),
13943                "WitTarget::{variant:?} pan-arm payload() must return \
13944                 Some on every payload-carrying arm the trio partitions",
13945            );
13946        }
13947        // The payload-less Capability arm must return None on every
13948        // per-arm accessor — the partition's terminal-fallback shape.
13949        let cap = WitTarget::Capability;
13950        assert_eq!(cap.http_endpoint(), None);
13951        assert_eq!(cap.pubsub_subject(), None);
13952        assert_eq!(cap.store_slot(), None);
13953        assert_eq!(
13954            cap.payload(),
13955            None,
13956            "WitTarget::Capability pan-arm payload() must return None — \
13957             the trio's payload-less-arm coherence witness",
13958        );
13959    }
13960
13961    #[test]
13962    fn wit_target_field_names_are_pairwise_distinct() {
13963        // Distinctness pin: if any two of the three payload-field-name
13964        // scalars ever collapse (e.g. an accidental `endpoint` copy-
13965        // paste over the `subject` const), the [`WitContract::target`]
13966        // gate's diagnostic would point authors at the wrong field —
13967        // an "expected `:endpoint`" error on a pub-sub edge would
13968        // silently misroute the fix. Same cross-axis-distinctness
13969        // discipline as the peer M3 `:placement :estrategia` variant-
13970        // discriminator scalar-value pins (cc8f749) applied to the
13971        // payload-field-name axis.
13972        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
13973        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
13974        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
13975    }
13976
13977    #[test]
13978    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
13979        // Fail-before-pass-after pin: the graph-verb payload column's
13980        // per-arm `{field}={payload}` byte-string is derived through the
13981        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
13982        // payload-carrying arms, not through a hand-rolled per-arm match
13983        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
13984        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13985        // inline. A future variant addition — the M4-and-later per-edge
13986        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
13987        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
13988        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
13989        // and both [`WitTarget::label`] (duplicate-`:contratos`
13990        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
13991        // payload column) pick up the new arm from the same dispatch.
13992        // Prior to this lift the graph verb open-coded the 4-arm match
13993        // in caixa-feira, so a variant addition would have to be threaded
13994        // through both projections in lockstep or the graph verb would
13995        // silently drop the new arm to `(capability-only)`.
13996        for variant in [
13997            WitTarget::Http {
13998                endpoint: "/charge",
13999            },
14000            WitTarget::PubSub {
14001                subject: "events.checkout.paid",
14002            },
14003            WitTarget::Store {
14004                slot: "checkout/$order",
14005            },
14006        ] {
14007            let (field, payload) = variant
14008                .payload_pair()
14009                .expect("payload arm must expose (field, payload)");
14010            assert_eq!(
14011                variant.graph_label(),
14012                format!("{field}={payload}"),
14013                "WitTarget::{variant:?} graph_label must route the \
14014                 `{{field}}={{payload}}` template through payload_pair — \
14015                 a regression to a hand-rolled per-arm match at the graph \
14016                 verb would silently disagree with a future variant \
14017                 addition landed only at payload_pair"
14018            );
14019        }
14020    }
14021
14022    #[test]
14023    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
14024        // Fail-before-pass-after pin on the payload-less arm: the graph
14025        // verb's `(capability-only)` byte-string routes through the
14026        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
14027        // [`WitTarget::Capability`] arm, not through an inline
14028        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
14029        // per-`:contratos` payload column. Peer of the sibling
14030        // [`wit_target_label_pins_per_variant_format`] Capability-arm
14031        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
14032        // extended here onto the third payload-less-arm consumer axis
14033        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
14034        // axis and the wrong-target diagnostic axis).
14035        assert_eq!(
14036            WitTarget::Capability.graph_label(),
14037            WitTarget::CAPABILITY_GRAPH_LABEL,
14038        );
14039        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
14040    }
14041
14042    #[test]
14043    fn wit_target_capability_graph_label_distinct_from_capability_label() {
14044        // Cross-consumer-axis distinctness pin: the graph-verb
14045        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
14046        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
14047        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
14048        // payload)`) surface the payload-less arm on two distinct
14049        // consumer axes; a collapse (an accidental rebrand that lands
14050        // one spelling on both consts, a copy-paste that unifies them
14051        // "for consistency") would silently merge the two byte-strings
14052        // and lose the vocabulary distinction the graph verb's
14053        // compact-column form and the diagnostic's descriptive-clause
14054        // form each carry on purpose. Peer of the sibling 4-way
14055        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
14056        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
14057        // extended here onto the cross-consumer-axis distinctness of the
14058        // two payload-less-arm consts.
14059        assert_ne!(
14060            WitTarget::CAPABILITY_GRAPH_LABEL,
14061            WitTarget::CAPABILITY_LABEL,
14062            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
14063             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
14064             diagnostic) must remain distinct — a collapse would silently \
14065             merge two consumer axes onto one spelling"
14066        );
14067    }
14068
14069    #[test]
14070    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
14071        // 4-way distinctness pin extending the sibling
14072        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
14073        // (which covers only the HTTP / PubSub / Store payload arms)
14074        // onto the fourth scalar the shared
14075        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
14076        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
14077        // (`"none"`), the payload-less Capability-arm rejection scalar.
14078        //
14079        // All four [`WitTarget::HTTP_FIELD_NAME`] /
14080        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14081        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
14082        // dispatch surface [`WitContract::target`] writes onto the
14083        // `ContratoWrongTarget::expected` field — the same `&'static
14084        // str` axis authors read as "this WIT world's shape admits
14085        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
14086        // downstream consumers rely on: an `expected: "endpoint"`
14087        // diagnostic on a Capability-shaped edge tells the author to
14088        // add a `:endpoint "…"` slot to a WIT world that admits none,
14089        // silently misrouting the fix. Until this pin landed the three
14090        // payload-arm consts were distinctness-guarded by the sibling
14091        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
14092        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
14093        // author-facing vocabulary shift from `"none"` to `"endpoint"`
14094        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
14095        // into per-shape peers) would have silently landed one
14096        // Capability-arm rejection on a payload-arm's `expected:` byte-
14097        // string and desynchronized the diagnostic from the author's
14098        // typed shape.
14099        //
14100        // Same 4-way pairwise-distinctness pin discipline as the peer
14101        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
14102        // (cc8f749) applies on the sibling M3 closed-set typed-enum
14103        // scalar-value dispatch axis; extends the pin trajectory the
14104        // sibling `wit_target_field_names_are_pairwise_distinct`
14105        // 3-way pin opened to cover the last unguarded corner on the
14106        // `ContratoWrongTarget::expected` scalar-value axis.
14107        //
14108        // Fail-before-pass-after locally verified by mutating
14109        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
14110        // — this pin fires as expected; restoring passes.
14111        let all = [
14112            WitTarget::HTTP_FIELD_NAME,
14113            WitTarget::PUBSUB_FIELD_NAME,
14114            WitTarget::STORE_FIELD_NAME,
14115            WitTarget::CAPABILITY_EXPECTED,
14116        ];
14117        for (i, a) in all.iter().enumerate() {
14118            for (j, b) in all.iter().enumerate() {
14119                if i != j {
14120                    assert_ne!(
14121                        a, b,
14122                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
14123                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
14124                         pairwise distinct — got duplicate {a:?} at indices \
14125                         {i} and {j}; all four scalars thread through the \
14126                         shared `AplicacaoError::ContratoWrongTarget::expected` \
14127                         &'static str axis, so a collapse silently misdirects \
14128                         the diagnostic on which typed shape the WIT world admits",
14129                    );
14130                }
14131            }
14132        }
14133    }
14134
14135    #[test]
14136    fn wit_target_is_variant_predicates_partition_the_arm_set() {
14137        // Fail-before-pass-after pin on the
14138        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
14139        // each of the four variants exactly one of the generated
14140        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
14141        // predicates returns `true` and the other three return
14142        // `false`. Prior to this derive the only production
14143        // arm-discriminator on [`WitTarget`] — the sync-cycle
14144        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
14145        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
14146        // the variant that expressed no compile-time link back to
14147        // the closed-set typed dispatch a future fifth
14148        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
14149        // split of [`WitTarget::PubSub`] into shape-specific peers,
14150        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
14151        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
14152        // to thread through in lockstep or the DFS exclusion would
14153        // silently disagree with the peer diagnostic templates on
14154        // which arms carry sync-versus-async semantics. Peer of the
14155        // sibling [`crate::CaixaKind`] (f5bba80),
14156        // [`PlacementStrategy`] (766ec63),
14157        // [`crate::supervisor::RestartStrategy`],
14158        // [`crate::supervisor::RestartPolicy`], and
14159        // [`crate::upgrade::UpgradeInstruction`] (915a934)
14160        // `IsVariant` derives on the sibling closed-set typed-enum
14161        // discriminator axes — extends the same one-typed-dispatch-
14162        // per-variant discipline onto the last unlifted closed-set
14163        // typed-enum discriminator on the caixa surface (the M3
14164        // mesh-slot per-`:contratos` target-arm axis), closing the
14165        // arm-discriminator convergence trajectory across every
14166        // closed-set typed enum in caixa-core.
14167        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
14168            (
14169                WitTarget::Http { endpoint: "/x" },
14170                [true, false, false, false],
14171            ),
14172            (
14173                WitTarget::PubSub {
14174                    subject: "events.x",
14175                },
14176                [false, true, false, false],
14177            ),
14178            (
14179                WitTarget::Store { slot: "kv/x" },
14180                [false, false, true, false],
14181            ),
14182            (WitTarget::Capability, [false, false, false, true]),
14183        ];
14184        for (variant, expected) in rows {
14185            let observed = [
14186                variant.is_http(),
14187                variant.is_pubsub(),
14188                variant.is_store(),
14189                variant.is_capability(),
14190            ];
14191            assert_eq!(
14192                observed, expected,
14193                "WitTarget::{variant:?} is_* predicates must partition \
14194                 the arm set (http, pubsub, store, capability); got {observed:?}"
14195            );
14196        }
14197    }
14198
14199    #[test]
14200    fn wit_target_is_variant_predicates_are_const_fn() {
14201        // The [`gen_platform::IsVariant`] derive emits `const fn`
14202        // predicates on the peer [`crate::CaixaKind`] +
14203        // [`crate::upgrade::UpgradeInstruction`] +
14204        // [`crate::supervisor::RestartStrategy`] +
14205        // [`crate::supervisor::RestartPolicy`] +
14206        // [`PlacementStrategy`] closed-set typed enums — pin the
14207        // same posture on [`WitTarget`] so a future accidental
14208        // downgrade to non-`const` (an added runtime helper reachable
14209        // only from a non-`const` context, a manual hand-rolled
14210        // `impl` that shadows the derive-generated method) trips at
14211        // caixa-core build time rather than surfacing as a downstream
14212        // `const`-context regression far from the derive declaration.
14213        //
14214        // Unlike the peer unit-variant enums (`CaixaKind` /
14215        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
14216        // whose `const` constructors need no arguments, the three
14217        // payload-carrying [`WitTarget`] arms are const-constructed
14218        // through `&'static str` payloads — the same `'static`
14219        // lifetime the closed-set typed enum's four-arm partition
14220        // pin above already threads through.
14221        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
14222        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
14223        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
14224        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
14225        const IS_HTTP: bool = HTTP.is_http();
14226        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
14227        const IS_STORE: bool = STORE.is_store();
14228        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
14229        assert!(IS_HTTP);
14230        assert!(IS_PUBSUB);
14231        assert!(IS_STORE);
14232        assert!(IS_CAPABILITY);
14233    }
14234
14235    #[test]
14236    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
14237        // Consumer-side pin on the sole production converge site:
14238        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
14239        // edges from the synchronous-subgraph DFS via the lifted
14240        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
14241        // predicate (rebound from the prior raw
14242        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
14243        // variant). Byte-equivalent today (`is_pubsub` is the
14244        // derive-generated `matches!(self, Self::PubSub { .. })` by
14245        // construction, the `#[is_variant(name = "pubsub")]` override
14246        // aliasing the auto-derived `is_pub_sub` back to the sibling
14247        // [`WitContract::is_pubsub`] name); pin the behavior so a
14248        // future accidental drift (a rebind onto a peer arm
14249        // predicate, a manual hand-rolled `impl` that shadows the
14250        // derive-generated method with different semantics, a peer
14251        // arm rename that shifts which variant carries sync-versus-
14252        // async semantics) trips at caixa-core test time rather than
14253        // at some downstream operator's runtime dispatch far from the
14254        // rebind commit.
14255        //
14256        // The fixture constructs a two-Servico Aplicacao with one
14257        // pub-sub edge that would close a sync-cycle if the DFS did
14258        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
14259        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
14260        // edge, which is not a cycle. A regression in the converge
14261        // (a rebind that reads the pub-sub arm as sync) would report
14262        // `AplicacaoError::ContratoCycle`.
14263        let s = AplicacaoSpec {
14264            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
14265            contratos: vec![
14266                // Pub-sub edge: DFS must skip via is_pubsub().
14267                WitContract {
14268                    de: "a".into(),
14269                    para: "b".into(),
14270                    wit: "nats:pub-sub".into(),
14271                    endpoint: None,
14272                    subject: Some("events.x".into()),
14273                    slot: None,
14274                },
14275                // HTTP edge: DFS must include.
14276                WitContract {
14277                    de: "b".into(),
14278                    para: "a".into(),
14279                    wit: "wasi:http/proxy".into(),
14280                    endpoint: Some("/x".into()),
14281                    subject: None,
14282                    slot: None,
14283                },
14284            ],
14285            politicas: MeshPolicy::default(),
14286            placement: Placement {
14287                estrategia: PlacementStrategy::Replicated,
14288                clusters: vec!["rio".into()],
14289                affinity: None,
14290                shard_key: None,
14291            },
14292            entrada: None,
14293        };
14294        s.validate()
14295            .expect("pub-sub edge must be excluded from sync-cycle DFS");
14296    }
14297
14298    #[test]
14299    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
14300        // Consumer-side pin: the same three peer consts thread through
14301        // both the [`WitTarget::label`] template (leading-`:` keyword
14302        // prefix in the duplicate-`:contratos` diagnostic) and the
14303        // [`WitContract::target`] gate's [`AplicacaoError::
14304        // ContratoMissingTarget`] `expected:` scalar (the field the
14305        // author needs to add). Pin both routes at once so a future
14306        // refactor can't accidentally split them onto separate string
14307        // literals — the "one place, everywhere reaches for it"
14308        // invariant the peer const set carries.
14309        let http_label = WitTarget::Http { endpoint: "/x" }.label();
14310        assert!(
14311            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
14312            "label must lead with :{} keyword (got {http_label:?})",
14313            WitTarget::HTTP_FIELD_NAME,
14314        );
14315
14316        let mut s = three_member_spec();
14317        s.contratos.push(WitContract {
14318            de: "cart".into(),
14319            para: "catalog".into(),
14320            wit: "kafka:topic".into(),
14321            endpoint: None,
14322            subject: None,
14323            slot: None,
14324        });
14325        match s.validate().unwrap_err() {
14326            AplicacaoError::ContratoMissingTarget { expected, .. } => {
14327                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
14328            }
14329            other => panic!("expected ContratoMissingTarget, got {other:?}"),
14330        }
14331    }
14332
14333    #[test]
14334    fn duplicate_pubsub_diagnostic_names_offending_subject() {
14335        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
14336        // on the pub-sub target axis: the duplicate-edge diagnostic
14337        // must name the `:subject` payload verbatim (not just the
14338        // `(de, para, wit)` triple). Prior to lifting the label onto
14339        // [`WitTarget::label`] the diagnostic derived the label from
14340        // raw [`WitContract`] `Option<String>` probes — a future
14341        // `WitTarget` variant addition (M4 per-edge WIT registry)
14342        // would silently fall through to the `Capability` "no
14343        // payload" default without a compiler warning. Pinning the
14344        // pub-sub arm's format closes the second of three
14345        // payload-carrying `WitTarget` arms this diagnostic threads
14346        // through.
14347        let mut s = three_member_spec();
14348        let pubsub = WitContract {
14349            de: "payment".into(),
14350            para: "cart".into(),
14351            wit: "nats:pub-sub".into(),
14352            endpoint: None,
14353            subject: Some("events.checkout.paid".into()),
14354            slot: None,
14355        };
14356        s.contratos.push(pubsub.clone());
14357        s.contratos.push(pubsub);
14358        let err = s.validate().unwrap_err();
14359        let msg = format!("{err}");
14360        assert!(
14361            msg.contains(":subject \"events.checkout.paid\""),
14362            "duplicate-pubsub diagnostic must name the offending \
14363             :subject payload (got: {msg:?})"
14364        );
14365    }
14366
14367    #[test]
14368    fn duplicate_store_diagnostic_names_offending_slot() {
14369        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
14370        // key-value target axis: the diagnostic must name the `:slot`
14371        // payload verbatim. Third of three payload-carrying
14372        // `WitTarget` arms this diagnostic threads through, closing
14373        // the per-arm label pin trilogy (`Http` — 6841,
14374        // `PubSub` + `Store` — this test + peer above).
14375        let mut s = three_member_spec();
14376        let store = WitContract {
14377            de: "cart".into(),
14378            para: "payment".into(),
14379            wit: "wasi:keyvalue/store".into(),
14380            endpoint: None,
14381            subject: None,
14382            slot: Some("checkout/$orderId".into()),
14383        };
14384        s.contratos
14385            .retain(|c| !(c.de == "cart" && c.para == "payment"));
14386        s.contratos.push(store.clone());
14387        s.contratos.push(store);
14388        let err = s.validate().unwrap_err();
14389        let msg = format!("{err}");
14390        assert!(
14391            msg.contains(":slot \"checkout/$orderId\""),
14392            "duplicate-store diagnostic must name the offending :slot \
14393             payload (got: {msg:?})"
14394        );
14395    }
14396
14397    #[test]
14398    fn rejects_entrada_path_without_leading_slash() {
14399        let mut s = three_member_spec();
14400        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
14401        let err = s.validate().unwrap_err();
14402        assert!(
14403            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
14404            "got {err:?}"
14405        );
14406    }
14407
14408    #[test]
14409    fn rejects_empty_entrada_path() {
14410        let mut s = three_member_spec();
14411        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
14412        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14413    }
14414
14415    #[test]
14416    fn rejects_duplicate_entrada_paths() {
14417        let mut s = three_member_spec();
14418        s.entrada.as_mut().unwrap().paths = vec![
14419            "/api/cart".into(),
14420            "/api/products".into(),
14421            "/api/cart".into(),
14422        ];
14423        let err = s.validate().unwrap_err();
14424        assert!(
14425            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
14426            "got {err:?}"
14427        );
14428    }
14429
14430    #[test]
14431    fn rejects_zero_entrada_port() {
14432        let mut s = three_member_spec();
14433        s.entrada.as_mut().unwrap().port = 0;
14434        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
14435    }
14436
14437    // ── :entrada :paths value-shape gate ─────────────────────────────
14438    //
14439    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
14440    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
14441    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
14442    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
14443    // time now becomes a caixa-build-time `EntradaPathInvalid` with
14444    // the offending `:paths` entry named verbatim.
14445
14446    #[test]
14447    fn rejects_entrada_path_with_query() {
14448        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
14449        // silently passed validate and the Gateway API webhook
14450        // rejected it at apply time with no source citation.
14451        let mut s = three_member_spec();
14452        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
14453        let err = s.validate().unwrap_err();
14454        assert!(
14455            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14456                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
14457            "got {err:?}"
14458        );
14459    }
14460
14461    #[test]
14462    fn rejects_entrada_path_with_fragment() {
14463        let mut s = three_member_spec();
14464        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
14465        let err = s.validate().unwrap_err();
14466        assert!(
14467            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14468                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
14469            "got {err:?}"
14470        );
14471    }
14472
14473    #[test]
14474    fn rejects_entrada_path_with_space() {
14475        let mut s = three_member_spec();
14476        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
14477        let err = s.validate().unwrap_err();
14478        assert!(
14479            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14480                if path == "/api/my cart" && reason.contains("whitespace")),
14481            "got {err:?}"
14482        );
14483    }
14484
14485    #[test]
14486    fn rejects_entrada_path_with_tab() {
14487        let mut s = three_member_spec();
14488        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
14489        let err = s.validate().unwrap_err();
14490        assert!(
14491            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14492                if path == "/api/\tcart" && reason.contains("whitespace")),
14493            "got {err:?}"
14494        );
14495    }
14496
14497    #[test]
14498    fn rejects_entrada_path_with_control_char() {
14499        // 0x01 (SOH) — a non-whitespace control char surfaces the
14500        // distinct "control character" reason arm, separate from
14501        // the whitespace arm. Pinned so a future refactor that
14502        // collapses the two arms can't accidentally drop the more
14503        // self-locating diagnostic.
14504        let mut s = three_member_spec();
14505        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
14506        let err = s.validate().unwrap_err();
14507        assert!(
14508            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14509                if path == "/api/\x01cart" && reason.contains("control character")),
14510            "got {err:?}"
14511        );
14512    }
14513
14514    #[test]
14515    fn rejects_entrada_path_with_non_ascii() {
14516        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
14517        // unreserved-set rule rejects. The Gateway API webhook
14518        // rejects literal non-ASCII bytes; percent-encoding is the
14519        // only way to author non-ASCII in a path.
14520        let mut s = three_member_spec();
14521        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
14522        let err = s.validate().unwrap_err();
14523        assert!(
14524            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14525                if path == "/api/café" && reason.contains("non-ASCII")),
14526            "got {err:?}"
14527        );
14528    }
14529
14530    #[test]
14531    fn rejects_entrada_path_with_consecutive_slashes() {
14532        let mut s = three_member_spec();
14533        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
14534        let err = s.validate().unwrap_err();
14535        assert!(
14536            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14537                if path == "/api//cart" && reason.contains("consecutive `/`")),
14538            "got {err:?}"
14539        );
14540    }
14541
14542    #[test]
14543    fn rejects_entrada_path_with_dot_segment() {
14544        let mut s = three_member_spec();
14545        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
14546        let err = s.validate().unwrap_err();
14547        assert!(
14548            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14549                if path == "/api/./cart" && reason.contains("`.` segment")),
14550            "got {err:?}"
14551        );
14552    }
14553
14554    #[test]
14555    fn rejects_entrada_path_with_trailing_dot_segment() {
14556        // The bare `/.` and the trailing `/foo/.` are both rejected
14557        // by the Gateway API webhook; pinned separately so a future
14558        // narrowing that catches only the inner form surfaces here.
14559        let mut s = three_member_spec();
14560        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
14561        let err = s.validate().unwrap_err();
14562        assert!(
14563            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14564                if path == "/api/." && reason.contains("`.` segment")),
14565            "got {err:?}"
14566        );
14567    }
14568
14569    #[test]
14570    fn rejects_entrada_path_with_parent_segment() {
14571        let mut s = three_member_spec();
14572        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
14573        let err = s.validate().unwrap_err();
14574        assert!(
14575            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14576                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
14577            "got {err:?}"
14578        );
14579    }
14580
14581    #[test]
14582    fn rejects_entrada_path_with_trailing_parent_segment() {
14583        // Trailing `/..` — symmetric arm of the parent-segment rule,
14584        // pinned separately so a future relaxation that only checks
14585        // the inner form (`/../`) surfaces here.
14586        let mut s = three_member_spec();
14587        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
14588        let err = s.validate().unwrap_err();
14589        assert!(
14590            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14591                if path == "/api/.." && reason.contains("`..` parent-segment")),
14592            "got {err:?}"
14593        );
14594    }
14595
14596    #[test]
14597    fn rejects_entrada_path_too_long() {
14598        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
14599        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
14600        // ASCII-alphanumeric body so only the length rule fires.
14601        let mut s = three_member_spec();
14602        let big = format!("/api/{}", "a".repeat(1020));
14603        assert_eq!(big.len(), 1025);
14604        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
14605        let err = s.validate().unwrap_err();
14606        assert!(
14607            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14608                if path == &big && reason.contains("max length of 1024")),
14609            "got {err:?}"
14610        );
14611    }
14612
14613    #[test]
14614    fn entrada_path_max_length_validates() {
14615        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
14616        // maxLength cap. Boundary pin: drift in the cap surfaces here
14617        // and at `rejects_entrada_path_too_long` simultaneously.
14618        let mut s = three_member_spec();
14619        let big = format!("/api/{}", "a".repeat(1019));
14620        assert_eq!(big.len(), 1024);
14621        s.entrada.as_mut().unwrap().paths = vec![big];
14622        s.validate().unwrap();
14623    }
14624
14625    #[test]
14626    fn entrada_accepts_canonical_paths() {
14627        // Positive-control sweep — every form the Gateway API
14628        // apiserver accepts must round-trip through validate. Covers
14629        // the root catch-all, plain paths, dot-prefixed segments
14630        // (hidden-file-style, distinct from `.` and `..` segments
14631        // which are rejected), digit-bearing segments, the canonical
14632        // route-template `:param` form (`:` is RFC 3986 reserved-set
14633        // valid in paths), trailing-slash form, percent-encoded
14634        // segments, and an interior `..` *substring* (`/foo..bar` is
14635        // not the `..` segment and is allowed).
14636        for path in [
14637            "/",
14638            "/api/cart",
14639            "/healthz",
14640            "/api/.config",
14641            "/v1/products",
14642            "/products/:id",
14643            "/api/cart/",
14644            "/api/caf%C3%A9",
14645            "/foo..bar",
14646            "/...",
14647        ] {
14648            let mut s = three_member_spec();
14649            s.entrada.as_mut().unwrap().paths = vec![path.into()];
14650            s.validate()
14651                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
14652        }
14653    }
14654
14655    #[test]
14656    fn entrada_path_empty_takes_precedence_over_invalid() {
14657        // Ordering pin: `EntradaPathEmpty` is the more self-locating
14658        // diagnostic on `""` and must lead — `validate_entrada_path`
14659        // is only reached after the empty-check fires at the call
14660        // site. (The predicate itself defends against direct
14661        // invocation by returning the same error on `""`.)
14662        let mut s = three_member_spec();
14663        s.entrada.as_mut().unwrap().paths = vec!["".into()];
14664        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14665    }
14666
14667    #[test]
14668    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
14669        // Ordering pin: a path without a leading `/` surfaces the
14670        // narrower `EntradaPathNotAbsolute` diagnostic first; the
14671        // value-shape gate is only consulted on paths that already
14672        // satisfy the absolute-prefix invariant.
14673        let mut s = three_member_spec();
14674        // `bad path` would fire the whitespace rule under the
14675        // value-shape gate, but missing-leading-`/` is the more
14676        // self-locating diagnostic.
14677        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
14678        let err = s.validate().unwrap_err();
14679        assert!(
14680            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
14681            "got {err:?}"
14682        );
14683    }
14684
14685    #[test]
14686    fn entrada_path_invalid_fires_before_duplicate_check() {
14687        // Ordering pin: a malformed path on the *first* entry of a
14688        // would-be duplicate pair fires the value-shape gate before
14689        // the duplicate gate, mirroring the
14690        // `placement_cluster_invalid_fires_before_duplicate_check`
14691        // (6cbb900) pattern on the peer axis.
14692        let mut s = three_member_spec();
14693        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
14694        let err = s.validate().unwrap_err();
14695        assert!(
14696            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
14697            "got {err:?}"
14698        );
14699    }
14700
14701    #[test]
14702    fn entrada_path_diagnostic_carries_offending_path() {
14703        // Diagnostic-shape pin — the offending path + a non-empty
14704        // reason flow through verbatim so the author can grep their
14705        // caixa.lisp for `:paths` and fix it in one edit. Same shape
14706        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
14707        let mut s = three_member_spec();
14708        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
14709        let err = s.validate().unwrap_err();
14710        match err {
14711            AplicacaoError::EntradaPathInvalid { path, reason } => {
14712                assert_eq!(path, "/api?q=1");
14713                assert!(!reason.is_empty(), "reason field must be non-empty");
14714            }
14715            other => panic!("expected EntradaPathInvalid, got {other:?}"),
14716        }
14717    }
14718
14719    #[test]
14720    fn rejects_entrada_path_with_curly_brace_template_form() {
14721        // Per-axis pin on the shared `is_gateway_api_http_path`
14722        // reserved-byte arm: the canonical "I wrote an OpenAPI
14723        // path-template `{id}` instead of the Gateway API `:id` form"
14724        // footgun the K8s apiserver would otherwise catch at admission
14725        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
14726        // landing site, far from the caixa.lisp. Surfaces as
14727        // `EntradaPathInvalid` carrying the offending path verbatim
14728        // plus the canonical `%7B`/`%7D` percent-encoding remediation
14729        // — the substrate-side `gateway_api_http_path_rejects_every_
14730        // reserved_printable_ascii_byte` predicate-level sweep pins the
14731        // full eleven-byte set; this per-axis pin confirms the
14732        // diagnostic flows through to the `EntradaPathInvalid` variant.
14733        let mut s = three_member_spec();
14734        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
14735        let err = s.validate().unwrap_err();
14736        assert!(
14737            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14738                if path == "/api/cart/{id}"
14739                    && reason.contains("reserved character")
14740                    && reason.contains("'{'")
14741                    && reason.contains("%7B")),
14742            "got {err:?}"
14743        );
14744    }
14745
14746    #[test]
14747    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
14748        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
14749        // template_form` on the sibling `:contratos :endpoint` axis.
14750        // Same shared `is_gateway_api_http_path` reserved-byte arm
14751        // fires through `ContratoEndpointInvalid`, with the offending
14752        // endpoint + `:de` + `:para` + reason flowing through verbatim.
14753        // Pins that the lifted predicate's tightening lands on both
14754        // caller axes simultaneously — one source of truth for the
14755        // Gateway API HTTPPathMatch.value accepted set.
14756        let err = contrato_endpoint_err("/api/cart/{id}");
14757        assert!(
14758            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14759                if endpoint == "/api/cart/{id}"
14760                    && reason.contains("reserved character")
14761                    && reason.contains("'{'")
14762                    && reason.contains("%7B")),
14763            "got {err:?}"
14764        );
14765    }
14766
14767    // ── :entrada :host value-shape gate ──────────────────────────────
14768    //
14769    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
14770    // the sibling `:host` axis. Every authoring footgun the K8s
14771    // Gateway API v1 apiserver would catch at admission time becomes
14772    // a caixa-build-time `EntradaHostInvalid` with the offending
14773    // `:host` named verbatim. Same diagnostic shape as
14774    // `MembroVersaoInvalid` (9888b13).
14775
14776    #[test]
14777    fn rejects_entrada_host_with_scheme() {
14778        // Fail-before-pass-after pin — pre-gate codebases silently
14779        // accepted `https://…` and the apiserver rejected it at apply
14780        // time with no source citation.
14781        let mut s = three_member_spec();
14782        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
14783        let err = s.validate().unwrap_err();
14784        assert!(
14785            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14786                if host == "https://checkout.quero.cloud"),
14787            "got {err:?}"
14788        );
14789    }
14790
14791    #[test]
14792    fn rejects_entrada_host_with_port() {
14793        // The `:8080` port suffix is the canonical "I forgot the port
14794        // belongs in `:entrada :port`" footgun. The top-level `:` arm
14795        // (introduced after the per-label loop-only impl silently
14796        // surfaced a deep "label \"cloud:8080\" contains invalid
14797        // character ':'" leak) names the canonical fix verbatim — the
14798        // `:entrada :port` slot.
14799        let mut s = three_member_spec();
14800        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
14801        let err = s.validate().unwrap_err();
14802        assert!(
14803            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14804                if host == "checkout.quero.cloud:8080"
14805                && reason.contains(":entrada :port")),
14806            "got {err:?}"
14807        );
14808    }
14809
14810    #[test]
14811    fn rejects_entrada_host_with_trailing_colon() {
14812        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
14813        // edit) — the per-label loop would land it as a deep
14814        // "label \"com:\" must start and end with an alphanumeric"
14815        // / "contains invalid character ':'" leak. The top-level
14816        // `:` arm pre-empts with the canonical `:port` slot
14817        // diagnostic.
14818        let mut s = three_member_spec();
14819        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
14820        let err = s.validate().unwrap_err();
14821        assert!(
14822            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14823                if host == "checkout.quero.cloud:"
14824                && reason.contains(":entrada :port")),
14825            "got {err:?}"
14826        );
14827    }
14828
14829    #[test]
14830    fn rejects_entrada_host_unbracketed_ipv6_literal() {
14831        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
14832        // literals across the board (peer with `rejects_entrada_host_
14833        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
14834        // Before this top-level `:` arm landed the per-label loop
14835        // surfaced a single-label byte-class diagnostic that named the
14836        // `:` byte but not the IP-literal prohibition. The top-level
14837        // `:` arm names both the `:port` slot and the IP-literal
14838        // prohibition verbatim, so an author whose `:host "2001:..."`
14839        // value lands here gets a self-locating fix either way.
14840        let mut s = three_member_spec();
14841        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
14842        let err = s.validate().unwrap_err();
14843        assert!(
14844            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14845                if host == "2001:db8::1"
14846                && reason.contains("IPv6")),
14847            "got {err:?}"
14848        );
14849    }
14850
14851    #[test]
14852    fn rejects_entrada_host_wildcard_with_port() {
14853        // Wildcard host with port suffix — the `*.` strip and the
14854        // per-label loop on `["foo", "quero", "cloud:8080"]` would
14855        // surface the deep byte-class leak. The top-level `:` arm sits
14856        // upstream of the `*.` strip, so it names the canonical `:port`
14857        // fix verbatim regardless of whether the host is wildcard-led.
14858        let mut s = three_member_spec();
14859        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
14860        let err = s.validate().unwrap_err();
14861        assert!(
14862            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14863                if host == "*.quero.cloud:8080"
14864                && reason.contains(":entrada :port")),
14865            "got {err:?}"
14866        );
14867    }
14868
14869    #[test]
14870    fn rejects_entrada_host_with_path() {
14871        let mut s = three_member_spec();
14872        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
14873        let err = s.validate().unwrap_err();
14874        assert!(
14875            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14876                if host == "checkout.quero.cloud/api"),
14877            "got {err:?}"
14878        );
14879    }
14880
14881    #[test]
14882    fn rejects_entrada_host_with_uppercase() {
14883        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
14884        // rejected, not silently lower-cased.
14885        let mut s = three_member_spec();
14886        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
14887        let err = s.validate().unwrap_err();
14888        assert!(
14889            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14890                if reason.contains("uppercase")),
14891            "got {err:?}"
14892        );
14893    }
14894
14895    #[test]
14896    fn rejects_entrada_host_with_underscore() {
14897        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
14898        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
14899        let mut s = three_member_spec();
14900        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
14901        let err = s.validate().unwrap_err();
14902        assert!(
14903            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14904                if reason.contains('_')),
14905            "got {err:?}"
14906        );
14907    }
14908
14909    #[test]
14910    fn rejects_entrada_host_ipv4_literal() {
14911        // Gateway API v1 explicitly forbids IP literals as Hostnames.
14912        let mut s = three_member_spec();
14913        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
14914        let err = s.validate().unwrap_err();
14915        assert!(
14916            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14917                if reason.contains("IPv4")),
14918            "got {err:?}"
14919        );
14920    }
14921
14922    #[test]
14923    fn rejects_entrada_host_with_trailing_dot() {
14924        // The Gateway API regex anchors at end-of-string with no
14925        // trailing `.` allowance — the FQDN root-dot form is rejected.
14926        let mut s = three_member_spec();
14927        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
14928        let err = s.validate().unwrap_err();
14929        assert!(
14930            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14931                if host == "checkout.quero.cloud."),
14932            "got {err:?}"
14933        );
14934    }
14935
14936    #[test]
14937    fn rejects_entrada_host_with_leading_dot() {
14938        let mut s = three_member_spec();
14939        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
14940        let err = s.validate().unwrap_err();
14941        assert!(
14942            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14943                if reason.contains("empty label")),
14944            "got {err:?}"
14945        );
14946    }
14947
14948    #[test]
14949    fn rejects_entrada_host_with_consecutive_dots() {
14950        let mut s = three_member_spec();
14951        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
14952        let err = s.validate().unwrap_err();
14953        assert!(
14954            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14955                if reason.contains("empty label")),
14956            "got {err:?}"
14957        );
14958    }
14959
14960    #[test]
14961    fn rejects_entrada_host_with_leading_hyphen_label() {
14962        let mut s = three_member_spec();
14963        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
14964        let err = s.validate().unwrap_err();
14965        assert!(
14966            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14967                if reason.contains("alphanumeric")),
14968            "got {err:?}"
14969        );
14970    }
14971
14972    #[test]
14973    fn rejects_entrada_host_with_trailing_hyphen_label() {
14974        let mut s = three_member_spec();
14975        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
14976        let err = s.validate().unwrap_err();
14977        assert!(
14978            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14979                if reason.contains("alphanumeric")),
14980            "got {err:?}"
14981        );
14982    }
14983
14984    #[test]
14985    fn rejects_entrada_host_with_inner_wildcard() {
14986        // Gateway API allows `*` only as the first label (`*.foo`);
14987        // any inner or trailing `*` is rejected.
14988        let mut s = three_member_spec();
14989        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
14990        let err = s.validate().unwrap_err();
14991        assert!(
14992            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14993                if reason.contains("wildcard")),
14994            "got {err:?}"
14995        );
14996    }
14997
14998    #[test]
14999    fn rejects_entrada_host_bare_wildcard() {
15000        // `*.` with no domain is meaningless; Gateway API rejects it.
15001        let mut s = three_member_spec();
15002        s.entrada.as_mut().unwrap().host = "*.".into();
15003        let err = s.validate().unwrap_err();
15004        assert!(
15005            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15006                if reason.contains("wildcard")),
15007            "got {err:?}"
15008        );
15009    }
15010
15011    #[test]
15012    fn rejects_entrada_host_with_whitespace() {
15013        let mut s = three_member_spec();
15014        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15015        let err = s.validate().unwrap_err();
15016        assert!(
15017            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15018                if reason.contains("whitespace")),
15019            "got {err:?}"
15020        );
15021    }
15022
15023    #[test]
15024    fn rejects_entrada_host_space_names_offending_byte() {
15025        // Embedded space in the `:entrada :host` axis surfaces the
15026        // byte-naming diagnostic through the lifted
15027        // `find_ascii_whitespace_byte` predicate. Peer with the
15028        // sibling `parse_rejects_leading_whitespace` pins on
15029        // `supervisor::duration_codec` (a7ae622) — same "the
15030        // diagnostic carries the offending byte's `0x{b:02x}` shape"
15031        // discipline extended from the shared duration codec to the
15032        // Gateway API v1 Hostname axis.
15033        let mut s = three_member_spec();
15034        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15035        let err = s.validate().unwrap_err();
15036        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15037            panic!("expected EntradaHostInvalid, got {err:?}");
15038        };
15039        assert!(
15040            reason.contains("ASCII whitespace byte"),
15041            "expected byte-naming diagnostic, got {reason:?}"
15042        );
15043        assert!(
15044            reason.contains("0x20"),
15045            "expected offending space byte 0x20, got {reason:?}"
15046        );
15047    }
15048
15049    #[test]
15050    fn rejects_entrada_host_tab_names_offending_byte() {
15051        // Embedded tab byte in the `:entrada :host` axis — the
15052        // canonical paste-from-YAML-block-scalar / paste-from-
15053        // indented-doc footgun. Pins that the lifted predicate covers
15054        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
15055        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
15056        // not just the leading-space case the pre-lift `.bytes().any`
15057        // arm's opaque "must not contain whitespace" reason already
15058        // covered. Peer with `parse_rejects_tab_byte` on
15059        // `supervisor::duration_codec` (a7ae622).
15060        let mut s = three_member_spec();
15061        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
15062        let err = s.validate().unwrap_err();
15063        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15064            panic!("expected EntradaHostInvalid, got {err:?}");
15065        };
15066        assert!(
15067            reason.contains("ASCII whitespace byte"),
15068            "expected byte-naming diagnostic, got {reason:?}"
15069        );
15070        assert!(
15071            reason.contains("0x09"),
15072            "expected offending tab byte 0x09, got {reason:?}"
15073        );
15074    }
15075
15076    #[test]
15077    fn rejects_entrada_host_lf_names_offending_byte() {
15078        // Embedded LF byte in the `:entrada :host` axis — the
15079        // canonical paste-from-shell-heredoc / paste-from-multiline-
15080        // doc footgun the caixa-mesh YAML emitter would silently
15081        // reinterpret at the Gateway API v1 HTTPRoute admission
15082        // layer (an embedded LF byte in a YAML plain scalar either
15083        // truncates the value at the emitter or crashes the parser
15084        // on the k8s-apiserver side). Pins the third representative
15085        // of the full ASCII-whitespace set through the shared
15086        // predicate.
15087        let mut s = three_member_spec();
15088        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
15089        let err = s.validate().unwrap_err();
15090        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15091            panic!("expected EntradaHostInvalid, got {err:?}");
15092        };
15093        assert!(
15094            reason.contains("ASCII whitespace byte"),
15095            "expected byte-naming diagnostic, got {reason:?}"
15096        );
15097        assert!(
15098            reason.contains("0x0a"),
15099            "expected offending LF byte 0x0a, got {reason:?}"
15100        );
15101    }
15102
15103    #[test]
15104    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
15105        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
15106        // axis — the canonical paste-from-typography /
15107        // paste-from-word-processor footgun. Before the non-ASCII
15108        // Unicode `White_Space` scan lifted through the shared
15109        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
15110        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
15111        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
15112        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
15113        // with the far-from-source `label "…" must start and end
15114        // with an alphanumeric` diagnostic — burying the
15115        // paste-from-typography origin under a label-shape leak.
15116        // Peer with the sibling non-ASCII-whitespace pins at
15117        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
15118        // — 1b75b38), `limits::parse_duration`,
15119        // `limits::parse_millicores`, and the shared duration codec
15120        // — same "the diagnostic carries the offending Unicode
15121        // codepoint's `U+XXXX` shape" discipline extended from every
15122        // typed-magnitude codec to the Gateway API v1 Hostname axis.
15123        let mut s = three_member_spec();
15124        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
15125        let err = s.validate().unwrap_err();
15126        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15127            panic!("expected EntradaHostInvalid, got {err:?}");
15128        };
15129        assert!(
15130            reason.contains("non-ASCII Unicode whitespace character"),
15131            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15132        );
15133        assert!(
15134            reason.contains("U+00A0"),
15135            "expected offending NBSP codepoint U+00A0, got {reason:?}"
15136        );
15137    }
15138
15139    #[test]
15140    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
15141        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
15142        // `:entrada :host` axis — the canonical paste-from-web-doc /
15143        // paste-from-published-HTML footgun. `char::is_whitespace`
15144        // returns true for `U+2028` per the Unicode `White_Space`
15145        // property, so `str::trim` at any downstream site would
15146        // silently strip it — same drift class as NBSP but on a
15147        // different codepoint region. Pins the second representative
15148        // (non-Latin-1 `char::is_whitespace` member) through the
15149        // shared predicate. Peer with
15150        // `parse_byte_size_rejects_internal_line_separator` on
15151        // `limits::parse_byte_size` (1b75b38).
15152        let mut s = three_member_spec();
15153        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
15154        let err = s.validate().unwrap_err();
15155        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15156            panic!("expected EntradaHostInvalid, got {err:?}");
15157        };
15158        assert!(
15159            reason.contains("non-ASCII Unicode whitespace character"),
15160            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15161        );
15162        assert!(
15163            reason.contains("U+2028"),
15164            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
15165        );
15166    }
15167
15168    #[test]
15169    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
15170        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
15171        // labels in the `:entrada :host` axis — the canonical
15172        // paste-from-CJK-typography footgun (CJK IMEs default to
15173        // full-width whitespace when the space bar is pressed in
15174        // Japanese / Chinese input modes). Pins the third
15175        // representative of the non-ASCII Unicode `White_Space` set
15176        // through the shared predicate: the CJK block, distinct from
15177        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
15178        // SEPARATOR `U+2028` — covering the same axis breadth the
15179        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
15180        // (1b75b38) pins on `limits::parse_byte_size`.
15181        let mut s = three_member_spec();
15182        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
15183        let err = s.validate().unwrap_err();
15184        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15185            panic!("expected EntradaHostInvalid, got {err:?}");
15186        };
15187        assert!(
15188            reason.contains("non-ASCII Unicode whitespace character"),
15189            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15190        );
15191        assert!(
15192            reason.contains("U+3000"),
15193            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
15194        );
15195    }
15196
15197    #[test]
15198    fn rejects_entrada_host_too_long() {
15199        // Total length cap = 253; build a 254-byte host out of two
15200        // 63-byte labels + one 62-byte label + dots.
15201        let mut s = three_member_spec();
15202        let big = format!(
15203            "{}.{}.{}.{}",
15204            "a".repeat(63),
15205            "b".repeat(63),
15206            "c".repeat(63),
15207            "d".repeat(254 - 63 * 3 - 3)
15208        );
15209        assert_eq!(big.len(), 254);
15210        s.entrada.as_mut().unwrap().host = big;
15211        let err = s.validate().unwrap_err();
15212        assert!(
15213            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15214                if reason.contains("max length of 253")),
15215            "got {err:?}"
15216        );
15217    }
15218
15219    #[test]
15220    fn rejects_entrada_host_label_too_long() {
15221        let mut s = three_member_spec();
15222        // 64-byte label — one over the per-label cap.
15223        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
15224        let err = s.validate().unwrap_err();
15225        assert!(
15226            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15227                if reason.contains("label max length of 63")),
15228            "got {err:?}"
15229        );
15230    }
15231
15232    #[test]
15233    fn entrada_host_diagnostic_carries_offending_host() {
15234        // Diagnostic-shape pin — the offending host + a non-empty
15235        // reason flow through verbatim so the author can grep their
15236        // caixa.lisp for `:host "<host>"` and fix it in one edit.
15237        let mut s = three_member_spec();
15238        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
15239        let err = s.validate().unwrap_err();
15240        match err {
15241            AplicacaoError::EntradaHostInvalid { host, reason } => {
15242                assert_eq!(host, "checkout.quero.cloud:8080");
15243                assert!(!reason.is_empty(), "reason field must be non-empty");
15244            }
15245            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15246        }
15247    }
15248
15249    #[test]
15250    fn entrada_host_empty_takes_precedence_over_invalid() {
15251        // Ordering pin: `EmptyEntradaHost` is the more self-locating
15252        // diagnostic on `""` and must lead — `validate_entrada_host`
15253        // is only reached after the empty-check fires at the call
15254        // site. (The predicate itself defends against direct
15255        // invocation by returning the same error on `""`.)
15256        let mut s = three_member_spec();
15257        s.entrada.as_mut().unwrap().host = String::new();
15258        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
15259    }
15260
15261    #[test]
15262    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
15263        // Ordering pin: a missing :para member is the more
15264        // self-locating diagnostic and fires before the host gate.
15265        let mut s = three_member_spec();
15266        let e = s.entrada.as_mut().unwrap();
15267        e.para = "ghost".into();
15268        e.host = "BAD HOST".into();
15269        let err = s.validate().unwrap_err();
15270        assert!(
15271            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
15272            "got {err:?}"
15273        );
15274    }
15275
15276    #[test]
15277    fn entrada_host_invalid_fires_before_port_zero() {
15278        // Ordering pin: the host gate fires before the port gate so
15279        // a malformed host is named even when the port is also wrong.
15280        let mut s = three_member_spec();
15281        let e = s.entrada.as_mut().unwrap();
15282        e.host = "Checkout.quero.cloud".into();
15283        e.port = 0;
15284        let err = s.validate().unwrap_err();
15285        assert!(
15286            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15287                if host == "Checkout.quero.cloud"),
15288            "got {err:?}"
15289        );
15290    }
15291
15292    #[test]
15293    fn entrada_accepts_canonical_hosts() {
15294        // Positive-control sweep — every form the Gateway API
15295        // apiserver accepts must round-trip through validate. Covers
15296        // a plain DNS subdomain, a leading wildcard, a single-label
15297        // host (cluster-internal), a max-length-edge label, a
15298        // hyphen-bearing label, and a Punycode IDN label.
15299        for host in [
15300            "checkout.quero.cloud",
15301            "*.quero.cloud",
15302            "checkout",
15303            // 63-byte label — exactly the per-label cap.
15304            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
15305            "foo-bar.quero.cloud",
15306            // Punycode IDN — valid because the author pre-encoded.
15307            "xn--bcher-kva.example.com",
15308        ] {
15309            let mut s = three_member_spec();
15310            s.entrada.as_mut().unwrap().host = host.into();
15311            s.validate()
15312                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
15313        }
15314    }
15315
15316    #[test]
15317    fn entrada_host_max_length_validates() {
15318        // 253-byte host is the cap exactly — must validate. Build a
15319        // 253-byte host out of three 63-byte labels + one 61-byte
15320        // label + 3 dots = 252 bytes, then pad one byte to 253.
15321        let mut s = three_member_spec();
15322        let host = format!(
15323            "{}.{}.{}.{}",
15324            "a".repeat(63),
15325            "b".repeat(63),
15326            "c".repeat(63),
15327            "d".repeat(253 - 63 * 3 - 3)
15328        );
15329        assert_eq!(host.len(), 253);
15330        s.entrada.as_mut().unwrap().host = host;
15331        s.validate().unwrap();
15332    }
15333
15334    #[test]
15335    fn entrada_host_total_length_cap_threads_lifted_render_const() {
15336        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
15337        // total-length gate now reads the K8s Gateway API v1 Hostname
15338        // `maxLength: 253` cap from the lifted
15339        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
15340        // of truth — the same constant every future Gateway-API-Hostname
15341        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
15342        // materializer's per-host validator, the future per-`Certificate`
15343        // SAN emitter for cert-manager, the multi-`:entrada`
15344        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
15345        // from. Before the lift, the aplicacao-side reader consumed a
15346        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
15347        // 253-byte value as the peer render-side canonical bounds
15348        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
15349        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
15350        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
15351        // module boundary — a future 253-byte drift on either side would
15352        // silently split into two axes' worth of admission-schema mismatch
15353        // without a build-time signal. Pin the cap through a fresh 254-
15354        // byte host that hits the total-length arm, then read the reason
15355        // for the exact byte count the shared constant carries: any future
15356        // regression on the lift (a private alias reintroduced, a hard-
15357        // coded literal at the arm, a mismatch between the aplicacao-side
15358        // and render-side canonicals) surfaces as this pin's diagnostic
15359        // failing to match, not as a per-cluster admission rejection far
15360        // from the caixa.lisp source line.
15361        let mut s = three_member_spec();
15362        let over_cap = format!(
15363            "{}.{}.{}.{}",
15364            "a".repeat(63),
15365            "b".repeat(63),
15366            "c".repeat(63),
15367            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
15368        );
15369        assert_eq!(
15370            over_cap.len(),
15371            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
15372        );
15373        s.entrada.as_mut().unwrap().host = over_cap;
15374        let err = s.validate().unwrap_err();
15375        match err {
15376            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15377                let needle = format!(
15378                    "max length of {} bytes",
15379                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
15380                );
15381                assert!(
15382                    reason.contains(&needle),
15383                    "diagnostic must name the lifted \
15384                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
15385                );
15386            }
15387            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15388        }
15389    }
15390
15391    #[test]
15392    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
15393        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
15394        // on the per-label-cap axis. Before the lift, the aplicacao-side
15395        // per-label arm consumed a private const alias
15396        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
15397        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
15398        // split from it at the module boundary — every `.`-separated
15399        // label in a Gateway API v1 Hostname is a DNS-1123 label under
15400        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
15401        // so the private alias's 63 and the canonical const's 63 were
15402        // pinning the same underlying rule twice. Pin the cap through a
15403        // 64-byte label that hits the per-label arm, then read the reason
15404        // for the exact byte count the shared constant carries: any
15405        // future drift on either side (a private alias reintroduced, a
15406        // hard-coded literal at the arm, a mismatch between the two
15407        // 63-byte pins) surfaces at this pin's diagnostic rather than at
15408        // a per-cluster admission rejection whose "field is invalid"
15409        // opacity misframes the root cause.
15410        let mut s = three_member_spec();
15411        let over_cap_label = format!(
15412            "{}.quero.cloud",
15413            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
15414        );
15415        s.entrada.as_mut().unwrap().host = over_cap_label;
15416        let err = s.validate().unwrap_err();
15417        match err {
15418            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15419                let needle = format!(
15420                    "label max length of {} bytes",
15421                    crate::render::DNS_1123_LABEL_MAX_LEN,
15422                );
15423                assert!(
15424                    reason.contains(&needle),
15425                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
15426                     cap verbatim on the per-label arm, got: {reason:?}",
15427                );
15428            }
15429            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15430        }
15431    }
15432
15433    #[test]
15434    fn entrada_with_empty_paths_validates() {
15435        // Empty `:paths` is the documented "match every path" form;
15436        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
15437        let mut s = three_member_spec();
15438        s.entrada.as_mut().unwrap().paths = vec![];
15439        s.validate().unwrap();
15440    }
15441
15442    #[test]
15443    fn entrada_root_path_validates() {
15444        // The author-supplied bare-root `:entrada :paths` entry is the
15445        // same byte-shape the peer emit-side catch-all constant
15446        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
15447        // the author's `:paths` list is empty — sweeping the test-side
15448        // probe literal onto the lifted const closes the two-axis pin
15449        // (author-side admit + emit-side canonical fallback) around
15450        // one `&'static str`, so a future rebrand of the catch-all
15451        // reaches both consumers by construction. Peer to
15452        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
15453        // on the canonical-literal pin surface.
15454        let mut s = three_member_spec();
15455        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
15456        s.validate().unwrap();
15457    }
15458
15459    #[test]
15460    fn placement_strategy_variants_round_trip() {
15461        for s in [
15462            PlacementStrategy::SingleNode,
15463            PlacementStrategy::Replicated,
15464            PlacementStrategy::Sharded,
15465        ] {
15466            let p = Placement {
15467                estrategia: s,
15468                clusters: vec!["rio".into()],
15469                affinity: None,
15470                // Route the paired `:shard-key` fixture-builder through the
15471                // typed cross-slot invariant predicate
15472                // [`PlacementStrategy::requires_shard_key`] rather than the
15473                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
15474                // arm-identity predicate — the two answer the same
15475                // question under today's closed accept-set but a future
15476                // arm addition that consumed `:shard-key` under a
15477                // non-`Sharded` name would silently mis-attach the
15478                // fixture's `:shard-key` if the builder read through the
15479                // arm-identity predicate. The cross-slot-invariant
15480                // predicate migrates through one caixa-core edit on any
15481                // future arm addition; the fixture keeps producing a
15482                // `validate()`-passing round-trip by construction.
15483                shard_key: if s.requires_shard_key() {
15484                    Some("$key".into())
15485                } else {
15486                    None
15487                },
15488            };
15489            let json = serde_json::to_string(&p).unwrap();
15490            let back: Placement = serde_json::from_str(&json).unwrap();
15491            assert_eq!(back, p);
15492        }
15493    }
15494
15495    #[test]
15496    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
15497        // The fail-before-pass-after pin: pre-lift there was no
15498        // single-source binding between the [`PlacementStrategy`]
15499        // variant name the `Serialize` derive emits and the byte-
15500        // string every downstream cluster-side dispatcher (the
15501        // `lareira-fleet-programs` aggregator's per-entry strategy
15502        // branch, the future `app-operator` reconciler, the M3
15503        // Adaptive compression pass's per-strategy weighting) probes
15504        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
15505        // future `#[serde(rename_all = "kebab-case")]` attribute on
15506        // the enum — or a variant rename in the source — would
15507        // silently rebrand the emitted scalar under one spelling
15508        // while every downstream dispatcher still probed the other,
15509        // with the failure surfacing at the aggregator's dispatch
15510        // step or the operator's reconcile posture (workloads coming
15511        // up under the `default()` `Replicated` arm rather than the
15512        // typed slot's declared strategy) far from the source
15513        // rebrand commit and with no field naming the drift. Pinning
15514        // the two paths (the `Serialize` derive's serialized string
15515        // AND the [`PlacementStrategy::as_str`] helper) to the same
15516        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
15517        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15518        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
15519        // makes any future drift on either endpoint fail here at
15520        // caixa-core build time.
15521        for (variant, expected) in [
15522            (
15523                PlacementStrategy::SingleNode,
15524                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15525            ),
15526            (
15527                PlacementStrategy::Replicated,
15528                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15529            ),
15530            (
15531                PlacementStrategy::Sharded,
15532                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15533            ),
15534        ] {
15535            let json = serde_json::to_string(&variant).unwrap();
15536            assert_eq!(
15537                json,
15538                format!("\"{expected}\""),
15539                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
15540            );
15541            assert_eq!(
15542                variant.as_str(),
15543                expected,
15544                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
15545                 M3_PLACEMENT_ESTRATEGIA_* constant"
15546            );
15547        }
15548    }
15549
15550    #[test]
15551    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
15552        // Cross-arm drift-detection pin on the M3
15553        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
15554        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15555        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
15556        // scalar-value pentad: a future collapse of two canonical
15557        // variant byte-strings onto the same value (an accidental
15558        // copy-paste flip of
15559        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
15560        // read `"SingleNode"`, a per-arm rebrand that lands one const
15561        // without touching its paired peer) would silently reroute
15562        // every downstream operator's per-strategy dispatch onto the
15563        // sibling arm's reconcile branch and pass every
15564        // propagation-probe test that expected only the stale arm's
15565        // value — a `Replicated`-declared Aplicacao would come up
15566        // under the `SingleNode` primary-and-standby reconcile
15567        // posture, so every-cluster active-active workload would
15568        // silently collapse onto one-cluster-runs-at-a-time takeover
15569        // semantics against its declared strategy, with no field
15570        // naming the strategy-value drift root cause. Peer of the
15571        // sibling
15572        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
15573        // (09ffb2d) /
15574        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
15575        // (ccdf955) /
15576        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
15577        // (d739850) distinctness pins on the sibling OTP-shape /
15578        // caixa-kind closed-set typed-enum discriminator axes — the
15579        // fourth (and structurally the M3 mesh-primitive-defining)
15580        // closed-set typed-enum axis to converge on the same
15581        // "pairwise-distinct-by-construction" discipline.
15582        //
15583        // Fail-before-pass-after locally verified by mutating
15584        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
15585        // also read `"SingleNode"` — this pin fires as expected;
15586        // restoring passes.
15587        let all = [
15588            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15589            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15590            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15591        ];
15592        for (i, a) in all.iter().enumerate() {
15593            for (j, b) in all.iter().enumerate() {
15594                if i != j {
15595                    assert_ne!(
15596                        a, b,
15597                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
15598                         distinct — got duplicate {a:?} at indices {i} and {j}",
15599                    );
15600                }
15601            }
15602        }
15603    }
15604
15605    #[test]
15606    fn placement_strategy_display_routes_through_as_str_helper() {
15607        // The fail-before-pass-after pin: pre-lift the sibling
15608        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
15609        // / [`crate::supervisor::RestartPolicy`] both carried a stable
15610        // [`std::fmt::Display`] surface via their
15611        // `#[discriminant(also_display)]` gen-platform derive, but
15612        // [`PlacementStrategy`] did not — every consumer reaching for
15613        // a strategy byte-string past the wire format had to pick
15614        // between three paths ([`PlacementStrategy::as_str`], the
15615        // `Serialize` derive's serialized string, or `format!("{v:?}")`
15616        // on the `Debug` derive), any two of which a future variant
15617        // rename or `#[serde(rename_all = "kebab-case")]` attribute
15618        // would silently desynchronize. Wiring [`std::fmt::Display`]
15619        // through [`PlacementStrategy::as_str`] closes the third path:
15620        // every `format!("{v}")` call reaches the same lifted
15621        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
15622        // and the [`PlacementStrategy::as_str`] helper already route
15623        // through, so a future variant rename lands at exactly one
15624        // place. Pin the routing here so a future
15625        // `impl std::fmt::Display for PlacementStrategy` reimplementation
15626        // that hand-rolls the arms instead of delegating to
15627        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
15628        for variant in [
15629            PlacementStrategy::SingleNode,
15630            PlacementStrategy::Replicated,
15631            PlacementStrategy::Sharded,
15632        ] {
15633            assert_eq!(
15634                variant.to_string(),
15635                variant.as_str(),
15636                "PlacementStrategy::{variant:?} Display must route through \
15637                 PlacementStrategy::as_str (single source of truth: the lifted \
15638                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
15639            );
15640        }
15641    }
15642
15643    #[test]
15644    fn placement_strategy_display_matches_serialized_wire_byte_string() {
15645        // The fail-before-pass-after pin on the second half of the
15646        // three-path convergence: `Display` (user-facing text) agrees
15647        // byte-for-byte with the `Serialize` derive's wire format
15648        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
15649        // scalar) on every variant. Pre-lift the two paths were
15650        // structurally independent — a future
15651        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
15652        // would silently rebrand the emitted wire scalar
15653        // (`single-node`, `replicated`, `sharded`) while every consumer
15654        // that pretty-prints the strategy (the M3 diagnostic templates,
15655        // the future `feira app graph` per-Aplicacao strategy line,
15656        // the future M4 CR materializer's admission-webhook rejection
15657        // body) would still emit the TitleCase form the `as_str` /
15658        // `Display` route returns, with the mismatch surfacing at
15659        // consumer parse time / operator dispatch time far from the
15660        // source rebrand commit. Pin the two paths byte-for-byte here
15661        // so any future serde-attribute or variant-rename drift is a
15662        // caixa-core-build-time test failure at this call, not a
15663        // silent per-consumer dispatch miss.
15664        for variant in [
15665            PlacementStrategy::SingleNode,
15666            PlacementStrategy::Replicated,
15667            PlacementStrategy::Sharded,
15668        ] {
15669            let wire = serde_json::to_string(&variant).unwrap();
15670            // Strip the outer `"…"` the JSON string form carries — the
15671            // wire scalar the K8s / YAML apiserver consumes is the
15672            // enclosed byte-string, not the quote wrapper.
15673            let unquoted = wire
15674                .strip_prefix('"')
15675                .and_then(|s| s.strip_suffix('"'))
15676                .expect("serialized PlacementStrategy is a JSON string");
15677            assert_eq!(
15678                variant.to_string(),
15679                unquoted,
15680                "PlacementStrategy::{variant:?} Display byte-string must match the \
15681                 Serialize derive's wire byte-string (three-path convergence: \
15682                 Display + as_str + Serialize all resolve to the same \
15683                 M3_PLACEMENT_ESTRATEGIA_* const)"
15684            );
15685        }
15686    }
15687
15688    #[test]
15689    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
15690        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
15691        // derive on [`PlacementStrategy`]: for each of the three variants
15692        // exactly one of the generated `is_single_node` / `is_replicated`
15693        // / `is_sharded` predicates returns `true` and the other two
15694        // return `false`. Prior to this derive the three per-arm
15695        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
15696        // (the `placement_strategy_variants_round_trip` fixture, the
15697        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
15698        // fixture, and the
15699        // `validate_placement_reads_through_lifted_estrategia_accessor`
15700        // fixture) each open-coded a per-arm PartialEq compare against
15701        // the enum variant — three sites that expressed no compile-time
15702        // link back to the closed-set typed dispatch a future fourth
15703        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
15704        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
15705        // would have to thread through in lockstep or one fixture would
15706        // silently disagree with the others on which arms consume the
15707        // `:shard-key` axis. Peer of the sibling
15708        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
15709        // / [`crate::supervisor::RestartPolicy`] /
15710        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
15711        // the sibling closed-set typed-enum discriminator axes — extends
15712        // the same one-typed-dispatch-per-variant discipline onto the
15713        // fifth (and only remaining) closed-set typed-enum discriminator
15714        // on the caixa surface, closing the axis on the M3 mesh-slot
15715        // family.
15716        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
15717            (PlacementStrategy::SingleNode, [true, false, false]),
15718            (PlacementStrategy::Replicated, [false, true, false]),
15719            (PlacementStrategy::Sharded, [false, false, true]),
15720        ];
15721        for (variant, expected) in rows {
15722            let observed = [
15723                variant.is_single_node(),
15724                variant.is_replicated(),
15725                variant.is_sharded(),
15726            ];
15727            assert_eq!(
15728                observed, expected,
15729                "PlacementStrategy::{variant:?} is_* predicates must partition \
15730                 the arm set (single_node, replicated, sharded); got {observed:?}"
15731            );
15732        }
15733    }
15734
15735    #[test]
15736    fn placement_strategy_is_variant_predicates_are_const_fn() {
15737        // The [`gen_platform::IsVariant`] derive emits `const fn`
15738        // predicates on the peer [`crate::CaixaKind`] +
15739        // [`crate::upgrade::UpgradeInstruction`] +
15740        // [`crate::supervisor::RestartStrategy`] +
15741        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
15742        // pin the same posture on [`PlacementStrategy`] so a future
15743        // accidental downgrade to non-`const` (an added runtime helper
15744        // reachable only from a non-`const` context, a manual hand-rolled
15745        // `impl` that shadows the derive-generated method) trips at
15746        // caixa-core build time rather than surfacing as a downstream
15747        // `const`-context regression far from the derive declaration.
15748        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
15749        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
15750        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
15751        assert!(IS_SINGLE_NODE);
15752        assert!(IS_REPLICATED);
15753        assert!(IS_SHARDED);
15754    }
15755
15756    #[test]
15757    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
15758        // Fail-before-pass-after pin on the substrate-lifted
15759        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
15760        // per-arm predicate: for each variant in the closed accept-set the
15761        // predicate returns `true` iff the variant consumes the paired
15762        // [`Placement::shard_key`] axis under
15763        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
15764        // partition. Today the accept-set is the singleton `{Sharded}` —
15765        // `Sharded` is the Akka-style hash-keyed distribution arm
15766        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
15767        // §II.1) and `Replicated` (active-active) refuse the axis through
15768        // [`AplicacaoError::ShardKeyOnNonSharded`].
15769        //
15770        // Pins the per-arm truth-table so a future arm addition (an
15771        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
15772        // roadmap names, a `WeightedShard` promotion the future M5
15773        // adaptive-placement engine acknowledges) that landed a variant
15774        // without extending this predicate's arm-set would surface as a
15775        // caixa-core build-time exhaustiveness error at the
15776        // `match self { … }` arm-fan below rather than a silent per-consumer
15777        // mis-classification at renderer emit time. The paired
15778        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
15779        // predicate stays a distinct question — arm-identity (which the
15780        // sibling
15781        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
15782        // pin already locks) is not cross-slot-invariant consumption; today
15783        // they trip on the same singleton but the pair migrates through
15784        // one caixa-core edit on any future arm addition.
15785        //
15786        // Peer of the sibling per-arm classifier pins
15787        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
15788        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
15789        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
15790        // derived paired predicate on the post-projection typed-view axis
15791        // — same "per-arm semantic-classification predicate paired with
15792        // the arm-identity predicate the derive already emits" discipline
15793        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
15794        // `:placement :shard-key` cross-slot-invariant axis.
15795        let rows: [(PlacementStrategy, bool); 3] = [
15796            (PlacementStrategy::SingleNode, false),
15797            (PlacementStrategy::Replicated, false),
15798            (PlacementStrategy::Sharded, true),
15799        ];
15800        for (variant, expected) in rows {
15801            assert_eq!(
15802                variant.requires_shard_key(),
15803                expected,
15804                "PlacementStrategy::{variant:?}.requires_shard_key() must \
15805                 be {expected} (the substrate-canonical cross-slot invariant \
15806                 on the :placement :shard-key axis; today `Sharded` is the \
15807                 singleton consuming arm — MESH-COMPOSITION §II.4)",
15808            );
15809        }
15810    }
15811
15812    #[test]
15813    fn placement_strategy_requires_shard_key_is_const_fn() {
15814        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
15815        // invariant per-arm predicate is declared `#[must_use] pub const
15816        // fn` — pin the `const`-eval posture here so a future accidental
15817        // downgrade to non-`const` (an added runtime helper reachable
15818        // only from a non-`const` context, a manual hand-rolled `impl`
15819        // that shadows the current three-arm `match self { … }` dispatch)
15820        // trips at caixa-core build time rather than surfacing as a
15821        // downstream `const`-context regression far from the declaration.
15822        // Same shape as the sibling
15823        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
15824        // the peer [`gen_platform::IsVariant`]-derived arm-identity
15825        // predicate axis, but here the load-bearing assertions live in
15826        // module-scope `const _: () = assert!(…)` items so a violation
15827        // fails at compile time (const-eval trip) rather than test time —
15828        // strictly stronger than the runtime `assert!(CONST)` pattern the
15829        // sibling pin uses, and side-steps the
15830        // `clippy::assertions_on_constants` lint the runtime pattern
15831        // otherwise accumulates on the module baseline.
15832        //
15833        // The test body simply witnesses that the module-scope items
15834        // compiled and the runtime dispatch agrees with the const-eval
15835        // dispatch on every arm — the runtime read gives the test a
15836        // failure surface (rather than an empty test body clippy would
15837        // flag as a no-op).
15838        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
15839        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
15840        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
15841        assert_eq!(
15842            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
15843            [
15844                PlacementStrategy::SingleNode.requires_shard_key(),
15845                PlacementStrategy::Replicated.requires_shard_key(),
15846                PlacementStrategy::Sharded.requires_shard_key(),
15847            ],
15848            "runtime and const-eval dispatch on \
15849             PlacementStrategy::requires_shard_key must agree on every arm",
15850        );
15851    }
15852
15853    #[test]
15854    fn placement_estrategia_accessor_is_const_fn() {
15855        // The [`Placement::estrategia`] per-`:placement` distribution-
15856        // strategy `Copy`-return scalar accessor is declared
15857        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
15858        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
15859        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
15860        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
15861        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
15862        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
15863        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
15864        // [`RateLimit`], every one a `pub const fn`). Pin the
15865        // `const`-eval posture here so a future accidental downgrade to
15866        // non-`const` (an added runtime helper reachable only from a
15867        // non-`const` context, a slot promotion to a non-`Copy` return
15868        // that would silently drop the `const` qualifier, a manual
15869        // hand-rolled shadow) trips at caixa-core build time rather
15870        // than surfacing as a downstream `const`-context regression far
15871        // from the declaration.
15872        //
15873        // Same shape as the sibling
15874        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
15875        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
15876        // predicate axis — the load-bearing witness lives in the
15877        // module-scope `const fn` wrapper `estrategia_via_const_fn`
15878        // below: a body that calls [`Placement::estrategia`] under a
15879        // `const fn` signature is well-formed only when the callee is
15880        // itself `const fn`, so any future accidental downgrade of
15881        // [`Placement::estrategia`] to non-`const` fails at caixa-core
15882        // build time (const-eval E0015 / E0658 depending on the arm),
15883        // strictly stronger than a runtime `assert!(CONST)` and
15884        // side-stepping the destructor-in-const restriction that
15885        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
15886        // items on `Placement`'s `Vec<String>` / `Option<String>`
15887        // carriers.
15888        //
15889        // The runtime body witnesses that the const-eval-shaped
15890        // wrapper agrees with a direct call on every closed-set arm.
15891        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
15892            p.estrategia()
15893        }
15894        for estrategia in [
15895            PlacementStrategy::SingleNode,
15896            PlacementStrategy::Replicated,
15897            PlacementStrategy::Sharded,
15898        ] {
15899            let placement = Placement {
15900                estrategia,
15901                clusters: Vec::new(),
15902                affinity: None,
15903                shard_key: None,
15904            };
15905            assert_eq!(
15906                estrategia_via_const_fn(&placement),
15907                placement.estrategia(),
15908                "const-fn-wrapped and direct dispatch on \
15909                 Placement::estrategia must agree for {estrategia:?}",
15910            );
15911        }
15912    }
15913
15914    #[test]
15915    fn entrada_port_accessor_is_const_fn() {
15916        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
15917        // scalar accessor is declared `#[must_use] pub const fn` —
15918        // matching the peer M3 mesh-slot `Copy`-return accessor family
15919        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
15920        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
15921        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
15922        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
15923        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
15924        // [`RateLimit::window`] on the sibling [`RateLimit`], the
15925        // sibling per-`:placement` [`Placement::estrategia`] pinned by
15926        // [`placement_estrategia_accessor_is_const_fn`] above — every
15927        // one a `pub const fn`). Pin the `const`-eval posture here so
15928        // a future accidental downgrade to non-`const` (an added
15929        // runtime helper reachable only from a non-`const` context, an
15930        // `Option<u16>`-shape migration once the substrate grows
15931        // per-`:membros` heterogeneous listener ports that would
15932        // silently drop the `const` qualifier, a manual hand-rolled
15933        // shadow) trips at caixa-core build time rather than surfacing
15934        // as a downstream `const`-context regression far from the
15935        // declaration.
15936        //
15937        // Same shape as the sibling
15938        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
15939        // load-bearing witness lives in the module-scope `const fn`
15940        // wrapper `port_via_const_fn`: a body that calls
15941        // [`Entrada::port`] under a `const fn` signature is well-formed
15942        // only when the callee is itself `const fn`, side-stepping the
15943        // destructor-in-const restriction that would otherwise block a
15944        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
15945        // `String` / `Vec<String>` carriers.
15946        //
15947        // The runtime body sweeps a representative port set spanning
15948        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
15949        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
15950        // ceiling — the const-fn-wrapped call must agree with a direct
15951        // call on every fixture (a violation trips the test) and every
15952        // returned scalar must byte-equal the input `port` (a violation
15953        // means the accessor stopped being a raw field-return copy).
15954        const fn port_via_const_fn(e: &Entrada) -> u16 {
15955            e.port()
15956        }
15957        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
15958            let entrada = Entrada {
15959                host: String::new(),
15960                para: String::new(),
15961                port,
15962                paths: Vec::new(),
15963            };
15964            assert_eq!(
15965                port_via_const_fn(&entrada),
15966                entrada.port(),
15967                "const-fn-wrapped and direct dispatch on Entrada::port \
15968                 must agree for port={port}",
15969            );
15970            assert_eq!(
15971                entrada.port(),
15972                port,
15973                "Entrada::port must return the storage-side u16 verbatim \
15974                 for port={port}",
15975            );
15976        }
15977    }
15978
15979    #[test]
15980    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
15981        // Load-bearing cross-slot-partition pin closing the loop between
15982        // the substrate-lifted
15983        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
15984        // the closed-set typed enum and the actual
15985        // [`AplicacaoSpec::validate_placement`] runtime behavior across
15986        // the paired `:placement :shard-key` axis: every validated
15987        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
15988        // satisfies `placement.shard_key().is_some() ==
15989        // placement.estrategia().requires_shard_key()`. The four-cell
15990        // shape witness sweeps every combination of (variant in the
15991        // closed accept-set, `:shard-key` Some/None) and pins:
15992        //
15993        //   * variant.requires_shard_key() && shard_key.is_some() →
15994        //     validate() passes; the paired shape is the sole
15995        //     `requires_shard_key` arm-family accepted shape.
15996        //   * variant.requires_shard_key() && shard_key.is_none() →
15997        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
15998        //     the paired shape is the refused missing-key shape on
15999        //     Sharded-family arms.
16000        //   * !variant.requires_shard_key() && shard_key.is_some() →
16001        //     validate() fails with
16002        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
16003        //     is the refused declared-but-inert shape on non-Sharded-
16004        //     family arms.
16005        //   * !variant.requires_shard_key() && shard_key.is_none() →
16006        //     validate() passes; the paired shape is the sole
16007        //     non-`requires_shard_key` arm-family accepted shape.
16008        //
16009        // The compile-time-exhaustive `match p.estrategia()` dispatch at
16010        // [`AplicacaoSpec::validate_placement`] preserves its structural
16011        // arm-fan (a future arm addition still surfaces a build-time
16012        // exhaustiveness error there); this pin closes the semantic loop
16013        // between the arm-fan's shape-gate cascades and the substrate-
16014        // canonical predicate every downstream consumer of the paired
16015        // shape reads through. Fail-before-pass-after locally verified by
16016        // mutating the predicate's `Sharded => true` arm to `false` — the
16017        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
16018        // `validate() must pass` assertion; restoring passes. Same "close
16019        // the loop between the typed predicate and the runtime behavior"
16020        // discipline as the sibling
16021        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
16022        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
16023        // per-arm classifier axis.
16024        for variant in [
16025            PlacementStrategy::SingleNode,
16026            PlacementStrategy::Replicated,
16027            PlacementStrategy::Sharded,
16028        ] {
16029            for present in [false, true] {
16030                let mut spec = three_member_spec();
16031                spec.placement.estrategia = variant;
16032                spec.placement.shard_key = present.then(|| "tenantId".into());
16033                let expects_ok = variant.requires_shard_key() == present;
16034                let result = spec.validate();
16035                match (expects_ok, &result) {
16036                    (true, Ok(())) => {}
16037                    (false, Err(err)) => {
16038                        // Cross-check the refusal diagnostic names the
16039                        // right cell of the four-cell shape witness — the
16040                        // `requires_shard_key && !present` cell must trip
16041                        // [`AplicacaoError::ShardedWithoutKey`]; the
16042                        // `!requires_shard_key && present` cell must trip
16043                        // [`AplicacaoError::ShardKeyOnNonSharded`].
16044                        match (variant.requires_shard_key(), present, err) {
16045                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
16046                            (
16047                                false,
16048                                true,
16049                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
16050                            ) => {
16051                                assert_eq!(
16052                                    *e, variant,
16053                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
16054                                     the paired PlacementStrategy",
16055                                );
16056                            }
16057                            _ => panic!(
16058                                "unexpected refusal for estrategia={variant:?} \
16059                                 present={present}: {err:?}"
16060                            ),
16061                        }
16062                    }
16063                    (true, Err(err)) => panic!(
16064                        "validate() must pass for estrategia={variant:?} \
16065                         present={present} (requires_shard_key={} == present={present}), \
16066                         got {err:?}",
16067                        variant.requires_shard_key(),
16068                    ),
16069                    (false, Ok(())) => panic!(
16070                        "validate() must fail for estrategia={variant:?} \
16071                         present={present} (requires_shard_key={} != present={present})",
16072                        variant.requires_shard_key(),
16073                    ),
16074                }
16075            }
16076        }
16077    }
16078
16079    #[test]
16080    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
16081        // Pin the M3 diagnostic template routes through the typed
16082        // [`PlacementStrategy`] Display byte-string (rebound from the
16083        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
16084        // routes emitted identical bytes (the `Debug` derive on a
16085        // unit variant emits the variant name verbatim, exactly what
16086        // `as_str` returns), but the two paths were structurally
16087        // independent — a future `#[serde(rename_all = "…")]`
16088        // attribute or variant rename would coordinate the wire /
16089        // `Display` / `as_str` triple through the lifted const but
16090        // leave the `Debug` route on the compiler-derived variant name,
16091        // silently desynchronizing the diagnostic byte-string from the
16092        // wire byte-string. Rebinding the template onto `Display`
16093        // ties the diagnostic to the same lifted
16094        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
16095        // emits — drift becomes structurally impossible. Pin the
16096        // byte-string here so a future edit that reverts the template
16097        // to `{estrategia:?}` is caught at caixa-core test time, not
16098        // at consumer dispatch time.
16099        for (variant, expected_scalar) in [
16100            (
16101                PlacementStrategy::SingleNode,
16102                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16103            ),
16104            (
16105                PlacementStrategy::Replicated,
16106                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16107            ),
16108            (
16109                PlacementStrategy::Sharded,
16110                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16111            ),
16112        ] {
16113            let err = AplicacaoError::PlacementWithoutClusters {
16114                estrategia: variant,
16115            };
16116            let msg = err.to_string();
16117            assert!(
16118                msg.starts_with(&format!(":placement {expected_scalar} requires")),
16119                "PlacementWithoutClusters diagnostic for {variant:?} must open \
16120                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16121            );
16122        }
16123    }
16124
16125    #[test]
16126    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
16127        // Peer of
16128        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
16129        // on the second M3 diagnostic that carries the typed
16130        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
16131        // diagnostics now route the strategy scalar through the same
16132        // [`std::fmt::Display`] surface, tying the diagnostic
16133        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
16134        // const set the wire format also emits. The two non-Sharded
16135        // arms are exercised here (the diagnostic exists to flag a
16136        // `:shard-key` slot the current strategy will never consume);
16137        // the peer `Sharded` arm never reaches this diagnostic (the
16138        // `Sharded` strategy consumes `:shard-key` — the
16139        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
16140        // slot instead).
16141        for (variant, expected_scalar) in [
16142            (
16143                PlacementStrategy::SingleNode,
16144                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16145            ),
16146            (
16147                PlacementStrategy::Replicated,
16148                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16149            ),
16150        ] {
16151            let err = AplicacaoError::ShardKeyOnNonSharded {
16152                estrategia: variant,
16153                shard_key: "$tenantId".into(),
16154            };
16155            let msg = err.to_string();
16156            assert!(
16157                msg.starts_with(&format!(":placement {expected_scalar} carries")),
16158                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
16159                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16160            );
16161        }
16162    }
16163
16164    #[test]
16165    fn placement_strategy_all_enumerates_every_variant_once() {
16166        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
16167        // exhaustive-iteration surface: every variant appears exactly
16168        // once, and the slice length matches the arm count of the
16169        // closed set. Every consumer that walks the accepted-strategy
16170        // set (a future `feira app placement --list` CLI-side surfacing,
16171        // a future M4 admission-webhook's rejection body naming the
16172        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
16173        // reverse-projection consumers that iterate the accept-set for
16174        // a "did you mean" hint) reads through this slice, so a future
16175        // variant addition (an `Anycast` mesh-anycast arm the
16176        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
16177        // grows the enum but forgets to grow [`Self::ALL`] silently
16178        // truncates every downstream consumer's accept-set at the same
16179        // pre-addition boundary — this pin fails at caixa-core build
16180        // time on the pairwise-distinct + arm-count invariants.
16181        //
16182        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
16183        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
16184        // pins on the peer closed-set typed-enum axes.
16185        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
16186        assert_eq!(
16187            all.len(),
16188            3,
16189            "PlacementStrategy::ALL must enumerate every variant of the \
16190             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
16191        );
16192        for (i, a) in all.iter().enumerate() {
16193            for (j, b) in all.iter().enumerate() {
16194                if i != j {
16195                    assert_ne!(
16196                        a, b,
16197                        "PlacementStrategy::ALL must carry every variant exactly \
16198                         once — got duplicate {a:?} at indices {i} and {j}"
16199                    );
16200                }
16201            }
16202        }
16203        for variant in [
16204            PlacementStrategy::SingleNode,
16205            PlacementStrategy::Replicated,
16206            PlacementStrategy::Sharded,
16207        ] {
16208            assert!(
16209                all.contains(&variant),
16210                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
16211                 addition that grows the enum but forgets to grow the ALL slice \
16212                 silently truncates every downstream consumer's accept-set at the \
16213                 pre-addition boundary"
16214            );
16215        }
16216    }
16217
16218    #[test]
16219    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
16220        // Fail-before-pass-after pin on the forward accept-set of the
16221        // [`PlacementStrategy::from_wire`] reverse projection: every
16222        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
16223        // constant the [`PlacementStrategy::as_str`] emitter walks
16224        // parses back to its paired variant. Any future arm addition
16225        // that grows the emitter's `as_str` match but forgets to grow
16226        // the parser's `from_str` match silently splits the two halves
16227        // of the round-trip — the wire byte-string one non-serde
16228        // consumer parses from the one the emitter wrote — with the
16229        // failure surfacing at parse time far from the rebrand commit.
16230        // Pinning the three-arm accept-set here catches the drift at
16231        // caixa-core build time.
16232        //
16233        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
16234        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
16235        // closed-set typed-enum `str → Self` axes.
16236        for (wire, expected) in [
16237            (
16238                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16239                PlacementStrategy::SingleNode,
16240            ),
16241            (
16242                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16243                PlacementStrategy::Replicated,
16244            ),
16245            (
16246                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16247                PlacementStrategy::Sharded,
16248            ),
16249        ] {
16250            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16251                panic!(
16252                    "PlacementStrategy::from_wire({wire:?}) must accept every \
16253                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
16254                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
16255                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
16256                )
16257            });
16258            assert_eq!(
16259                parsed, expected,
16260                "PlacementStrategy::from_wire({wire:?}) must return \
16261                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
16262            );
16263        }
16264    }
16265
16266    #[test]
16267    fn placement_strategy_from_wire_round_trips_through_as_str() {
16268        // Fail-before-pass-after pin on the closed round-trip between
16269        // the forward [`PlacementStrategy::as_str`] emitter and the
16270        // reverse [`PlacementStrategy::from_wire`] parser: for every
16271        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
16272        // output must return exactly the same variant. Any per-arm
16273        // divergence — a future arm added to `as_str` but not
16274        // `from_str`, an accidental copy-paste flip in one but not the
16275        // other — silently splits the emit and parse halves and the
16276        // failure surfaces at consumer parse time far from the drift
16277        // site. The `ALL`-iterating shape means a future variant
16278        // addition picks up the coverage by construction.
16279        //
16280        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
16281        // [`crate::CaixaKind::from_wire`] and the
16282        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
16283        // sibling round-trip pin on [`RateLimitUnit`].
16284        for &variant in PlacementStrategy::ALL {
16285            let wire = variant.as_str();
16286            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16287                panic!(
16288                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16289                     must be Some({variant:?}) — the two halves of the round-trip \
16290                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
16291                     got None on wire byte-string {wire:?}"
16292                )
16293            });
16294            assert_eq!(
16295                parsed, variant,
16296                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16297                 must round-trip to the same variant; got {parsed:?}"
16298            );
16299        }
16300    }
16301
16302    #[test]
16303    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
16304        // Fail-before-pass-after pin on the closed-set refusal
16305        // discipline of [`PlacementStrategy::from_wire`]: every
16306        // byte-string outside the three-arm accept-set returns `None`
16307        // rather than silently collapsing onto the [`Default`]
16308        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
16309        // exercised here sweeps the load-bearing drift shapes: the
16310        // empty string (a stripped serde-attribute drift), an all-
16311        // whitespace string (the canonical text-editor accidental
16312        // padding shape), the lowercased kebab-case forms a future
16313        // `#[serde(rename_all = "kebab-case")]` attribute would emit
16314        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
16315        // coincidentally match the accepted canonical scalars, so only
16316        // `"single-node"` fires as a refusal, but pinning the case-
16317        // sensitivity of the accepted arms via the peer [`SingleNode`]
16318        // assertion in the round-trip pin makes the discipline
16319        // structurally clear), the lowercased single-word forms
16320        // (`"singlenode"`), the padded canonical scalar
16321        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
16322        // (`"Sharded\n"`), and a pointer-different `&'static str` that
16323        // happens to alias a canonical byte-string by content but not
16324        // by identity (validated implicitly by the emitter's routing
16325        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
16326        // identity a paired [`crate::assert_str_reexport_identity`] pin
16327        // in caixa-core's per-const declaration surface would catch).
16328        //
16329        // Peer of the sibling
16330        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
16331        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
16332        for bad in [
16333            "",
16334            " ",
16335            "\n",
16336            "\t",
16337            "single-node",
16338            "singlenode",
16339            "SingleNodes",
16340            "single_node",
16341            "single node",
16342            "SINGLENODE",
16343            "SingleNode ",
16344            " SingleNode",
16345            " Sharded ",
16346            "Sharded\n",
16347            "replicated ",
16348            "sharded",
16349            "REPLICATED",
16350            "Anycast",
16351            "Global",
16352            "?",
16353        ] {
16354            assert!(
16355                PlacementStrategy::from_wire(bad).is_none(),
16356                "PlacementStrategy::from_wire({bad:?}) must return None — the \
16357                 parser's accept-set is exactly the three PlacementStrategy::as_str \
16358                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
16359                 is outside that closed set"
16360            );
16361        }
16362    }
16363
16364    #[test]
16365    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
16366        // Fail-before-pass-after pin on the third path of the four-path
16367        // convergence: `from_str` (the reverse projection) inverts the
16368        // `Serialize` derive's wire byte-string on every variant.
16369        // Together with the pre-existing three-path convergence
16370        // (`Display` + `as_str` + `Serialize` all resolve to the same
16371        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
16372        // the peer
16373        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
16374        // this closes the round-trip: the wire byte-string the
16375        // `Serialize` derive emits parses back to the same variant
16376        // through `from_str`, so any future serde-attribute or variant-
16377        // rename drift on the emit half now surfaces as a matched drift
16378        // on the parse half at caixa-core build time — the two halves
16379        // migrate as a unit through the lifted consts on any future
16380        // rename, and the round-trip cannot silently split.
16381        //
16382        // Peer of the sibling
16383        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
16384        // wire-format pin — extends the three-path convergence
16385        // (`Display` + `as_str` + `Serialize`) onto the fourth path
16386        // (`from_str`), closing the `str ↔ Self` round-trip on the
16387        // M3 `:placement :estrategia` closed-set axis.
16388        for &variant in PlacementStrategy::ALL {
16389            let wire = serde_json::to_string(&variant).unwrap();
16390            let unquoted = wire
16391                .strip_prefix('"')
16392                .and_then(|s| s.strip_suffix('"'))
16393                .expect("serialized PlacementStrategy is a JSON string");
16394            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
16395                panic!(
16396                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
16397                     Serialize derive's wire byte-string for \
16398                     PlacementStrategy::{variant:?} — the four-path convergence \
16399                     (Display + as_str + Serialize + from_str) resolves through \
16400                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
16401                )
16402            });
16403            assert_eq!(
16404                parsed, variant,
16405                "PlacementStrategy::from_wire of the Serialize derive's wire \
16406                 byte-string for PlacementStrategy::{variant:?} must round-trip \
16407                 to the same variant; got {parsed:?}"
16408            );
16409        }
16410    }
16411
16412    #[test]
16413    fn rejects_zero_policy_timeout() {
16414        let mut s = three_member_spec();
16415        s.politicas.timeout = Some(Duration::ZERO);
16416        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
16417    }
16418
16419    #[test]
16420    fn rejects_zero_policy_retries() {
16421        let mut s = three_member_spec();
16422        s.politicas.retries = Some(0);
16423        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
16424    }
16425
16426    #[test]
16427    fn rejects_policy_retries_above_cap() {
16428        // The fail-before-pass-after pin: `Some(11)` is structurally
16429        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
16430        // passed validate on every pre-gate codebase because the
16431        // typed slot's only check was the zero-floor arm. The
16432        // thundering-herd amplification vector only surfaced at the
16433        // runtime substrate (Envoy / Cilium L7 retry overlay)
16434        // far from the source caixa.lisp with no field naming the
16435        // offending policy.
16436        let mut s = three_member_spec();
16437        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
16438        assert_eq!(
16439            s.validate().unwrap_err(),
16440            AplicacaoError::PolicyRetriesExceedsCap {
16441                retries: POLICY_RETRIES_MAX + 1
16442            }
16443        );
16444    }
16445
16446    #[test]
16447    fn rejects_policy_retries_far_above_cap() {
16448        // The `u32::MAX` worst case — the four-billion-retry policy
16449        // a typo (`(:retries 4294967295)`) or struct-literal
16450        // copy-paste lands in the slot. Pin the cap arm's coverage
16451        // explicitly across the full `u32` overflow so a future
16452        // relaxation that drops the upper bound surfaces here.
16453        let mut s = three_member_spec();
16454        s.politicas.retries = Some(u32::MAX);
16455        assert_eq!(
16456            s.validate().unwrap_err(),
16457            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
16458        );
16459    }
16460
16461    #[test]
16462    fn accepts_policy_retries_at_cap() {
16463        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
16464        // must validate. The cap is inclusive on the top edge,
16465        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16466        // discipline on the sibling [`crate::LimitsSpec::memory`]
16467        // axis. Pin the boundary explicitly so a future off-by-one
16468        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
16469        // surfaces here as a test failure rather than a silent
16470        // contract narrowing.
16471        let mut s = three_member_spec();
16472        s.politicas.retries = Some(POLICY_RETRIES_MAX);
16473        s.validate()
16474            .expect("retries == POLICY_RETRIES_MAX must validate");
16475    }
16476
16477    #[test]
16478    fn accepts_policy_retries_typical_values() {
16479        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
16480        // every value in the validated set must pass. The
16481        // Envoy / Istio production-playbook recommendation band
16482        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
16483        // (`maxRetries ≤ 10`) both lie within this set.
16484        for r in 1..=POLICY_RETRIES_MAX {
16485            let mut s = three_member_spec();
16486            s.politicas.retries = Some(r);
16487            s.validate()
16488                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
16489        }
16490    }
16491
16492    #[test]
16493    fn policy_retries_zero_takes_precedence_over_cap() {
16494        // The cross-arm ordering pin: `Some(0)` is structurally
16495        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
16496        // (cap), but the zero-floor diagnostic is the more
16497        // self-locating one (it directly names the omit-axis
16498        // remediation), so the validate gate must fire on zero
16499        // first. Pin the order so a future refactor that reorders
16500        // the arms surfaces here as a test failure rather than a
16501        // silent diagnostic regression. Same shape every other
16502        // zero-then-shape ordering on this surface uses
16503        // ([`AplicacaoError::PolicyTimeoutZero`] then
16504        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
16505        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
16506        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
16507        let mut s = three_member_spec();
16508        s.politicas.retries = Some(0);
16509        assert_eq!(
16510            s.validate().unwrap_err(),
16511            AplicacaoError::PolicyRetriesZero,
16512            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
16513        );
16514    }
16515
16516    #[test]
16517    fn policy_retries_cap_diagnostic_carries_offending_value() {
16518        // The diagnostic-shape pin: the offending `u32` is carried
16519        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
16520        // variant so the surfaced error message names the value the
16521        // author wrote (`":politicas :retries (47) exceeds the
16522        // mesh-policy ceiling …"`), not just the cap. Same
16523        // self-locating diagnostic shape every other typed-cap arm
16524        // on this surface carries
16525        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16526        // offending byte count verbatim).
16527        let mut s = three_member_spec();
16528        s.politicas.retries = Some(47);
16529        let err = s.validate().unwrap_err();
16530        assert!(
16531            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
16532            "got {err:?}"
16533        );
16534        let msg = err.to_string();
16535        assert!(
16536            msg.contains("47"),
16537            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
16538        );
16539    }
16540
16541    #[test]
16542    fn policy_retries_cap_is_aws_app_mesh_aligned() {
16543        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
16544        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
16545        // schema cap — the only upstream mesh-policy schema that
16546        // documents an explicit hard cap. Pinning the literal value
16547        // here surfaces a future drift (a relaxation to 20, a
16548        // tightening to 5) as a deliberate test edit, not a silent
16549        // contract narrowing.
16550        assert_eq!(POLICY_RETRIES_MAX, 10);
16551    }
16552
16553    #[test]
16554    fn rejects_circuit_breaker_zero_max_failures() {
16555        let mut s = three_member_spec();
16556        s.politicas.circuit_breaker = Some(CircuitBreaker {
16557            max_failures: 0,
16558            window: Duration::from_secs(60),
16559        });
16560        assert_eq!(
16561            s.validate().unwrap_err(),
16562            AplicacaoError::PolicyBreakerZeroFailures
16563        );
16564    }
16565
16566    #[test]
16567    fn rejects_circuit_breaker_max_failures_above_cap() {
16568        // The fail-before-pass-after pin: `1001` is structurally one
16569        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
16570        // silently passed validate on every pre-gate codebase
16571        // because the typed slot's only check was the zero-floor
16572        // arm. The breaker-no-op vector only surfaced at the runtime
16573        // substrate (Envoy / Cilium L7 outlier-detection overlay)
16574        // far from the source caixa.lisp with no field naming the
16575        // offending policy.
16576        let mut s = three_member_spec();
16577        s.politicas.circuit_breaker = Some(CircuitBreaker {
16578            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16579            window: Duration::from_secs(60),
16580        });
16581        assert_eq!(
16582            s.validate().unwrap_err(),
16583            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16584                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16585            }
16586        );
16587    }
16588
16589    #[test]
16590    fn rejects_circuit_breaker_max_failures_far_above_cap() {
16591        // The `u32::MAX` worst case — the four-billion-failure
16592        // threshold a typo (`(:max-failures 4294967295)`) or a
16593        // struct-literal copy-paste lands in the slot. Pin the cap
16594        // arm's coverage explicitly across the full `u32` overflow
16595        // so a future relaxation that drops the upper bound surfaces
16596        // here.
16597        let mut s = three_member_spec();
16598        s.politicas.circuit_breaker = Some(CircuitBreaker {
16599            max_failures: u32::MAX,
16600            window: Duration::from_secs(60),
16601        });
16602        assert_eq!(
16603            s.validate().unwrap_err(),
16604            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16605                max_failures: u32::MAX,
16606            }
16607        );
16608    }
16609
16610    #[test]
16611    fn accepts_circuit_breaker_max_failures_at_cap() {
16612        // The boundary value — exactly
16613        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
16614        // cap is inclusive on the top edge, matching the
16615        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16616        // discipline on the sibling capped axes. Pin the boundary
16617        // explicitly so a future off-by-one tightening
16618        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
16619        // surfaces here as a test failure rather than a silent
16620        // contract narrowing.
16621        let mut s = three_member_spec();
16622        s.politicas.circuit_breaker = Some(CircuitBreaker {
16623            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
16624            window: Duration::from_secs(60),
16625        });
16626        s.validate()
16627            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
16628    }
16629
16630    #[test]
16631    fn accepts_circuit_breaker_max_failures_typical_values() {
16632        // The documented production-playbook band positive-control
16633        // sweep — every value Hystrix / Istio / Envoy / Polly /
16634        // Resilience4j recommend (5..=50) must pass, plus a sweep
16635        // through the hyperscale band (100, 500, 1000) the cap
16636        // accepts. Pin the inclusive validated set explicitly so a
16637        // future tightening of the ceiling surfaces here.
16638        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
16639            let mut s = three_member_spec();
16640            s.politicas.circuit_breaker = Some(CircuitBreaker {
16641                max_failures: n,
16642                window: Duration::from_secs(60),
16643            });
16644            s.validate()
16645                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
16646        }
16647    }
16648
16649    #[test]
16650    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
16651        // The cross-arm ordering pin: `0` is structurally outside
16652        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
16653        // (cap), but the zero-floor diagnostic is the more
16654        // self-locating one (it directly names the omit-axis
16655        // remediation), so the validate gate must fire on zero
16656        // first. Same shape every other zero-then-shape ordering on
16657        // this surface uses
16658        // ([`AplicacaoError::PolicyRetriesZero`] then
16659        // [`AplicacaoError::PolicyRetriesExceedsCap`];
16660        // [`AplicacaoError::PolicyTimeoutZero`] then
16661        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
16662        let mut s = three_member_spec();
16663        s.politicas.circuit_breaker = Some(CircuitBreaker {
16664            max_failures: 0,
16665            window: Duration::from_secs(60),
16666        });
16667        assert_eq!(
16668            s.validate().unwrap_err(),
16669            AplicacaoError::PolicyBreakerZeroFailures,
16670            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
16671        );
16672    }
16673
16674    #[test]
16675    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
16676        // The cross-arm ordering pin between the cap and the
16677        // sibling `:window` gates (zero-window, canonical-window).
16678        // A breaker carrying both an over-cap `max_failures` AND a
16679        // structurally invalid window (zero, sub-ms) must surface
16680        // the cap diagnostic first — the cap arm is wired
16681        // immediately after the zero-failure arm and strictly
16682        // before the window arms, so the offending value the
16683        // diagnostic names matches the order the author would
16684        // discover the gates by reading top-to-bottom through
16685        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
16686        // future refactor that reorders the arms surfaces here as a
16687        // test failure rather than a silent diagnostic regression.
16688        let mut s = three_member_spec();
16689        s.politicas.circuit_breaker = Some(CircuitBreaker {
16690            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16691            window: Duration::ZERO,
16692        });
16693        assert_eq!(
16694            s.validate().unwrap_err(),
16695            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16696                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16697            },
16698            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
16699        );
16700    }
16701
16702    #[test]
16703    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
16704        // The diagnostic-shape pin: the offending `u32` is carried
16705        // verbatim into the
16706        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
16707        // variant so the surfaced error message names the value the
16708        // author wrote (`":politicas :circuit-breaker :max-failures
16709        // (50000) exceeds the mesh-policy ceiling …"`), not just
16710        // the cap. Same self-locating diagnostic shape every other
16711        // typed-cap arm on this surface carries
16712        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
16713        // offending retry count verbatim,
16714        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16715        // offending byte count verbatim).
16716        let mut s = three_member_spec();
16717        s.politicas.circuit_breaker = Some(CircuitBreaker {
16718            max_failures: 50_000,
16719            window: Duration::from_secs(60),
16720        });
16721        let err = s.validate().unwrap_err();
16722        assert!(
16723            matches!(
16724                err,
16725                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16726                    max_failures: 50_000
16727                }
16728            ),
16729            "got {err:?}"
16730        );
16731        let msg = err.to_string();
16732        assert!(
16733            msg.contains("50000"),
16734            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
16735        );
16736    }
16737
16738    #[test]
16739    fn policy_breaker_max_failures_cap_pins_canonical_value() {
16740        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
16741        // value at 1000 — an order of magnitude above every
16742        // documented production-playbook recommendation band
16743        // (Hystrix `requestVolumeThreshold` default 20, Istio
16744        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
16745        // `outlier_detection.consecutive_5xx` default 5, Polly /
16746        // Resilience4j typical 5..=50) and below the
16747        // clearly-pathological "effectively no protection" floor
16748        // (10_000, 100_000, u32::MAX). Pinning the literal value
16749        // here surfaces a future drift (a relaxation to 10_000, a
16750        // tightening to 100) as a deliberate test edit, not a
16751        // silent contract narrowing.
16752        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
16753    }
16754
16755    #[test]
16756    fn rejects_circuit_breaker_zero_window() {
16757        let mut s = three_member_spec();
16758        s.politicas.circuit_breaker = Some(CircuitBreaker {
16759            max_failures: 5,
16760            window: Duration::ZERO,
16761        });
16762        assert_eq!(
16763            s.validate().unwrap_err(),
16764            AplicacaoError::PolicyBreakerZeroWindow
16765        );
16766    }
16767
16768    #[test]
16769    fn rejects_zero_rate_limit() {
16770        let mut s = three_member_spec();
16771        s.politicas.rate_limit = Some(RateLimit {
16772            rate: 0,
16773            window: Duration::from_secs(1),
16774        });
16775        assert_eq!(
16776            s.validate().unwrap_err(),
16777            AplicacaoError::PolicyRateLimitZero
16778        );
16779    }
16780
16781    #[test]
16782    fn rejects_rate_limit_zero_window() {
16783        // `RateLimit { rate: 100, window: Duration::ZERO }` is
16784        // constructible programmatically (the typed `Duration` field
16785        // imposes no nonzero invariant) but renders through
16786        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
16787        // codec's `parse` rejects as `unknown rate-limit window unit
16788        // "0s"`. Until this validate-time gate landed the typed slot
16789        // accepted the value silently and the round-trip break only
16790        // surfaced at deserialize time (potentially in a downstream
16791        // consumer that never re-validates). Pin the rejection at
16792        // `AplicacaoSpec::validate` so the typed slot's valid set
16793        // matches the codec's round-trippable set structurally.
16794        let mut s = three_member_spec();
16795        s.politicas.rate_limit = Some(RateLimit {
16796            rate: 100,
16797            window: Duration::ZERO,
16798        });
16799        assert_eq!(
16800            s.validate().unwrap_err(),
16801            AplicacaoError::PolicyRateLimitWindowNotCanonical {
16802                window: Duration::ZERO
16803            }
16804        );
16805    }
16806
16807    #[test]
16808    fn rejects_rate_limit_arbitrary_seconds_window() {
16809        // 45 seconds is a valid `Duration` but not one of the three
16810        // canonical rate-limit windows the codec round-trips
16811        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
16812        // refuses on round-trip — same round-trip-break shape the
16813        // zero-window arm above pins, with a non-zero magnitude to
16814        // guard against a future "reject only zero" half-measure.
16815        let mut s = three_member_spec();
16816        let window = Duration::from_secs(45);
16817        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
16818        assert_eq!(
16819            s.validate().unwrap_err(),
16820            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16821        );
16822    }
16823
16824    #[test]
16825    fn rejects_rate_limit_two_minute_window() {
16826        // 120 seconds = 2 minutes is a "looks-canonical" but
16827        // not-canonical window: it's a clean integer multiple of the
16828        // minute unit, but the codec only round-trips the
16829        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
16830        // A `Duration::from_secs(120)` window renders as `"100/120s"`
16831        // which the parser rejects. Pinning this case rules out a
16832        // future "accept any clean multiple of s/m/h" relaxation
16833        // that would silently break the codec contract.
16834        let mut s = three_member_spec();
16835        let window = Duration::from_secs(120);
16836        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
16837        assert_eq!(
16838            s.validate().unwrap_err(),
16839            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16840        );
16841    }
16842
16843    #[test]
16844    fn rejects_rate_limit_subsecond_window() {
16845        // A sub-second window (e.g. 500ms) is a valid `Duration` but
16846        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
16847        // Pin the rejection so a future relaxation can't silently
16848        // admit fractional-second windows that the codec can't
16849        // round-trip.
16850        let mut s = three_member_spec();
16851        let window = Duration::from_millis(500);
16852        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
16853        assert_eq!(
16854            s.validate().unwrap_err(),
16855            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16856        );
16857    }
16858
16859    #[test]
16860    fn rejects_policy_rate_limit_above_cap() {
16861        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
16862        // is structurally one past the cap and silently passed
16863        // validate on every pre-gate codebase because the typed slot's
16864        // only `rate` check was the zero-floor arm. The no-op-limiter
16865        // shape only surfaced at the runtime substrate (Envoy's
16866        // `local_rate_limit.token_bucket.max_tokens`, the future
16867        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
16868        // with no field naming the offending policy.
16869        let mut s = three_member_spec();
16870        s.politicas.rate_limit = Some(RateLimit {
16871            rate: POLICY_RATE_LIMIT_MAX + 1,
16872            window: Duration::from_secs(1),
16873        });
16874        assert_eq!(
16875            s.validate().unwrap_err(),
16876            AplicacaoError::PolicyRateLimitExceedsCap {
16877                rate: POLICY_RATE_LIMIT_MAX + 1
16878            }
16879        );
16880    }
16881
16882    #[test]
16883    fn rejects_policy_rate_limit_far_above_cap() {
16884        // The `u32::MAX` worst case — the four-billion-token rate-limit
16885        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
16886        // copy-paste lands in the slot. Pin the cap arm's coverage
16887        // explicitly across the full `u32` overflow so a future
16888        // relaxation that drops the upper bound surfaces here. Peer to
16889        // `rejects_policy_retries_far_above_cap` on the sibling
16890        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
16891        // on the sibling `:max-failures` axis.
16892        let mut s = three_member_spec();
16893        s.politicas.rate_limit = Some(RateLimit {
16894            rate: u32::MAX,
16895            window: Duration::from_secs(1),
16896        });
16897        assert_eq!(
16898            s.validate().unwrap_err(),
16899            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
16900        );
16901    }
16902
16903    #[test]
16904    fn accepts_policy_rate_limit_at_cap() {
16905        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
16906        // must validate. The cap is inclusive on the top edge, matching
16907        // every other typed upper bound in this crate
16908        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
16909        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
16910        // across all three canonical windows so a future off-by-one
16911        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
16912        // window-conditional cap surfaces here as a test failure rather
16913        // than a silent contract narrowing.
16914        for secs in [1u64, 60, 3600] {
16915            let mut s = three_member_spec();
16916            s.politicas.rate_limit = Some(RateLimit {
16917                rate: POLICY_RATE_LIMIT_MAX,
16918                window: Duration::from_secs(secs),
16919            });
16920            s.validate().unwrap_or_else(|e| {
16921                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
16922            });
16923        }
16924    }
16925
16926    #[test]
16927    fn accepts_policy_rate_limit_typical_values() {
16928        // The documented production-playbook recommendation band —
16929        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
16930        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
16931        // Enterprise ~1M per-hour. Every value in the validated set
16932        // must pass; pin the band explicitly so a future tightening
16933        // surfaces here.
16934        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
16935            for secs in [1u64, 60, 3600] {
16936                let mut s = three_member_spec();
16937                s.politicas.rate_limit = Some(RateLimit {
16938                    rate,
16939                    window: Duration::from_secs(secs),
16940                });
16941                s.validate().unwrap_or_else(|e| {
16942                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
16943                });
16944            }
16945        }
16946    }
16947
16948    #[test]
16949    fn policy_rate_limit_zero_takes_precedence_over_cap() {
16950        // The cross-arm ordering pin: `rate == 0` is structurally
16951        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
16952        // (cap), but the zero-floor diagnostic is the more
16953        // self-locating one (it directly names the omit-axis
16954        // remediation). Pin the order so a future refactor that
16955        // reorders the arms surfaces here as a test failure rather
16956        // than a silent diagnostic regression. Same shape every other
16957        // zero-then-cap ordering on this surface uses
16958        // ([`AplicacaoError::PolicyRetriesZero`] then
16959        // [`AplicacaoError::PolicyRetriesExceedsCap`];
16960        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
16961        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
16962        let mut s = three_member_spec();
16963        s.politicas.rate_limit = Some(RateLimit {
16964            rate: 0,
16965            window: Duration::from_secs(1),
16966        });
16967        assert_eq!(
16968            s.validate().unwrap_err(),
16969            AplicacaoError::PolicyRateLimitZero,
16970            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
16971        );
16972    }
16973
16974    #[test]
16975    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
16976        // Two-axis-bad pin: rate above cap *and* window non-canonical.
16977        // The validate gate must fire on the rate cap first — the
16978        // amplification-shape (no-op limiter) diagnostic is the more
16979        // fundamental one; the window-canonical diagnostic is the
16980        // narrower codec-round-trip shape. Pin the ordering so a future
16981        // refactor that reorders the rate-then-window check arms
16982        // surfaces here as a test failure rather than a silent
16983        // diagnostic regression.
16984        let mut s = three_member_spec();
16985        s.politicas.rate_limit = Some(RateLimit {
16986            rate: POLICY_RATE_LIMIT_MAX + 1,
16987            window: Duration::from_secs(45),
16988        });
16989        assert_eq!(
16990            s.validate().unwrap_err(),
16991            AplicacaoError::PolicyRateLimitExceedsCap {
16992                rate: POLICY_RATE_LIMIT_MAX + 1
16993            },
16994            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
16995        );
16996    }
16997
16998    #[test]
16999    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
17000        // The diagnostic-shape pin: the offending `u32` is carried
17001        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
17002        // variant so the surfaced error message names the value the
17003        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
17004        // the mesh-policy ceiling …"`), not just the cap. Same
17005        // self-locating diagnostic shape every other typed-cap arm on
17006        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
17007        // carries the offending retries count verbatim,
17008        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
17009        // the offending failure count verbatim).
17010        let mut s = three_member_spec();
17011        s.politicas.rate_limit = Some(RateLimit {
17012            rate: 5_000_000,
17013            window: Duration::from_secs(1),
17014        });
17015        let err = s.validate().unwrap_err();
17016        assert!(
17017            matches!(
17018                err,
17019                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
17020            ),
17021            "got {err:?}"
17022        );
17023        let msg = err.to_string();
17024        assert!(
17025            msg.contains("5000000"),
17026            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
17027        );
17028    }
17029
17030    #[test]
17031    fn policy_rate_limit_cap_pins_canonical_value() {
17032        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
17033        // 1_000_000 — two-to-three orders of magnitude above every
17034        // documented production-playbook recommendation band (Envoy /
17035        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
17036        // Gateway 10_000..=100_000 per-minute) and below the
17037        // clearly-pathological "paste-from-binary blob" floor
17038        // (100_000_000, u32::MAX). Pinning the literal value here
17039        // surfaces a future drift (a relaxation to 10_000_000, a
17040        // tightening to 100_000) as a deliberate test edit, not a
17041        // silent contract narrowing.
17042        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
17043    }
17044
17045    #[test]
17046    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
17047        // Both axes are invalid here: rate == 0 *and* window is
17048        // non-canonical. The validate gate must fire on rate first
17049        // (matching the existing `rejects_zero_rate_limit` ordering),
17050        // so the existing diagnostic continues to lead with the
17051        // simpler "zero rate" framing. Pinning the order of checks
17052        // so a future refactor that reorders the arms surfaces here
17053        // as a test failure rather than a silent diagnostic
17054        // regression.
17055        let mut s = three_member_spec();
17056        s.politicas.rate_limit = Some(RateLimit {
17057            rate: 0,
17058            window: Duration::from_secs(45),
17059        });
17060        assert_eq!(
17061            s.validate().unwrap_err(),
17062            AplicacaoError::PolicyRateLimitZero
17063        );
17064    }
17065
17066    #[test]
17067    fn rate_limit_canonical_windows_validate() {
17068        // The three canonical windows the codec round-trips
17069        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
17070        // unchanged. Pin the full canonical set as a positive case
17071        // (the existing `rate_limit_round_trip_seconds` /
17072        // `rate_limit_round_trip_minutes` tests pin the
17073        // serialize-then-deserialize property at the codec layer; this
17074        // test pins the validate-side complement so a future tightening
17075        // of the canonical set — e.g. dropping `:hour` — surfaces here
17076        // as a test failure rather than a silent contract narrowing).
17077        for secs in [1u64, 60, 3600] {
17078            let mut s = three_member_spec();
17079            s.politicas.rate_limit = Some(RateLimit {
17080                rate: 100,
17081                window: Duration::from_secs(secs),
17082            });
17083            s.validate().expect("canonical window must validate");
17084        }
17085    }
17086
17087    #[test]
17088    fn rate_limit_validated_value_round_trips_through_codec() {
17089        // The structural property the validate gate enforces:
17090        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
17091        // losslessly through the `rate_limit_codec` (serialize → string
17092        // → deserialize → equal value). Pin this end-to-end so a future
17093        // change to either side (the validate gate's accepted window
17094        // set, the codec's parse/render unit set) that breaks the
17095        // alignment surfaces here. The previous-state shape (typed
17096        // slot accepts arbitrary `Duration`, codec only round-trips
17097        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
17098        // window — the validate gate now forecloses that.
17099        for secs in [1u64, 60, 3600] {
17100            let mut s = three_member_spec();
17101            s.politicas.rate_limit = Some(RateLimit {
17102                rate: 250,
17103                window: Duration::from_secs(secs),
17104            });
17105            s.validate().unwrap();
17106            let json = serde_json::to_string(&s.politicas).unwrap();
17107            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17108            assert_eq!(
17109                back.rate_limit, s.politicas.rate_limit,
17110                "every validated :rate-limit must round-trip losslessly through the codec"
17111            );
17112        }
17113    }
17114
17115    #[test]
17116    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
17117        // The hour-window canonical form (`"<n>/h"`) was missing from
17118        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
17119        // pair. Now that the validate gate pins 3600s as part of the
17120        // canonical set, pin its serialize-side render shape too so
17121        // the third leg of the s/m/h tripod is explicitly tested.
17122        let policy = MeshPolicy {
17123            rate_limit: Some(RateLimit {
17124                rate: 10000,
17125                window: Duration::from_secs(3600),
17126            }),
17127            ..Default::default()
17128        };
17129        let json = serde_json::to_string(&policy).unwrap();
17130        assert!(
17131            json.contains("\"10000/h\""),
17132            "hour-window canonical form must render with `h` suffix (got: {json})"
17133        );
17134        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17135        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
17136    }
17137
17138    #[test]
17139    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
17140        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
17141        // typed accessor's accepted-window set against the codec's
17142        // accepted set explicitly. A future addition to the codec
17143        // (e.g. accepting `:day`/`:week` as authoring units) must be
17144        // accompanied by a parallel addition here, and a regression
17145        // that drops one of the three canonical units from either
17146        // side surfaces as a test failure. The accessor is the
17147        // single source of truth for the canonical-window set —
17148        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
17149        // gate and [`rate_limit_codec::render`]'s canonical arm both
17150        // read through it — this test enshrines that its
17151        // `Duration → Option<RateLimitUnit>` projection matches the
17152        // codec's parse / render arms' accepted-window set exactly.
17153        //
17154        // Predecessor: this pin previously read the module-private
17155        // free helper `is_canonical_rate_limit_window` — a delegate
17156        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
17157        // — but the helper had no production consumers left after the
17158        // validate-gate migration onto [`RateLimit::canonical_unit`]
17159        // and was deleted; the closed-set arm-window bijection now
17160        // lives on exactly one typed dispatch on the substrate
17161        // primitive.
17162        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
17163            RateLimit { rate: 1, window }.canonical_unit()
17164        };
17165        assert!(canonical_unit(Duration::from_secs(1)).is_some());
17166        assert!(canonical_unit(Duration::from_secs(60)).is_some());
17167        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
17168        // Non-canonical windows the accessor rejects.
17169        assert!(canonical_unit(Duration::ZERO).is_none());
17170        assert!(canonical_unit(Duration::from_secs(2)).is_none());
17171        assert!(canonical_unit(Duration::from_secs(30)).is_none());
17172        assert!(canonical_unit(Duration::from_secs(120)).is_none());
17173        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
17174        // Sub-second windows: even `Duration::from_millis(1000)` is
17175        // exactly 1s and accepted; `Duration::from_millis(500)` is
17176        // sub-second and rejected.
17177        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
17178        assert!(canonical_unit(Duration::from_millis(500)).is_none());
17179        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
17180    }
17181
17182    #[test]
17183    fn rate_limit_unit_table_projections_are_mutual_inverses() {
17184        // Bidirection pin against the closed-set typed enum
17185        // [`RateLimitUnit`] arm-table (the canonical
17186        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
17187        // of the rate-limit unit surface reads from). The two
17188        // projection directions [`RateLimitUnit::from_suffix`] /
17189        // [`RateLimitUnit::window`] (str → Duration, exposed as one
17190        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
17191        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
17192        // (Duration → str, exposed as one typed dispatch through
17193        // [`RateLimit::canonical_unit`] composed with
17194        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
17195        // codec's parse arm ([`rate_limit_codec::parse`] via
17196        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
17197        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
17198        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
17199        // via [`RateLimit::canonical_unit`]) all key off. A future
17200        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
17201        // sub-second window) is one variant + one arm per method on the
17202        // closed-set enum; the compiler-enforced exhaustiveness on
17203        // every consumer's `match self` arms picks it up by
17204        // construction. This pin enshrines that both projection
17205        // directions agree on every canonical arm row and neither
17206        // leaks a spurious entry the other doesn't recognize.
17207        //
17208        // Predecessor: this test previously read the two vestigial
17209        // module-private free helpers `rate_limit_window_unit` and
17210        // `rate_limit_window_from_unit` on the `Duration → &str` and
17211        // `&str → Duration` axes; the former was deleted after its
17212        // sole production consumer ([`rate_limit_codec::render`])
17213        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
17214        // the latter is folded here into the substrate primitive
17215        // [`RateLimitUnit::window_from_suffix`] so both projection
17216        // directions live on the closed-set enum's arm-table.
17217        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
17218            let window = super::RateLimitUnit::window_from_suffix(unit)
17219                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
17220            assert_eq!(
17221                window,
17222                Duration::from_secs(secs),
17223                "unit {unit:?} must resolve to {secs}s"
17224            );
17225            let projected_suffix = RateLimit { rate: 1, window }
17226                .canonical_unit()
17227                .map(super::RateLimitUnit::as_suffix);
17228            assert_eq!(
17229                projected_suffix,
17230                Some(unit),
17231                "Duration({secs}s) must render as {unit:?} \
17232                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
17233            );
17234        }
17235        // Non-table units yield None on the `unit → Duration`
17236        // projection — a future `"d"` addition to the table would
17237        // flip this arm; today it pins the current three-row table's
17238        // rejection semantics.
17239        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
17240        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
17241        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
17242        // Non-table Durations yield None on the `Duration → unit`
17243        // projection — pins that the two projections agree on the
17244        // "not in the table" semantic too, so a drift where the
17245        // parse-side accepts a value the render-side can't emit is
17246        // a build error at the two-arm pair, not a silent codec
17247        // round-trip break.
17248        let projected_suffix = |window: Duration| -> Option<&'static str> {
17249            RateLimit { rate: 1, window }
17250                .canonical_unit()
17251                .map(super::RateLimitUnit::as_suffix)
17252        };
17253        assert!(projected_suffix(Duration::from_secs(2)).is_none());
17254        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
17255        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
17256    }
17257
17258    #[test]
17259    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
17260        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
17261        // substrate-primitive `&str → Duration` associated method the
17262        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
17263        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
17264        // to the same [`Duration`] the two-step composition
17265        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
17266        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
17267        // `"MIN"`) must project to [`None`] on both paths. A future
17268        // implementation of `window_from_suffix` that took a shortcut
17269        // through a per-suffix `match` table (bypassing the arm-table's
17270        // `Self::from_suffix` scan and the arm-table's `Self::window`
17271        // dispatch) would silently split the accept-set — the parse
17272        // arm would accept a suffix the enum's arm-table doesn't know,
17273        // or reject a suffix the enum's arm-table does; this pin
17274        // surfaces that drift at caixa-core build time rather than at a
17275        // downstream serde round-trip audit on a live `MeshPolicy`.
17276        //
17277        // Same byte-parity discipline the sibling
17278        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
17279        // pin carries on the peer `Duration → RateLimitUnit` axis via
17280        // [`RateLimit::canonical_unit`], and the peer
17281        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17282        // carries on the bidirectional arm-table axis — extended here
17283        // onto the fifth (and last unlifted) projection axis on the
17284        // closed-set enum's arm-table.
17285        let composition = |suffix: &str| -> Option<Duration> {
17286            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
17287        };
17288        for suffix in ["s", "m", "h"] {
17289            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17290            let via_composition = composition(suffix);
17291            assert_eq!(
17292                via_method, via_composition,
17293                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17294                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
17295                 method must delegate to the arm-table's two typed dispatches, \
17296                 not shortcut through a per-suffix match table"
17297            );
17298            assert!(
17299                via_method.is_some(),
17300                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
17301                 RateLimitUnit::window_from_suffix"
17302            );
17303        }
17304        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
17305            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17306            let via_composition = composition(suffix);
17307            assert_eq!(
17308                via_method, via_composition,
17309                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17310                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
17311                 axis too"
17312            );
17313            assert!(
17314                via_method.is_none(),
17315                "non-arm suffix {suffix:?} must project to None via \
17316                 RateLimitUnit::window_from_suffix — a future extension that \
17317                 accepted this suffix without a corresponding arm on the enum \
17318                 would split the codec's parse-accepted set from the enum's \
17319                 arm-table"
17320            );
17321        }
17322        // And the codec's parse arm now reads through this method: a
17323        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
17324        // the same `Duration` the method returns for its unit, closing
17325        // the two-consumer drift surface (the codec's parse arm and the
17326        // enum's arm-table) with one typed dispatch on the substrate
17327        // primitive.
17328        for suffix in ["s", "m", "h"] {
17329            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
17330            let mp: MeshPolicy = serde_json::from_str(&wire)
17331                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
17332            let parsed = mp.rate_limit().expect("rate_limit payload present");
17333            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
17334                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
17335            assert_eq!(
17336                parsed.window(),
17337                via_method,
17338                "codec parse arm on {wire:?} must resolve the window through \
17339                 RateLimitUnit::window_from_suffix, not a divergent path"
17340            );
17341        }
17342    }
17343
17344    #[test]
17345    fn rate_limit_unit_all_enumerates_every_arm_once() {
17346        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
17347        // enumerate every arm of the closed-set enum exactly once, in
17348        // the canonical shortest-to-longest window order (Second before
17349        // Minute before Hour) — the same order the sibling
17350        // [`crate::supervisor::RestartStrategy`] /
17351        // [`crate::supervisor::RestartPolicy`] /
17352        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
17353        // typed enums carry (the arm declared first is the arm listed
17354        // first). A future variant addition that extends the enum
17355        // without appending to [`RateLimitUnit::ALL`] leaves the
17356        // exhaustive iteration surface silently short one arm — the
17357        // codec's parse arm would then reject the new suffix even
17358        // though the enum knows it. This pin closes the drift.
17359        assert_eq!(
17360            super::RateLimitUnit::ALL,
17361            &[
17362                super::RateLimitUnit::Second,
17363                super::RateLimitUnit::Minute,
17364                super::RateLimitUnit::Hour,
17365            ],
17366            "RateLimitUnit::ALL must enumerate every arm exactly once, \
17367             in canonical shortest-to-longest window order"
17368        );
17369    }
17370
17371    #[test]
17372    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
17373        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
17374        // every arm's [`RateLimitUnit::as_suffix`] output must parse
17375        // back through [`RateLimitUnit::from_suffix`] to the same
17376        // variant. A future arm addition that lands `as_suffix` but
17377        // forgets `from_suffix` (`from_suffix` iterates
17378        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
17379        // is the load-bearing carrier of the round-trip; the sibling
17380        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
17381        // the `ALL` half) trips here at caixa-core build time rather
17382        // than surfacing as a codec round-trip miss (a `render` emit
17383        // that lands a suffix the paired `parse` cannot decode).
17384        for unit in super::RateLimitUnit::ALL {
17385            let suffix = unit.as_suffix();
17386            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
17387                panic!(
17388                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
17389                     RateLimitUnit::as_suffix output — got None for {unit:?}"
17390                )
17391            });
17392            assert_eq!(
17393                parsed, *unit,
17394                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
17395                 must return RateLimitUnit::{unit:?}"
17396            );
17397        }
17398    }
17399
17400    #[test]
17401    fn rate_limit_unit_from_window_and_window_round_trip() {
17402        // Total round-trip pin on the `(from_window, window)` pair:
17403        // every arm's [`RateLimitUnit::window`] output must parse back
17404        // through [`RateLimitUnit::from_window`] to the same variant.
17405        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
17406        // on the peer `Duration` axis — the two round-trip pins
17407        // together enshrine that both projections of the typed
17408        // canonical-unit bijection are total on the arm-set.
17409        for unit in super::RateLimitUnit::ALL {
17410            let window = unit.window();
17411            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
17412                panic!(
17413                    "RateLimitUnit::from_window({window:?}) must accept every \
17414                     RateLimitUnit::window output — got None for {unit:?}"
17415                )
17416            });
17417            assert_eq!(
17418                parsed, *unit,
17419                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17420                 must return RateLimitUnit::{unit:?}"
17421            );
17422        }
17423    }
17424
17425    #[test]
17426    fn rate_limit_unit_from_window_accessor_is_const_fn() {
17427        // Fail-before-pass-after pin: witnesses the
17428        // [`RateLimitUnit::from_window`] `const`-eval posture via a
17429        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
17430        // -> Option<RateLimitUnit>` whose body calls
17431        // `RateLimitUnit::from_window(window)`, well-formed only when
17432        // the callee is itself `const fn` (any future downgrade to
17433        // non-`const` fails at caixa-core build time with E0015 `cannot
17434        // call non-const function`, strictly stronger than a runtime
17435        // `assert!`, side-stepping the destructor-in-const restriction
17436        // that blocks direct `const _: Option<RateLimitUnit> =
17437        // RateLimitUnit::from_window(...)` items on `Duration`'s
17438        // carrier). The runtime body sweeps every closed-set
17439        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
17440        // rejection sample (`Duration::from_millis(500)` sub-second
17441        // residue) and asserts the wrapped and direct dispatches agree
17442        // — a violation means the wrapper stopped compiling under a
17443        // future `const`-posture downgrade, or the reverse resolver's
17444        // arm-set silently split from the peer `Self::window` emitter's
17445        // arm-set. Peer of the sibling
17446        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
17447        // (152c868) /
17448        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
17449        // (152c868) /
17450        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
17451        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
17452        // `const`-eval-surface pins on the peer M2 / M3 substrate-
17453        // primitive `Copy`-return accessor axes, extended onto the
17454        // reverse `Duration → RateLimitUnit` projection axis on the
17455        // M3 mesh-slot rate-limit closed-set typed enum.
17456        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
17457            super::RateLimitUnit::from_window(window)
17458        }
17459        for unit in super::RateLimitUnit::ALL {
17460            let window = unit.window();
17461            let via_wrapper = from_window_via_const_fn(window);
17462            let direct = super::RateLimitUnit::from_window(window);
17463            assert_eq!(
17464                via_wrapper, direct,
17465                "RateLimitUnit::from_window({window:?}) via const fn \
17466                 wrapper must agree with direct dispatch for {unit:?}"
17467            );
17468            assert_eq!(
17469                via_wrapper,
17470                Some(*unit),
17471                "RateLimitUnit::from_window({window:?}) via const fn \
17472                 wrapper must return Some({unit:?}) for the peer \
17473                 window() output"
17474            );
17475        }
17476        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
17477        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
17478    }
17479
17480    #[test]
17481    fn rate_limit_unit_from_window_composes_through_window_accessor() {
17482        // Composition-witness pin on the routing-through-peer discipline:
17483        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
17484        // through the peer `pub const fn` [`RateLimitUnit::window`]
17485        // canonical-`Duration` projection rather than a hand-authored
17486        // per-arm second-magnitude literal — a future arm-magnitude edit
17487        // on the sibling `window()` accessor (a `Second → 2s` typo, a
17488        // `Hour → 3599s` off-by-one) must therefore reach this reverse
17489        // resolver by construction. A pin that hard-coded the three
17490        // second-magnitudes here would silently split from the peer
17491        // emitter on any such edit; instead, this pin asserts the
17492        // composition invariant `from_window(u.window()) == Some(u)`
17493        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
17494        // arm — a violation means either the peer `Self::window`
17495        // accessor drifted (breaking every downstream consumer that
17496        // reads through it), or the reverse resolver stopped routing
17497        // through the peer (introducing a hand-authored literal that
17498        // silently disagrees with the emitter). Either failure is a
17499        // caixa-core-build-time surface, not a downstream renderer
17500        // round-trip regression.
17501        //
17502        // Peer of the sibling
17503        // [`crate::render::assert_str_reexport_identity`] discipline on
17504        // the substrate-primitive `&'static str` re-export axis and the
17505        // [`rate_limit_unit_from_window_and_window_round_trip`]
17506        // round-trip pin on the peer projection direction; extends the
17507        // one-canonical-dispatch-per-projection discipline onto the
17508        // reverse-resolver's per-arm probe axis.
17509        for unit in super::RateLimitUnit::ALL {
17510            let window_via_peer = unit.window();
17511            let resolved = super::RateLimitUnit::from_window(window_via_peer);
17512            assert_eq!(
17513                resolved,
17514                Some(*unit),
17515                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17516                 must return Some({unit:?}) — the reverse resolver's per-arm \
17517                 probes must route through the peer `Self::window` accessor \
17518                 so any future arm-magnitude edit reaches both projection \
17519                 directions by construction"
17520            );
17521        }
17522    }
17523
17524    #[test]
17525    fn rate_limit_canonical_unit_accessor_is_const_fn() {
17526        // Fail-before-pass-after pin: witnesses the
17527        // [`RateLimit::canonical_unit`] `const`-eval posture via a
17528        // `const fn` wrapper
17529        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
17530        // whose body calls `rl.canonical_unit()`, well-formed only when
17531        // the callee is itself `const fn` (any future downgrade to
17532        // non-`const` fails at caixa-core build time with E0015 `cannot
17533        // call non-const method`). The runtime body sweeps every
17534        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
17535        // constructs a typed [`RateLimit`] with the peer `Self::window`
17536        // canonical `Duration`, then asserts both the wrapper and the
17537        // direct dispatch agree and both return `Some(unit)`. Composes
17538        // with the sibling
17539        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
17540        // typed [`RateLimit`] projection layer's `const`-posture is
17541        // load-bearing on the reverse resolver's `const`-posture, and
17542        // both must migrate together (a downgrade of either surface
17543        // splits the paired `const`-eval-surface pass on the M3
17544        // mesh-slot rate-limit `Duration ↔ Self` bijection).
17545        const fn canonical_unit_via_const_fn(
17546            rl: &super::RateLimit,
17547        ) -> Option<super::RateLimitUnit> {
17548            rl.canonical_unit()
17549        }
17550        for unit in super::RateLimitUnit::ALL {
17551            let rl = super::RateLimit {
17552                rate: 1,
17553                window: unit.window(),
17554            };
17555            let via_wrapper = canonical_unit_via_const_fn(&rl);
17556            let direct = rl.canonical_unit();
17557            assert_eq!(
17558                via_wrapper, direct,
17559                "RateLimit::canonical_unit() via const fn wrapper must \
17560                 agree with direct dispatch for {unit:?}"
17561            );
17562            assert_eq!(
17563                via_wrapper,
17564                Some(*unit),
17565                "RateLimit::canonical_unit() via const fn wrapper must \
17566                 return Some({unit:?}) for a RateLimit whose window is \
17567                 the peer RateLimitUnit::{unit:?}.window() output"
17568            );
17569        }
17570    }
17571
17572    #[test]
17573    fn rate_limit_unit_projections_are_pairwise_distinct() {
17574        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
17575        // [`RateLimitUnit::window`] outputs must be pairwise distinct
17576        // across every arm — an accidental copy-paste flip that
17577        // reroutes one arm's suffix or window to also match another
17578        // silently collapses two arms onto one, so
17579        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
17580        // (both using `find` on `Self::ALL`) would return whichever
17581        // arm the linear scan lands on first — a match-arm-ordering-
17582        // dependent outcome the closed-set typed-enum shape is meant
17583        // to rule out structurally. Peer of the sibling
17584        // `caixa_kind_wire_consts_are_pairwise_distinct` /
17585        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
17586        // other closed-set typed-enum discriminator axes.
17587        let all = super::RateLimitUnit::ALL;
17588        for (i, a) in all.iter().enumerate() {
17589            for (j, b) in all.iter().enumerate() {
17590                if i != j {
17591                    assert_ne!(
17592                        a.as_suffix(),
17593                        b.as_suffix(),
17594                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
17595                         must be distinct — a collision silently collapses two \
17596                         arms onto one under from_suffix's linear scan"
17597                    );
17598                    assert_ne!(
17599                        a.window(),
17600                        b.window(),
17601                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
17602                         must be distinct — a collision silently collapses two \
17603                         arms onto one under from_window's linear scan"
17604                    );
17605                }
17606            }
17607        }
17608    }
17609
17610    #[test]
17611    fn rate_limit_unit_display_routes_through_as_suffix() {
17612        // Route pin: [`std::fmt::Display`] must byte-equal
17613        // [`RateLimitUnit::as_suffix`] on every arm — the single
17614        // source of truth for the canonical suffix. A future
17615        // reimplementation that hand-rolls the arms instead of
17616        // delegating to [`RateLimitUnit::as_suffix`] would silently
17617        // desynchronize `format!("{u}")` from the codec's parse arm
17618        // (which uses `as_suffix` to compare suffixes). Peer of the
17619        // sibling `caixa_kind_display_routes_through_as_str_helper` /
17620        // `placement_strategy_display_routes_through_as_str_helper`
17621        // pins on the peer closed-set typed-enum Display axes.
17622        for unit in super::RateLimitUnit::ALL {
17623            assert_eq!(
17624                unit.to_string(),
17625                unit.as_suffix(),
17626                "RateLimitUnit::{unit:?} Display must route through \
17627                 as_suffix (single source of truth: the canonical suffix \
17628                 the codec parses and renders)"
17629            );
17630        }
17631    }
17632
17633    #[test]
17634    fn rate_limit_unit_from_window_rejects_non_canonical() {
17635        // Rejection pin on the parser's accept-set: any Duration
17636        // outside the three-arm [`RateLimitUnit::window`] output set
17637        // (sub-second residue, or a second-magnitude outside `{1, 60,
17638        // 3600}`) must return `None`. A future accidental widening of
17639        // the accept-set (rounding down sub-second residue to the
17640        // nearest arm, admitting `Duration::from_secs(30)` as a
17641        // half-minute unit) would silently drift the parser's accept-
17642        // set from the emitter's — a validated slot with a
17643        // non-canonical window would then round-trip through the
17644        // codec to a canonical form the author never wrote.
17645        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
17646        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
17647        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
17648        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
17649        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
17650        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
17651        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
17652    }
17653
17654    #[test]
17655    fn rate_limit_unit_from_suffix_rejects_unknown() {
17656        // Rejection pin on the suffix parser's accept-set: any string
17657        // outside the three-arm [`RateLimitUnit::as_suffix`] output
17658        // set must return `None`. Peer of the sibling
17659        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
17660        // the [`crate::CaixaKind`] `from_wire` accept-set.
17661        for bad in [
17662            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
17663            " s",
17664        ] {
17665            assert!(
17666                super::RateLimitUnit::from_suffix(bad).is_none(),
17667                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
17668                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
17669                 outputs"
17670            );
17671        }
17672    }
17673
17674    #[test]
17675    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
17676        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
17677        // every canonical `:window` magnitude the validate gate
17678        // accepts must map to the paired [`RateLimitUnit`] arm through
17679        // this accessor. A future validate-gate rebrand that widened
17680        // the accepted-window set without extending [`RateLimitUnit`]
17681        // would silently split the accessor's `Some`-return set from
17682        // the validate gate's accept-set — a slot that satisfies
17683        // validate would land at the accessor with `None`, so a
17684        // consumer past validate that pattern-matches on the returned
17685        // `Some` would silently miss the newly-accepted magnitude.
17686        for (window_secs, expected) in [
17687            (1u64, super::RateLimitUnit::Second),
17688            (60, super::RateLimitUnit::Minute),
17689            (3600, super::RateLimitUnit::Hour),
17690        ] {
17691            let rl = RateLimit {
17692                rate: 100,
17693                window: Duration::from_secs(window_secs),
17694            };
17695            assert_eq!(
17696                rl.canonical_unit(),
17697                Some(expected),
17698                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
17699                 must return Some({expected:?})"
17700            );
17701        }
17702        // Non-canonical windows the validate gate rejects also return
17703        // None here — the accessor is the typed-enum projection of
17704        // the sibling `is_canonical_rate_limit_window` predicate.
17705        let bad = RateLimit {
17706            rate: 100,
17707            window: Duration::from_secs(30),
17708        };
17709        assert!(
17710            bad.canonical_unit().is_none(),
17711            "RateLimit with a non-canonical window must return None from \
17712             canonical_unit — the validate gate rejects the same set"
17713        );
17714    }
17715
17716    #[test]
17717    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
17718        // Fail-before-pass-after byte-parity pin: for every canonical
17719        // window the [`rate_limit_codec::render`] arm's emitted string
17720        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
17721        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
17722        // the vestigial free helper [`rate_limit_window_unit`] (a
17723        // `find_map`-walked `Duration → &'static str` delegate) onto the
17724        // substrate primitive [`RateLimit::canonical_unit`] typed method
17725        // (a closed-set `match self.window` arm on
17726        // [`RateLimitUnit::from_window`], projected through
17727        // [`RateLimitUnit::as_suffix`] via the enum's
17728        // [`std::fmt::Display`] impl). A future re-routing of the render
17729        // arm through a differently-computed unit projection would break
17730        // this pin at build time rather than as a silent per-consumer
17731        // codec round-trip drift far from the substrate primitive edit.
17732        //
17733        // Sibling to the peer
17734        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17735        // on the free-helper axis: that pin locks the two projections
17736        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
17737        // on the closed-set arm table; this pin locks the codec's render
17738        // arm reads through the typed accessor rather than the free
17739        // helper. Two production consumers of the canonical-unit axis
17740        // now key off one typed dispatch on the substrate primitive.
17741        for (window_secs, unit) in [
17742            (1u64, super::RateLimitUnit::Second),
17743            (60, super::RateLimitUnit::Minute),
17744            (3600, super::RateLimitUnit::Hour),
17745        ] {
17746            let rl = RateLimit {
17747                rate: 42,
17748                window: Duration::from_secs(window_secs),
17749            };
17750            let policy = MeshPolicy {
17751                rate_limit: Some(rl),
17752                ..Default::default()
17753            };
17754            let json = serde_json::to_string(&policy).unwrap();
17755            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
17756            assert!(
17757                json.contains(&expected),
17758                "rate_limit_codec::render must emit {expected} (via \
17759                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
17760                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
17761            );
17762            // And the accessor route resolves to the same typed unit
17763            // the render arm's Display formatting is asked to produce —
17764            // so a future edit that split the two paths (one through
17765            // the accessor, one through a re-introduced free helper)
17766            // trips this pin.
17767            assert_eq!(
17768                rl.canonical_unit(),
17769                Some(unit),
17770                "RateLimit::canonical_unit must return Some({unit:?}) for a \
17771                 {window_secs}s window; the codec render arm reads the same \
17772                 typed unit through this accessor"
17773            );
17774        }
17775    }
17776
17777    #[test]
17778    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
17779        // Fail-before-pass-after byte-parity pin on the validate gate's
17780        // canonical-window shape probe: every non-canonical `:window`
17781        // the free-helper predicate [`is_canonical_rate_limit_window`]
17782        // rejects is also rejected by the substrate primitive
17783        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
17784        // gate now reads through, and vice versa on the accepted set
17785        // (the three canonical windows). Locks the migration from the
17786        // free helper onto the substrate primitive: a future re-routing
17787        // of one of the two paths through a differently-computed unit
17788        // projection would silently split the codec's accepted set from
17789        // the validate gate's accepted set — a two-consumer drift the
17790        // codec-round-trip pin
17791        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
17792        // above closes on the render arm and this pin closes on the
17793        // validate arm.
17794        for canonical_window_secs in [1u64, 60, 3600] {
17795            let mut s = three_member_spec();
17796            let rl = RateLimit {
17797                rate: 100,
17798                window: Duration::from_secs(canonical_window_secs),
17799            };
17800            s.politicas.rate_limit = Some(rl);
17801            assert!(
17802                s.validate().is_ok(),
17803                "canonical {canonical_window_secs}s window must pass \
17804                 validate_politicas — the validate gate now reads \
17805                 RateLimit::canonical_unit().is_none() and the accessor \
17806                 returns Some on every canonical arm"
17807            );
17808            assert!(
17809                rl.canonical_unit().is_some(),
17810                "canonical {canonical_window_secs}s window must resolve to \
17811                 Some on RateLimit::canonical_unit — the validate gate reads \
17812                 this accessor directly"
17813            );
17814        }
17815        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
17816            let mut s = three_member_spec();
17817            let rl = RateLimit {
17818                rate: 100,
17819                window: Duration::from_secs(non_canonical_window_secs),
17820            };
17821            s.politicas.rate_limit = Some(rl);
17822            assert_eq!(
17823                s.validate().unwrap_err(),
17824                AplicacaoError::PolicyRateLimitWindowNotCanonical {
17825                    window: rl.window(),
17826                },
17827                "non-canonical {non_canonical_window_secs}s window must be \
17828                 rejected by validate_politicas — the validate gate now \
17829                 keys off RateLimit::canonical_unit().is_none()"
17830            );
17831            assert!(
17832                rl.canonical_unit().is_none(),
17833                "non-canonical {non_canonical_window_secs}s window must \
17834                 resolve to None on RateLimit::canonical_unit — the two \
17835                 paths (the free helper the validate gate previously read \
17836                 and the substrate primitive the validate gate now reads) \
17837                 must agree on the same rejected set"
17838            );
17839        }
17840        // And the substrate-primitive [`RateLimit::canonical_unit`]
17841        // accessor's accepted-window set matches the codec's parse arm's
17842        // accepted-suffix set on every canonical / non-canonical shape,
17843        // so a future silent drift between the codec's accepted set and
17844        // the validate gate's accepted set is a build error at test time
17845        // (both consumers key off the same closed-set enum's `match self`
17846        // arms). The predecessor free helper `is_canonical_rate_limit_window`
17847        // — a delegate that composed [`RateLimitUnit::from_window`] with
17848        // `.is_some()` — was deleted after this migration; the
17849        // canonical-window set now lives on exactly one typed dispatch
17850        // on the substrate primitive.
17851        for (secs, expected) in [
17852            (1u64, true),
17853            (60, true),
17854            (3600, true),
17855            (2, false),
17856            (30, false),
17857            (86_400, false),
17858        ] {
17859            let window = Duration::from_secs(secs);
17860            let rl = RateLimit { rate: 1, window };
17861            assert_eq!(
17862                rl.canonical_unit().is_some(),
17863                expected,
17864                "RateLimit::canonical_unit().is_some() must agree with the \
17865                 codec-accepted canonical-window set on {secs}s"
17866            );
17867            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
17868                1 => "s",
17869                60 => "m",
17870                3600 => "h",
17871                _ => return,
17872            })
17873            .is_some_and(|d| d == window);
17874            if expected {
17875                assert!(
17876                    suffix_from_axis,
17877                    "the codec's `&str → Duration` axis \
17878                     ({secs}s) must round-trip to the same Duration the \
17879                     substrate primitive's accessor returns Some on"
17880                );
17881            }
17882        }
17883    }
17884
17885    #[test]
17886    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
17887        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
17888        // derive: for each of the three variants, exactly one of the
17889        // generated `is_second` / `is_minute` / `is_hour` predicates
17890        // returns `true` and the other two return `false`. Peer of
17891        // the sibling
17892        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
17893        // sibling `IsVariant`-derived closed-set typed-enum pins.
17894        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
17895            (super::RateLimitUnit::Second, [true, false, false]),
17896            (super::RateLimitUnit::Minute, [false, true, false]),
17897            (super::RateLimitUnit::Hour, [false, false, true]),
17898        ];
17899        for (variant, expected) in rows {
17900            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
17901            assert_eq!(
17902                observed, expected,
17903                "RateLimitUnit::{variant:?} is_* predicates must partition \
17904                 the arm set (second, minute, hour); got {observed:?}"
17905            );
17906        }
17907    }
17908
17909    #[test]
17910    fn rejects_policy_timeout_sub_millisecond() {
17911        // A purely sub-millisecond `Duration` (`from_micros(500)` =
17912        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
17913        // arm passes — but `as_millis() == 0`, so the shared codec's
17914        // `render` arm returns the literal `"0s"`, which the
17915        // codec's `parse` arm then deserializes as `Duration::ZERO`
17916        // and the `PolicyTimeoutZero` zero-floor gate would reject
17917        // on re-validate. Pin the rejection at the typed slot's
17918        // canonical-floor gate so the round-trip break surfaces at
17919        // validate time, naming the offending `Duration`, rather
17920        // than at the next serialize → deserialize round-trip far
17921        // from the source `caixa.lisp`.
17922        let mut s = three_member_spec();
17923        let timeout = Duration::from_micros(500);
17924        s.politicas.timeout = Some(timeout);
17925        assert_eq!(
17926            s.validate().unwrap_err(),
17927            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
17928        );
17929    }
17930
17931    #[test]
17932    fn rejects_policy_timeout_non_integer_millisecond() {
17933        // A `Duration` with non-integer-millisecond residue
17934        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
17935        // through the shared codec's `render` arm as `"1ms"` (the
17936        // `as_millis()` floor truncates), which the codec's `parse`
17937        // arm then deserializes as `Duration::from_millis(1)` =
17938        // 1_000_000 ns — silently *different* from the original.
17939        // Pin the rejection so this round-trip break surfaces at
17940        // validate time, where the offending `Duration` is named,
17941        // rather than as a silent value-laundered round-trip on the
17942        // next codec round-trip.
17943        let mut s = three_member_spec();
17944        let timeout = Duration::from_micros(1500);
17945        s.politicas.timeout = Some(timeout);
17946        assert_eq!(
17947            s.validate().unwrap_err(),
17948            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
17949        );
17950    }
17951
17952    #[test]
17953    fn accepts_policy_timeout_integer_millisecond_forms() {
17954        // The codec's accepted set — integer multiples of 1ms — is
17955        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
17956        // `1h` all pass the canonical gate. Pin the canonical-forms
17957        // sweep so a future tightening of the codec's grammar (e.g.
17958        // dropping `:ms`) surfaces here as a test failure rather
17959        // than a silent contract narrowing on the typed slot.
17960        for timeout in [
17961            Duration::from_millis(1),
17962            Duration::from_millis(500),
17963            Duration::from_millis(1500),
17964            Duration::from_secs(30),
17965            Duration::from_secs(120),
17966            Duration::from_secs(3600),
17967        ] {
17968            let mut s = three_member_spec();
17969            s.politicas.timeout = Some(timeout);
17970            s.validate()
17971                .expect("integer-millisecond :timeout must validate");
17972        }
17973    }
17974
17975    #[test]
17976    fn policy_timeout_zero_takes_precedence_over_canonical() {
17977        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
17978        // pass the canonical-millisecond gate; the more self-locating
17979        // `PolicyTimeoutZero` arm (which names the omit-axis
17980        // remediation directly) must fire first. Pin the ordering so
17981        // a future refactor that reorders the arms surfaces here as a
17982        // test failure rather than a silent diagnostic regression.
17983        let mut s = three_member_spec();
17984        s.politicas.timeout = Some(Duration::ZERO);
17985        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
17986    }
17987
17988    #[test]
17989    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
17990        // The diagnostic envelope carries the offending `Duration`
17991        // verbatim so the author can grep their `caixa.lisp` for
17992        // `:timeout "<value>"` and fix it in one edit. Same
17993        // diagnostic shape every other typed-slot canonical-form
17994        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
17995        // peer `:rate-limit :window` axis.
17996        let mut s = three_member_spec();
17997        let timeout = Duration::from_nanos(1_000_001);
17998        s.politicas.timeout = Some(timeout);
17999        match s.validate().unwrap_err() {
18000            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
18001                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
18002            }
18003            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
18004        }
18005    }
18006
18007    #[test]
18008    fn rejects_policy_timeout_above_cap() {
18009        // The fail-before-pass-after pin: 3601s = 1h + 1s is
18010        // structurally one canonical-tick past the
18011        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
18012        // integer-millisecond magnitude the canonical-form arm above
18013        // accepts cleanly, that the codec round-trips losslessly as
18014        // `"3601s"`, and that silently passed validate on every
18015        // pre-gate codebase because the typed slot's only checks were
18016        // the zero-floor and canonical-form arms. The mesh-level
18017        // deadline degenerates only at the runtime substrate (Envoy
18018        // / Cilium L7 timeout overlay) far from the source
18019        // `caixa.lisp` with no field naming the offending policy.
18020        let mut s = three_member_spec();
18021        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
18022        s.politicas.timeout = Some(timeout);
18023        assert_eq!(
18024            s.validate().unwrap_err(),
18025            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18026        );
18027    }
18028
18029    #[test]
18030    fn rejects_policy_timeout_one_millisecond_above_cap() {
18031        // Boundary case: exactly 1ms past the cap (the granularity
18032        // the canonical-form gate enforces). Catches a future
18033        // "strictly less than" half-measure and pins the diagnostic
18034        // to name the offending `Duration` verbatim. Peer of
18035        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
18036        // boundary pin on the sibling `:limits :memory` top edge.
18037        let mut s = three_member_spec();
18038        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
18039        s.politicas.timeout = Some(timeout);
18040        assert_eq!(
18041            s.validate().unwrap_err(),
18042            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18043        );
18044    }
18045
18046    #[test]
18047    fn rejects_policy_timeout_far_above_cap() {
18048        // The "obvious authoring footgun" case: a `(:timeout "24h")`
18049        // or `(:timeout "86400s")` — values the canonical-form arm
18050        // accepts as integer-millisecond magnitudes, the codec
18051        // round-trips losslessly through serde, but the mesh-level
18052        // policy cannot honor (a 24-hour synchronous-`:contratos`
18053        // deadline is operationally indistinguishable from
18054        // omit-the-axis). Until this gate landed validate accepted
18055        // it. Pin both common above-cap values (24h, 7d) so a future
18056        // relaxation that drops the upper bound surfaces here.
18057        for timeout in [
18058            Duration::from_secs(86_400),    // 24h
18059            Duration::from_secs(604_800),   // 7d
18060            Duration::from_secs(1_000_000), // ~11.5 days
18061        ] {
18062            let mut s = three_member_spec();
18063            s.politicas.timeout = Some(timeout);
18064            assert_eq!(
18065                s.validate().unwrap_err(),
18066                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18067            );
18068        }
18069    }
18070
18071    #[test]
18072    fn accepts_policy_timeout_at_cap() {
18073        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
18074        // must validate. The cap is inclusive on the top edge,
18075        // matching the [`POLICY_RETRIES_MAX`] /
18076        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
18077        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18078        // sibling capped axes. Pin the boundary explicitly so a
18079        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
18080        // instead of `>`) surfaces here as a test failure rather
18081        // than a silent contract narrowing.
18082        let mut s = three_member_spec();
18083        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
18084        s.validate()
18085            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
18086    }
18087
18088    #[test]
18089    fn accepts_policy_timeout_typical_values() {
18090        // The documented production-playbook band positive-control
18091        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
18092        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
18093        // plus a sweep through the long-running-workflow band
18094        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
18095        // validated set explicitly so a future tightening of the
18096        // ceiling surfaces here as a deliberate test edit, not a
18097        // silent contract narrowing.
18098        for timeout in [
18099            Duration::from_millis(1),
18100            Duration::from_millis(500),
18101            Duration::from_secs(1),
18102            Duration::from_secs(10),
18103            Duration::from_secs(15), // Envoy default
18104            Duration::from_secs(30),
18105            Duration::from_secs(60), // AWS App Mesh typical
18106            Duration::from_secs(300),
18107            Duration::from_secs(900),
18108            Duration::from_secs(1800),
18109            Duration::from_secs(3600), // exactly 1h, the cap
18110        ] {
18111            let mut s = three_member_spec();
18112            s.politicas.timeout = Some(timeout);
18113            s.validate()
18114                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
18115        }
18116    }
18117
18118    #[test]
18119    fn policy_timeout_zero_takes_precedence_over_cap() {
18120        // The cross-arm ordering pin: `Duration::ZERO` is
18121        // structurally outside both `>= 1ms` (zero-floor) and
18122        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
18123        // diagnostic is the more self-locating one (it directly
18124        // names the omit-axis remediation), so the validate gate
18125        // must fire on zero first. Same shape every other
18126        // zero-then-shape ordering on this surface uses
18127        // ([`AplicacaoError::PolicyRetriesZero`] then
18128        // [`AplicacaoError::PolicyRetriesExceedsCap`];
18129        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18130        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18131        let mut s = three_member_spec();
18132        s.politicas.timeout = Some(Duration::ZERO);
18133        assert_eq!(
18134            s.validate().unwrap_err(),
18135            AplicacaoError::PolicyTimeoutZero,
18136            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18137        );
18138    }
18139
18140    #[test]
18141    fn policy_timeout_canonical_takes_precedence_over_cap() {
18142        // The cross-arm ordering pin: a `Duration` that is *both*
18143        // sub-millisecond (non-canonical-form) and structurally
18144        // above the cap surfaces the canonical-form diagnostic
18145        // first, because the round-trip-shape break is the more
18146        // fundamental issue (the value can't even round-trip
18147        // through the codec, so the cap diagnostic naming
18148        // `1ms..=1h` would be misleading — there's no integer-ms
18149        // form of the offending value). Pin the order so a future
18150        // refactor that reorders the arms surfaces here as a test
18151        // failure rather than a silent diagnostic regression.
18152        let mut s = three_member_spec();
18153        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
18154        // *and* total magnitude above the 1h cap.
18155        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
18156        s.politicas.timeout = Some(timeout);
18157        assert_eq!(
18158            s.validate().unwrap_err(),
18159            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
18160            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18161        );
18162    }
18163
18164    #[test]
18165    fn policy_timeout_cap_diagnostic_carries_offending_value() {
18166        // The diagnostic-shape pin: the offending `Duration` is
18167        // carried verbatim into the
18168        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
18169        // surfaced error message names the value the author wrote
18170        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
18171        // exceeds the mesh-policy ceiling …"`), not just the cap.
18172        // Same self-locating diagnostic shape every other typed-cap
18173        // arm on this surface carries
18174        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
18175        // offending retry count verbatim).
18176        let mut s = three_member_spec();
18177        let timeout = Duration::from_secs(7200); // 2h
18178        s.politicas.timeout = Some(timeout);
18179        let err = s.validate().unwrap_err();
18180        assert!(
18181            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
18182            "got {err:?}"
18183        );
18184        let msg = err.to_string();
18185        assert!(
18186            msg.contains("7200"),
18187            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
18188        );
18189    }
18190
18191    #[test]
18192    fn policy_timeout_cap_pins_canonical_value() {
18193        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
18194        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
18195        // the shared duration codec emits as a clean canonical
18196        // string (`"<n>h"`). Pinning the literal value here surfaces
18197        // a future drift (a relaxation to 24h, a tightening to 5m)
18198        // as a deliberate test edit, not a silent contract
18199        // narrowing. Same shape every other typed-cap value pin on
18200        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
18201        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
18202        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
18203    }
18204
18205    #[test]
18206    fn policy_timeout_cap_value_round_trips_through_codec() {
18207        // The codec round-trip property the cap arm preserves: the
18208        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
18209        // the shared duration codec — every value at the cap renders
18210        // to a clean canonical string (`"1h"`) and parses back to
18211        // the same `Duration`. Pin this so a future drift between
18212        // the cap constant and the codec's largest emitted unit
18213        // surfaces here. Same shape every other typed boundary pin
18214        // on this surface uses
18215        // (`wasm32_memory_cap_matches_parsed_4_gib`).
18216        let policy = MeshPolicy {
18217            timeout: Some(POLICY_TIMEOUT_MAX),
18218            ..Default::default()
18219        };
18220        let json = serde_json::to_string(&policy).unwrap();
18221        // The codec emits `"1h"` for the canonical 1-hour magnitude.
18222        assert!(
18223            json.contains("\"1h\""),
18224            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
18225        );
18226        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18227        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
18228    }
18229
18230    #[test]
18231    fn rejects_circuit_breaker_window_sub_millisecond() {
18232        // Peer of the `:timeout` sub-millisecond arm on the second
18233        // typed-`Duration` `:politicas` axis: a purely sub-ms
18234        // `Duration` (`from_micros(500)`) renders through the shared
18235        // codec as `"0s"`, which the codec parses back to
18236        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
18237        // zero-floor gate then rejects on re-validate.
18238        let mut s = three_member_spec();
18239        let window = Duration::from_micros(500);
18240        s.politicas.circuit_breaker = Some(CircuitBreaker {
18241            max_failures: 5,
18242            window,
18243        });
18244        assert_eq!(
18245            s.validate().unwrap_err(),
18246            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18247        );
18248    }
18249
18250    #[test]
18251    fn rejects_circuit_breaker_window_non_integer_millisecond() {
18252        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
18253        // with non-integer-millisecond residue renders through the
18254        // shared codec as the truncated `"<n>ms"` form, parsing back
18255        // to a *different* `Duration` on the next round-trip.
18256        let mut s = three_member_spec();
18257        let window = Duration::from_micros(1500);
18258        s.politicas.circuit_breaker = Some(CircuitBreaker {
18259            max_failures: 5,
18260            window,
18261        });
18262        assert_eq!(
18263            s.validate().unwrap_err(),
18264            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18265        );
18266    }
18267
18268    #[test]
18269    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
18270        // The canonical-forms sweep on the breaker axis: every
18271        // integer-ms multiple the codec round-trips losslessly
18272        // passes the canonical gate.
18273        for window in [
18274            Duration::from_millis(1),
18275            Duration::from_millis(500),
18276            Duration::from_millis(1500),
18277            Duration::from_secs(30),
18278            Duration::from_secs(60),
18279            Duration::from_secs(3600),
18280        ] {
18281            let mut s = three_member_spec();
18282            s.politicas.circuit_breaker = Some(CircuitBreaker {
18283                max_failures: 5,
18284                window,
18285            });
18286            s.validate()
18287                .expect("integer-millisecond :circuit-breaker :window must validate");
18288        }
18289    }
18290
18291    #[test]
18292    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
18293        // `Duration::ZERO` would pass the canonical-ms gate (the
18294        // sub-ns residue is zero) but must surface the narrower
18295        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
18296        // remediation.
18297        let mut s = three_member_spec();
18298        s.politicas.circuit_breaker = Some(CircuitBreaker {
18299            max_failures: 5,
18300            window: Duration::ZERO,
18301        });
18302        assert_eq!(
18303            s.validate().unwrap_err(),
18304            AplicacaoError::PolicyBreakerZeroWindow
18305        );
18306    }
18307
18308    #[test]
18309    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
18310        // Both axes invalid: max_failures == 0 *and* window is
18311        // sub-ms. The validate gate must fire on max_failures first
18312        // (matching the existing ordering pin
18313        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
18314        // the existing diagnostic continues to lead with the simpler
18315        // "zero threshold" framing.
18316        let mut s = three_member_spec();
18317        s.politicas.circuit_breaker = Some(CircuitBreaker {
18318            max_failures: 0,
18319            window: Duration::from_micros(500),
18320        });
18321        assert_eq!(
18322            s.validate().unwrap_err(),
18323            AplicacaoError::PolicyBreakerZeroFailures
18324        );
18325    }
18326
18327    #[test]
18328    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
18329        let mut s = three_member_spec();
18330        let window = Duration::from_nanos(60_000_000_001);
18331        s.politicas.circuit_breaker = Some(CircuitBreaker {
18332            max_failures: 5,
18333            window,
18334        });
18335        match s.validate().unwrap_err() {
18336            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
18337                assert_eq!(w, window, "diagnostic must carry the offending Duration");
18338            }
18339            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
18340        }
18341    }
18342
18343    #[test]
18344    fn rejects_circuit_breaker_window_above_cap() {
18345        // The fail-before-pass-after pin: 3601s = 1h + 1s is
18346        // structurally one canonical-tick past the
18347        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
18348        // integer-millisecond magnitude the canonical-form arm above
18349        // accepts cleanly, that the codec round-trips losslessly as
18350        // `"3601s"`, and that silently passed validate on every
18351        // pre-gate codebase because the typed slot's only checks were
18352        // the zero-floor and canonical-form arms. The
18353        // rolling-window-to-lifetime-counter degeneration surfaces
18354        // only at the runtime substrate (Envoy's outlier_detection
18355        // interval, the future CiliumClusterwideEnvoyConfig overlay)
18356        // far from the source `caixa.lisp` with no field naming the
18357        // offending policy.
18358        let mut s = three_member_spec();
18359        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18360        s.politicas.circuit_breaker = Some(CircuitBreaker {
18361            max_failures: 5,
18362            window,
18363        });
18364        assert_eq!(
18365            s.validate().unwrap_err(),
18366            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18367        );
18368    }
18369
18370    #[test]
18371    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
18372        // Boundary case: exactly 1ms past the cap (the granularity the
18373        // canonical-form gate enforces). Catches a future "strictly
18374        // less than" half-measure and pins the diagnostic to name the
18375        // offending `Duration` verbatim. Peer of
18376        // `rejects_policy_timeout_one_millisecond_above_cap` on the
18377        // sibling duration-typed `:politicas :timeout` top edge.
18378        let mut s = three_member_spec();
18379        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
18380        s.politicas.circuit_breaker = Some(CircuitBreaker {
18381            max_failures: 5,
18382            window,
18383        });
18384        assert_eq!(
18385            s.validate().unwrap_err(),
18386            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18387        );
18388    }
18389
18390    #[test]
18391    fn rejects_circuit_breaker_window_far_above_cap() {
18392        // The "obvious authoring footgun" case: a `(:window "24h")` or
18393        // `(:window "86400s")` — values the canonical-form arm
18394        // accepts as integer-millisecond magnitudes, the codec
18395        // round-trips losslessly through serde, but the
18396        // rolling-window breaker contract cannot honor (a 24-hour
18397        // rolling failure window is operationally a lifetime counter).
18398        // Until this gate landed validate accepted it. Pin both common
18399        // above-cap values (24h, 7d) so a future relaxation that
18400        // drops the upper bound surfaces here.
18401        for window in [
18402            Duration::from_secs(86_400),    // 24h
18403            Duration::from_secs(604_800),   // 7d
18404            Duration::from_secs(1_000_000), // ~11.5 days
18405        ] {
18406            let mut s = three_member_spec();
18407            s.politicas.circuit_breaker = Some(CircuitBreaker {
18408                max_failures: 5,
18409                window,
18410            });
18411            assert_eq!(
18412                s.validate().unwrap_err(),
18413                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18414            );
18415        }
18416    }
18417
18418    #[test]
18419    fn accepts_circuit_breaker_window_at_cap() {
18420        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
18421        // (1h) — must validate. The cap is inclusive on the top edge,
18422        // matching the [`POLICY_TIMEOUT_MAX`] /
18423        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
18424        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18425        // sibling capped axes. Pin the boundary explicitly so a
18426        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
18427        // instead of `>`) surfaces here as a test failure rather than
18428        // a silent contract narrowing.
18429        let mut s = three_member_spec();
18430        s.politicas.circuit_breaker = Some(CircuitBreaker {
18431            max_failures: 5,
18432            window: POLICY_BREAKER_WINDOW_MAX,
18433        });
18434        s.validate()
18435            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
18436    }
18437
18438    #[test]
18439    fn accepts_circuit_breaker_window_typical_values() {
18440        // The documented production-playbook band positive-control
18441        // sweep — every value Hystrix / resilience4j / Istio / Envoy
18442        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
18443        // through the long-tail failure-detection band (15m, 30m, 1h)
18444        // the cap accepts. Pin the inclusive validated set explicitly
18445        // so a future tightening of the ceiling surfaces here as a
18446        // deliberate test edit, not a silent contract narrowing.
18447        for window in [
18448            Duration::from_millis(1),
18449            Duration::from_millis(500),
18450            Duration::from_secs(1),
18451            Duration::from_secs(10), // Hystrix / Istio / Envoy default
18452            Duration::from_secs(30),
18453            Duration::from_secs(60),  // resilience4j typical
18454            Duration::from_secs(300), // AWS App Mesh typical
18455            Duration::from_secs(900),
18456            Duration::from_secs(1800),
18457            Duration::from_secs(3600), // exactly 1h, the cap
18458        ] {
18459            let mut s = three_member_spec();
18460            s.politicas.circuit_breaker = Some(CircuitBreaker {
18461                max_failures: 5,
18462                window,
18463            });
18464            s.validate()
18465                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
18466        }
18467    }
18468
18469    #[test]
18470    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
18471        // The cross-arm ordering pin: `Duration::ZERO` is structurally
18472        // outside both `>= 1ms` (zero-floor) and
18473        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
18474        // diagnostic is the more self-locating one (it directly names
18475        // the omit-axis remediation), so the validate gate must fire
18476        // on zero first. Same shape every other zero-then-cap
18477        // ordering on this surface uses
18478        // ([`AplicacaoError::PolicyTimeoutZero`] then
18479        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
18480        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18481        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18482        let mut s = three_member_spec();
18483        s.politicas.circuit_breaker = Some(CircuitBreaker {
18484            max_failures: 5,
18485            window: Duration::ZERO,
18486        });
18487        assert_eq!(
18488            s.validate().unwrap_err(),
18489            AplicacaoError::PolicyBreakerZeroWindow,
18490            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18491        );
18492    }
18493
18494    #[test]
18495    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
18496        // The cross-arm ordering pin: a `Duration` that is *both*
18497        // sub-millisecond (non-canonical-form) and structurally above
18498        // the cap surfaces the canonical-form diagnostic first,
18499        // because the round-trip-shape break is the more fundamental
18500        // issue (the value can't even round-trip through the codec, so
18501        // the cap diagnostic naming `1ms..=1h` would be misleading —
18502        // there's no integer-ms form of the offending value). Pin the
18503        // order so a future refactor that reorders the arms surfaces
18504        // here as a test failure rather than a silent diagnostic
18505        // regression. Peer of
18506        // `policy_timeout_canonical_takes_precedence_over_cap` on the
18507        // sibling duration-typed `:politicas :timeout` axis.
18508        let mut s = three_member_spec();
18509        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
18510        s.politicas.circuit_breaker = Some(CircuitBreaker {
18511            max_failures: 5,
18512            window,
18513        });
18514        assert_eq!(
18515            s.validate().unwrap_err(),
18516            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
18517            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18518        );
18519    }
18520
18521    #[test]
18522    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
18523        // The cross-arm ordering pin between the two breaker axes: a
18524        // `CircuitBreaker` whose *both* `max_failures` is above its
18525        // cap *and* `window` is above its cap surfaces the
18526        // max-failures cap diagnostic first, because the validate
18527        // gate visits the failures arm before the window arm. Pin the
18528        // order so a future refactor that reorders the breaker arms
18529        // surfaces here.
18530        let mut s = three_member_spec();
18531        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18532        s.politicas.circuit_breaker = Some(CircuitBreaker {
18533            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18534            window,
18535        });
18536        assert_eq!(
18537            s.validate().unwrap_err(),
18538            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18539                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
18540            },
18541            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
18542        );
18543    }
18544
18545    #[test]
18546    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
18547        // The diagnostic-shape pin: the offending `Duration` is
18548        // carried verbatim into the
18549        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
18550        // the surfaced error message names the value the author wrote
18551        // (`":politicas :circuit-breaker :window (Duration { secs:
18552        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
18553        // just the cap. Same self-locating diagnostic shape every
18554        // other typed-cap arm on this surface carries
18555        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
18556        // offending `Duration` verbatim).
18557        let mut s = three_member_spec();
18558        let window = Duration::from_secs(7200); // 2h
18559        s.politicas.circuit_breaker = Some(CircuitBreaker {
18560            max_failures: 5,
18561            window,
18562        });
18563        let err = s.validate().unwrap_err();
18564        assert!(
18565            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
18566            "got {err:?}"
18567        );
18568        let msg = err.to_string();
18569        assert!(
18570            msg.contains("7200"),
18571            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
18572        );
18573    }
18574
18575    #[test]
18576    fn circuit_breaker_window_cap_pins_canonical_value() {
18577        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
18578        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
18579        // shared duration codec emits as a clean canonical string
18580        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
18581        // the sibling duration-typed `:politicas :timeout` axis (the
18582        // two duration-typed `:politicas` axes share a uniform top
18583        // edge). Pinning the literal value here surfaces a future
18584        // drift (a relaxation to 24h, a tightening to 5m) as a
18585        // deliberate test edit, not a silent contract narrowing. Same
18586        // shape every other typed-cap value pin on this surface uses
18587        // (`policy_timeout_cap_pins_canonical_value`).
18588        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
18589        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
18590        assert_eq!(
18591            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
18592            "the two duration-typed `:politicas` caps share the same top edge"
18593        );
18594    }
18595
18596    #[test]
18597    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
18598        // The codec round-trip property the cap arm preserves: the
18599        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
18600        // through the shared duration codec — every value at the cap
18601        // renders to a clean canonical string (`"1h"`) and parses back
18602        // to the same `Duration`. Pin this so a future drift between
18603        // the cap constant and the codec's largest emitted unit
18604        // surfaces here. Same shape every other typed boundary pin on
18605        // this surface uses
18606        // (`policy_timeout_cap_value_round_trips_through_codec`).
18607        let policy = MeshPolicy {
18608            circuit_breaker: Some(CircuitBreaker {
18609                max_failures: 5,
18610                window: POLICY_BREAKER_WINDOW_MAX,
18611            }),
18612            ..Default::default()
18613        };
18614        let json = serde_json::to_string(&policy).unwrap();
18615        // The codec emits `"1h"` for the canonical 1-hour magnitude.
18616        assert!(
18617            json.contains("\"1h\""),
18618            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
18619        );
18620        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18621        assert_eq!(
18622            back.circuit_breaker.unwrap().window,
18623            POLICY_BREAKER_WINDOW_MAX
18624        );
18625    }
18626
18627    #[test]
18628    fn is_integer_millisecond_duration_predicate_tracks_codec() {
18629        // Pin the predicate's accepted set against the codec's
18630        // accepted set explicitly. The codec parses
18631        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
18632        // accepted value is an integer-millisecond multiple — so the
18633        // predicate must accept exactly that set. Same shape every
18634        // other predicate-on-the-typed-slot helper carries
18635        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
18636        // Read directly from the codec-owned predicate — the crate's
18637        // single source of truth every typed-`Duration` axis now routes
18638        // through via
18639        // [`crate::render::require_positive_canonical_bounded_duration`].
18640        use super::supervisor::duration_codec::is_integer_millisecond_duration;
18641        assert!(is_integer_millisecond_duration(Duration::ZERO));
18642        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
18643        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
18644        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
18645        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
18646        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
18647        // Non-integer-millisecond residue: rejected.
18648        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
18649        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
18650        assert!(!is_integer_millisecond_duration(Duration::from_micros(
18651            1500
18652        )));
18653        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
18654        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
18655            999_999
18656        )));
18657        // The 1-ns-past-1ms boundary: rejected (no longer a clean
18658        // integer-millisecond multiple).
18659        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
18660            1_000_001
18661        )));
18662    }
18663
18664    #[test]
18665    fn policy_timeout_validated_value_round_trips_through_codec() {
18666        // The structural property the canonical-ms gate enforces:
18667        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
18668        // round-trips losslessly through the shared `duration_codec`
18669        // (serialize → string → deserialize → equal value). Pin this
18670        // end-to-end so a future change to either side (the validate
18671        // gate's accepted granularity, the codec's parse/render unit
18672        // set) that breaks the alignment surfaces here. The
18673        // previous-state shape (typed slot accepts arbitrary
18674        // `Duration`, codec only round-trips integer-ms) would fail
18675        // this test for any `Duration::from_micros(1500)` timeout —
18676        // the validate gate now forecloses that.
18677        for timeout in [
18678            Duration::from_millis(1),
18679            Duration::from_millis(1500),
18680            Duration::from_secs(30),
18681            Duration::from_secs(3600),
18682        ] {
18683            let mut s = three_member_spec();
18684            s.politicas.timeout = Some(timeout);
18685            s.validate().unwrap();
18686            let json = serde_json::to_string(&s.politicas).unwrap();
18687            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18688            assert_eq!(
18689                back.timeout, s.politicas.timeout,
18690                "every validated :timeout must round-trip losslessly through the codec"
18691            );
18692        }
18693    }
18694
18695    #[test]
18696    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
18697        // Peer of the `:timeout` round-trip property on the breaker
18698        // axis.
18699        for window in [
18700            Duration::from_millis(1),
18701            Duration::from_millis(1500),
18702            Duration::from_secs(30),
18703            Duration::from_secs(3600),
18704        ] {
18705            let mut s = three_member_spec();
18706            s.politicas.circuit_breaker = Some(CircuitBreaker {
18707                max_failures: 5,
18708                window,
18709            });
18710            s.validate().unwrap();
18711            let json = serde_json::to_string(&s.politicas).unwrap();
18712            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18713            assert_eq!(
18714                back.circuit_breaker.unwrap().window,
18715                window,
18716                "every validated :circuit-breaker :window must round-trip losslessly"
18717            );
18718        }
18719    }
18720
18721    #[test]
18722    fn empty_politicas_validates() {
18723        // Omitting every policy axis is fine — defaults express "no
18724        // policy on this axis", not "policy = 0". The fixture's typical
18725        // values continue to validate; this test pins that
18726        // MeshPolicy::default() is a clean pass through validate().
18727        let mut s = three_member_spec();
18728        s.politicas = MeshPolicy::default();
18729        s.validate().unwrap();
18730    }
18731
18732    #[test]
18733    fn typical_politicas_validates_with_every_axis_set() {
18734        // The full §III.1 example block (timeout + retries + breaker +
18735        // mtls + rate-limit) — every axis nonzero — must remain a
18736        // clean pass.
18737        let mut s = three_member_spec();
18738        s.politicas = MeshPolicy {
18739            timeout: Some(Duration::from_secs(30)),
18740            retries: Some(3),
18741            circuit_breaker: Some(CircuitBreaker {
18742                max_failures: 5,
18743                window: Duration::from_secs(60),
18744            }),
18745            mtls_required: Some(true),
18746            rate_limit: Some(RateLimit {
18747                rate: 100,
18748                window: Duration::from_secs(1),
18749            }),
18750        };
18751        s.validate().unwrap();
18752    }
18753
18754    #[test]
18755    fn rejects_empty_cluster_name() {
18756        let mut s = three_member_spec();
18757        s.placement.clusters = vec!["rio".into(), "".into()];
18758        assert_eq!(
18759            s.validate().unwrap_err(),
18760            AplicacaoError::PlacementClusterEmpty
18761        );
18762    }
18763
18764    #[test]
18765    fn rejects_duplicate_cluster_names() {
18766        let mut s = three_member_spec();
18767        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
18768        let err = s.validate().unwrap_err();
18769        assert!(
18770            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
18771            "got {err:?}"
18772        );
18773    }
18774
18775    #[test]
18776    fn rejects_placement_cluster_with_uppercase() {
18777        // The canonical "I copied the cluster's display name verbatim"
18778        // typo — K8s context names are lowercase per DNS-1123 label
18779        // rule, but org docs often round-trip a TitleCase identifier
18780        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
18781        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
18782        // on the peer name axis.
18783        let mut s = three_member_spec();
18784        s.placement.clusters = vec!["Rio".into(), "mar".into()];
18785        let err = s.validate().unwrap_err();
18786        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18787            panic!("expected PlacementClusterInvalid, got other variant");
18788        };
18789        assert_eq!(cluster, "Rio");
18790        assert!(
18791            reason.contains("uppercase"),
18792            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
18793        );
18794        assert!(
18795            reason.contains("\"rio\""),
18796            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
18797        );
18798    }
18799
18800    #[test]
18801    fn rejects_placement_cluster_with_underscore() {
18802        // The canonical "I'm thinking of an env var / hostname slug"
18803        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
18804        // schema. K8s context filtering on `my_cluster` silently misses
18805        // the cluster the author intended; the gate moves it to caixa-
18806        // build time. Same shape as `rejects_membro_caixa_with_underscore`
18807        // (3f9d7a0).
18808        let mut s = three_member_spec();
18809        s.placement.clusters = vec!["my_cluster".into()];
18810        let err = s.validate().unwrap_err();
18811        assert!(
18812            matches!(
18813                err,
18814                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18815                    if cluster == "my_cluster" && reason.contains('_')
18816            ),
18817            "got {err:?}"
18818        );
18819    }
18820
18821    #[test]
18822    fn rejects_placement_cluster_with_dot() {
18823        // A `:placement :clusters` entry is a single DNS-1123 *label*,
18824        // not a subdomain — even though K8s context names sometimes
18825        // carry a dotted form via kubeconfig conventions, the strictest
18826        // floor among the use sites (DNS-1035 cluster.x-k8s.io
18827        // `metadata.name`, Cilium identity label values) wins. The "I
18828        // want to namespace my cluster names with `.`" intent is
18829        // expressed via `-` (`mar-east`).
18830        let mut s = three_member_spec();
18831        s.placement.clusters = vec!["team.rio".into()];
18832        let err = s.validate().unwrap_err();
18833        assert!(
18834            matches!(
18835                err,
18836                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18837                    if cluster == "team.rio" && reason.contains('.')
18838            ),
18839            "got {err:?}"
18840        );
18841    }
18842
18843    #[test]
18844    fn rejects_placement_cluster_with_leading_hyphen() {
18845        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
18846        // with an alphanumeric. The K8s apiserver rejects `-rio`
18847        // outright; the rendered fan-out would emit a `metadata.name:
18848        // "-rio"` that fails admission far from the source caixa.lisp.
18849        let mut s = three_member_spec();
18850        s.placement.clusters = vec!["-rio".into()];
18851        let err = s.validate().unwrap_err();
18852        assert!(
18853            matches!(
18854                err,
18855                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18856                    if cluster == "-rio" && reason.contains("start and end")
18857            ),
18858            "got {err:?}"
18859        );
18860    }
18861
18862    #[test]
18863    fn rejects_placement_cluster_with_trailing_hyphen() {
18864        // The symmetric arm of the boundary rule. Pin separately so
18865        // both ends are covered against a future relaxation that only
18866        // checks one boundary (parallel to
18867        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
18868        let mut s = three_member_spec();
18869        s.placement.clusters = vec!["rio-".into()];
18870        let err = s.validate().unwrap_err();
18871        assert!(
18872            matches!(
18873                err,
18874                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18875                    if cluster == "rio-"
18876            ),
18877            "got {err:?}"
18878        );
18879    }
18880
18881    #[test]
18882    fn rejects_placement_cluster_with_unicode() {
18883        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
18884        // before it reaches K8s. The byte-by-byte ASCII validity check
18885        // rejects multi-byte UTF-8 sequences by the first byte that
18886        // fails `[a-z0-9-]`.
18887        let mut s = three_member_spec();
18888        s.placement.clusters = vec!["rió".into()];
18889        let err = s.validate().unwrap_err();
18890        assert!(
18891            matches!(
18892                err,
18893                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18894                    if cluster == "rió"
18895            ),
18896            "got {err:?}"
18897        );
18898    }
18899
18900    #[test]
18901    fn rejects_placement_cluster_with_whitespace() {
18902        // Whitespace is the canonical "I pasted from a sketch / doc"
18903        // footgun. The apiserver rejects every cluster `metadata.name`
18904        // value carrying whitespace.
18905        let mut s = three_member_spec();
18906        s.placement.clusters = vec!["rio cluster".into()];
18907        let err = s.validate().unwrap_err();
18908        assert!(
18909            matches!(
18910                err,
18911                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18912                    if cluster == "rio cluster"
18913            ),
18914            "got {err:?}"
18915        );
18916    }
18917
18918    #[test]
18919    fn rejects_placement_cluster_too_long() {
18920        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
18921        // pin. The diagnostic names both the cap (63) and the actual
18922        // length so the author can shorten in one edit. Mirrors
18923        // `rejects_membro_caixa_too_long` (3f9d7a0).
18924        let mut s = three_member_spec();
18925        let too_long = "a".repeat(64);
18926        s.placement.clusters = vec![too_long.clone()];
18927        let err = s.validate().unwrap_err();
18928        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18929            panic!("expected PlacementClusterInvalid");
18930        };
18931        assert_eq!(cluster, too_long);
18932        assert!(
18933            reason.contains("63") && reason.contains("64"),
18934            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18935        );
18936    }
18937
18938    #[test]
18939    fn placement_cluster_max_length_validates() {
18940        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
18941        // future tightening (e.g. dropping to 62) surfaces here as a
18942        // regression, mirroring `membro_caixa_max_length_validates`
18943        // (3f9d7a0).
18944        let mut s = three_member_spec();
18945        s.placement.clusters = vec!["a".repeat(63)];
18946        s.validate().unwrap();
18947    }
18948
18949    #[test]
18950    fn accepts_canonical_placement_cluster_forms() {
18951        // The DNS-1123 label shapes a caixa author is realistically
18952        // going to write for cluster names: single-word lowercase
18953        // (`rio`), regional hyphen-joined (`mar-east`), single
18954        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
18955        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
18956        // Pin every leg so a future tightening that bans (e.g.) digit-
18957        // start identifiers surfaces here.
18958        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
18959            let mut s = three_member_spec();
18960            s.placement.clusters = vec![form.into()];
18961            s.validate().unwrap_or_else(|e| {
18962                panic!("canonical cluster form {form:?} must validate, got {e:?}")
18963            });
18964        }
18965    }
18966
18967    #[test]
18968    fn placement_cluster_empty_takes_precedence_over_invalid() {
18969        // Order pin: the existing `PlacementClusterEmpty` diagnostic
18970        // (which doesn't try to parse) fires before the new
18971        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
18972        // `:clusters` entry keeps its narrower error message — the new
18973        // gate would also reject `""`, but the empty-string arm is the
18974        // more self-locating diagnostic. Mirrors the
18975        // `membro_caixa_empty_takes_precedence_over_invalid` pin
18976        // (3f9d7a0).
18977        let mut s = three_member_spec();
18978        s.placement.clusters = vec!["rio".into(), "".into()];
18979        let err = s.validate().unwrap_err();
18980        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
18981    }
18982
18983    #[test]
18984    fn placement_cluster_invalid_fires_before_duplicate_check() {
18985        // Order pin: a malformed-shape `:clusters` entry surfaces *its
18986        // own* diagnostic, even when a later entry would otherwise
18987        // collapse onto a duplicate name. The per-entry shape gate runs
18988        // inline before the duplicate-key insert, parallel to
18989        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
18990        let mut s = three_member_spec();
18991        s.placement.clusters = vec!["Rio".into(), "rio".into()];
18992        let err = s.validate().unwrap_err();
18993        assert!(
18994            matches!(
18995                err,
18996                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
18997            ),
18998            "got {err:?}"
18999        );
19000    }
19001
19002    #[test]
19003    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
19004        // The diagnostic-shape pin: the error names the offending
19005        // `:clusters` value verbatim so the author can grep their
19006        // caixa.lisp without re-running the build, and carries a
19007        // non-empty `reason` naming the specific violation. Same shape
19008        // every typed-shape gate enshrines
19009        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
19010        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
19011        let mut s = three_member_spec();
19012        s.placement.clusters = vec!["BAD_CLUSTER".into()];
19013        let err = s.validate().unwrap_err();
19014        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19015            panic!("expected PlacementClusterInvalid");
19016        };
19017        assert_eq!(cluster, "BAD_CLUSTER");
19018        assert!(
19019            !reason.is_empty(),
19020            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
19021        );
19022    }
19023
19024    #[test]
19025    fn rejects_sharded_with_empty_clusters() {
19026        // §III.1: Sharded uses :clusters as the shard pool. An empty
19027        // pool means "shard across no clusters" — meaningless, same as
19028        // Replicated with no hosts.
19029        let mut s = three_member_spec();
19030        s.placement.estrategia = PlacementStrategy::Sharded;
19031        s.placement.shard_key = Some("$tenantId".into());
19032        s.placement.clusters = vec![];
19033        assert!(matches!(
19034            s.validate().unwrap_err(),
19035            AplicacaoError::PlacementWithoutClusters {
19036                estrategia: PlacementStrategy::Sharded
19037            }
19038        ));
19039    }
19040
19041    #[test]
19042    fn rejects_sharded_with_empty_shard_key() {
19043        let mut s = three_member_spec();
19044        s.placement.estrategia = PlacementStrategy::Sharded;
19045        s.placement.shard_key = Some("".into());
19046        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
19047    }
19048
19049    #[test]
19050    fn rejects_shard_key_under_replicated_strategy() {
19051        // The fail-before-pass-after pin: a `:placement (:estrategia
19052        // Replicated :shard-key "tenantId")` manifest carries the
19053        // hash-keyed-distribution slot on a strategy that never consumes
19054        // it. Before the gate the typed slot's value silently vanished
19055        // at the renderer layer (caixa-mesh emits `placement.shardKey`
19056        // verbatim regardless of strategy; the Akka-style cluster-
19057        // sharding reconciler keys off `estrategia == Sharded` and
19058        // ignores the slot otherwise), with no diagnostic. Lifting the
19059        // rejection to a build-time gate makes the
19060        // `shard_key.is_some() == matches!(estrategia, Sharded)`
19061        // partition a structural property of every validated
19062        // [`Placement`].
19063        let mut s = three_member_spec();
19064        // The fixture already uses Replicated; just add a shard-key.
19065        s.placement.shard_key = Some("$tenantId".into());
19066        let err = s.validate().unwrap_err();
19067        let AplicacaoError::ShardKeyOnNonSharded {
19068            estrategia,
19069            shard_key,
19070        } = err
19071        else {
19072            panic!("expected ShardKeyOnNonSharded, got {err:?}");
19073        };
19074        assert_eq!(estrategia, PlacementStrategy::Replicated);
19075        assert_eq!(shard_key, "$tenantId");
19076    }
19077
19078    #[test]
19079    fn rejects_shard_key_under_singlenode_strategy() {
19080        // Peer of the Replicated case above on the SingleNode arm: OTP
19081        // distributed-app takeover (one cluster runs at a time) has no
19082        // hash-keyed routing axis to consume `:shard-key` either, so
19083        // the rejection fires on both non-Sharded arms uniformly.
19084        let mut s = three_member_spec();
19085        s.placement.estrategia = PlacementStrategy::SingleNode;
19086        s.placement.shard_key = Some("$tenantId".into());
19087        let err = s.validate().unwrap_err();
19088        let AplicacaoError::ShardKeyOnNonSharded {
19089            estrategia,
19090            shard_key,
19091        } = err
19092        else {
19093            panic!("expected ShardKeyOnNonSharded, got {err:?}");
19094        };
19095        assert_eq!(estrategia, PlacementStrategy::SingleNode);
19096        assert_eq!(shard_key, "$tenantId");
19097    }
19098
19099    #[test]
19100    fn rejects_empty_shard_key_under_replicated_strategy() {
19101        // The `Some("")` case under non-Sharded is rejected by
19102        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
19103        // fires before the empty-value gate), not
19104        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
19105        // the `Sharded` arm). Pin the partition so a future reorder of
19106        // the validate_placement match arms doesn't silently swap which
19107        // diagnostic the author sees — both are author errors, but
19108        // ShardKeyOnNonSharded names which strategy is the actual fix
19109        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
19110        // only says "pick a non-empty key".
19111        let mut s = three_member_spec();
19112        s.placement.shard_key = Some(String::new());
19113        let err = s.validate().unwrap_err();
19114        assert!(
19115            matches!(
19116                err,
19117                AplicacaoError::ShardKeyOnNonSharded {
19118                    estrategia: PlacementStrategy::Replicated,
19119                    ref shard_key,
19120                } if shard_key.is_empty()
19121            ),
19122            "got {err:?}"
19123        );
19124    }
19125
19126    #[test]
19127    fn replicated_without_shard_key_validates() {
19128        // The complement of the rejection: `:placement :estrategia
19129        // Replicated` with `:shard-key None` is the canonical happy
19130        // path on every existing fixture. Pin the no-shard-key case so
19131        // the new gate doesn't accidentally fire on `None`.
19132        let mut s = three_member_spec();
19133        assert!(matches!(
19134            s.placement.estrategia,
19135            PlacementStrategy::Replicated
19136        ));
19137        s.placement.shard_key = None;
19138        s.validate().unwrap();
19139    }
19140
19141    #[test]
19142    fn singlenode_without_shard_key_validates() {
19143        // Peer of the Replicated no-shard-key case on the SingleNode
19144        // arm — both non-Sharded strategies must validate cleanly when
19145        // the slot is omitted.
19146        let mut s = three_member_spec();
19147        s.placement.estrategia = PlacementStrategy::SingleNode;
19148        s.placement.shard_key = None;
19149        s.validate().unwrap();
19150    }
19151
19152    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
19153        // Fixture builder for the `:placement :shard-key` shape gate
19154        // tests: a three-member Aplicacao on the `Sharded` strategy
19155        // with the supplied `:shard-key` slot. Co-locates the
19156        // arm-construction so every test below carries one line of
19157        // setup (the offending `:shard-key` value) and the assertion.
19158        let mut s = three_member_spec();
19159        s.placement.estrategia = PlacementStrategy::Sharded;
19160        s.placement.shard_key = Some(key.into());
19161        s
19162    }
19163
19164    #[test]
19165    fn rejects_shard_key_with_embedded_space() {
19166        // The canonical paste-from-aligned-doc footgun:
19167        // `:shard-key "$tenant Id"` — the Akka-style entity-id
19168        // extractor reads the slot as a single-token reference, and an
19169        // embedded space breaks the token boundary at the runtime
19170        // hash-extractor pass with no diagnostic naming the offending
19171        // entry.
19172        let s = sharded_spec_with_key("$tenant Id");
19173        let err = s.validate().unwrap_err();
19174        assert!(
19175            matches!(
19176                err,
19177                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19178                    if shard_key == "$tenant Id" && reason.contains("space")
19179            ),
19180            "got {err:?}"
19181        );
19182    }
19183
19184    #[test]
19185    fn rejects_shard_key_with_leading_space() {
19186        // Leading-space arm of the embedded-whitespace footgun — the
19187        // paste-from-aligned-doc / paste-from-CSV-cell variant where
19188        // the leading column-padding leaked into the slot.
19189        let s = sharded_spec_with_key(" $tenantId");
19190        let err = s.validate().unwrap_err();
19191        assert!(
19192            matches!(
19193                err,
19194                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
19195                    if shard_key == " $tenantId"
19196            ),
19197            "got {err:?}"
19198        );
19199    }
19200
19201    #[test]
19202    fn rejects_shard_key_with_trailing_newline() {
19203        // The canonical paste-from-shell-heredoc footgun — every
19204        // `<<EOF` heredoc terminator paste leaves a trailing newline
19205        // the YAML emitter then folds away inconsistently across
19206        // emitter implementations.
19207        let s = sharded_spec_with_key("$tenantId\n");
19208        let err = s.validate().unwrap_err();
19209        assert!(
19210            matches!(
19211                err,
19212                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19213                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
19214            ),
19215            "got {err:?}"
19216        );
19217    }
19218
19219    #[test]
19220    fn rejects_shard_key_with_embedded_tab() {
19221        // The paste-from-aligned-doc tab-stop variant — tabs land
19222        // alongside spaces in copy-paste from formatted columns.
19223        let s = sharded_spec_with_key("$tenant\tId");
19224        let err = s.validate().unwrap_err();
19225        assert!(
19226            matches!(
19227                err,
19228                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19229                    if shard_key == "$tenant\tId" && reason.contains("tab")
19230            ),
19231            "got {err:?}"
19232        );
19233    }
19234
19235    #[test]
19236    fn rejects_shard_key_with_control_character() {
19237        // The paste-from-binary / paste-from-screen-cleared-terminal
19238        // footgun — an embedded `\x01` (SOH) byte that some YAML
19239        // emitters silently strip and others escape as ``,
19240        // breaking round-trip across emitter implementations.
19241        let s = sharded_spec_with_key("$tenant\u{0001}Id");
19242        let err = s.validate().unwrap_err();
19243        assert!(
19244            matches!(
19245                err,
19246                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19247                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
19248            ),
19249            "got {err:?}"
19250        );
19251    }
19252
19253    #[test]
19254    fn rejects_shard_key_with_non_ascii() {
19255        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
19256        // footgun — non-ASCII bytes normalize differently between the
19257        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
19258        // YAML parser, the same entity ID can silently map to two
19259        // distinct shards on a re-render.
19260        let s = sharded_spec_with_key("$tenàntId");
19261        let err = s.validate().unwrap_err();
19262        assert!(
19263            matches!(
19264                err,
19265                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19266                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
19267            ),
19268            "got {err:?}"
19269        );
19270    }
19271
19272    #[test]
19273    fn rejects_shard_key_too_long() {
19274        // Length cap pin: 64 bytes — one byte over the
19275        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
19276        // here is a paste-from-doc multi-line blob landing in
19277        // `:shard-key` instead of a single-token extractor expression.
19278        let too_long = "a".repeat(64);
19279        let s = sharded_spec_with_key(&too_long);
19280        let err = s.validate().unwrap_err();
19281        let AplicacaoError::ShardKeyInvalid {
19282            ref shard_key,
19283            ref reason,
19284        } = err
19285        else {
19286            panic!("expected ShardKeyInvalid, got {err:?}");
19287        };
19288        assert_eq!(shard_key, &too_long);
19289        assert!(
19290            reason.contains("63") && reason.contains("64"),
19291            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19292        );
19293    }
19294
19295    #[test]
19296    fn shard_key_max_length_validates() {
19297        // Boundary pin: 63 bytes exactly — the
19298        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
19299        // dropping to 62) surfaces here as a regression, mirroring
19300        // `placement_cluster_max_length_validates` /
19301        // `placement_affinity_max_length_validates` on the peer
19302        // identifier-shaped slots.
19303        let s = sharded_spec_with_key(&"a".repeat(63));
19304        s.validate().unwrap();
19305    }
19306
19307    #[test]
19308    fn accepts_canonical_shard_key_forms() {
19309        // The Akka-style entity-id extractor shapes a caixa author is
19310        // realistically going to write — pin every leg so a future
19311        // tightening that bans (e.g.) the `${...}` interpolation
19312        // variant or the `metadata.<field>` JSONPath form surfaces
19313        // here as a regression. The canonical forms span:
19314        //
19315        //   - bare property name (`tenantId`, `customerId`)
19316        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
19317        //   - JSONPath-style nested reference (`metadata.tenantId`,
19318        //     `$.user.id`)
19319        //   - interpolation-style template (`${tenant}`)
19320        //   - snake_case property name (`customer_id`)
19321        //   - kebab-case property name (`customer-id` — accepted
19322        //     because the slot is a printable-ASCII single-token
19323        //     reference, not a DNS-1123 label like
19324        //     `:placement :affinity` / `:clusters`)
19325        //   - single character (`a`, `$` — boundary)
19326        for form in [
19327            "tenantId",
19328            "customerId",
19329            "$tenantId",
19330            "metadata.tenantId",
19331            "$.user.id",
19332            "${tenant}",
19333            "customer_id",
19334            "customer-id",
19335            "a",
19336            "$",
19337        ] {
19338            let s = sharded_spec_with_key(form);
19339            s.validate().unwrap_or_else(|e| {
19340                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
19341            });
19342        }
19343    }
19344
19345    #[test]
19346    fn shard_key_empty_takes_precedence_over_invalid() {
19347        // Order pin: the existing `ShardedKeyEmpty` diagnostic
19348        // (reserved for the `Sharded` `Some("")` arm) fires before the
19349        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
19350        // `:shard-key` keeps its narrower error message — the new gate
19351        // would also reject `""` defensively, but the empty-string arm
19352        // is the more self-locating diagnostic. Mirrors the
19353        // `placement_cluster_empty_takes_precedence_over_invalid` pin
19354        // on the peer identifier-shaped slot.
19355        let s = sharded_spec_with_key("");
19356        let err = s.validate().unwrap_err();
19357        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
19358    }
19359
19360    #[test]
19361    fn shard_key_invalid_diagnostic_carries_offending_value() {
19362        // The diagnostic-shape pin: the error names the offending
19363        // `:shard-key` value verbatim so the author can grep their
19364        // caixa.lisp without re-running the build, and carries a
19365        // parser-shaped `reason:` naming the specific violation —
19366        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19367        // on the peer identifier-shaped slot.
19368        let s = sharded_spec_with_key("$tenant Id");
19369        let err = s.validate().unwrap_err();
19370        let AplicacaoError::ShardKeyInvalid {
19371            ref shard_key,
19372            ref reason,
19373        } = err
19374        else {
19375            panic!("expected ShardKeyInvalid, got {err:?}");
19376        };
19377        assert_eq!(shard_key, "$tenant Id");
19378        assert!(
19379            !reason.is_empty(),
19380            "reason must name the specific violation, got empty string"
19381        );
19382    }
19383
19384    #[test]
19385    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
19386        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
19387        // `:shard-key` carried on non-Sharded strategies) fires before
19388        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
19389        // a `Replicated` strategy surfaces the more self-locating
19390        // strategy-mismatch diagnostic (naming the actual fix — drop
19391        // the slot, or switch to Sharded) rather than the shape
19392        // diagnostic. The strategy-mismatch arm is the more actionable
19393        // diagnostic: a malformed shard-key on Replicated is "you
19394        // shouldn't have a :shard-key here at all", not "your
19395        // :shard-key value is malformed".
19396        let mut s = three_member_spec();
19397        // Replicated is the default fixture strategy.
19398        s.placement.shard_key = Some("$tenant Id".into());
19399        let err = s.validate().unwrap_err();
19400        assert!(
19401            matches!(
19402                err,
19403                AplicacaoError::ShardKeyOnNonSharded {
19404                    estrategia: PlacementStrategy::Replicated,
19405                    ..
19406                }
19407            ),
19408            "got {err:?}"
19409        );
19410    }
19411
19412    #[test]
19413    fn rejects_empty_affinity_hint() {
19414        let mut s = three_member_spec();
19415        s.placement.affinity = Some("".into());
19416        assert_eq!(
19417            s.validate().unwrap_err(),
19418            AplicacaoError::PlacementAffinityEmpty
19419        );
19420    }
19421
19422    #[test]
19423    fn placement_without_affinity_validates() {
19424        // Omitting :affinity is fine — the placement engine falls back
19425        // to the default heuristic. Pin the no-hint case so the
19426        // affinity-empty rejection doesn't accidentally fire on `None`.
19427        let mut s = three_member_spec();
19428        s.placement.affinity = None;
19429        s.validate().unwrap();
19430    }
19431
19432    #[test]
19433    fn rejects_placement_affinity_with_uppercase() {
19434        // The canonical "I copied the ADR's display name verbatim" typo
19435        // — placement hints land verbatim in K8s label-selector
19436        // territory, where the apiserver enforces the DNS-1123 label
19437        // rule (lowercase-only) on every identity-keyed admission axis.
19438        // Mirrors `rejects_placement_cluster_with_uppercase` on the
19439        // sibling slot.
19440        let mut s = three_member_spec();
19441        s.placement.affinity = Some("DataLocality".into());
19442        let err = s.validate().unwrap_err();
19443        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19444            panic!("expected PlacementAffinityInvalid, got other variant");
19445        };
19446        assert_eq!(affinity, "DataLocality");
19447        assert!(
19448            reason.contains("uppercase"),
19449            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19450        );
19451        assert!(
19452            reason.contains("\"datalocality\""),
19453            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19454        );
19455    }
19456
19457    #[test]
19458    fn rejects_placement_affinity_with_underscore() {
19459        // The canonical "I'm thinking of an env var / Python identifier"
19460        // leak — `_` is forbidden by every DNS-1123 label schema. Same
19461        // shape as `rejects_placement_cluster_with_underscore` on the
19462        // sibling slot.
19463        let mut s = three_member_spec();
19464        s.placement.affinity = Some("data_locality".into());
19465        let err = s.validate().unwrap_err();
19466        assert!(
19467            matches!(
19468                err,
19469                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19470                    if affinity == "data_locality" && reason.contains('_')
19471            ),
19472            "got {err:?}"
19473        );
19474    }
19475
19476    #[test]
19477    fn rejects_placement_affinity_with_dot() {
19478        // A `:placement :affinity` value is a single DNS-1123 *label*
19479        // (it lands as a K8s label value selector key), not a subdomain.
19480        // The "I want to namespace my hint with `.`" intent is expressed
19481        // via `-` (`data-locality-east`).
19482        let mut s = three_member_spec();
19483        s.placement.affinity = Some("data.locality".into());
19484        let err = s.validate().unwrap_err();
19485        assert!(
19486            matches!(
19487                err,
19488                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19489                    if affinity == "data.locality" && reason.contains('.')
19490            ),
19491            "got {err:?}"
19492        );
19493    }
19494
19495    #[test]
19496    fn rejects_placement_affinity_with_unicode() {
19497        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19498        // before it reaches K8s. The byte-by-byte ASCII validity check
19499        // rejects multi-byte UTF-8 sequences by the first byte that
19500        // fails `[a-z0-9-]`.
19501        let mut s = three_member_spec();
19502        s.placement.affinity = Some("data-localité".into());
19503        let err = s.validate().unwrap_err();
19504        assert!(
19505            matches!(
19506                err,
19507                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19508                    if affinity == "data-localité"
19509            ),
19510            "got {err:?}"
19511        );
19512    }
19513
19514    #[test]
19515    fn rejects_placement_affinity_with_leading_hyphen() {
19516        // DNS-1123 boundary rule: labels must start with an
19517        // alphanumeric. Pin separately from the trailing-hyphen arm so
19518        // a future relaxation that only checks one boundary surfaces
19519        // here as a regression (parallel to
19520        // `rejects_placement_cluster_with_leading_hyphen`).
19521        let mut s = three_member_spec();
19522        s.placement.affinity = Some("-data-locality".into());
19523        let err = s.validate().unwrap_err();
19524        assert!(
19525            matches!(
19526                err,
19527                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19528                    if affinity == "-data-locality" && reason.contains("start and end")
19529            ),
19530            "got {err:?}"
19531        );
19532    }
19533
19534    #[test]
19535    fn rejects_placement_affinity_with_trailing_hyphen() {
19536        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
19537        // ends are covered against a future relaxation.
19538        let mut s = three_member_spec();
19539        s.placement.affinity = Some("data-locality-".into());
19540        let err = s.validate().unwrap_err();
19541        assert!(
19542            matches!(
19543                err,
19544                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19545                    if affinity == "data-locality-"
19546            ),
19547            "got {err:?}"
19548        );
19549    }
19550
19551    #[test]
19552    fn rejects_placement_affinity_with_whitespace() {
19553        // Whitespace is the canonical "I pasted from a sketch / doc"
19554        // footgun. The apiserver rejects every label-selector value
19555        // carrying whitespace.
19556        let mut s = three_member_spec();
19557        s.placement.affinity = Some("data locality".into());
19558        let err = s.validate().unwrap_err();
19559        assert!(
19560            matches!(
19561                err,
19562                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19563                    if affinity == "data locality"
19564            ),
19565            "got {err:?}"
19566        );
19567    }
19568
19569    #[test]
19570    fn rejects_placement_affinity_too_long() {
19571        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
19572        // pin. The diagnostic names both the cap (63) and the actual
19573        // length so the author can shorten in one edit. Mirrors
19574        // `rejects_placement_cluster_too_long`.
19575        let mut s = three_member_spec();
19576        let too_long = "a".repeat(64);
19577        s.placement.affinity = Some(too_long.clone());
19578        let err = s.validate().unwrap_err();
19579        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19580            panic!("expected PlacementAffinityInvalid");
19581        };
19582        assert_eq!(affinity, too_long);
19583        assert!(
19584            reason.contains("63") && reason.contains("64"),
19585            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19586        );
19587    }
19588
19589    #[test]
19590    fn placement_affinity_max_length_validates() {
19591        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
19592        // future tightening (e.g. dropping to 62) surfaces here as a
19593        // regression, mirroring `placement_cluster_max_length_validates`.
19594        let mut s = three_member_spec();
19595        s.placement.affinity = Some("a".repeat(63));
19596        s.validate().unwrap();
19597    }
19598
19599    #[test]
19600    fn accepts_canonical_placement_affinity_forms() {
19601        // The DNS-1123 label shapes a caixa author is realistically
19602        // going to write for placement hints: the M3 canonical examples
19603        // (`data-locality`, `low-latency`, `anti-affinity`), the
19604        // single-token form (`affinity`), the single-character boundary
19605        // (`a`), the digit-start (DNS-1123 allows this, unlike
19606        // DNS-1035), and a regional-suffixed form. Pin every leg so a
19607        // future tightening that bans (e.g.) digit-start identifiers
19608        // surfaces here.
19609        for form in [
19610            "data-locality",
19611            "low-latency",
19612            "anti-affinity",
19613            "affinity",
19614            "a",
19615            "3-tier",
19616            "locality-east",
19617        ] {
19618            let mut s = three_member_spec();
19619            s.placement.affinity = Some(form.into());
19620            s.validate().unwrap_or_else(|e| {
19621                panic!("canonical affinity form {form:?} must validate, got {e:?}")
19622            });
19623        }
19624    }
19625
19626    #[test]
19627    fn placement_affinity_empty_takes_precedence_over_invalid() {
19628        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
19629        // (which doesn't try to parse) fires before the new
19630        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
19631        // `:affinity` keeps its narrower error message — the new gate
19632        // would also reject `""`, but the empty-string arm is the more
19633        // self-locating diagnostic. Mirrors the
19634        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
19635        let mut s = three_member_spec();
19636        s.placement.affinity = Some(String::new());
19637        let err = s.validate().unwrap_err();
19638        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
19639    }
19640
19641    #[test]
19642    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
19643        // The diagnostic shape pin: every rejection carries the offending
19644        // `affinity:` verbatim plus a parser-shaped `reason:` so the
19645        // author can grep their caixa.lisp for `:affinity "<hint>"` and
19646        // fix it in one edit. Mirrors the
19647        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19648        // pin on the sibling slot.
19649        let mut s = three_member_spec();
19650        s.placement.affinity = Some("Data_Locality".into());
19651        let err = s.validate().unwrap_err();
19652        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19653            panic!("expected PlacementAffinityInvalid");
19654        };
19655        assert_eq!(affinity, "Data_Locality");
19656        assert!(
19657            !reason.is_empty(),
19658            "diagnostic reason must not be empty (got: {reason:?})"
19659        );
19660    }
19661
19662    #[test]
19663    fn singlenode_with_takeover_candidates_validates() {
19664        // OTP distributed-application convention (MESH-COMPOSITION
19665        // §II.1): SingleNode runs on one cluster at a time but the
19666        // :clusters list enumerates the takeover candidates. Multiple
19667        // entries are not a contradiction — they are the failover pool.
19668        let mut s = three_member_spec();
19669        s.placement.estrategia = PlacementStrategy::SingleNode;
19670        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
19671        s.validate().unwrap();
19672    }
19673
19674    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
19675
19676    #[test]
19677    fn mesh_policy_default_is_empty() {
19678        // The Default impl carries None on every axis — the typed
19679        // analog of an unset `:politicas (())` slot. Renderers that
19680        // overlay the policy onto a cluster artifact key off this
19681        // predicate to skip the slot entirely; pinning so a future
19682        // axis added to MeshPolicy can't silently break the contract
19683        // (a new field whose Default is non-None would flip is_empty
19684        // to false on every existing caixa, surfacing here).
19685        assert!(MeshPolicy::default().is_empty());
19686    }
19687
19688    #[test]
19689    fn mesh_policy_with_only_timeout_is_not_empty() {
19690        let p = MeshPolicy {
19691            timeout: Some(Duration::from_secs(30)),
19692            ..Default::default()
19693        };
19694        assert!(!p.is_empty());
19695    }
19696
19697    #[test]
19698    fn mesh_policy_with_only_retries_is_not_empty() {
19699        let p = MeshPolicy {
19700            retries: Some(3),
19701            ..Default::default()
19702        };
19703        assert!(!p.is_empty());
19704    }
19705
19706    #[test]
19707    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
19708        let p = MeshPolicy {
19709            circuit_breaker: Some(CircuitBreaker {
19710                max_failures: 5,
19711                window: Duration::from_secs(60),
19712            }),
19713            ..Default::default()
19714        };
19715        assert!(!p.is_empty());
19716    }
19717
19718    #[test]
19719    fn mesh_policy_with_only_mtls_required_is_not_empty() {
19720        // Even `mtls_required: Some(false)` (an explicit opt-out) is
19721        // not empty — the author *named* the axis, the renderer needs
19722        // to honor that vs. fall back to the cluster default.
19723        let p = MeshPolicy {
19724            mtls_required: Some(false),
19725            ..Default::default()
19726        };
19727        assert!(!p.is_empty());
19728    }
19729
19730    #[test]
19731    fn mesh_policy_with_only_rate_limit_is_not_empty() {
19732        let p = MeshPolicy {
19733            rate_limit: Some(RateLimit {
19734                rate: 100,
19735                window: Duration::from_secs(1),
19736            }),
19737            ..Default::default()
19738        };
19739        assert!(!p.is_empty());
19740    }
19741
19742    #[test]
19743    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
19744        // The three-member happy-path fixture sets timeout + retries +
19745        // mtls_required — every populated axis must read non-empty.
19746        // Pin the round-trip so the M3.x per-:politicas emitter (the
19747        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
19748        // on is_empty() to decide whether to emit at all without
19749        // re-deriving the contract from inline field probes.
19750        assert!(!three_member_spec().politicas.is_empty());
19751    }
19752
19753    // ── shared duration codec: cross-slot integer-magnitude gate ──
19754    //
19755    // The integer-magnitude discipline applied to
19756    // `supervisor::duration_codec::parse` lifts onto every typed slot
19757    // that routes through the shared codec — `MeshPolicy::timeout`
19758    // (`:politicas :timeout`) and `CircuitBreaker::window`
19759    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
19760    // These cross-slot tests pin that the gate fires at the serde
19761    // layer for both typed slots, not just for the supervisor side.
19762
19763    #[test]
19764    fn policy_timeout_serde_rejects_fractional_seconds() {
19765        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
19766        // so the shared codec's integer-magnitude gate applies on
19767        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
19768        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
19769        // deserialize with the canonical-form diagnostic naming the
19770        // offending `"1.5"` and the remediation `"1500ms"`.
19771        let payload = r#"{"timeout":"1.5s"}"#;
19772        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19773        let msg = err.to_string();
19774        assert!(
19775            msg.contains("not a non-negative integer"),
19776            "expected integer-magnitude diagnostic in {msg:?}"
19777        );
19778        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
19779        assert!(
19780            msg.contains("\"1500ms\""),
19781            "missing canonical-form remediation in {msg:?}"
19782        );
19783    }
19784
19785    #[test]
19786    fn policy_timeout_serde_rejects_leading_plus_sign() {
19787        // Pin the leading-`+` arm cross-slot — the prior f64 parser
19788        // accepted `"+30s"` silently and round-tripped to `"30s"`.
19789        let payload = r#"{"timeout":"+30s"}"#;
19790        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19791        let msg = err.to_string();
19792        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
19793    }
19794
19795    #[test]
19796    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
19797        // `CircuitBreaker::window` uses `with =
19798        // "supervisor::duration_codec_required"` (the required-Duration
19799        // variant that delegates to the same shared parser). `"0.5m"`
19800        // parsed to 30s and round-tripped to `"30s"` on next emit —
19801        // DRIFT closed.
19802        let payload = format!(
19803            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
19804            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
19805            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
19806        );
19807        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
19808        let msg = err.to_string();
19809        assert!(
19810            msg.contains("not a non-negative integer"),
19811            "expected integer-magnitude diagnostic in {msg:?}"
19812        );
19813        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
19814        assert!(
19815            msg.contains("\"30s\""),
19816            "missing canonical-form remediation in {msg:?}"
19817        );
19818    }
19819
19820    #[test]
19821    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
19822        // Pin the happy-path on the cross-slot side: every canonical
19823        // author shape `render` ever emits parses cleanly through the
19824        // shared codec on the `CircuitBreaker` slot. The
19825        // codec's accepted set (post-gate) is exactly its emitted set
19826        // for the integer-magnitude class.
19827        for window_lit in ["30s", "500ms", "2m", "1h"] {
19828            let payload = format!(
19829                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
19830                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
19831                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
19832            );
19833            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
19834                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
19835            });
19836            assert_eq!(cb.max_failures, 5);
19837        }
19838    }
19839
19840    // ── rate_limit_codec: integer-magnitude gate ──
19841    //
19842    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
19843    // / 737a676 / d53c922 trajectory landed on every typed-duration /
19844    // typed-byte-size codec in caixa-core lifts onto the fifth typed
19845    // codec — `rate_limit_codec` — through the digit-only magnitude
19846    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
19847    // These tests pin the gate at the serde layer for `:politicas
19848    // :rate-limit` (the only typed slot the codec backs), and at the
19849    // codec-internal `parse` layer for the canonical positive cases.
19850
19851    #[test]
19852    fn rate_limit_serde_rejects_fractional_rate() {
19853        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
19854        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
19855        // wording, which didn't name the canonical-form remediation or
19856        // the round-trip drift the next emit would produce. Now refused
19857        // at deserialize with the canonical-form diagnostic naming the
19858        // offending `"1.5"` magnitude and the round-trip drift wording.
19859        let payload = r#"{"rateLimit":"1.5/s"}"#;
19860        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19861        let msg = err.to_string();
19862        assert!(
19863            msg.contains("not a non-negative integer"),
19864            "expected integer-magnitude diagnostic in {msg:?}"
19865        );
19866        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
19867        assert!(
19868            msg.contains("THEORY.md"),
19869            "missing render-determinism contract citation in {msg:?}"
19870        );
19871    }
19872
19873    #[test]
19874    fn rate_limit_serde_rejects_leading_plus_sign() {
19875        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
19876        // permissive-`+` parse), so `"+100/s"` silently parsed to
19877        // `RateLimit { 100, 1s }` and round-tripped through `render` to
19878        // `"100/s"` — a *different* canonical string on the next emit,
19879        // breaking the THEORY.md Part V render-determinism contract
19880        // exactly the way the peer duration codecs' `"+30s"` case did.
19881        // This is the load-bearing class the digit-only gate closes
19882        // beyond what `u32::from_str`'s strictness covers on its own.
19883        let payload = r#"{"rateLimit":"+100/s"}"#;
19884        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19885        let msg = err.to_string();
19886        assert!(
19887            msg.contains("not a non-negative integer"),
19888            "expected integer-magnitude diagnostic in {msg:?}"
19889        );
19890        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
19891    }
19892
19893    #[test]
19894    fn rate_limit_serde_rejects_leading_minus_sign() {
19895        // The signed-negative arm: `"-1/s"` lands on the
19896        // non-canonical-but-numeric branch via the `i64` fallback (the
19897        // `f64` parse also succeeds), surfacing the canonical-form
19898        // diagnostic. Replaces the prior value-laundered "not a u32"
19899        // wording with the unified diagnostic across signs.
19900        let payload = r#"{"rateLimit":"-1/s"}"#;
19901        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19902        let msg = err.to_string();
19903        assert!(
19904            msg.contains("not a non-negative integer"),
19905            "expected integer-magnitude diagnostic in {msg:?}"
19906        );
19907        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
19908    }
19909
19910    #[test]
19911    fn rate_limit_serde_rejects_decimal_shaped_integer() {
19912        // `"100.0/s"` is integer-valued numerically but not in the
19913        // codec's accepted set — `render` emits `"100/s"`, so the
19914        // round-trip would drift. Lifted to the canonical-form
19915        // diagnostic peer with the duration codec's `"1.0s"` case
19916        // (1c55a2a).
19917        let payload = r#"{"rateLimit":"100.0/s"}"#;
19918        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19919        let msg = err.to_string();
19920        assert!(
19921            msg.contains("not a non-negative integer"),
19922            "expected integer-magnitude diagnostic in {msg:?}"
19923        );
19924        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
19925    }
19926
19927    #[test]
19928    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
19929        // Non-numeric, non-digit-only input lands on the existing
19930        // narrower `"not a u32"` arm (preserved for diagnostic-shape
19931        // stability on the parser-shape footgun case). Pin this so a
19932        // future relaxation of the numeric-fallback predicate doesn't
19933        // silently collapse garbage onto the canonical-form arm — same
19934        // partition the peer duration codecs draw between
19935        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
19936        let payload = r#"{"rateLimit":"abc/s"}"#;
19937        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19938        let msg = err.to_string();
19939        assert!(
19940            msg.contains("not a u32"),
19941            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
19942        );
19943        assert!(
19944            !msg.contains("not a non-negative integer"),
19945            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
19946        );
19947    }
19948
19949    #[test]
19950    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
19951        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
19952        // u32's range. The digit-only gate passes; `u32::from_str`
19953        // fails on overflow. Surface that with the overflow-shaped
19954        // diagnostic naming the offending magnitude verbatim, peer
19955        // with `supervisor::duration_codec`'s overflow arm. Pinning
19956        // the wording so a future refactor doesn't silently collapse
19957        // overflow onto the canonical-form arm.
19958        let payload = r#"{"rateLimit":"4294967296/s"}"#;
19959        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19960        let msg = err.to_string();
19961        assert!(
19962            msg.contains("overflows u32"),
19963            "expected overflow diagnostic in {msg:?}"
19964        );
19965        assert!(
19966            msg.contains("\"4294967296\""),
19967            "missing offending magnitude in {msg:?}"
19968        );
19969    }
19970
19971    #[test]
19972    fn rate_limit_serde_rejects_leading_zero_magnitude() {
19973        // `"0100/s"` is digit-only, so the existing
19974        // non-digit-only / sign / fractional arm doesn't catch it —
19975        // `u32::from_str("0100")` returns `Ok(100)`, so before this
19976        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
19977        // round-tripped through `render` to `"100/s"` — a *different*
19978        // canonical string on the next emit, breaking the THEORY.md
19979        // Part V render-determinism contract exactly the way the
19980        // peer `"+100/s"` case did before the leading-`+` arm landed.
19981        // This is the load-bearing class the leading-zero gate closes
19982        // beyond what the existing digit-only / sign / fractional
19983        // gates cover, and the peer arm to the leading-`+` test
19984        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
19985        // canonical-form-drift axis.
19986        let payload = r#"{"rateLimit":"0100/s"}"#;
19987        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19988        let msg = err.to_string();
19989        assert!(
19990            msg.contains("non-canonical leading zero"),
19991            "expected leading-zero diagnostic in {msg:?}"
19992        );
19993        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
19994        assert!(
19995            msg.contains("THEORY.md"),
19996            "missing render-determinism contract citation in {msg:?}"
19997        );
19998    }
19999
20000    #[test]
20001    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
20002        // `"00/s"` is the degenerate leading-zero case — every byte
20003        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
20004        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
20005        // a *different* canonical string, same render-determinism
20006        // violation. The single-byte `"0/s"` itself is in the
20007        // accepted set (round-trips losslessly through `render`,
20008        // refused downstream by `PolicyRateLimitZero`); the
20009        // multi-byte `"00/s"` is not. Pins the boundary between the
20010        // accepted single-`0` and the rejected leading-zero class.
20011        let payload = r#"{"rateLimit":"00/s"}"#;
20012        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20013        let msg = err.to_string();
20014        assert!(
20015            msg.contains("non-canonical leading zero"),
20016            "expected leading-zero diagnostic in {msg:?}"
20017        );
20018        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
20019    }
20020
20021    #[test]
20022    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
20023        // Cross-window pin — the gate is window-agnostic; the
20024        // leading-zero class is a property of the magnitude, not the
20025        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
20026        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
20027        // single-window coverage extended across the three canonical
20028        // windows the codec accepts.
20029        let payload = r#"{"rateLimit":"007/h"}"#;
20030        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20031        let msg = err.to_string();
20032        assert!(
20033            msg.contains("non-canonical leading zero"),
20034            "expected leading-zero diagnostic in {msg:?}"
20035        );
20036        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
20037    }
20038
20039    #[test]
20040    fn rate_limit_serde_rejects_leading_whitespace() {
20041        // `" 100/s"` — the canonical paste-from-aligned-doc /
20042        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
20043        // the top-level `s.trim()` silently ate the leading space and
20044        // parsed the value to `RateLimit { 100, 1s }`, which then
20045        // round-tripped through `render` to `"100/s"` (a *different*
20046        // canonical string on the next emit) — the exact
20047        // canonical-form-drift class the leading-`+` / leading-zero
20048        // arms already close, extended to the whitespace byte class.
20049        let payload = r#"{"rateLimit":" 100/s"}"#;
20050        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20051        let msg = err.to_string();
20052        assert!(
20053            msg.contains("contains whitespace byte"),
20054            "expected whitespace diagnostic in {msg:?}"
20055        );
20056        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20057        assert!(
20058            msg.contains("THEORY.md"),
20059            "missing render-determinism contract citation in {msg:?}"
20060        );
20061    }
20062
20063    #[test]
20064    fn rate_limit_serde_rejects_trailing_whitespace() {
20065        // `"100/s "` — the canonical shell-history / trailing-space
20066        // paste footgun. Before this gate the top-level `s.trim()`
20067        // silently ate the trailing space and parsed to
20068        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
20069        // next emit — same canonical-form drift as the leading-space
20070        // sibling, closed on the same whitespace-byte arm.
20071        let payload = r#"{"rateLimit":"100/s "}"#;
20072        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20073        let msg = err.to_string();
20074        assert!(
20075            msg.contains("contains whitespace byte"),
20076            "expected whitespace diagnostic in {msg:?}"
20077        );
20078        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20079    }
20080
20081    #[test]
20082    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
20083        // `"100 / s"` — the canonical typographically-spaced author
20084        // shape (the same idiom every prose reference to a rate limit
20085        // renders as, mistakenly retained when the value is pasted
20086        // into a codec-shaped slot). Before this gate the per-part
20087        // `rate_str.trim()` / `unit.trim()` calls silently ate both
20088        // spaces on either side of `/` and parsed to
20089        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
20090        // codec's *internal* whitespace-tolerance vector, orthogonal
20091        // to the leading / trailing surface but the same canonical-
20092        // form-drift class. Pins the arm as strictly stronger than the
20093        // pre-existing top-level `s.trim()` behavior: it fires on
20094        // whitespace anywhere in the value, not just at the string
20095        // boundary.
20096        let payload = r#"{"rateLimit":"100 / s"}"#;
20097        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20098        let msg = err.to_string();
20099        assert!(
20100            msg.contains("contains whitespace byte"),
20101            "expected whitespace diagnostic in {msg:?}"
20102        );
20103        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20104    }
20105
20106    #[test]
20107    fn rate_limit_serde_rejects_tab_byte() {
20108        // `"\t100/s"` — the canonical paste-from-indented-doc /
20109        // paste-from-YAML-block-scalar footgun where a tab byte leads
20110        // the magnitude. Pins that the gate covers tab (`0x09`) as
20111        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
20112        // members and both would be silently swallowed by `s.trim()`
20113        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
20114        // space alone to the full ASCII-whitespace set (space `0x20`,
20115        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
20116        // the tab arm as a representative of the non-space members.
20117        let payload = r#"{"rateLimit":"\t100/s"}"#;
20118        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20119        let msg = err.to_string();
20120        assert!(
20121            msg.contains("contains whitespace byte"),
20122            "expected whitespace diagnostic in {msg:?}"
20123        );
20124        assert!(
20125            msg.contains("0x09"),
20126            "missing offending tab byte in {msg:?}"
20127        );
20128    }
20129
20130    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
20131    //
20132    // Successor to the ASCII-whitespace arm (1ad7755) on
20133    // `rate_limit_codec` — closes the strictly-complementary class the
20134    // byte-scan cannot see, through the lifted
20135    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
20136
20137    #[test]
20138    fn rate_limit_serde_rejects_leading_nbsp() {
20139        // NBSP prefix — paste-from-typography footgun. Byte-scan
20140        // misses, `str::trim` silently strips it, value drifts to
20141        // `"100/s"` on next serialize.
20142        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
20143        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20144        let msg = err.to_string();
20145        assert!(
20146            msg.contains("non-ASCII Unicode whitespace character"),
20147            "expected non-ASCII whitespace diagnostic in {msg:?}"
20148        );
20149        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
20150    }
20151
20152    #[test]
20153    fn rate_limit_serde_rejects_internal_em_space() {
20154        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
20155        // paste-from-typography footgun on the `<integer>/<unit>`
20156        // shape.
20157        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
20158        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20159        let msg = err.to_string();
20160        assert!(
20161            msg.contains("non-ASCII Unicode whitespace character"),
20162            "expected non-ASCII whitespace diagnostic in {msg:?}"
20163        );
20164        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
20165    }
20166
20167    #[test]
20168    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
20169        // Positive-control pin: every ASCII-only canonical form the
20170        // renderer emits stays accepted through the new arm.
20171        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
20172            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
20173            let p: MeshPolicy = serde_json::from_str(&payload)
20174                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
20175            assert!(p.rate_limit.is_some());
20176        }
20177    }
20178
20179    #[test]
20180    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
20181        // The boundary case — `"0/s"` is the canonical form
20182        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
20183        // it at the parse layer; the downstream
20184        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
20185        // `rate == 0` at the typed-validate layer above. Pins the
20186        // partition: the leading-zero gate at the codec layer does
20187        // not poach the rate-zero semantic-validation arm at the
20188        // typed-validate layer above (a future stricter codec must
20189        // not reject `"0/s"` here, or it'd collapse the diagnostic
20190        // partitioning that lets `PolicyRateLimitZero` name the
20191        // offending typed slot).
20192        let payload = r#"{"rateLimit":"0/s"}"#;
20193        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
20194            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
20195        });
20196        let rl = policy.rate_limit.expect("rate_limit must be Some");
20197        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
20198        assert_eq!(
20199            rl.window,
20200            Duration::from_secs(1),
20201            "single-`0` magnitude with `s` unit must parse to window=1s"
20202        );
20203    }
20204
20205    #[test]
20206    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
20207        // The complementary boundary pin — every magnitude
20208        // `render` emits starts with `[1-9]` (or is the single byte
20209        // `"0"`), so the canonical-form predicate is `(len == 1) ||
20210        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
20211        // '1'` case explicitly so a future tightening of the gate
20212        // (e.g. an over-eager "no leading digit < 5" rule, or a
20213        // mistakenly anchored start-of-magnitude byte check) lands
20214        // here before the canonical-forms-iterating test would catch
20215        // it.
20216        let payload = r#"{"rateLimit":"100/s"}"#;
20217        let policy: MeshPolicy = serde_json::from_str(payload)
20218            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
20219        let rl = policy.rate_limit.expect("rate_limit must be Some");
20220        assert_eq!(
20221            rl.rate, 100,
20222            "canonical-100 magnitude must parse to rate=100"
20223        );
20224    }
20225
20226    #[test]
20227    fn rate_limit_serde_accepts_integer_canonical_forms() {
20228        // Pin the happy-path: every canonical author shape `render`
20229        // ever emits parses cleanly through the codec post-gate. The
20230        // codec's accepted set (post-gate) is exactly its emitted set
20231        // for the integer-magnitude class — same property
20232        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
20233        // gates guarantee on the peer codecs. Iterating across rate
20234        // magnitudes (including `"0"`, which the codec accepts even
20235        // though `validate_politicas` rejects `rate == 0` at the typed
20236        // layer above) closes the codec contract at the parse layer
20237        // independently of the validate layer.
20238        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
20239            for unit_lit in ["s", "m", "h"] {
20240                let lit = format!("{rate_lit}/{unit_lit}");
20241                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
20242                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
20243                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
20244                });
20245                let rl = policy.rate_limit.expect("rate_limit must be Some");
20246                assert_eq!(
20247                    rl.rate,
20248                    rate_lit.parse::<u32>().unwrap(),
20249                    "rate mismatch for {lit:?}"
20250                );
20251            }
20252        }
20253    }
20254
20255    #[test]
20256    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
20257        // The structural property the gate enforces: serialize ∘
20258        // deserialize is the identity on every canonical author shape.
20259        // Peer of `parse_byte_size`'s and `parse_duration`'s
20260        // `_round_trips_through_render_for_every_canonical_form` tests
20261        // on the rate-limit axis. Before the gate, `"+100/s"` violated
20262        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
20263        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
20264        for rate in [1u32, 100, 5000, 1_000_000] {
20265            for (window, unit) in [
20266                (Duration::from_secs(1), "s"),
20267                (Duration::from_secs(60), "m"),
20268                (Duration::from_secs(3600), "h"),
20269            ] {
20270                let policy = MeshPolicy {
20271                    rate_limit: Some(RateLimit { rate, window }),
20272                    ..Default::default()
20273                };
20274                let json = serde_json::to_string(&policy).unwrap();
20275                let expected = format!("\"{rate}/{unit}\"");
20276                assert!(
20277                    json.contains(&expected),
20278                    "expected {expected:?} in {json:?}"
20279                );
20280                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20281                assert_eq!(
20282                    back.rate_limit, policy.rate_limit,
20283                    "round-trip for {json:?}"
20284                );
20285            }
20286        }
20287    }
20288
20289    // ── self-membership cross-slot gate ──────────────────────────────
20290
20291    #[test]
20292    fn validate_no_self_membership_rejects_self_named_membro() {
20293        // An Aplicacao whose `:membros` lists its own `:nome` is a
20294        // one-node lacre-closure recursion — rejected, naming the parent.
20295        let membros = vec![
20296            membro("catalog", "^0.1"),
20297            membro("checkout", "^0.1"),
20298            membro("cart", "^0.1"),
20299        ];
20300        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
20301        assert!(
20302            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
20303            "got {err:?}"
20304        );
20305    }
20306
20307    #[test]
20308    fn validate_no_self_membership_accepts_distinct_membros() {
20309        // Positive control: distinct member names (including a member
20310        // that is itself an Aplicacao — recursive composition is valid,
20311        // MESH-COMPOSITION §V) pass the gate.
20312        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
20313        validate_no_self_membership(&membros, "checkout").unwrap();
20314    }
20315
20316    #[test]
20317    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
20318        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
20319        // `NoMembros` arm (the more-fundamental "graph must have nodes"
20320        // gate), not by this cross-slot self-edge gate. Keeping the
20321        // self-membership predicate vacuously-ok on the empty input
20322        // matches its supervisor-axis peer
20323        // (`validate_no_self_supervision_empty_children_is_ok`) and
20324        // makes the gate composable from any future call site (an M4
20325        // CR materializer's per-membros validator) without re-checking
20326        // emptiness.
20327        validate_no_self_membership(&[], "checkout").unwrap();
20328    }
20329
20330    #[test]
20331    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
20332        // Pinning the Display: the self-membership diagnostic must name
20333        // the offending caixa verbatim + the "lists itself" framing the
20334        // author can grep for, so the cluster-far failure surfaces at
20335        // build time with one-line remediation. Same diagnostic shape
20336        // as the supervisor-axis `ChildSupervisesSelf` peer.
20337        let membros = vec![membro("orquestra", "^0.1")];
20338        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
20339        let msg = err.to_string();
20340        assert!(
20341            msg.contains("orquestra"),
20342            "diagnostic must name the offending caixa nome (got: {msg:?})"
20343        );
20344        assert!(
20345            msg.contains("lists itself"),
20346            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
20347        );
20348    }
20349
20350    #[test]
20351    fn default_servico_port_constant_pins_canonical_8080_literal() {
20352        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
20353        // at the verbatim `8080` literal both consumers (the
20354        // `Entrada::port` serde default via [`default_port`] and the
20355        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
20356        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
20357        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
20358        // discipline (a085b26) on the per-renderer canonical-K8s-axis
20359        // string-constant axis: a future refactor that drifts the
20360        // constant out from under either consumer surfaces here ahead
20361        // of every per-renderer's first emission. The literal value
20362        // matches the well-known HTTP-alt port the `pleme-computeunit`
20363        // library chart already emits as its `trigger.service.port`
20364        // default — by construction the same value the substrate
20365        // assumes about every Servico's in-cluster L4 listener.
20366        assert_eq!(
20367            DEFAULT_SERVICO_PORT, 8080,
20368            "canonical Servico port literal must remain `8080` verbatim — \
20369             this is the value both the `Entrada::port` serde default and the \
20370             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
20371        );
20372    }
20373
20374    #[test]
20375    fn default_port_helper_returns_canonical_servico_port_constant() {
20376        // The bridge-arm — pins that the [`default_port`] helper
20377        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
20378        // attribute hooks routes through the lifted
20379        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
20380        // literal. A future refactor that re-introduces the `8080`
20381        // literal at the helper's return site (silently re-opening
20382        // the drift footgun this lift closed) surfaces here ahead of
20383        // every author-side `(:entrada (:host … :para …))` slot
20384        // without an explicit `:port`. Peer with the
20385        // `default_namespace_re_export_points_at_caixa_core_canonical`
20386        // pin on the caixa-mesh-side re-export axis.
20387        assert_eq!(
20388            default_port(),
20389            DEFAULT_SERVICO_PORT,
20390            "the serde-default helper must route through the lifted constant"
20391        );
20392    }
20393
20394    #[test]
20395    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
20396        // The end-to-end pin — an author-surface `(:entrada (:host …
20397        // :para …))` without an explicit `:port` slot deserializes to
20398        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
20399        // verbatim. Routes the canonical lifted constant through both
20400        // the serde-default machinery (the `#[serde(default =
20401        // "default_port")]` attribute) and the typed-value-shape
20402        // contract (the resulting [`Entrada::port`] value). A future
20403        // refactor that drifts either axis — replacing the serde
20404        // hook's helper, changing the typed slot's wire shape — would
20405        // surface here before any per-renderer's CNP / Gateway /
20406        // HTTPRoute emission consumed the drifted default.
20407        let entrada: Entrada =
20408            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
20409        assert_eq!(
20410            entrada.port, DEFAULT_SERVICO_PORT,
20411            "the serde default must materialize as the lifted canonical Servico port"
20412        );
20413    }
20414
20415    #[test]
20416    fn servico_port_min_pins_canonical_accept_set_floor() {
20417        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
20418        // verbatim `1` literal every typed `:entrada :port` acceptance
20419        // gate keys off. Peer with the
20420        // [`default_servico_port_constant_pins_canonical_8080_literal`]
20421        // discipline on the canonical-Servico-port-constant axis: a
20422        // future refactor that drifts the accept-set floor out from
20423        // under the sole consumer at [`AplicacaoSpec::validate`]'s
20424        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
20425        // every per-`:entrada` `EntradaPortZero` diagnostic. The
20426        // literal value matches the IANA-registered TCP/UDP port
20427        // space floor (`1..=65535` — port `0` is the "any ephemeral"
20428        // sentinel, not a well-defined destination the substrate's
20429        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
20430        // axis can honor).
20431        assert_eq!(
20432            SERVICO_PORT_MIN, 1,
20433            "canonical Servico port accept-set floor must remain `1` verbatim — \
20434             this is the value the `AplicacaoSpec::validate` gate at \
20435             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
20436        );
20437    }
20438
20439    #[test]
20440    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
20441        // The cross-const invariant pin — the substrate's canonical
20442        // default port must satisfy its own accept-set floor by
20443        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
20444        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
20445        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
20446        // override the operator pins through a future
20447        // `:placement :default-port` slot that lands out-of-range, a
20448        // per-edition Servico-port migration that lifted the floor
20449        // above the previous default without coordinating the pair —
20450        // would silently invalidate the serde-default emission at
20451        // every author-side `(:entrada (:host … :para …))` slot
20452        // without an explicit `:port`: the default port would fall
20453        // below the accept-set floor, the `AplicacaoSpec::validate`
20454        // gate would reject every default-carrying Aplicacao as
20455        // `EntradaPortZero`, and the substrate's typed
20456        // `(defcaixa … :kind Aplicacao)` surface would fail validate
20457        // on every Aplicacao whose author omitted `:entrada :port`
20458        // for the substrate's chosen default — a class of authoring-
20459        // surface footguns the compile-time pin structurally closes.
20460        // Peer with the
20461        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
20462        // (27f9b34) cross-const invariant pin discipline on the peer
20463        // canonical-Helm-per-values-block child-chart-enablement-toggle
20464        // axis pair.
20465        assert!(
20466            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
20467            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
20468             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
20469             every default-carrying `(:entrada (:host … :para …))` slot without an \
20470             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
20471             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
20472        );
20473    }
20474
20475    #[test]
20476    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
20477        // The gate-site pin — asserts the `AplicacaoSpec::validate`
20478        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
20479        // `EntradaPortZero` diagnostic on the below-floor input
20480        // `port: 0` (the only below-floor value the `u16` field can
20481        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
20482        // is the singleton `{0}`). A future refactor that drifts the
20483        // gate off the lifted const (silently re-introducing an
20484        // inline `if e.port == 0` byte-check) surfaces here — the
20485        // pin cannot distinguish `< 1` from `== 0` on the current
20486        // floor, but it *does* pin that the diagnostic fires on `0`
20487        // through whichever gate is wired, so any future accept-set
20488        // floor migration (a hypothetical unprivileged-only
20489        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
20490        // update this test alongside the const declaration —
20491        // structurally guaranteeing the gate + accept-set + pin
20492        // trio move together. Peer with the
20493        // [`rejects_zero_entrada_port`] behavioral pin on the same
20494        // per-`:entrada :port` axis — that pin asserts the pre-lift
20495        // behavioral contract (`port: 0` → `EntradaPortZero`); this
20496        // pin adds the structural link to the lifted floor const.
20497        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
20498        let mut s = three_member_spec();
20499        s.entrada.as_mut().unwrap().port = 0;
20500        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
20501    }
20502
20503    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
20504
20505    #[test]
20506    fn membro_serde_keys_match_lifted_membro_key_consts() {
20507        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
20508        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
20509        // name the exact camelCase JSON keys the
20510        // `#[serde(rename_all = "camelCase")]` attribute on
20511        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
20512        // that each canonical byte-sequence appears verbatim in the
20513        // JSON — a future accidental `rename_all = "snake_case"` /
20514        // `"kebab-case"` / verbatim-field-name flip at the derive
20515        // attribute (any of which would silently break every downstream
20516        // JSON consumer that reaches for one of the two consts via
20517        // `Value::get(...)`) surfaces here as a build-time test failure
20518        // at `aplicacao.rs`, not as an apply-time
20519        // `.get(<stale-canonical-const>)` returning `None` far from the
20520        // derive-attr drift's commit. Peer with the sibling
20521        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
20522        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
20523        // same discipline the SupervisorSpec top-level lift established,
20524        // extended here to the M3 [`Membro`] per-`:membros` axis.
20525        let m = Membro {
20526            caixa: "catalog".into(),
20527            versao: "^0.1".into(),
20528        };
20529        let json = serde_json::to_string(&m).unwrap();
20530        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
20531            let quoted = format!("\"{key}\"");
20532            assert!(
20533                json.contains(&quoted),
20534                "serialized Membro must carry the lifted MEMBRO_KEY_* \
20535                 byte-sequence {quoted} verbatim in the JSON emission \
20536                 (got: {json})",
20537            );
20538        }
20539    }
20540
20541    #[test]
20542    fn membro_key_consts_are_pairwise_distinct() {
20543        // Cross-axis drift-detection pin: a future collapse of the two
20544        // canonical [`Membro`] per-entry byte-strings onto the same
20545        // value (e.g. an accidental copy-paste flip of
20546        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
20547        // silently reroute every downstream probe on one axis onto the
20548        // sibling axis's overlay entry and pass every propagation-probe
20549        // test that expected only the stale axis's value. Peer of the
20550        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
20551        // (40cc4e5).
20552        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
20553        for (i, a) in all.iter().enumerate() {
20554            for b in all.iter().skip(i + 1) {
20555                assert_ne!(
20556                    a, b,
20557                    "MEMBRO_KEY_* consts must be pairwise-distinct \
20558                     canonical byte-sequences — got `{a}` == `{b}`",
20559                );
20560            }
20561        }
20562    }
20563
20564    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
20565    //    URL-path fallback resolver every HTTPRoute-aware renderer
20566    //    reaching for a per-rule path-list resolution routes through.
20567    //    The four pin tests below fix the four-way accept-set the
20568    //    resolver must always honor: (:paths-non-empty-verbatim,
20569    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
20570    //    :paths-preserves-order-across-multiple-entries) — drift on any
20571    //    arm surfaces at caixa-core build time rather than at cluster-
20572    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
20573    //    sibling `:politicas` typed-primitive dispatch axis.
20574
20575    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
20576        Entrada {
20577            host: "example.com".into(),
20578            para: "cart".into(),
20579            paths: paths.into_iter().map(String::from).collect(),
20580            port: DEFAULT_SERVICO_PORT,
20581        }
20582    }
20583
20584    #[test]
20585    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
20586        // The typed `:entrada :paths` slot carries an author-declared
20587        // list — the resolver returns each entry verbatim, no
20588        // catch-all substitution. The canonical "author declared
20589        // paths, honor them verbatim" arm of the path-list dispatch.
20590        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
20591        assert_eq!(
20592            e.resolved_paths(),
20593            vec!["/api/cart", "/api/products"],
20594            "resolved_paths must return each `:entrada :paths` entry \
20595             verbatim when the typed slot is non-empty (got {:?})",
20596            e.resolved_paths(),
20597        );
20598    }
20599
20600    #[test]
20601    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
20602        // Empty `:entrada :paths` slot — the resolver substitutes the
20603        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
20604        // catch-all fallback verbatim. Pins the empty-arm of the
20605        // resolver's four-way accept-set against a future silent
20606        // detour that returned an empty Vec (which would emit an
20607        // HTTPRoute with zero rules — silently dropping every
20608        // external `:entrada` flow at admission time), routed to a
20609        // different fallback shape, or dropped the catch-all
20610        // altogether.
20611        let e = entrada_with_paths(vec![]);
20612        assert_eq!(
20613            e.resolved_paths(),
20614            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
20615            "resolved_paths on empty `:entrada :paths` must fall back \
20616             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
20617             all — got {:?}",
20618            e.resolved_paths(),
20619        );
20620    }
20621
20622    #[test]
20623    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
20624        // Single-entry `:entrada :paths` — the resolver returns the
20625        // single declared path verbatim, NOT the catch-all fallback
20626        // (author declared a path, honor it — the empty-arm and the
20627        // len-1 arm are semantically distinct axes of the resolver's
20628        // accept-set). Pins that the resolver treats "author declared
20629        // one path" as authored input, not as the empty case.
20630        let e = entrada_with_paths(vec!["/api/only"]);
20631        assert_eq!(
20632            e.resolved_paths(),
20633            vec!["/api/only"],
20634            "resolved_paths on single-entry `:entrada :paths` must \
20635             return the declared path verbatim, NOT the catch-all \
20636             fallback (got {:?})",
20637            e.resolved_paths(),
20638        );
20639    }
20640
20641    #[test]
20642    fn resolved_paths_preserves_author_declared_order() {
20643        // The `:entrada :paths` list is author-ordered — the resolver
20644        // preserves the author's declaration order verbatim, since
20645        // per-rule dispatch order at the K8s Gateway API HTTPRoute
20646        // consumer is significant (first-match-wins under the
20647        // path-prefix matcher). Pins against a future silent
20648        // re-sort / dedup / normalize detour that reordered author
20649        // input.
20650        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
20651        assert_eq!(
20652            e.resolved_paths(),
20653            vec!["/z/last", "/a/first", "/m/mid"],
20654            "resolved_paths must preserve author-declared `:entrada \
20655             :paths` order verbatim — got {:?}",
20656            e.resolved_paths(),
20657        );
20658    }
20659
20660    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
20661    //    slot `&[String]` slice accessor every per-`:entrada` consumer
20662    //    that must see the author's declaration verbatim (not the
20663    //    fallback-applied projection the sibling `resolved_paths`
20664    //    returns) routes through. The three pin tests below fix the
20665    //    accept-set the accessor must honor: (:non-empty-byte-equal,
20666    //    :empty-projects-empty-slice, :preserves-author-declared-order)
20667    //    — drift on any arm surfaces at caixa-core build time rather
20668    //    than at cluster-apply time. Peer discipline with the sibling
20669    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
20670    //    peer M3 mesh-slot `Vec<String>`-carry axis.
20671
20672    #[test]
20673    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
20674        // Byte-equal pin: [`Entrada::paths`] must project the raw
20675        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
20676        // slice borrowed from the typed slot's own [`Vec<String>`]
20677        // storage — no re-ordering, no dedup, no per-entry normalization,
20678        // no fallback substitution (the fallback-applying projection is
20679        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
20680        // a future silent detour that re-normalized the list, dropped
20681        // duplicates the [`AplicacaoSpec::validate`]
20682        // `EntradaPathDuplicate` refusal already rejects at build time,
20683        // or (most severe) accidentally routed through the fallback-
20684        // applying sibling and returned the substrate catch-all when
20685        // the author declared an empty list — collapsing the raw-slot
20686        // and fallback-applied axes into one and breaking the
20687        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
20688        //
20689        // Peer of the sibling
20690        // [`Placement::clusters`]-shape byte-equal pin
20691        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20692        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
20693        let fixtures: Vec<Vec<String>> = vec![
20694            Vec::new(),
20695            vec!["/api/cart".into()],
20696            vec!["/api/cart".into(), "/api/products".into()],
20697            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
20698        ];
20699        for paths in fixtures {
20700            let e = Entrada {
20701                host: "example.com".into(),
20702                para: "cart".into(),
20703                paths: paths.clone(),
20704                port: DEFAULT_SERVICO_PORT,
20705            };
20706            assert_eq!(
20707                e.paths(),
20708                paths.as_slice(),
20709                "Entrada::paths must return :entrada :paths verbatim \
20710                 (got {:?}, expected {:?})",
20711                e.paths(),
20712                paths.as_slice(),
20713            );
20714            assert_eq!(
20715                e.paths(),
20716                e.paths.as_slice(),
20717                "Entrada::paths accessor and .paths.as_slice() field \
20718                 access must byte-equal — the accessor is the substrate-\
20719                 primitive typed dispatch every downstream per-`:entrada` \
20720                 raw-slot path-list consumer must route through",
20721            );
20722            assert_eq!(
20723                e.paths().len(),
20724                e.paths.len(),
20725                "Entrada::paths().len() must byte-equal self.paths.len() \
20726                 — a length drift would silently split the paired \
20727                 pre-flight cascade-head `.is_empty()` probe input in \
20728                 the sibling [`Entrada::resolved_paths`] resolver from \
20729                 the per-entry validate loop's traversal input in \
20730                 [`AplicacaoSpec::validate`]",
20731            );
20732        }
20733    }
20734
20735    #[test]
20736    fn resolved_paths_reads_through_lifted_paths_accessor() {
20737        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
20738        // pre-flight `.paths().is_empty()` cascade-head probe (which
20739        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
20740        // catch-all fallback arm when the accessor projects the empty
20741        // slice) and the per-entry `.paths().iter().map(String::as_str)`
20742        // projection (which must reach every entry in the same order
20743        // the accessor projects, so the sibling
20744        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
20745        // per-entry projection stay in lockstep by construction) must
20746        // both key off the lifted accessor. Pins the two-site coherence
20747        // by exercising each production consumer end-to-end: (1) the
20748        // catch-all-fallback arm under the empty slice, (2) the
20749        // author-declared-verbatim arm under a two-entry cohort whose
20750        // per-entry projection must byte-equal the input's per-entry
20751        // author-declared paths in the author's declared order.
20752        //
20753        // Peer of the sibling M3
20754        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
20755        // `validate_placement_reads_through_lifted_clusters_accessor`
20756        // on the sibling `Placement::clusters` reader-site convergence.
20757        let empty = entrada_with_paths(vec![]);
20758        assert_eq!(
20759            empty.resolved_paths(),
20760            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
20761            "resolved_paths on empty :entrada :paths must trip the \
20762             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
20763             catch-all fallback — routing through the lifted paths() \
20764             accessor must not silently drop the fallback arm",
20765        );
20766
20767        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
20768        assert_eq!(
20769            declared.resolved_paths(),
20770            vec!["/api/cart", "/api/products"],
20771            "resolved_paths on non-empty :entrada :paths must return each \
20772             entry verbatim in the author's declared order — routing \
20773             through the lifted paths() accessor must not silently \
20774             reorder or drop entries",
20775        );
20776        // Byte-equal pin against the raw-slot accessor to keep the
20777        // fallback-applying resolver's per-entry projection input in
20778        // lockstep with the raw-slot accessor's projection.
20779        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
20780        assert_eq!(
20781            declared.resolved_paths(),
20782            raw_projected,
20783            "resolved_paths non-empty projection must byte-equal the \
20784             lifted paths() accessor's per-entry String::as_str projection \
20785             — the two projections share the same input slice by \
20786             construction, so any drift here would surface a silent \
20787             re-ordering / dedup / normalization detour in the resolver",
20788        );
20789    }
20790
20791    #[test]
20792    fn validate_reads_through_lifted_entrada_paths_accessor() {
20793        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
20794        // per-entry value-shape gate's `for p in e.paths()` traversal
20795        // (which must reach every entry in the same order the accessor
20796        // projects, so both the per-entry `EntradaPathEmpty` /
20797        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
20798        // the duplicate-detection HashSet insert that trips
20799        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
20800        // projection) must route through the lifted accessor. Pins the
20801        // coherence by exercising each production consumer end-to-end:
20802        // (1) the `EntradaPathEmpty` refusal fires on the second entry
20803        // of a two-entry cohort whose head is valid but tail is empty
20804        // (which requires the loop to reach the second entry through
20805        // the accessor), and (2) the `EntradaPathDuplicate` refusal
20806        // fires on the second entry of a two-entry cohort that shares
20807        // a path (which requires the loop to reach both entries — a
20808        // first-entry-only projection would silently pass since the
20809        // dedup HashSet has room for the first insert).
20810        //
20811        // Peer of the sibling
20812        // `validate_placement_reads_through_lifted_clusters_accessor`
20813        // on the sibling `Placement::clusters` reader-site convergence.
20814        let base = crate::AplicacaoSpec {
20815            membros: vec![crate::Membro {
20816                caixa: "cart".into(),
20817                versao: "^0.1".into(),
20818            }],
20819            contratos: Vec::new(),
20820            politicas: crate::MeshPolicy::default(),
20821            placement: crate::Placement {
20822                estrategia: crate::PlacementStrategy::SingleNode,
20823                clusters: vec!["rio".into()],
20824                shard_key: None,
20825                affinity: None,
20826            },
20827            entrada: Some(Entrada {
20828                host: "example.com".into(),
20829                para: "cart".into(),
20830                paths: vec!["/api/cart".into(), String::new()],
20831                port: DEFAULT_SERVICO_PORT,
20832            }),
20833        };
20834        assert_eq!(
20835            base.validate(),
20836            Err(crate::AplicacaoError::EntradaPathEmpty),
20837            "validate must trip EntradaPathEmpty on the second entry of \
20838             a two-entry cohort — routing through the lifted paths() \
20839             accessor must not silently short-circuit the loop at the \
20840             valid head entry",
20841        );
20842
20843        let mut dup = base;
20844        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
20845        assert_eq!(
20846            dup.validate(),
20847            Err(crate::AplicacaoError::EntradaPathDuplicate {
20848                path: "/api/cart".into(),
20849            }),
20850            "validate must trip EntradaPathDuplicate on the second entry \
20851             of a two-entry cohort that shares a path — routing through \
20852             the lifted paths() accessor must not silently short-circuit \
20853             the dedup HashSet insert at the first entry",
20854        );
20855    }
20856
20857    // ── Entrada::hostname / Entrada::hostnames — the substrate-
20858    //    canonical per-`:entrada` DNS-hostname resolver pair every
20859    //    Gateway-API-aware renderer reaching for a per-listener
20860    //    singular `hostname:` filter (Gateway) or a per-route plural
20861    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
20862    //    The three pin tests below fix the two-way accept-set the pair
20863    //    must always honor: (:singular-byte-equal-to-host,
20864    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
20865    //    on any arm surfaces at caixa-core build time rather than at
20866    //    cluster-apply time when the API server refuses the HTTPRoute
20867    //    for non-intersecting hostname filters. Peer discipline with
20868    //    the sibling `resolved_paths` accept-set pin block above on the
20869    //    per-`:entrada` path-list resolver axis.
20870
20871    fn entrada_with_host(host: &str) -> Entrada {
20872        Entrada {
20873            host: host.into(),
20874            para: "cart".into(),
20875            paths: Vec::new(),
20876            port: DEFAULT_SERVICO_PORT,
20877        }
20878    }
20879
20880    #[test]
20881    fn hostname_returns_entrada_host_byte_equal() {
20882        // The canonical singular-axis pin: [`Entrada::hostname`] must
20883        // return the `:entrada :host` field byte-for-byte, borrowed
20884        // from the typed slot's own [`String`] storage. Pins against a
20885        // future silent detour that re-normalized the host (an
20886        // accidental `.to_lowercase()` — validate_entrada_host already
20887        // enforces lowercase, so any re-normalization is redundant + a
20888        // drift surface between the validator and the accessor), a
20889        // trailing-`.` fully-qualified DNS shape substitution, or a
20890        // Punycode round-trip that lowered a Unicode host through IDNA.
20891        let e = entrada_with_host("checkout.quero.cloud");
20892        assert_eq!(
20893            e.hostname(),
20894            "checkout.quero.cloud",
20895            "Entrada::hostname must return :entrada :host verbatim \
20896             (got {:?})",
20897            e.hostname(),
20898        );
20899        assert_eq!(
20900            e.hostname(),
20901            e.host.as_str(),
20902            "Entrada::hostname must byte-equal the .host field access",
20903        );
20904    }
20905
20906    #[test]
20907    fn hostnames_returns_singleton_of_hostname_accessor() {
20908        // The pair-invariant pin: [`Entrada::hostnames`] must always
20909        // return exactly `vec![hostname()]` — the singleton list whose
20910        // sole entry is the substrate's canonical per-`:entrada`
20911        // singular hostname. Pins the two-consumer coherence axis: the
20912        // Gateway listener's singular `hostname:` filter and the
20913        // HTTPRoute's plural `spec.hostnames[]` filter list must
20914        // agree, else the Gateway API v1.x conformance layer rejects
20915        // the HTTPRoute at attach time with
20916        // `Accepted:False/NoMatchingParent` (the parent Gateway's
20917        // listener hostname doesn't intersect the route's hostname
20918        // filter list) — a divergence whose apply-time symptom is far
20919        // from any single-site commit and never surfaces in the
20920        // emitted YAML. Pinning the pair-invariant here makes any
20921        // future accidental split (an accidental `.to_string() + "."`
20922        // trailing-`.` on the plural side that didn't land on the
20923        // singular side, an accidental prefix stripping on one axis,
20924        // an accidental wildcard prepend the SNI fan-out overlay
20925        // authors on the plural side without a paired singular
20926        // migration) trip at caixa-core build time.
20927        let e = entrada_with_host("checkout.quero.cloud");
20928        assert_eq!(
20929            e.hostnames(),
20930            vec![e.hostname()],
20931            "Entrada::hostnames must return `vec![hostname()]` under \
20932             the pair-invariant — got {:?} vs. singleton {:?}",
20933            e.hostnames(),
20934            vec![e.hostname()],
20935        );
20936    }
20937
20938    #[test]
20939    fn hostnames_is_singleton_under_single_host_author_surface() {
20940        // The singleton-shape pin: under today's single-hostname-per-
20941        // `:entrada` author surface (the `:host` slot is a single
20942        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
20943        // must always return a list of length exactly one. Pins
20944        // against a future silent detour that returned an empty list
20945        // (which would emit an HTTPRoute with `spec.hostnames: []` —
20946        // matching every incoming Host header regardless of the
20947        // Aplicacao's declared ingress apex, silently over-matching
20948        // every foreign VirtualHost the parent Gateway also fronts) or
20949        // a duplicated entry (which the Gateway API v1.x parser
20950        // accepts as a `[]-length-2 list of equal hostnames]` but
20951        // whose semantics differ from the intended singleton). The
20952        // author-surface extension point ("a future `:entrada
20953        // :alt-hosts` list overlay" the docstring names) is the sole
20954        // future axis that flips this pin — that migration will re-
20955        // author this test to pin the new plural cardinality.
20956        let e = entrada_with_host("checkout.quero.cloud");
20957        assert_eq!(
20958            e.hostnames().len(),
20959            1,
20960            "Entrada::hostnames must be a singleton under today's \
20961             single-hostname-per-`:entrada` author surface — got \
20962             length {}: {:?}",
20963            e.hostnames().len(),
20964            e.hostnames(),
20965        );
20966    }
20967
20968    // ── Entrada::destination — the substrate-canonical per-`:entrada`
20969    //    destination-Servico scalar accessor every Gateway-API
20970    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
20971    //    discriminator arg (HTTPRoute name composer) or a per-rule
20972    //    `backendRefs[0].name` axis routes through. The two pin tests
20973    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
20974    //    either arm surfaces at caixa-core build time rather than at
20975    //    cluster-apply time when an HTTPRoute's `metadata.name` and
20976    //    `backendRefs[]` silently disagree on which destination Servico
20977    //    the ingress fronts. Peer discipline with the sibling
20978    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
20979    //    blocks above on the per-`:entrada` path-list / DNS-hostname
20980    //    resolver axes.
20981
20982    #[test]
20983    fn destination_returns_entrada_para_byte_equal() {
20984        // The canonical destination-scalar pin: [`Entrada::destination`]
20985        // must return the `:entrada :para` field byte-for-byte, borrowed
20986        // from the typed slot's own [`String`] storage. Pins against a
20987        // future silent detour that re-normalized the destination (an
20988        // accidental `.to_lowercase()` — the destination Servico is
20989        // already validated as a DNS-1123 label upstream, so any
20990        // re-normalization is redundant + a drift surface between the
20991        // validator and the accessor), a namespace-prefix rewrite (an
20992        // accidental `format!("{namespace}/{para}")` per-CR fully-
20993        // qualified rewrite that didn't land on the peer axis), or a
20994        // per-cluster suffix stamp the operator authors on one
20995        // consumer without the other.
20996        for para in ["cart", "checkout", "catalog", "orders-v2"] {
20997            let e = Entrada {
20998                host: "checkout.quero.cloud".into(),
20999                para: para.into(),
21000                paths: Vec::new(),
21001                port: DEFAULT_SERVICO_PORT,
21002            };
21003            assert_eq!(
21004                e.destination(),
21005                para,
21006                "Entrada::destination must return :entrada :para verbatim \
21007                 (got {:?}, expected {para:?})",
21008                e.destination(),
21009            );
21010            assert_eq!(
21011                e.destination(),
21012                e.para.as_str(),
21013                "Entrada::destination must byte-equal the .para field access",
21014            );
21015        }
21016    }
21017
21018    #[test]
21019    fn destination_borrows_from_entrada_para_storage() {
21020        // The borrow-not-copy pin: [`Entrada::destination`] must
21021        // return a `&str` slice that borrows from the typed slot's
21022        // own [`String`] storage — same-address invariant with
21023        // `entrada.para.as_str()`. Pins against a future silent detour
21024        // that allocated a fresh `String` (`self.para.clone()` in the
21025        // body would type-check but silently drop the borrow, and
21026        // every downstream consumer that assumed the returned slice
21027        // outlives `&self` would break on a stale-reference use-after-
21028        // free). Peer with the sibling `hostname_returns_entrada_
21029        // host_byte_equal` on the singular-DNS-hostname axis.
21030        let e = entrada_with_host("checkout.quero.cloud");
21031        let dest = e.destination();
21032        let para_slice = e.para.as_str();
21033        assert_eq!(
21034            dest.as_ptr(),
21035            para_slice.as_ptr(),
21036            "Entrada::destination must borrow from the .para String's \
21037             backing storage — a fresh allocation here means the \
21038             accessor no longer names the substrate-primitive typed \
21039             dispatch and every downstream consumer would silently \
21040             carry a detached copy",
21041        );
21042        assert_eq!(
21043            dest.len(),
21044            para_slice.len(),
21045            "Entrada::destination and .para.as_str() must byte-equal in \
21046             length as well as in address",
21047        );
21048    }
21049
21050    #[test]
21051    fn port_returns_entrada_port_verbatim_across_permutations() {
21052        // The canonical L4-port-scalar pin: [`Entrada::port`] must
21053        // return the `:entrada :port` field verbatim as a `u16` across
21054        // every author-declared value in the validated accept-set
21055        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
21056        // silent detour that clamped the port (an accidental
21057        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
21058        // land on the peer [`AplicacaoSpec::port_for_destination`]
21059        // resolver), rewrote it through a per-cluster port-remap table
21060        // the operator authors on one consumer without the other, or
21061        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
21062        // serde-default value (which would silently collapse the
21063        // distinction between "author explicitly declared `:port 8080`"
21064        // and "author omitted the slot and inherited the default" the
21065        // future per-cluster override slot depends on). Peer with the
21066        // sibling `destination_returns_entrada_para_byte_equal` +
21067        // `hostname_returns_entrada_host_byte_equal` pins on the
21068        // per-`:entrada` `&str` scalar axes.
21069        for port in [
21070            SERVICO_PORT_MIN,
21071            DEFAULT_SERVICO_PORT,
21072            8443u16,
21073            9090u16,
21074            u16::MAX,
21075        ] {
21076            let e = Entrada {
21077                host: "checkout.quero.cloud".into(),
21078                para: "cart".into(),
21079                paths: Vec::new(),
21080                port,
21081            };
21082            assert_eq!(
21083                e.port(),
21084                port,
21085                "Entrada::port must return :entrada :port verbatim \
21086                 (got {}, expected {port})",
21087                e.port(),
21088            );
21089            assert_eq!(
21090                e.port(),
21091                e.port,
21092                "Entrada::port accessor and .port field access must \
21093                 byte-equal — the accessor is the substrate-primitive \
21094                 typed dispatch every downstream L4-port consumer must \
21095                 route through",
21096            );
21097        }
21098    }
21099
21100    #[test]
21101    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
21102        // Two-consumer coherence pin: the
21103        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
21104        // (which reads through [`Entrada::port`] to compare against
21105        // [`SERVICO_PORT_MIN`]) and the
21106        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
21107        // through [`Entrada::port`] to emit the per-destination
21108        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
21109        // lifted accessor, so any future rebrand on the typed slot's
21110        // reader shape lands at exactly one place. Pins the two-site
21111        // coherence by exercising a below-floor port through validate
21112        // (which must reject) and a validated in-accept-set port through
21113        // port_for_destination (which must emit the same value the
21114        // accessor returns).
21115        let mut spec = three_member_spec();
21116        if let Some(e) = spec.entrada.as_mut() {
21117            e.port = 0;
21118        }
21119        assert_eq!(
21120            spec.validate().unwrap_err(),
21121            AplicacaoError::EntradaPortZero,
21122            "validate must reject `:entrada :port 0` through the lifted \
21123             Entrada::port accessor — port zero lies below \
21124             SERVICO_PORT_MIN and the validator routes through port() \
21125             to name the floor",
21126        );
21127
21128        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
21129            let mut spec = three_member_spec();
21130            if let Some(e) = spec.entrada.as_mut() {
21131                e.port = port;
21132            }
21133            spec.validate().expect(
21134                "entrada with in-accept-set :port must validate — the \
21135                 structural-floor gate reads through Entrada::port",
21136            );
21137            let entrada_ref = spec.entrada().expect(":entrada present");
21138            assert_eq!(
21139                spec.port_for_destination(entrada_ref.destination()),
21140                entrada_ref.port(),
21141                "port_for_destination(entrada.destination()) must equal \
21142                 entrada.port() — the two consumers of the per-:entrada \
21143                 L4-port axis (validator, per-destination resolver) both \
21144                 route through Entrada::port",
21145            );
21146        }
21147    }
21148
21149    #[test]
21150    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
21151        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
21152        // must return the `:contratos :de` field byte-for-byte, borrowed
21153        // from the typed slot's own [`String`] storage. Peer of the
21154        // sibling `destination_returns_entrada_para_byte_equal` pin on
21155        // the per-`:entrada` axis — same "the substrate-primitive
21156        // accessor must byte-equal the raw field access verbatim across
21157        // every author-declared value" discipline extended to the
21158        // per-`:contratos` caller arm. Pins against a future silent
21159        // detour that re-normalized the caller (an accidental
21160        // `.to_lowercase()` — every `:contratos :de` is validated as a
21161        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
21162        // re-normalization is redundant + a drift surface between the
21163        // validator and the accessor), a namespace-prefix rewrite (an
21164        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
21165        // rewrite that didn't land on the peer axis), or a per-cluster
21166        // suffix stamp the operator authors on one consumer without the
21167        // other.
21168        for de in ["cart", "checkout", "catalog", "orders-v2"] {
21169            let c = WitContract {
21170                de: de.into(),
21171                para: "downstream".into(),
21172                wit: "wasi:http/proxy".into(),
21173                endpoint: Some("/lookup".into()),
21174                subject: None,
21175                slot: None,
21176            };
21177            assert_eq!(
21178                c.source(),
21179                de,
21180                "WitContract::source must return :contratos :de verbatim \
21181                 (got {:?}, expected {de:?})",
21182                c.source(),
21183            );
21184            assert_eq!(
21185                c.source(),
21186                c.de.as_str(),
21187                "WitContract::source must byte-equal the .de field access",
21188            );
21189        }
21190    }
21191
21192    #[test]
21193    fn wit_contract_source_borrows_from_de_storage() {
21194        // The borrow-not-copy pin: [`WitContract::source`] must return a
21195        // `&str` slice that borrows from the typed slot's own [`String`]
21196        // storage — same-address invariant with `c.de.as_str()`. Pins
21197        // against a future silent detour that allocated a fresh `String`
21198        // (`self.de.clone()` in the body would type-check but silently
21199        // drop the borrow, and every downstream consumer that assumed
21200        // the returned slice outlives `&self` would break on a stale-
21201        // reference use-after-free). Peer of the sibling
21202        // `destination_borrows_from_entrada_para_storage` on the
21203        // per-`:entrada` axis.
21204        let c = WitContract {
21205            de: "cart".into(),
21206            para: "catalog".into(),
21207            wit: "wasi:http/proxy".into(),
21208            endpoint: Some("/lookup".into()),
21209            subject: None,
21210            slot: None,
21211        };
21212        let src = c.source();
21213        let de_slice = c.de.as_str();
21214        assert_eq!(
21215            src.as_ptr(),
21216            de_slice.as_ptr(),
21217            "WitContract::source must borrow from the .de String's \
21218             backing storage — a fresh allocation here means the \
21219             accessor no longer names the substrate-primitive typed \
21220             dispatch and every downstream consumer would silently \
21221             carry a detached copy",
21222        );
21223        assert_eq!(
21224            src.len(),
21225            de_slice.len(),
21226            "WitContract::source and .de.as_str() must byte-equal in \
21227             length as well as in address",
21228        );
21229    }
21230
21231    #[test]
21232    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
21233        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
21234        // must return the `:contratos :para` field byte-for-byte,
21235        // borrowed from the typed slot's own [`String`] storage. Peer of
21236        // the sibling `destination_returns_entrada_para_byte_equal` on
21237        // the per-`:entrada` axis — both accessors name "the destination-
21238        // Servico byte-string" concept on their respective mesh-slot
21239        // atoms (per-ingress apex vs. per-typed-edge callee) and both
21240        // must project the underlying `.para` field verbatim so every
21241        // downstream renderer that composes them with peer accessors
21242        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
21243        // per-edge L4 port emit site) reads the same byte-string the
21244        // author declared.
21245        for para in ["catalog", "payment", "orders", "inventory-v3"] {
21246            let c = WitContract {
21247                de: "cart".into(),
21248                para: para.into(),
21249                wit: "wasi:http/proxy".into(),
21250                endpoint: Some("/lookup".into()),
21251                subject: None,
21252                slot: None,
21253            };
21254            assert_eq!(
21255                c.destination(),
21256                para,
21257                "WitContract::destination must return :contratos :para \
21258                 verbatim (got {:?}, expected {para:?})",
21259                c.destination(),
21260            );
21261            assert_eq!(
21262                c.destination(),
21263                c.para.as_str(),
21264                "WitContract::destination must byte-equal the .para \
21265                 field access",
21266            );
21267        }
21268    }
21269
21270    #[test]
21271    fn wit_contract_destination_borrows_from_para_storage() {
21272        // The borrow-not-copy pin: [`WitContract::destination`] must
21273        // return a `&str` slice that borrows from the typed slot's own
21274        // [`String`] storage — same-address invariant with
21275        // `c.para.as_str()`. Peer of the sibling
21276        // `destination_borrows_from_entrada_para_storage` on the
21277        // per-`:entrada` axis.
21278        let c = WitContract {
21279            de: "cart".into(),
21280            para: "catalog".into(),
21281            wit: "wasi:http/proxy".into(),
21282            endpoint: Some("/lookup".into()),
21283            subject: None,
21284            slot: None,
21285        };
21286        let dest = c.destination();
21287        let para_slice = c.para.as_str();
21288        assert_eq!(
21289            dest.as_ptr(),
21290            para_slice.as_ptr(),
21291            "WitContract::destination must borrow from the .para \
21292             String's backing storage — a fresh allocation here means \
21293             the accessor no longer names the substrate-primitive typed \
21294             dispatch and every downstream consumer would silently \
21295             carry a detached copy",
21296        );
21297        assert_eq!(
21298            dest.len(),
21299            para_slice.len(),
21300            "WitContract::destination and .para.as_str() must byte-equal \
21301             in length as well as in address",
21302        );
21303    }
21304
21305    #[test]
21306    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
21307        // The canonical per-`:contratos` WIT-world-reference scalar pin:
21308        // [`WitContract::world_ref`] must return the `:contratos :wit`
21309        // field byte-for-byte, borrowed from the typed slot's own
21310        // [`String`] storage. Sibling of the peer per-`:contratos`
21311        // [`WitContract::source`] / [`WitContract::destination`]
21312        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
21313        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
21314        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
21315        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
21316        // "the substrate-primitive accessor must byte-equal the raw
21317        // field access verbatim across every author-declared value"
21318        // discipline extended to the per-`:contratos` WIT-world arm.
21319        // Pins against a future silent detour that re-canonicalized the
21320        // WIT world reference (an accidental `.to_lowercase()` pass that
21321        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
21322        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
21323        // gate is already lowercase-prefixed so any re-normalization is
21324        // redundant + a drift surface between the validator and the
21325        // accessor), an M4-promotion-shape rewrite that formatted a
21326        // typed WIT-world enum through [`Display`] and silently drifted
21327        // the printer output from the source `caixa.lisp`, or a per-
21328        // cluster WIT-alias rewrite that didn't land on the peer field-
21329        // access sites. Five values sweep the shape-dispatch accept-set
21330        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
21331        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
21332        // `wasi:keyvalue/`).
21333        for (wit, endpoint, subject, slot) in [
21334            ("wasi:http/proxy", Some("/lookup"), None, None),
21335            ("http:proxy", Some("/health"), None, None),
21336            ("nats:pub-sub", None, Some("orders.paid"), None),
21337            ("kafka:events", None, Some("checkout-events"), None),
21338            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
21339        ] {
21340            let c = WitContract {
21341                de: "cart".into(),
21342                para: "downstream".into(),
21343                wit: wit.into(),
21344                endpoint: endpoint.map(str::to_string),
21345                subject: subject.map(str::to_string),
21346                slot: slot.map(str::to_string),
21347            };
21348            assert_eq!(
21349                c.world_ref(),
21350                wit,
21351                "WitContract::world_ref must return :contratos :wit \
21352                 verbatim (got {:?}, expected {wit:?})",
21353                c.world_ref(),
21354            );
21355            assert_eq!(
21356                c.world_ref(),
21357                c.wit.as_str(),
21358                "WitContract::world_ref must byte-equal the .wit field \
21359                 access",
21360            );
21361        }
21362    }
21363
21364    #[test]
21365    fn wit_contract_world_ref_borrows_from_wit_storage() {
21366        // The borrow-not-copy pin: [`WitContract::world_ref`] must
21367        // return a `&str` slice that borrows from the typed slot's own
21368        // [`String`] storage — same-address invariant with
21369        // `c.wit.as_str()`. Pins against a future silent detour that
21370        // allocated a fresh `String` (`self.wit.clone()` in the body
21371        // would type-check but silently drop the borrow, and every
21372        // downstream consumer that assumed the returned slice outlives
21373        // `&self` would break on a stale-reference use-after-free — the
21374        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
21375        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
21376        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
21377        // / [`is_pubsub`][WitContract::is_pubsub] /
21378        // [`is_store`][WitContract::is_store] methods route through —
21379        // each borrow from the WitContract's own storage and each would
21380        // silently misbehave if this accessor produced a detached copy).
21381        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
21382        // [`WitContract::destination`] and per-`:entrada`
21383        // [`Entrada::destination`] / [`Entrada::hostname`] and
21384        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
21385        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
21386        let c = WitContract {
21387            de: "cart".into(),
21388            para: "catalog".into(),
21389            wit: "wasi:http/proxy".into(),
21390            endpoint: Some("/lookup".into()),
21391            subject: None,
21392            slot: None,
21393        };
21394        let world = c.world_ref();
21395        let wit_slice = c.wit.as_str();
21396        assert_eq!(
21397            world.as_ptr(),
21398            wit_slice.as_ptr(),
21399            "WitContract::world_ref must borrow from the .wit String's \
21400             backing storage — a fresh allocation here means the \
21401             accessor no longer names the substrate-primitive typed \
21402             dispatch and every downstream consumer would silently carry \
21403             a detached copy",
21404        );
21405        assert_eq!(
21406            world.len(),
21407            wit_slice.len(),
21408            "WitContract::world_ref and .wit.as_str() must byte-equal in \
21409             length as well as in address",
21410        );
21411    }
21412
21413    #[test]
21414    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
21415        // Sibling-triple invariant pin composing all three per-`:contratos`
21416        // substrate-primitive typed dispatches — [`WitContract::source`]
21417        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
21418        // [`WitContract::world_ref`] — at the joint
21419        // `(source(), destination(), world_ref())` call shape every
21420        // renderer that fans on per-edge caller-callee-shape identity
21421        // keys off. The invariant, evaluated per-contract:
21422        //
21423        //   (c.source(), c.destination(), c.world_ref())
21424        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
21425        //
21426        // Closes the last unlifted per-`:contratos` scalar axis — every
21427        // downstream consumer that reads the triple now routes through
21428        // exactly three typed dispatches on the substrate primitive,
21429        // not two typed + one open-coded field access. A future refactor
21430        // that silently split any one accessor's projection (an
21431        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
21432        // canonicalization that didn't reach the peer `source`/
21433        // `destination` arms, an accidental `source()` per-cluster
21434        // caller-alias rewrite that didn't land on the `world_ref` peer)
21435        // surfaces at caixa-core build time. Peer of the sibling per-
21436        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
21437        // per-`:entrada` `(hostname(), destination())` (6db982c /
21438        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
21439        // axes, extended to the per-`:contratos` triple.
21440        for (de, para, wit, endpoint, subject, slot) in [
21441            (
21442                "cart",
21443                "catalog",
21444                "wasi:http/proxy",
21445                Some("/lookup"),
21446                None,
21447                None,
21448            ),
21449            (
21450                "checkout",
21451                "orders",
21452                "nats:pub-sub",
21453                None,
21454                Some("orders.paid"),
21455                None,
21456            ),
21457            (
21458                "cart",
21459                "kv",
21460                "wasi:keyvalue/store",
21461                None,
21462                None,
21463                Some("carts/{cart_id}"),
21464            ),
21465            (
21466                "orders-v2",
21467                "inventory-v3",
21468                "http:proxy",
21469                Some("/reserve"),
21470                None,
21471                None,
21472            ),
21473        ] {
21474            let c = WitContract {
21475                de: de.into(),
21476                para: para.into(),
21477                wit: wit.into(),
21478                endpoint: endpoint.map(str::to_string),
21479                subject: subject.map(str::to_string),
21480                slot: slot.map(str::to_string),
21481            };
21482            assert_eq!(
21483                (c.source(), c.destination(), c.world_ref()),
21484                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
21485                "(WitContract::source, ::destination, ::world_ref) must \
21486                 project (.de, .para, .wit) verbatim across every author-\
21487                 declared triple (got ({:?}, {:?}, {:?}), expected \
21488                 ({de:?}, {para:?}, {wit:?}))",
21489                c.source(),
21490                c.destination(),
21491                c.world_ref(),
21492            );
21493        }
21494    }
21495
21496    #[test]
21497    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
21498        // The canonical per-`:contratos` owned-form caller-callee-pair
21499        // pin: [`WitContract::edge_pair`] must return the
21500        // `(source(), destination())` tuple in owned form byte-for-byte,
21501        // projected through the lifted [`WitContract::source`] /
21502        // [`WitContract::destination`] scalar accessors. Pins the
21503        // composite-projection invariant on the per-`:contratos`
21504        // mesh-slot atom — every author-declared `(de, para)` pair must
21505        // round-trip verbatim through the substrate primitive's typed
21506        // dispatch, so the nine [`AplicacaoError`] diagnostic-
21507        // construction sites the accessor now feeds
21508        // ([`AplicacaoError::EmptyWit`],
21509        // [`AplicacaoError::ContratoEndpointEmpty`],
21510        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
21511        // [`AplicacaoError::ContratoEndpointInvalid`],
21512        // [`AplicacaoError::ContratoSubjectEmpty`],
21513        // [`AplicacaoError::ContratoSubjectInvalid`],
21514        // [`AplicacaoError::ContratoSlotEmpty`],
21515        // [`AplicacaoError::ContratoSlotInvalid`],
21516        // [`AplicacaoError::ContratoDuplicate`]) all read the same
21517        // `(de, para)` label pair every author sees at the source
21518        // `caixa.lisp`. Pins against a future silent detour that swapped
21519        // the `.0` / `.1` arms (an accidental `(destination(),
21520        // source())` re-order in the body would silently invert every
21521        // downstream diagnostic's `de:` / `para:` label pair, silently
21522        // reversing the direction of every operator-facing typed error
21523        // arrow), a fresh-allocation shape drift (an accidental
21524        // `.to_string()` on one arm but not the other would leave the
21525        // owned/borrowed pair mismatched vs. the sibling `source()` /
21526        // `destination()` returns), or an M4 per-cluster caller/callee-
21527        // alias rewrite that landed on `source()` without reaching
21528        // `destination()` (or vice versa). Peer of the sibling per-
21529        // `:contratos` `(source, destination, world_ref)` triple
21530        // pin above on the mesh-slot-atom scalar-value axes, extended
21531        // to the owned-form pair-projection axis.
21532        for (de, para, wit, endpoint, subject, slot) in [
21533            (
21534                "cart",
21535                "catalog",
21536                "wasi:http/proxy",
21537                Some("/lookup"),
21538                None,
21539                None,
21540            ),
21541            (
21542                "checkout",
21543                "orders",
21544                "nats:pub-sub",
21545                None,
21546                Some("orders.paid"),
21547                None,
21548            ),
21549            (
21550                "cart",
21551                "kv",
21552                "wasi:keyvalue/store",
21553                None,
21554                None,
21555                Some("carts/{cart_id}"),
21556            ),
21557            (
21558                "orders-v2",
21559                "inventory-v3",
21560                "http:proxy",
21561                Some("/reserve"),
21562                None,
21563                None,
21564            ),
21565        ] {
21566            let c = WitContract {
21567                de: de.into(),
21568                para: para.into(),
21569                wit: wit.into(),
21570                endpoint: endpoint.map(str::to_string),
21571                subject: subject.map(str::to_string),
21572                slot: slot.map(str::to_string),
21573            };
21574            assert_eq!(
21575                c.edge_pair(),
21576                (de.to_string(), para.to_string()),
21577                "WitContract::edge_pair must return (:contratos :de, \
21578                 :contratos :para) as an owned tuple verbatim (got {:?}, \
21579                 expected ({de:?}, {para:?}))",
21580                c.edge_pair(),
21581            );
21582        }
21583    }
21584
21585    #[test]
21586    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
21587        // The composition pin: [`WitContract::edge_pair`] must return
21588        // exactly `(source().to_string(), destination().to_string())` —
21589        // the owned form of the sibling accessor pair — so any future
21590        // refactor that silently re-authored the caller-arm / callee-arm
21591        // projection to bypass the lifted scalar accessors (an accidental
21592        // `(self.de.clone(), self.para.clone())` regression back to the
21593        // raw field-access shape, an M4-typed-caller-enum `Display`
21594        // re-canonicalization on `source()` that didn't reach
21595        // `edge_pair()`, a per-cluster alias rewrite the operator lands
21596        // on `destination()` without reaching this composite projection)
21597        // trips at caixa-core build time. Pins the "typed dispatch
21598        // composes with typed dispatch, not with raw field access"
21599        // discipline every downstream diagnostic-construction site now
21600        // routes through — a `de:` / `para:` label pair whose
21601        // projection silently drifted off the substrate primitive's
21602        // scalar accessors would silently split the diagnostic's self-
21603        // locating signal from the source `caixa.lisp` author's view.
21604        // Peer of the sibling per-`:politicas` `is_empty` /
21605        // `validate_politicas` accessor-routing-pin family on the M3
21606        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
21607        let c = WitContract {
21608            de: "cart".into(),
21609            para: "catalog".into(),
21610            wit: "wasi:http/proxy".into(),
21611            endpoint: Some("/lookup".into()),
21612            subject: None,
21613            slot: None,
21614        };
21615        assert_eq!(
21616            c.edge_pair(),
21617            (c.source().to_string(), c.destination().to_string()),
21618            "WitContract::edge_pair must compose exactly \
21619             (source().to_string(), destination().to_string()) — a \
21620             bypass of either sibling accessor here would silently \
21621             decouple the composite-projection axis from the \
21622             substrate-primitive scalar accessors every downstream \
21623             consumer routes through",
21624        );
21625    }
21626
21627    #[test]
21628    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
21629     {
21630        // The canonical per-`:contratos` owned-form
21631        // caller-callee-world-ref-triple pin:
21632        // [`WitContract::edge_triple`] must return the
21633        // `(source(), destination(), world_ref())` tuple in owned form
21634        // byte-for-byte, projected through the lifted
21635        // [`WitContract::source`] / [`WitContract::destination`] /
21636        // [`WitContract::world_ref`] scalar accessors. Pins the
21637        // composite-projection invariant on the per-`:contratos`
21638        // mesh-slot atom — every author-declared `(de, para, wit)`
21639        // triple must round-trip verbatim through the substrate
21640        // primitive's typed dispatch, so the nine
21641        // [`AplicacaoError`] diagnostic-construction sites the
21642        // accessor now feeds (the [`WitTarget`]-dispatch's eight
21643        // wrong-target / missing-target / invalid-wit / capability-
21644        // with-payload arms in [`WitContract::target`], plus the
21645        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
21646        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
21647        // read the same `(de, para, wit)` triple every author sees at
21648        // the source `caixa.lisp`. Pins against a future silent
21649        // detour that swapped any two arms (an accidental `(destination(),
21650        // source(), world_ref())` re-order in the body would silently
21651        // invert every downstream diagnostic's `de:` / `para:` label
21652        // pair, silently reversing the direction of every operator-
21653        // facing typed error arrow), a fresh-allocation shape drift
21654        // (an accidental `.to_string()` skipped on one arm would leave
21655        // the owned/borrowed triple mismatched vs. the sibling
21656        // `source()` / `destination()` / `world_ref()` returns), or an
21657        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
21658        // canonicalization pass that landed on one accessor without
21659        // reaching the peers. Peer of the sibling per-`:contratos`
21660        // caller-callee-pair
21661        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
21662        // pin on the mesh-slot-atom composite-projection axis,
21663        // extended to the triple-projection axis.
21664        for (de, para, wit, endpoint, subject, slot) in [
21665            (
21666                "cart",
21667                "catalog",
21668                "wasi:http/proxy",
21669                Some("/lookup"),
21670                None,
21671                None,
21672            ),
21673            (
21674                "checkout",
21675                "orders",
21676                "nats:pub-sub",
21677                None,
21678                Some("orders.paid"),
21679                None,
21680            ),
21681            (
21682                "cart",
21683                "kv",
21684                "wasi:keyvalue/store",
21685                None,
21686                None,
21687                Some("carts/{cart_id}"),
21688            ),
21689            (
21690                "orders-v2",
21691                "inventory-v3",
21692                "http:proxy",
21693                Some("/reserve"),
21694                None,
21695                None,
21696            ),
21697        ] {
21698            let c = WitContract {
21699                de: de.into(),
21700                para: para.into(),
21701                wit: wit.into(),
21702                endpoint: endpoint.map(str::to_string),
21703                subject: subject.map(str::to_string),
21704                slot: slot.map(str::to_string),
21705            };
21706            assert_eq!(
21707                c.edge_triple(),
21708                (de.to_string(), para.to_string(), wit.to_string()),
21709                "WitContract::edge_triple must return (:contratos :de, \
21710                 :contratos :para, :contratos :wit) as an owned triple \
21711                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
21712                c.edge_triple(),
21713            );
21714        }
21715    }
21716
21717    #[test]
21718    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
21719        // The composition pin: [`WitContract::edge_triple`] must return
21720        // exactly `(source().to_string(), destination().to_string(),
21721        // world_ref().to_string())` — the owned form of the sibling
21722        // scalar-accessor triple — so any future refactor that silently
21723        // re-authored one arm's projection to bypass the lifted scalar
21724        // accessors (an accidental `(self.de.clone(), self.para.clone(),
21725        // self.wit.clone())` regression back to the raw field-access
21726        // shape the internal `edge` closure and the ContratoDuplicate
21727        // diagnostic both carried before this lift landed, an
21728        // M4-typed-caller-enum `Display` re-canonicalization on
21729        // `source()` that didn't reach `edge_triple()`, a per-cluster
21730        // alias rewrite the operator lands on `destination()` /
21731        // `world_ref()` without reaching this composite projection)
21732        // trips at caixa-core build time. Pins the "typed dispatch
21733        // composes with typed dispatch, not with raw field access"
21734        // discipline every downstream diagnostic-construction site now
21735        // routes through — a `de:` / `para:` / `wit:` triple whose
21736        // projection silently drifted off the substrate primitive's
21737        // scalar accessors would silently split the diagnostic's self-
21738        // locating signal from the source `caixa.lisp` author's view.
21739        // Peer of the sibling per-`:contratos` edge_pair composition-
21740        // pin above on the mesh-slot-atom composite-projection axis.
21741        let c = WitContract {
21742            de: "cart".into(),
21743            para: "catalog".into(),
21744            wit: "wasi:http/proxy".into(),
21745            endpoint: Some("/lookup".into()),
21746            subject: None,
21747            slot: None,
21748        };
21749        assert_eq!(
21750            c.edge_triple(),
21751            (
21752                c.source().to_string(),
21753                c.destination().to_string(),
21754                c.world_ref().to_string(),
21755            ),
21756            "WitContract::edge_triple must compose exactly \
21757             (source().to_string(), destination().to_string(), \
21758             world_ref().to_string()) — a bypass of any sibling accessor \
21759             here would silently decouple the composite-projection axis \
21760             from the substrate-primitive scalar accessors every \
21761             downstream consumer routes through",
21762        );
21763    }
21764
21765    #[test]
21766    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
21767        // The canonical semantics-pin: [`WitContract::edge_triple`] must
21768        // project the full `(de, para, wit)` identity of a `:contratos`
21769        // edge — the sub-triple every triple-carrying
21770        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
21771        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
21772        // missing-target, capability-with-payload, invalid-wit, and the
21773        // duplicate-gate). Rejects a drift in shape (an accidental
21774        // silent detour that returned a `(de, para)` pair or added an
21775        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
21776        // would trip here because the return type would no longer
21777        // pattern-match the eight `let (de, para, wit) = edge();`
21778        // destructures the [`WitContract::target`] dispatch feeds off
21779        // + the paired duplicate-gate `let (de, para, wit) =
21780        // c.edge_triple();` destructure in
21781        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
21782        // `:contratos` caller-callee-pair pin above extended to the
21783        // triple projection surface: closes the "one composite
21784        // accessor per typed diagnostic-construction sub-tuple"
21785        // discipline on the per-`:contratos` mesh-slot-atom axis.
21786        let c = WitContract {
21787            de: "checkout".into(),
21788            para: "orders".into(),
21789            wit: "nats:pub-sub".into(),
21790            endpoint: None,
21791            subject: Some("orders.paid".into()),
21792            slot: None,
21793        };
21794        let (de, para, wit) = c.edge_triple();
21795        assert_eq!(de, "checkout");
21796        assert_eq!(para, "orders");
21797        assert_eq!(wit, "nats:pub-sub");
21798    }
21799
21800    #[test]
21801    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
21802     {
21803        // The composition pin: [`WitContract::identity`] must return
21804        // exactly `(source(), destination(), world_ref(), endpoint(),
21805        // subject(), slot())` — the borrowed form of the six-scalar-
21806        // accessor identity axis. Any future refactor that silently
21807        // re-authored one arm's projection to bypass a scalar accessor
21808        // (a `self.de.as_str()` regression back to raw field access on
21809        // any of the three required arms, a `self.endpoint.as_deref()`
21810        // regression on any of the three optional arms, an M4 per-
21811        // cluster caller/callee-alias rewrite the operator lands on
21812        // `source()` / `destination()` without reaching this composite
21813        // projection) trips at caixa-core build time. Sweeps four
21814        // permutations of the WIT-shape × payload lattice — HTTP with
21815        // endpoint, pub-sub with subject, store with slot, payload-less
21816        // capability — so every payload arm is exercised. Peer of the
21817        // sibling per-`:contratos`
21818        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
21819        // composition pin on the mesh-slot-atom composite-projection
21820        // axis; extends the discipline from the (de, para, wit) prefix
21821        // onto the full-identity axis carrying the three payload arms.
21822        for (de, para, wit, endpoint, subject, slot) in [
21823            (
21824                "cart",
21825                "catalog",
21826                "wasi:http/proxy",
21827                Some("/lookup"),
21828                None,
21829                None,
21830            ),
21831            (
21832                "checkout",
21833                "orders",
21834                "nats:pub-sub",
21835                None,
21836                Some("orders.paid"),
21837                None,
21838            ),
21839            (
21840                "cart",
21841                "kv",
21842                "wasi:keyvalue/store",
21843                None,
21844                None,
21845                Some("carts/{cart_id}"),
21846            ),
21847            ("audit", "sink", "wasi:logging", None, None, None),
21848        ] {
21849            let c = WitContract {
21850                de: de.into(),
21851                para: para.into(),
21852                wit: wit.into(),
21853                endpoint: endpoint.map(str::to_owned),
21854                subject: subject.map(str::to_owned),
21855                slot: slot.map(str::to_owned),
21856            };
21857            assert_eq!(
21858                c.identity(),
21859                (
21860                    c.source(),
21861                    c.destination(),
21862                    c.world_ref(),
21863                    c.endpoint(),
21864                    c.subject(),
21865                    c.slot(),
21866                ),
21867                "WitContract::identity must compose exactly \
21868                 (source(), destination(), world_ref(), endpoint(), \
21869                 subject(), slot()) — a bypass of any sibling accessor \
21870                 here would silently decouple the identity-projection \
21871                 axis from the substrate-primitive scalar accessors \
21872                 every dedup-key consumer routes through",
21873            );
21874        }
21875    }
21876
21877    #[test]
21878    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
21879        // The canonical semantics-pin: [`WitContract::identity`] must
21880        // project the six-axis (de, para, wit, endpoint, subject, slot)
21881        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
21882        // gate keys off — two `WitContract`s that agree on all six axes
21883        // are the same typed edge declared twice, the graph-edge
21884        // analogue of duplicate `:membros` / `:placement :clusters` /
21885        // `:entrada :paths` entries. Rejects a shape drift (an
21886        // accidental silent detour that returned a prefix tuple or
21887        // added an extra field) by pattern-matching the six-arm shape.
21888        // Peer of the sibling per-`:contratos`
21889        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
21890        // pin extended from the (de, para, wit) prefix onto the full
21891        // six-axis identity that the dedup key rides.
21892        let c = WitContract {
21893            de: "cart".into(),
21894            para: "catalog".into(),
21895            wit: "wasi:http/proxy".into(),
21896            endpoint: Some("/products/:id".into()),
21897            subject: None,
21898            slot: None,
21899        };
21900        let (de, para, wit, endpoint, subject, slot) = c.identity();
21901        assert_eq!(de, "cart");
21902        assert_eq!(para, "catalog");
21903        assert_eq!(wit, "wasi:http/proxy");
21904        assert_eq!(endpoint, Some("/products/:id"));
21905        assert_eq!(subject, None);
21906        assert_eq!(slot, None);
21907
21908        // Two byte-identical contracts must produce equal identities —
21909        // the dedup key's foundational invariant.
21910        let c2 = c.clone();
21911        assert_eq!(c.identity(), c2.identity());
21912
21913        // Any change on any of the six axes must break the identity —
21914        // sweeps by mutating one axis at a time.
21915        let mut mutated = c.clone();
21916        mutated.de = "search".into();
21917        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
21918        let mut mutated = c.clone();
21919        mutated.para = "warehouse".into();
21920        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
21921        let mut mutated = c.clone();
21922        mutated.wit = "http:legacy".into();
21923        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
21924        let mut mutated = c.clone();
21925        mutated.endpoint = Some("/search".into());
21926        assert_ne!(
21927            c.identity(),
21928            mutated.identity(),
21929            "endpoint axis must partition"
21930        );
21931        let mut mutated = c.clone();
21932        mutated.subject = Some("orders.paid".into());
21933        assert_ne!(
21934            c.identity(),
21935            mutated.identity(),
21936            "subject axis must partition"
21937        );
21938        let mut mutated = c;
21939        mutated.slot = Some("carts/{id}".into());
21940        assert_ne!(mutated.identity().5, None, "slot axis must partition");
21941    }
21942
21943    #[test]
21944    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
21945        // The canonical per-`:contratos` structural-self-edge pin:
21946        // [`WitContract::is_self_loop`] must return `true` when the
21947        // `:de` and `:para` fields agree byte-for-byte, across every
21948        // WIT-shape variant the per-edge shape family carries. Pins
21949        // the shape-agnostic identity-space partition the
21950        // [`AplicacaoSpec::validate`] self-edge gate at
21951        // caixa-core/src/aplicacao.rs:5559 fires against — all four
21952        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
21953        // under the same one predicate. Four permutations sweep the
21954        // accept-set: HTTP with endpoint, pub-sub with subject, KV
21955        // store with slot, and payload-less capability.
21956        for (nome, wit, endpoint, subject, slot) in [
21957            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
21958            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
21959            (
21960                "kv",
21961                "wasi:keyvalue/store",
21962                None,
21963                None,
21964                Some("carts/{cart_id}"),
21965            ),
21966            ("audit", "wasi:logging", None, None, None),
21967        ] {
21968            let c = WitContract {
21969                de: nome.into(),
21970                para: nome.into(),
21971                wit: wit.into(),
21972                endpoint: endpoint.map(str::to_string),
21973                subject: subject.map(str::to_string),
21974                slot: slot.map(str::to_string),
21975            };
21976            assert!(
21977                c.is_self_loop(),
21978                "WitContract::is_self_loop must return true when \
21979                 :contratos :de == :contratos :para (got false on \
21980                 {nome:?} under {wit:?})",
21981            );
21982        }
21983    }
21984
21985    #[test]
21986    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
21987        // The complement pin: [`WitContract::is_self_loop`] must return
21988        // `false` on every well-shaped inter-Servico contract (the
21989        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
21990        // names — "Servico A calls Servico B" between two distinct
21991        // graph nodes). Pins against a future silent detour that
21992        // inverted the predicate (an accidental `!= ` swap for `==`
21993        // would silently reject every legitimate inter-Servico edge
21994        // and admit every self-edge — the exact inversion of the
21995        // author-intended shape). Four permutations sweep the same
21996        // WIT-shape accept-set the sibling positive-arm test carries.
21997        for (de, para, wit, endpoint, subject, slot) in [
21998            (
21999                "cart",
22000                "catalog",
22001                "wasi:http/proxy",
22002                Some("/lookup"),
22003                None,
22004                None,
22005            ),
22006            (
22007                "checkout",
22008                "orders",
22009                "nats:pub-sub",
22010                None,
22011                Some("orders.paid"),
22012                None,
22013            ),
22014            (
22015                "cart",
22016                "kv",
22017                "wasi:keyvalue/store",
22018                None,
22019                None,
22020                Some("carts/{cart_id}"),
22021            ),
22022            ("audit", "sink", "wasi:logging", None, None, None),
22023        ] {
22024            let c = WitContract {
22025                de: de.into(),
22026                para: para.into(),
22027                wit: wit.into(),
22028                endpoint: endpoint.map(str::to_string),
22029                subject: subject.map(str::to_string),
22030                slot: slot.map(str::to_string),
22031            };
22032            assert!(
22033                !c.is_self_loop(),
22034                "WitContract::is_self_loop must return false when \
22035                 :contratos :de differs from :contratos :para (got true \
22036                 on {de:?} → {para:?} under {wit:?})",
22037            );
22038        }
22039    }
22040
22041    #[test]
22042    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
22043        // The composition pin: [`WitContract::is_self_loop`] must
22044        // resolve to exactly `self.source() == self.destination()` —
22045        // the equality probe of the sibling scalar-accessor pair — so
22046        // any future refactor that silently re-authored the predicate
22047        // to bypass the lifted scalar accessors (an accidental
22048        // `self.de == self.para` regression back to the raw field-
22049        // access shape, an M4-typed-caller-enum identity-comparison
22050        // rule that landed on `source()` without reaching
22051        // `destination()`, a per-cluster alias rewrite the operator
22052        // pins on `destination()` without reaching this predicate)
22053        // trips at caixa-core build time. Pins the "typed dispatch
22054        // composes with typed dispatch, not with raw field access"
22055        // discipline the sibling [`WitContract::edge_pair`] /
22056        // [`WitContract::edge_triple`] composite-projection accessors
22057        // already carry, extended onto the per-edge endpoint-equality
22058        // predicate axis. Positive and complement arms both fire.
22059        let self_edge = WitContract {
22060            de: "cart".into(),
22061            para: "cart".into(),
22062            wit: "wasi:http/proxy".into(),
22063            endpoint: Some("/lookup".into()),
22064            subject: None,
22065            slot: None,
22066        };
22067        assert_eq!(
22068            self_edge.is_self_loop(),
22069            self_edge.source() == self_edge.destination(),
22070            "WitContract::is_self_loop must compose exactly \
22071             `source() == destination()` — a bypass of either sibling \
22072             accessor here would silently decouple the endpoint-\
22073             equality predicate from the substrate-primitive scalar \
22074             accessors every downstream consumer routes through",
22075        );
22076        let inter_edge = WitContract {
22077            de: "cart".into(),
22078            para: "catalog".into(),
22079            wit: "wasi:http/proxy".into(),
22080            endpoint: Some("/lookup".into()),
22081            subject: None,
22082            slot: None,
22083        };
22084        assert_eq!(
22085            inter_edge.is_self_loop(),
22086            inter_edge.source() == inter_edge.destination(),
22087            "WitContract::is_self_loop must compose exactly \
22088             `source() == destination()` on the complement arm too",
22089        );
22090    }
22091
22092    #[test]
22093    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
22094        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
22095        // pin: [`WitContract::endpoint`] must return the `:contratos
22096        // :endpoint` field byte-for-byte, borrowed from the typed slot's
22097        // own `Option<String>` storage. Peer of the sibling
22098        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
22099        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
22100        // mesh-slot `Option<String>` optional-scalar axes — same "the
22101        // substrate-primitive accessor must byte-equal the raw field
22102        // access verbatim across every author-declared value" discipline
22103        // extended to the per-`:contratos` HTTP-payload-carrier arm.
22104        // Pins against a future silent detour that re-canonicalized the
22105        // endpoint (an accidental percent-encoding pass that didn't
22106        // reach the peer field-access site at the dedup key, a per-CR
22107        // fully-qualified prefix rewrite the operator authors on one
22108        // consumer without the other, or an M4 typed-path-template
22109        // `Display` re-canonicalization that silently drifted the
22110        // printer output from the source `caixa.lisp`). Four values
22111        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
22112        // gate upstream admits (short root-path, dashed, param-shaped,
22113        // deep-hierarchy).
22114        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
22115            let c = WitContract {
22116                de: "cart".into(),
22117                para: "catalog".into(),
22118                wit: "wasi:http/proxy".into(),
22119                endpoint: Some(endpoint.into()),
22120                subject: None,
22121                slot: None,
22122            };
22123            assert_eq!(
22124                c.endpoint(),
22125                Some(endpoint),
22126                "WitContract::endpoint must return :contratos :endpoint \
22127                 verbatim (got {:?}, expected Some({endpoint:?}))",
22128                c.endpoint(),
22129            );
22130            assert_eq!(
22131                c.endpoint(),
22132                c.endpoint.as_deref(),
22133                "WitContract::endpoint must byte-equal the .endpoint \
22134                 field's `.as_deref()` projection",
22135            );
22136        }
22137    }
22138
22139    #[test]
22140    fn wit_contract_endpoint_none_when_field_is_none() {
22141        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
22142        // payload-carrier accessor pin: when the typed slot is absent —
22143        // the canonical shape under a non-HTTP `:wit` world per the
22144        // [`WitContract::target`]-enforced shape ↔ target partition
22145        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
22146        // carries `:slot`, [`WitTarget::Capability`] carries none) —
22147        // [`WitContract::endpoint`] must return `None`. Pins against a
22148        // future silent detour that projected the absent slot to a
22149        // `Some("")` empty-string default (the canonical `Option<String>`
22150        // → `String` collapse footgun the sibling M2
22151        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22152        // emptiness predicates already guard on the peer M2 typed-slot
22153        // surfaces), a `Some("None")` stringified-None round-trip, or a
22154        // `Some` arm whose contents were derived from a sibling slot (an
22155        // accidental fallback to the `:subject` / `:slot` payload that
22156        // read the pub-sub / store payload into the endpoint axis).
22157        // Three contracts sweep the accept-set every non-HTTP `:wit`
22158        // world lands on — pub-sub NATS, key/value, and payload-less
22159        // capability.
22160        for (wit, subject, slot) in [
22161            ("nats:pub-sub", Some("orders.paid"), None),
22162            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22163            ("wasi:cli/environment", None, None),
22164        ] {
22165            let c = WitContract {
22166                de: "cart".into(),
22167                para: "downstream".into(),
22168                wit: wit.into(),
22169                endpoint: None,
22170                subject: subject.map(str::to_string),
22171                slot: slot.map(str::to_string),
22172            };
22173            assert!(
22174                c.endpoint().is_none(),
22175                "WitContract::endpoint must return None when the typed \
22176                 slot is absent under :wit {wit:?} (got {:?})",
22177                c.endpoint(),
22178            );
22179            assert_eq!(
22180                c.endpoint(),
22181                c.endpoint.as_deref(),
22182                "WitContract::endpoint must byte-equal the .endpoint \
22183                 field's `.as_deref()` projection in the absent arm",
22184            );
22185        }
22186    }
22187
22188    #[test]
22189    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
22190        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
22191        // an `Option<&str>` whose `Some` arm borrows from the typed
22192        // slot's own [`String`] storage — same-address invariant with
22193        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
22194        // detour that allocated a fresh `String`
22195        // (`self.endpoint.clone().map(...)` in the body would type-check
22196        // but silently drop the borrow, and every downstream consumer
22197        // that assumed the returned slice outlives `&self` would break
22198        // on a stale-reference use-after-free — the [`WitContract::target`]
22199        // Http-arm payload extraction rebinds the returned `Option<&str>`
22200        // through `.ok_or_else(...)` and threads the `&str` payload into
22201        // [`WitTarget::Http { endpoint: &'a str }`], the
22202        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
22203        // [`ContratoIdentity`] dedup key threads the returned
22204        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
22205        // from the WitContract's own storage and each would silently
22206        // misbehave if this accessor produced a detached copy). Peer of
22207        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
22208        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22209        // shaped optional-scalar axes — first extension of the
22210        // `Option<&str>` borrow-not-copy discipline onto the
22211        // per-`:contratos` HTTP-shaped payload-carrier axis.
22212        let c = WitContract {
22213            de: "cart".into(),
22214            para: "catalog".into(),
22215            wit: "wasi:http/proxy".into(),
22216            endpoint: Some("/lookup".into()),
22217            subject: None,
22218            slot: None,
22219        };
22220        let ep = c.endpoint().expect("Some arm");
22221        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
22222        assert_eq!(
22223            ep.as_ptr(),
22224            storage_slice.as_ptr(),
22225            "WitContract::endpoint must borrow from the .endpoint \
22226             String's backing storage — a fresh allocation here means \
22227             the accessor no longer names the substrate-primitive typed \
22228             dispatch and every downstream consumer would silently \
22229             carry a detached copy",
22230        );
22231        assert_eq!(
22232            ep.len(),
22233            storage_slice.len(),
22234            "WitContract::endpoint and .endpoint.as_deref() must byte-\
22235             equal in length as well as in address",
22236        );
22237    }
22238
22239    #[test]
22240    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
22241        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
22242        // pin: [`WitContract::subject`] must return the `:contratos
22243        // :subject` field byte-for-byte, borrowed from the typed slot's
22244        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
22245        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
22246        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22247        // optional-scalar axis — same "the substrate-primitive accessor
22248        // must byte-equal the raw field access verbatim across every
22249        // author-declared value" discipline extended to the pub-sub arm.
22250        // Pins against a future silent detour that re-canonicalized the
22251        // subject (an accidental `.to_lowercase()` normalization that
22252        // didn't reach the peer field-access site at the dedup key, a
22253        // per-CR fully-qualified prefix rewrite the operator authors on
22254        // one consumer without the other, or an M4 typed-subject-template
22255        // `Display` re-canonicalization that silently drifted the printer
22256        // output from the source `caixa.lisp`). Four values sweep the
22257        // NATS accept-set every pub-sub author-declared subject lands on
22258        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
22259        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
22260            let c = WitContract {
22261                de: "cart".into(),
22262                para: "notifier".into(),
22263                wit: "nats:pub-sub".into(),
22264                endpoint: None,
22265                subject: Some(subject.into()),
22266                slot: None,
22267            };
22268            assert_eq!(
22269                c.subject(),
22270                Some(subject),
22271                "WitContract::subject must return :contratos :subject \
22272                 verbatim (got {:?}, expected Some({subject:?}))",
22273                c.subject(),
22274            );
22275            assert_eq!(
22276                c.subject(),
22277                c.subject.as_deref(),
22278                "WitContract::subject must byte-equal the .subject \
22279                 field's `.as_deref()` projection",
22280            );
22281        }
22282    }
22283
22284    #[test]
22285    fn wit_contract_subject_none_when_field_is_none() {
22286        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
22287        // shaped payload-carrier accessor pin: when the typed slot is
22288        // absent — the canonical shape under a non-pub-sub `:wit` world
22289        // per the [`WitContract::target`]-enforced shape ↔ target
22290        // partition ([`WitTarget::Http`] carries `:endpoint`,
22291        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
22292        // carries none) — [`WitContract::subject`] must return `None`.
22293        // Pins against a future silent detour that projected the absent
22294        // slot to a `Some("")` empty-string default (the canonical
22295        // `Option<String>` → `String` collapse footgun the sibling M2
22296        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22297        // emptiness predicates already guard on the peer M2 typed-slot
22298        // surfaces), a `Some("None")` stringified-None round-trip, or a
22299        // `Some` arm whose contents were derived from a sibling slot (an
22300        // accidental fallback to the `:endpoint` / `:slot` payload that
22301        // read the HTTP / store payload into the subject axis). Three
22302        // contracts sweep the accept-set every non-pub-sub `:wit` world
22303        // lands on — HTTP proxy, key/value store, and payload-less
22304        // capability.
22305        for (wit, endpoint, slot) in [
22306            ("wasi:http/proxy", Some("/lookup"), None),
22307            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22308            ("wasi:cli/environment", None, None),
22309        ] {
22310            let c = WitContract {
22311                de: "cart".into(),
22312                para: "downstream".into(),
22313                wit: wit.into(),
22314                endpoint: endpoint.map(str::to_string),
22315                subject: None,
22316                slot: slot.map(str::to_string),
22317            };
22318            assert!(
22319                c.subject().is_none(),
22320                "WitContract::subject must return None when the typed \
22321                 slot is absent under :wit {wit:?} (got {:?})",
22322                c.subject(),
22323            );
22324            assert_eq!(
22325                c.subject(),
22326                c.subject.as_deref(),
22327                "WitContract::subject must byte-equal the .subject \
22328                 field's `.as_deref()` projection in the absent arm",
22329            );
22330        }
22331    }
22332
22333    #[test]
22334    fn wit_contract_subject_borrows_from_subject_storage() {
22335        // The borrow-not-copy pin: [`WitContract::subject`] must return
22336        // an `Option<&str>` whose `Some` arm borrows from the typed
22337        // slot's own [`String`] storage — same-address invariant with
22338        // `c.subject.as_deref().unwrap()`. Pins against a future silent
22339        // detour that allocated a fresh `String`
22340        // (`self.subject.clone().map(...)` in the body would type-check
22341        // but silently drop the borrow, and every downstream consumer
22342        // that assumed the returned slice outlives `&self` would break
22343        // on a stale-reference use-after-free — the [`WitContract::target`]
22344        // PubSub-arm payload extraction rebinds the returned
22345        // `Option<&str>` through `.ok_or_else(...)` and threads the
22346        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
22347        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22348        // [`ContratoIdentity`] dedup key threads the returned
22349        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
22350        // from the WitContract's own storage and each would silently
22351        // misbehave if this accessor produced a detached copy). Peer of
22352        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
22353        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22354        // shaped optional-scalar axis — second extension of the
22355        // `Option<&str>` borrow-not-copy discipline onto the
22356        // per-`:contratos` payload-carrier family, this time on the
22357        // pub-sub arm.
22358        let c = WitContract {
22359            de: "cart".into(),
22360            para: "notifier".into(),
22361            wit: "nats:pub-sub".into(),
22362            endpoint: None,
22363            subject: Some("orders.paid".into()),
22364            slot: None,
22365        };
22366        let sub = c.subject().expect("Some arm");
22367        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
22368        assert_eq!(
22369            sub.as_ptr(),
22370            storage_slice.as_ptr(),
22371            "WitContract::subject must borrow from the .subject \
22372             String's backing storage — a fresh allocation here means \
22373             the accessor no longer names the substrate-primitive typed \
22374             dispatch and every downstream consumer would silently \
22375             carry a detached copy",
22376        );
22377        assert_eq!(
22378            sub.len(),
22379            storage_slice.len(),
22380            "WitContract::subject and .subject.as_deref() must byte-\
22381             equal in length as well as in address",
22382        );
22383    }
22384
22385    #[test]
22386    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
22387        // The canonical per-`:contratos` key/value-store-shaped
22388        // `:slot`-scalar pin: [`WitContract::slot`] must return the
22389        // `:contratos :slot` field byte-for-byte, borrowed from the
22390        // typed slot's own `Option<String>` storage. Peer of the
22391        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
22392        // [`WitContract::subject`] (90de675) accessor pins on the M3
22393        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22394        // optional-scalar axis — same "the substrate-primitive
22395        // accessor must byte-equal the raw field access verbatim
22396        // across every author-declared value" discipline extended to
22397        // the store arm. Pins against a future silent detour that
22398        // re-canonicalized the slot template (an accidental
22399        // `.to_lowercase()` bucket-prefix normalization that didn't
22400        // reach the peer field-access site at the dedup key, a per-CR
22401        // fully-qualified prefix rewrite the operator authors on one
22402        // consumer without the other, or an M4 typed-key-template
22403        // `Display` re-canonicalization that silently drifted the
22404        // printer output from the source `caixa.lisp`). Four values
22405        // sweep the wasi:keyvalue accept-set every store-shaped
22406        // author-declared slot lands on (flat bucket, single-param
22407        // template, multi-param template, nested-hierarchy template).
22408        for slot in [
22409            "sessions",
22410            "carts/{cart_id}",
22411            "orders/{tenant}/{order_id}",
22412            "cache/tenant-a/orders/{id}",
22413        ] {
22414            let c = WitContract {
22415                de: "cart".into(),
22416                para: "kv".into(),
22417                wit: "wasi:keyvalue/store".into(),
22418                endpoint: None,
22419                subject: None,
22420                slot: Some(slot.into()),
22421            };
22422            assert_eq!(
22423                c.slot(),
22424                Some(slot),
22425                "WitContract::slot must return :contratos :slot \
22426                 verbatim (got {:?}, expected Some({slot:?}))",
22427                c.slot(),
22428            );
22429            assert_eq!(
22430                c.slot(),
22431                c.slot.as_deref(),
22432                "WitContract::slot must byte-equal the .slot field's \
22433                 `.as_deref()` projection",
22434            );
22435        }
22436    }
22437
22438    #[test]
22439    fn wit_contract_slot_none_when_field_is_none() {
22440        // The absent-`:slot` arm of the per-`:contratos` store-shaped
22441        // payload-carrier accessor pin: when the typed slot is absent —
22442        // the canonical shape under a non-store `:wit` world per the
22443        // [`WitContract::target`]-enforced shape ↔ target partition
22444        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
22445        // carries `:subject`, [`WitTarget::Capability`] carries none) —
22446        // [`WitContract::slot`] must return `None`. Pins against a
22447        // future silent detour that projected the absent slot to a
22448        // `Some("")` empty-string default (the canonical
22449        // `Option<String>` → `String` collapse footgun the sibling M2
22450        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22451        // emptiness predicates already guard on the peer M2 typed-slot
22452        // surfaces), a `Some("None")` stringified-None round-trip, or
22453        // a `Some` arm whose contents were derived from a sibling
22454        // slot (an accidental fallback to the `:endpoint` / `:subject`
22455        // payload that read the HTTP / pub-sub payload into the store
22456        // axis). Three contracts sweep the accept-set every non-store
22457        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
22458        // payload-less capability.
22459        for (wit, endpoint, subject) in [
22460            ("wasi:http/proxy", Some("/lookup"), None),
22461            ("nats:pub-sub", None, Some("orders.paid")),
22462            ("wasi:cli/environment", None, None),
22463        ] {
22464            let c = WitContract {
22465                de: "cart".into(),
22466                para: "downstream".into(),
22467                wit: wit.into(),
22468                endpoint: endpoint.map(str::to_string),
22469                subject: subject.map(str::to_string),
22470                slot: None,
22471            };
22472            assert!(
22473                c.slot().is_none(),
22474                "WitContract::slot must return None when the typed \
22475                 slot is absent under :wit {wit:?} (got {:?})",
22476                c.slot(),
22477            );
22478            assert_eq!(
22479                c.slot(),
22480                c.slot.as_deref(),
22481                "WitContract::slot must byte-equal the .slot field's \
22482                 `.as_deref()` projection in the absent arm",
22483            );
22484        }
22485    }
22486
22487    #[test]
22488    fn wit_contract_slot_borrows_from_slot_storage() {
22489        // The borrow-not-copy pin: [`WitContract::slot`] must return
22490        // an `Option<&str>` whose `Some` arm borrows from the typed
22491        // slot's own [`String`] storage — same-address invariant with
22492        // `c.slot.as_deref().unwrap()`. Pins against a future silent
22493        // detour that allocated a fresh `String`
22494        // (`self.slot.clone().map(...)` in the body would type-check
22495        // but silently drop the borrow, and every downstream consumer
22496        // that assumed the returned slice outlives `&self` would
22497        // break on a stale-reference use-after-free — the
22498        // [`WitContract::target`] Store-arm payload extraction rebinds
22499        // the returned `Option<&str>` through `.ok_or_else(...)` and
22500        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
22501        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22502        // [`ContratoIdentity`] dedup key threads the returned
22503        // `Option<&str>` into the six-tuple's store arm — each borrow
22504        // from the WitContract's own storage and each would silently
22505        // misbehave if this accessor produced a detached copy). Peer
22506        // of the sibling per-`:contratos` [`WitContract::endpoint`]
22507        // (7020470) / [`WitContract::subject`] (90de675)
22508        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
22509        // shaped optional-scalar axis — third and final extension of
22510        // the `Option<&str>` borrow-not-copy discipline onto the
22511        // per-`:contratos` payload-carrier family, this time on the
22512        // store arm.
22513        let c = WitContract {
22514            de: "cart".into(),
22515            para: "kv".into(),
22516            wit: "wasi:keyvalue/store".into(),
22517            endpoint: None,
22518            subject: None,
22519            slot: Some("carts/{cart_id}".into()),
22520        };
22521        let slot = c.slot().expect("Some arm");
22522        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
22523        assert_eq!(
22524            slot.as_ptr(),
22525            storage_slice.as_ptr(),
22526            "WitContract::slot must borrow from the .slot String's \
22527             backing storage — a fresh allocation here means the \
22528             accessor no longer names the substrate-primitive typed \
22529             dispatch and every downstream consumer would silently \
22530             carry a detached copy",
22531        );
22532        assert_eq!(
22533            slot.len(),
22534            storage_slice.len(),
22535            "WitContract::slot and .slot.as_deref() must byte-equal \
22536             in length as well as in address",
22537        );
22538    }
22539
22540    #[test]
22541    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
22542        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
22543        // [`Membro::nome`] must return the `:membros :caixa` field
22544        // byte-for-byte, borrowed from the typed slot's own [`String`]
22545        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
22546        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22547        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
22548        // slot-atom scalar-value axes — same "the substrate-primitive
22549        // accessor must byte-equal the raw field access verbatim across
22550        // every author-declared value" discipline extended to the
22551        // per-`:membros` member-identity arm. Pins against a future
22552        // silent detour that re-normalized the member identity (an
22553        // accidental `.to_lowercase()` — every `:membros :caixa` is
22554        // validated as a DNS-1123 label upstream via
22555        // [`validate_membro_caixa`], so any re-normalization is
22556        // redundant + a drift surface between the validator and the
22557        // accessor), a namespace-prefix rewrite (an accidental
22558        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
22559        // rewrite that didn't land on the peer axes), or a per-cluster
22560        // alias stamp the operator authors on one consumer without the
22561        // other. Four values sweep the accept-set the DNS-1123 gate
22562        // upstream admits (short single-word / dashed / v-suffixed
22563        // member names).
22564        for name in ["cart", "checkout", "catalog", "orders-v2"] {
22565            let m = Membro {
22566                caixa: name.into(),
22567                versao: "^0.1".into(),
22568            };
22569            assert_eq!(
22570                m.nome(),
22571                name,
22572                "Membro::nome must return :membros :caixa verbatim \
22573                 (got {:?}, expected {name:?})",
22574                m.nome(),
22575            );
22576            assert_eq!(
22577                m.nome(),
22578                m.caixa.as_str(),
22579                "Membro::nome must byte-equal the .caixa field access",
22580            );
22581        }
22582    }
22583
22584    #[test]
22585    fn membro_nome_borrows_from_caixa_storage() {
22586        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
22587        // slice that borrows from the typed slot's own [`String`]
22588        // storage — same-address invariant with `m.caixa.as_str()`. Pins
22589        // against a future silent detour that allocated a fresh `String`
22590        // (`self.caixa.clone()` in the body would type-check but
22591        // silently drop the borrow, and every downstream consumer that
22592        // assumed the returned slice outlives `&self` would break on a
22593        // stale-reference use-after-free — the `HashSet<&str>` collector
22594        // at [`AplicacaoSpec::validate`]'s `names` seed, the
22595        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
22596        // [`AplicacaoSpec::detect_sync_cycles`], the
22597        // [`crate::render::insert_first_seen`] dedup key at
22598        // [`AplicacaoSpec::validate_membros`] — each borrow from the
22599        // Membro's own storage and each would silently misbehave if
22600        // this accessor produced a detached copy). Peer of the sibling
22601        // per-`:contratos` [`WitContract::source`] /
22602        // [`WitContract::destination`] and per-`:entrada`
22603        // [`Entrada::destination`] borrow-invariant pins on the mesh-
22604        // slot-atom scalar-value axes.
22605        let m = Membro {
22606            caixa: "checkout".into(),
22607            versao: "^0.1".into(),
22608        };
22609        let name = m.nome();
22610        let caixa_slice = m.caixa.as_str();
22611        assert_eq!(
22612            name.as_ptr(),
22613            caixa_slice.as_ptr(),
22614            "Membro::nome must borrow from the .caixa String's backing \
22615             storage — a fresh allocation here means the accessor no \
22616             longer names the substrate-primitive typed dispatch and \
22617             every downstream consumer would silently carry a detached \
22618             copy",
22619        );
22620        assert_eq!(
22621            name.len(),
22622            caixa_slice.len(),
22623            "Membro::nome and .caixa.as_str() must byte-equal in length \
22624             as well as in address",
22625        );
22626    }
22627
22628    #[test]
22629    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
22630        // The canonical per-`:membros` member-`:versao`-scalar pin:
22631        // [`Membro::versao_requirement`] must return the
22632        // `:membros :versao` field byte-for-byte, borrowed from the typed
22633        // slot's own [`String`] storage. Sibling of the peer
22634        // `membro_nome_returns_caixa_byte_equal_across_permutations`
22635        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
22636        // — same "the substrate-primitive accessor must byte-equal the
22637        // raw field access verbatim across every author-declared value"
22638        // discipline extended to the per-`:membros` member-`:versao`
22639        // requirement-string arm. Pins against a future silent detour
22640        // that re-canonicalized the requirement (an accidental
22641        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
22642        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
22643        // drifted the printer output away from the source `caixa.lisp`,
22644        // an accidental whitespace trim on `"^ 0.1"` that no consumer
22645        // ever produced from the field-access side, an accidental
22646        // per-cluster lacre-projected concrete-version rewrite that
22647        // didn't land on the peer field-access sites). Five values sweep
22648        // the accept-set the shared
22649        // [`crate::render::require_valid_versao_requirement`] gate
22650        // admits (caret / tilde / exact / wildcard / bare-major).
22651        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
22652            let m = Membro {
22653                caixa: "cart".into(),
22654                versao: req.into(),
22655            };
22656            assert_eq!(
22657                m.versao_requirement(),
22658                req,
22659                "Membro::versao_requirement must return :membros :versao \
22660                 verbatim (got {:?}, expected {req:?})",
22661                m.versao_requirement(),
22662            );
22663            assert_eq!(
22664                m.versao_requirement(),
22665                m.versao.as_str(),
22666                "Membro::versao_requirement must byte-equal the .versao \
22667                 field access",
22668            );
22669        }
22670    }
22671
22672    #[test]
22673    fn membro_versao_requirement_borrows_from_versao_storage() {
22674        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
22675        // return a `&str` slice that borrows from the typed slot's own
22676        // [`String`] storage — same-address invariant with
22677        // `m.versao.as_str()`. Pins against a future silent detour that
22678        // allocated a fresh `String` (`self.versao.clone()` in the body
22679        // would type-check but silently drop the borrow, and every
22680        // downstream consumer that assumed the returned slice outlives
22681        // `&self` would break on a stale-reference use-after-free). Peer
22682        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
22683        // per-`:contratos` [`WitContract::source`] /
22684        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22685        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
22686        // the mesh-slot-atom scalar-value axes.
22687        let m = Membro {
22688            caixa: "checkout".into(),
22689            versao: "^0.1".into(),
22690        };
22691        let req = m.versao_requirement();
22692        let versao_slice = m.versao.as_str();
22693        assert_eq!(
22694            req.as_ptr(),
22695            versao_slice.as_ptr(),
22696            "Membro::versao_requirement must borrow from the .versao \
22697             String's backing storage — a fresh allocation here means \
22698             the accessor no longer names the substrate-primitive typed \
22699             dispatch and every downstream consumer would silently carry \
22700             a detached copy",
22701        );
22702        assert_eq!(
22703            req.len(),
22704            versao_slice.len(),
22705            "Membro::versao_requirement and .versao.as_str() must byte-\
22706             equal in length as well as in address",
22707        );
22708    }
22709
22710    #[test]
22711    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
22712        // Sibling-pair invariant pin composing both per-`:membros`
22713        // substrate-primitive typed dispatches — [`Membro::nome`]
22714        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
22715        // `(nome(), versao_requirement())` call shape every renderer
22716        // that fans on per-member identity + version pin keys off. The
22717        // invariant, evaluated per-member:
22718        //
22719        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
22720        //
22721        // Closes the last unlifted per-`:membros` scalar axis — every
22722        // downstream consumer that reads the pair now routes through
22723        // exactly two typed dispatches on the substrate primitive, not
22724        // one typed + one open-coded field access. A future refactor
22725        // that silently split either accessor's projection (an
22726        // accidental `nome()` namespace-prefix rewrite that didn't
22727        // reach the peer, an accidental `versao_requirement()` lacre-
22728        // projected concrete-version rewrite that didn't land on the
22729        // `nome()` peer) surfaces at caixa-core build time. Peer of the
22730        // sibling per-`:entrada` `(hostname(), destination())` and
22731        // per-`:contratos` `(source(), destination())` pair invariants
22732        // on the mesh-slot-atom scalar-value axes.
22733        for (caixa, versao) in [
22734            ("cart", "^0.1"),
22735            ("checkout", "~0.1.2"),
22736            ("catalog", "0.1.0"),
22737            ("orders-v2", "*"),
22738        ] {
22739            let m = Membro {
22740                caixa: caixa.into(),
22741                versao: versao.into(),
22742            };
22743            assert_eq!(
22744                (m.nome(), m.versao_requirement()),
22745                (m.caixa.as_str(), m.versao.as_str()),
22746                "(Membro::nome, Membro::versao_requirement) must project \
22747                 (.caixa, .versao) verbatim across every author-declared \
22748                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
22749                m.nome(),
22750                m.versao_requirement(),
22751            );
22752        }
22753    }
22754
22755    #[test]
22756    fn validate_membros_empty_gate_routes_through_nome_accessor() {
22757        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
22758        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
22759        // not the raw `.caixa` field access. Structurally: setting
22760        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
22761        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
22762        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
22763        // (i.e. the empty string) — so the emptiness predicate the
22764        // refusal arm reaches under is the accessor-projected value,
22765        // not a peer field that would silently drift under a future
22766        // accessor-side rewrite.
22767        //
22768        // Pins against a future silent detour that (a) re-derived the
22769        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
22770        // instead of `self.nome().is_empty()`, silently disagreeing with
22771        // every peer consumer (the `validate_membro_caixa(m.nome())`
22772        // call one line below, the dedup-key `insert_first_seen(&mut
22773        // seen, m.nome(), …)` two lines below, the emit-side per-
22774        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
22775        // (b) accessor-side introduced a per-tenant alias arm the
22776        // caller was unaware of, silently rewriting an author-declared
22777        // `:caixa "checkout"` to `""` — the raw-field-access gate
22778        // would fail-open while the accessor-routed peer consumers
22779        // would fail-closed, splitting the diagnostic from the actual
22780        // failure surface.
22781        //
22782        // Peer of the sibling
22783        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
22784        // (c0110f1) composition pin — same "the shape-gate predicate
22785        // must route through the substrate-primitive typed dispatch"
22786        // discipline extended onto the per-`:membros` empty-`:caixa`
22787        // refusal-arm axis. Closes the last unlifted `.caixa` production-
22788        // code read site on `Membro` — after this converge every
22789        // caixa-core `.caixa` field access outside the accessor's own
22790        // body is either a test-side field-setter (in-module tests
22791        // constructing invalid-shape inputs) or a doc-comment reference.
22792        let mut s = three_member_spec();
22793        s.membros[1].caixa = String::new();
22794        assert!(
22795            s.membros[1].nome().is_empty(),
22796            "Membro::nome must byte-equal the .caixa field access — an \
22797             accessor-side detour that no longer projects the raw field \
22798             would silently split this drift-detection test from the \
22799             validate() refusal arm",
22800        );
22801        assert_eq!(
22802            s.membros[1].nome(),
22803            s.membros[1].caixa.as_str(),
22804            "Membro::nome and .caixa.as_str() must byte-equal on an \
22805             empty-`:caixa` entry — the emptiness gate keys off the \
22806             accessor by construction",
22807        );
22808        assert_eq!(
22809            s.validate().unwrap_err(),
22810            AplicacaoError::MembroCaixaEmpty,
22811            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
22812             on an entry whose accessor-projected `nome()` is empty",
22813        );
22814    }
22815
22816    #[test]
22817    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
22818        // The canonical per-`:placement` Akka-cluster-sharding
22819        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
22820        // the `:placement :shard-key` field byte-for-byte, borrowed
22821        // from the typed slot's own `Option<String>` storage. Peer of
22822        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
22823        // per-`:contratos` [`WitContract::source`] /
22824        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22825        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
22826        // slot-atom scalar-value axes — same "the substrate-primitive
22827        // accessor must byte-equal the raw field access verbatim across
22828        // every author-declared value" discipline extended to the
22829        // per-`:placement` Akka-cluster-sharding key extractor arm.
22830        // Pins against a future silent detour that re-normalized the
22831        // key (an accidental `.to_lowercase()` — every non-empty
22832        // `:shard-key` is validated as a printable-ASCII single-token
22833        // reference upstream via [`validate_placement_shard_key`], so
22834        // any re-normalization is redundant + a drift surface between
22835        // the validator and the accessor), a per-cluster alias rewrite
22836        // the operator authors on one consumer without the other, or an
22837        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
22838        // that didn't land on the peer field-access sites. Four values
22839        // sweep the accept-set the shape gate admits — bare identifier,
22840        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
22841        // the four canonical Akka-style entity-id extractor shapes the
22842        // future M4 cluster-sharding reconciler hashes.
22843        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
22844            let p = Placement {
22845                estrategia: PlacementStrategy::Sharded,
22846                clusters: vec!["rio".into()],
22847                affinity: None,
22848                shard_key: Some(key.into()),
22849            };
22850            assert_eq!(
22851                p.shard_key(),
22852                Some(key),
22853                "Placement::shard_key must return :placement :shard-key \
22854                 verbatim (got {:?}, expected Some({key:?}))",
22855                p.shard_key(),
22856            );
22857            assert_eq!(
22858                p.shard_key(),
22859                p.shard_key.as_deref(),
22860                "Placement::shard_key must byte-equal the .shard_key \
22861                 field's `.as_deref()` projection",
22862            );
22863        }
22864    }
22865
22866    #[test]
22867    fn placement_shard_key_none_when_field_is_none() {
22868        // The absent-`:shard-key` arm of the per-`:placement`
22869        // Akka-cluster-sharding accessor pin: when the typed slot is
22870        // absent — the canonical shape under `:estrategia Replicated` /
22871        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
22872        // enforced `shard_key.is_some() == matches!(estrategia,
22873        // Sharded)` partition — [`Placement::shard_key`] must return
22874        // `None`. Pins against a future silent detour that projected
22875        // the absent slot to a `Some("")` empty-string default (the
22876        // canonical `Option<String>` → `String` collapse footgun the
22877        // sibling M2 [`crate::LimitsSpec::is_empty`] /
22878        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
22879        // already guard on the peer M2 typed-slot surfaces), a
22880        // `Some("None")` stringified-None round-trip, or a `Some` arm
22881        // whose contents were derived from a sibling slot (an
22882        // accidental fallback to `estrategia.as_str()` that read the
22883        // strategy discriminator into the key axis). Two placements
22884        // sweep the accept-set every `validate`-passing non-`Sharded`
22885        // shape lands on — `Replicated` (Erlang/OTP distributed-app
22886        // takeover) and `SingleNode` (single-node hosting).
22887        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
22888            let p = Placement {
22889                estrategia,
22890                clusters: vec!["rio".into()],
22891                affinity: None,
22892                shard_key: None,
22893            };
22894            assert!(
22895                p.shard_key().is_none(),
22896                "Placement::shard_key must return None when the typed \
22897                 slot is absent under :estrategia {estrategia:?} (got {:?})",
22898                p.shard_key(),
22899            );
22900            assert_eq!(
22901                p.shard_key(),
22902                p.shard_key.as_deref(),
22903                "Placement::shard_key must byte-equal the .shard_key \
22904                 field's `.as_deref()` projection in the absent arm",
22905            );
22906        }
22907    }
22908
22909    #[test]
22910    fn placement_shard_key_borrows_from_shard_key_storage() {
22911        // The borrow-not-copy pin: [`Placement::shard_key`] must return
22912        // an `Option<&str>` whose `Some` arm borrows from the typed
22913        // slot's own [`String`] storage — same-address invariant with
22914        // `p.shard_key.as_deref().unwrap()`. Pins against a future
22915        // silent detour that allocated a fresh `String`
22916        // (`self.shard_key.clone().map(...)` in the body would type-
22917        // check but silently drop the borrow, and every downstream
22918        // consumer that assumed the returned slice outlives `&self`
22919        // would break on a stale-reference use-after-free — the
22920        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
22921        // gate's `Some(k)`-bound match arm reads `k: &str` under the
22922        // accessor's return type and would silently misbehave if this
22923        // accessor produced a detached copy). Peer of the sibling
22924        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
22925        // [`WitContract::source`] / [`WitContract::destination`]
22926        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
22927        // (6db982c) borrow-invariant pins on the mesh-slot-atom
22928        // scalar-value axes — first extension of the discipline onto
22929        // an `Option<String>`-shaped optional-scalar axis.
22930        let p = Placement {
22931            estrategia: PlacementStrategy::Sharded,
22932            clusters: vec!["rio".into()],
22933            affinity: None,
22934            shard_key: Some("tenantId".into()),
22935        };
22936        let key = p.shard_key().expect("Some arm");
22937        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
22938        assert_eq!(
22939            key.as_ptr(),
22940            storage_slice.as_ptr(),
22941            "Placement::shard_key must borrow from the .shard_key \
22942             String's backing storage — a fresh allocation here means \
22943             the accessor no longer names the substrate-primitive typed \
22944             dispatch and every downstream consumer would silently \
22945             carry a detached copy",
22946        );
22947        assert_eq!(
22948            key.len(),
22949            storage_slice.len(),
22950            "Placement::shard_key and .shard_key.as_deref() must byte-\
22951             equal in length as well as in address",
22952        );
22953    }
22954
22955    #[test]
22956    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
22957        // The canonical per-`:placement` M3-Adaptive-compression-hint
22958        // scalar pin: [`Placement::affinity`] must return the
22959        // `:placement :affinity` field byte-for-byte, borrowed from the
22960        // typed slot's own `Option<String>` storage. Peer of the sibling
22961        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
22962        // pin on the sibling `Option<&str>` optional-scalar axis — same
22963        // "the substrate-primitive accessor must byte-equal the raw
22964        // field access verbatim across every author-declared value"
22965        // discipline extended to the peer per-`:placement` M3-Adaptive-
22966        // compression-hint arm. Pins against a future silent detour
22967        // that re-normalized the hint (an accidental `.to_lowercase()`
22968        // — every `:affinity` is already validated as a DNS-1123 label
22969        // upstream via [`validate_placement_affinity`], so any re-
22970        // normalization is redundant + a drift surface between the
22971        // validator and the accessor), a per-cluster alias rewrite the
22972        // operator authors on one consumer without the other, or an
22973        // accidental hint-family collapse (`low-latency` → `latency`
22974        // that dropped the qualifier prefix). Four values sweep the
22975        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
22976        // canonical adaptive-compression-weight biases the future M4
22977        // placement engine reads.
22978        for hint in [
22979            "data-locality",
22980            "low-latency",
22981            "high-throughput",
22982            "cost-optimized",
22983        ] {
22984            let p = Placement {
22985                estrategia: PlacementStrategy::Replicated,
22986                clusters: vec!["rio".into()],
22987                affinity: Some(hint.into()),
22988                shard_key: None,
22989            };
22990            assert_eq!(
22991                p.affinity(),
22992                Some(hint),
22993                "Placement::affinity must return :placement :affinity \
22994                 verbatim (got {:?}, expected Some({hint:?}))",
22995                p.affinity(),
22996            );
22997            assert_eq!(
22998                p.affinity(),
22999                p.affinity.as_deref(),
23000                "Placement::affinity must byte-equal the .affinity \
23001                 field's `.as_deref()` projection",
23002            );
23003        }
23004    }
23005
23006    #[test]
23007    fn placement_affinity_none_when_field_is_none() {
23008        // The absent-`:affinity` arm of the per-`:placement`
23009        // M3-Adaptive-compression-hint accessor pin: when the typed
23010        // slot is absent — the canonical shape of an Aplicacao that
23011        // leaves the compression weighting up to the placement engine's
23012        // cluster-default arm — [`Placement::affinity`] must return
23013        // `None`. Pins against a future silent detour that projected
23014        // the absent slot to a `Some("")` empty-string default (the
23015        // canonical `Option<String>` → `String` collapse footgun the
23016        // sibling M2 [`crate::LimitsSpec::is_empty`] /
23017        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
23018        // already guard on the peer M2 typed-slot surfaces), a
23019        // `Some("None")` stringified-None round-trip, a `Some` arm
23020        // whose contents were derived from a sibling slot (an
23021        // accidental fallback to `estrategia.as_str()` that read the
23022        // strategy discriminator into the hint axis), or a
23023        // `Some("default")` implicit-default that would silently biases
23024        // the routing without the author having written one. Three
23025        // placements sweep the accept-set every `validate`-passing
23026        // `:affinity None` shape lands on — one per PlacementStrategy
23027        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
23028        // with a shard-key), since `:affinity` is orthogonal to
23029        // `:estrategia` in the typed grammar.
23030        for (estrategia, shard_key) in [
23031            (PlacementStrategy::SingleNode, None),
23032            (PlacementStrategy::Replicated, None),
23033            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
23034        ] {
23035            let p = Placement {
23036                estrategia,
23037                clusters: vec!["rio".into()],
23038                affinity: None,
23039                shard_key,
23040            };
23041            assert!(
23042                p.affinity().is_none(),
23043                "Placement::affinity must return None when the typed \
23044                 slot is absent under :estrategia {estrategia:?} (got {:?})",
23045                p.affinity(),
23046            );
23047            assert_eq!(
23048                p.affinity(),
23049                p.affinity.as_deref(),
23050                "Placement::affinity must byte-equal the .affinity \
23051                 field's `.as_deref()` projection in the absent arm",
23052            );
23053        }
23054    }
23055
23056    #[test]
23057    fn placement_affinity_borrows_from_affinity_storage() {
23058        // The borrow-not-copy pin: [`Placement::affinity`] must return
23059        // an `Option<&str>` whose `Some` arm borrows from the typed
23060        // slot's own [`String`] storage — same-address invariant with
23061        // `p.affinity.as_deref().unwrap()`. Pins against a future
23062        // silent detour that allocated a fresh `String`
23063        // (`self.affinity.clone().map(...)` in the body would type-
23064        // check but silently drop the borrow, and every downstream
23065        // consumer that assumed the returned slice outlives `&self`
23066        // would break on a stale-reference use-after-free — the
23067        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
23068        // gate reads the accessor's `&str` return through the
23069        // [`validate_placement_affinity`] `&str` parameter and would
23070        // silently misbehave if this accessor produced a detached
23071        // copy). Peer of the sibling per-`:placement`
23072        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
23073        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
23074        // extends the discipline onto the sibling per-`:placement`
23075        // M3-Adaptive-compression-hint arm.
23076        let p = Placement {
23077            estrategia: PlacementStrategy::Replicated,
23078            clusters: vec!["rio".into()],
23079            affinity: Some("data-locality".into()),
23080            shard_key: None,
23081        };
23082        let hint = p.affinity().expect("Some arm");
23083        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
23084        assert_eq!(
23085            hint.as_ptr(),
23086            storage_slice.as_ptr(),
23087            "Placement::affinity must borrow from the .affinity \
23088             String's backing storage — a fresh allocation here means \
23089             the accessor no longer names the substrate-primitive typed \
23090             dispatch and every downstream consumer would silently \
23091             carry a detached copy",
23092        );
23093        assert_eq!(
23094            hint.len(),
23095            storage_slice.len(),
23096            "Placement::affinity and .affinity.as_deref() must byte-\
23097             equal in length as well as in address",
23098        );
23099    }
23100
23101    #[test]
23102    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
23103        // The canonical per-`:placement` distribution-strategy-scalar
23104        // pin: [`Placement::estrategia`] must return the `:placement
23105        // :estrategia` field verbatim as a [`PlacementStrategy`],
23106        // `Copy`-projected from the typed slot's own `PlacementStrategy`
23107        // storage across every variant in the closed accept-set
23108        // (`SingleNode` — Erlang/OTP distributed-app takeover;
23109        // `Replicated` — active-active across every named cluster;
23110        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
23111        // against a future silent detour that re-derived the strategy
23112        // from a peer axis (an accidental fallback to
23113        // `if shard_key.is_some() { Sharded } else { Replicated }`
23114        // collapse that read the shard-key axis into the strategy
23115        // discriminator), a variant remap the operator authors on one
23116        // consumer without the other, or a stale-derive detour that
23117        // substituted [`PlacementStrategy::default`] when the field
23118        // held any explicit variant (which would silently collapse the
23119        // distinction between "author explicitly declared `:estrategia
23120        // Replicated`" and "author omitted the slot and inherited the
23121        // default" the future per-cluster override slot depends on).
23122        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
23123        // pin on the `Copy`-return `u16` scalar axis — same "the
23124        // substrate-primitive accessor must byte-equal the raw field
23125        // access verbatim across every author-declared value" discipline
23126        // extended onto the per-`:placement` distribution-strategy
23127        // `Copy`-composite-enum scalar axis.
23128        for estrategia in [
23129            PlacementStrategy::SingleNode,
23130            PlacementStrategy::Replicated,
23131            PlacementStrategy::Sharded,
23132        ] {
23133            // Route the paired `:shard-key` fixture-builder through the
23134            // typed cross-slot invariant predicate
23135            // [`PlacementStrategy::requires_shard_key`] rather than the
23136            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
23137            // arm-identity predicate — same discipline the sibling
23138            // `placement_strategy_variants_round_trip` fixture builder now
23139            // reads through.
23140            let shard_key = estrategia
23141                .requires_shard_key()
23142                .then(|| "tenantId".to_string());
23143            let p = Placement {
23144                estrategia,
23145                clusters: vec!["rio".into()],
23146                affinity: None,
23147                shard_key,
23148            };
23149            assert_eq!(
23150                p.estrategia(),
23151                estrategia,
23152                "Placement::estrategia must return :placement :estrategia \
23153                 verbatim (got {:?}, expected {estrategia:?})",
23154                p.estrategia(),
23155            );
23156            assert_eq!(
23157                p.estrategia(),
23158                p.estrategia,
23159                "Placement::estrategia accessor and .estrategia field \
23160                 access must byte-equal — the accessor is the substrate-\
23161                 primitive typed dispatch every downstream distribution-\
23162                 strategy consumer must route through",
23163            );
23164        }
23165    }
23166
23167    #[test]
23168    fn validate_placement_reads_through_lifted_estrategia_accessor() {
23169        // Three-consumer coherence pin: the
23170        // [`AplicacaoSpec::validate_placement`]
23171        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
23172        // `estrategia:` field (which reads through
23173        // [`Placement::estrategia`] to name the strategy the empty
23174        // `:clusters` list was declared against), the same method's
23175        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
23176        // reads through [`Placement::estrategia`] to fan across the
23177        // shape-gate cascades), and the non-`Sharded`-arm
23178        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
23179        // `estrategia:` field (which reads through
23180        // [`Placement::estrategia`] to name the strategy the declared-
23181        // but-inert `:shard-key` was authored under) must all key off
23182        // the lifted accessor, so any future rebrand on the typed
23183        // slot's reader shape lands at exactly one place. Pins the
23184        // three-site coherence by exercising each error surface end-
23185        // to-end and asserting the surfaced `estrategia:` field byte-
23186        // equals the accessor's return. Peer of the sibling per-
23187        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
23188        // pin on the M3 mesh-slot `Copy`-return scalar axis.
23189
23190        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
23191        // whose `estrategia:` field must byte-equal the accessor's return
23192        // for every variant in the closed accept-set.
23193        for estrategia in [
23194            PlacementStrategy::SingleNode,
23195            PlacementStrategy::Replicated,
23196            PlacementStrategy::Sharded,
23197        ] {
23198            let mut spec = three_member_spec();
23199            spec.placement.estrategia = estrategia;
23200            spec.placement.clusters = Vec::new();
23201            // Route the paired `:shard-key` spec-mutator through the typed
23202            // cross-slot invariant predicate
23203            // [`PlacementStrategy::requires_shard_key`] rather than the
23204            // [`gen_platform::IsVariant`]-derived
23205            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
23206            // same discipline the sibling
23207            // `placement_strategy_variants_round_trip` and
23208            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
23209            // fixture builders now read through.
23210            spec.placement.shard_key = estrategia
23211                .requires_shard_key()
23212                .then(|| "tenantId".to_string());
23213            let err = spec.validate().unwrap_err();
23214            match err {
23215                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
23216                    assert_eq!(
23217                        e,
23218                        spec.placement.estrategia(),
23219                        "PlacementWithoutClusters.estrategia must byte-equal \
23220                         Placement::estrategia() — the error carrier reads \
23221                         through the lifted accessor",
23222                    );
23223                }
23224                other => panic!(
23225                    "expected PlacementWithoutClusters, got {other:?} for \
23226                     estrategia={estrategia:?}"
23227                ),
23228            }
23229        }
23230
23231        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
23232        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
23233        // must byte-equal the accessor's return for both non-`Sharded`
23234        // strategies.
23235        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
23236            let mut spec = three_member_spec();
23237            spec.placement.estrategia = estrategia;
23238            spec.placement.shard_key = Some("tenantId".into());
23239            let err = spec.validate().unwrap_err();
23240            match err {
23241                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
23242                    assert_eq!(
23243                        e,
23244                        spec.placement.estrategia(),
23245                        "ShardKeyOnNonSharded.estrategia must byte-equal \
23246                         Placement::estrategia() — the non-Sharded-arm \
23247                         refusal reads through the lifted accessor",
23248                    );
23249                }
23250                other => panic!(
23251                    "expected ShardKeyOnNonSharded, got {other:?} for \
23252                     estrategia={estrategia:?}"
23253                ),
23254            }
23255        }
23256    }
23257
23258    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
23259    //
23260    // The [`Placement::clusters`] accessor lift is the second slice-return
23261    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
23262    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
23263    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
23264    // below cover (1) the accessor's byte-equal projection against the raw
23265    // field access across the empty / singleton / cohort fixtures the
23266    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
23267    // and the per-cluster validate loop fan between, and (2) the two-
23268    // consumer coherence of the paired pre-flight refusal probe and the
23269    // per-cluster validate loop routing through the accessor on both arms.
23270
23271    #[test]
23272    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
23273        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
23274        // [`Placement::clusters`] must return the `:placement :clusters`
23275        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
23276        // the same backing buffer the raw `self.clusters.as_slice()`
23277        // field access borrows from, byte-equal across every
23278        // representative fixture in the accept-set — the empty slice
23279        // (the pre-validation sentinel every
23280        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
23281        // the singleton slice (the minimal `SingleNode`-shape cohort),
23282        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
23283        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
23284        //
23285        // Pins against a future silent detour that returned
23286        // `&Vec<String>` (which would type-check but leak the storage-
23287        // side `Vec`'s grow/push/reserve surface no consumer of the
23288        // typed view reaches for), a fresh-allocated `Vec<String>` copy
23289        // (which would type-check via a coercion but silently break
23290        // every downstream caller that relied on the slice sharing the
23291        // backing buffer's identity), or an out-of-order or length-
23292        // drifted projection (which would silently split the paired
23293        // pre-flight `.is_empty()` refusal probe's input from the per-
23294        // cluster validate loop's traversal input).
23295        //
23296        // Peer of the sibling M2
23297        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23298        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23299        // `:supervisor` static-child-list axis, extended onto the M3
23300        // per-`:placement` distribution-target-list `Vec`-carry axis.
23301        let fixtures: Vec<Vec<String>> = vec![
23302            Vec::new(),
23303            vec!["rio".into()],
23304            vec!["rio".into(), "mar".into()],
23305            vec!["rio".into(), "mar".into(), "plo".into()],
23306        ];
23307        for clusters in fixtures {
23308            let p = Placement {
23309                clusters: clusters.clone(),
23310                ..Placement::default()
23311            };
23312            assert_eq!(
23313                p.clusters(),
23314                clusters.as_slice(),
23315                "Placement::clusters must return :placement :clusters \
23316                 verbatim (got {:?}, expected {:?})",
23317                p.clusters(),
23318                clusters.as_slice(),
23319            );
23320            assert_eq!(
23321                p.clusters(),
23322                p.clusters.as_slice(),
23323                "Placement::clusters accessor and .clusters.as_slice() \
23324                 field access must byte-equal — the accessor is the \
23325                 substrate-primitive typed dispatch every downstream \
23326                 cluster-pool consumer must route through",
23327            );
23328            assert_eq!(
23329                p.clusters().len(),
23330                p.clusters.len(),
23331                "Placement::clusters().len() must byte-equal \
23332                 self.clusters.len() — a length-drift would silently \
23333                 split the paired pre-flight `.is_empty()` refusal \
23334                 probe input from the per-cluster validate loop's \
23335                 traversal input",
23336            );
23337        }
23338    }
23339
23340    #[test]
23341    fn validate_placement_reads_through_lifted_clusters_accessor() {
23342        // Two-consumer coherence pin: the
23343        // [`AplicacaoSpec::validate_placement`] pre-flight
23344        // `self.placement.clusters().is_empty()` refusal probe (which
23345        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
23346        // the accessor projects the empty slice) and the per-cluster
23347        // validate loop's `for c in self.placement.clusters()`
23348        // traversal (which must reach every entry in the same order
23349        // the accessor projects, so both the per-entry value-shape
23350        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
23351        // and the duplicate-detection HashSet insert that trips
23352        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
23353        // accessor's projection) must both key off the lifted
23354        // accessor, so any future rebrand on the typed slot's reader
23355        // shape lands at exactly one place. Pins the two-site
23356        // coherence by exercising each production consumer end-to-end:
23357        // (1) the `PlacementWithoutClusters` refusal under the empty
23358        // slice, (2) the `PlacementClusterInvalid` refusal fires on
23359        // the second entry of a two-cluster cohort whose head is
23360        // valid but tail is not (which requires the loop to reach the
23361        // second entry through the accessor), and (3) the
23362        // `PlacementClusterDuplicate` refusal fires on the second
23363        // entry of a two-cluster cohort that shares a name (which
23364        // requires the loop to reach both entries — a first-entry-only
23365        // projection would silently pass since the dedup HashSet has
23366        // room for the first insert).
23367        //
23368        // Peer of the sibling M2
23369        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23370        // (bc92bce) coherence pin on the per-`:supervisor` static-
23371        // child-list axis, extended onto the M3 per-`:placement`
23372        // distribution-target-list `Vec`-carry axis.
23373
23374        // (1) Pre-flight `.is_empty()` probe: the empty slice must
23375        // trip `PlacementWithoutClusters`.
23376        let mut spec = three_member_spec();
23377        spec.placement.clusters = Vec::new();
23378        match spec.validate().unwrap_err() {
23379            AplicacaoError::PlacementWithoutClusters { .. } => {}
23380            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
23381        }
23382        assert!(
23383            spec.placement.clusters().is_empty(),
23384            "the pre-flight refusal input must be the empty slice per \
23385             the accessor's projection",
23386        );
23387
23388        // (2) Per-cluster validate loop: a two-cluster cohort with an
23389        // invalid tail entry must trip `PlacementClusterInvalid` on
23390        // the tail — the loop must reach the second entry through
23391        // the accessor.
23392        let mut spec = three_member_spec();
23393        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
23394        match spec.validate().unwrap_err() {
23395            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
23396                assert_eq!(
23397                    cluster, "BAD_CLUSTER",
23398                    "PlacementClusterInvalid.cluster must carry the \
23399                     tail entry the loop reached through the accessor",
23400                );
23401            }
23402            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
23403        }
23404        assert_eq!(
23405            spec.placement.clusters().len(),
23406            2,
23407            "the per-cluster validate loop's traversal input must be \
23408             a two-element slice per the accessor's projection",
23409        );
23410
23411        // (3) Per-cluster validate loop: a two-cluster cohort that
23412        // shares a name must trip `PlacementClusterDuplicate` on the
23413        // second entry — the loop must reach both entries through the
23414        // accessor for the dedup HashSet's second insert to collide.
23415        let mut spec = three_member_spec();
23416        spec.placement.clusters = vec!["rio".into(), "rio".into()];
23417        match spec.validate().unwrap_err() {
23418            AplicacaoError::PlacementClusterDuplicate { cluster } => {
23419                assert_eq!(
23420                    cluster, "rio",
23421                    "PlacementClusterDuplicate.cluster must carry the \
23422                     shared cluster name verbatim",
23423                );
23424            }
23425            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
23426        }
23427        assert_eq!(
23428            spec.placement.clusters().len(),
23429            2,
23430            "the per-cluster validate loop's traversal input must be \
23431             a two-element slice per the accessor's projection",
23432        );
23433    }
23434
23435    #[test]
23436    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
23437        // The canonical per-`:membros` member-list-slice-shape pin:
23438        // [`AplicacaoSpec::membros`] must return the `:membros` typed
23439        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
23440        // same backing buffer the raw `self.membros.as_slice()` field
23441        // access borrows from, byte-equal across every representative
23442        // fixture in the accept-set — the empty slice (the pre-
23443        // validation sentinel every [`AplicacaoError::NoMembros`]
23444        // refusal keys off), the singleton slice (the minimal one-
23445        // Servico Aplicacao shape), and multi-entry cohorts (the peer
23446        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
23447        // load-bearing identity of the application graph).
23448        //
23449        // Pins against a future silent detour that returned
23450        // `&Vec<Membro>` (which would type-check but leak the storage-
23451        // side `Vec`'s grow/push/reserve surface no consumer of the
23452        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
23453        // (which would type-check via a coercion but silently break
23454        // every downstream caller that relied on the slice sharing the
23455        // backing buffer's identity), or an out-of-order or length-
23456        // drifted projection (which would silently split the paired
23457        // `HashSet<&str>` name-set seed's collect input from the
23458        // pre-flight `.is_empty()` refusal probe's input from the per-
23459        // member validate loop's traversal input from the
23460        // programs.yaml emitter's per-entry fan-out loop's input from
23461        // the `feira app graph` per-member print traversal's input).
23462        //
23463        // Peer of the sibling M2
23464        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23465        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23466        // `:supervisor` static-child-list axis and the sibling M3
23467        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
23468        // (a6e18d7) `&[String]` byte-equal pin on the per-
23469        // `:placement` distribution-target-list axis — extends the
23470        // slice-return-accessor byte-equal-projection discipline onto
23471        // the outermost M3 mesh-slot type's per-Aplicacao member-list
23472        // `Vec`-carry axis.
23473        let fixtures: Vec<Vec<Membro>> = vec![
23474            Vec::new(),
23475            vec![membro("catalog", "^0.1")],
23476            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23477            vec![
23478                membro("catalog", "^0.1"),
23479                membro("cart", "^0.1"),
23480                membro("payment", "^0.2"),
23481            ],
23482        ];
23483        for membros in fixtures {
23484            let s = AplicacaoSpec {
23485                membros: membros.clone(),
23486                contratos: Vec::new(),
23487                politicas: MeshPolicy::default(),
23488                placement: Placement::default(),
23489                entrada: None,
23490            };
23491            assert_eq!(
23492                s.membros(),
23493                membros.as_slice(),
23494                "AplicacaoSpec::membros must return :membros verbatim \
23495                 (got {:?}, expected {:?})",
23496                s.membros(),
23497                membros.as_slice(),
23498            );
23499            assert_eq!(
23500                s.membros(),
23501                s.membros.as_slice(),
23502                "AplicacaoSpec::membros accessor and .membros.as_slice() \
23503                 field access must byte-equal — the accessor is the \
23504                 substrate-primitive typed dispatch every downstream \
23505                 member-list consumer must route through",
23506            );
23507            assert_eq!(
23508                s.membros().len(),
23509                s.membros.len(),
23510                "AplicacaoSpec::membros().len() must byte-equal \
23511                 self.membros.len() — a length-drift would silently \
23512                 split the paired `HashSet<&str>` name-set seed's \
23513                 collect input from the pre-flight `.is_empty()` \
23514                 refusal probe input from the per-member validate \
23515                 loop's traversal input",
23516            );
23517        }
23518    }
23519
23520    #[test]
23521    fn validate_reads_through_lifted_membros_accessor() {
23522        // Three-consumer coherence pin: the
23523        // [`AplicacaoSpec::validate_membros`] pre-flight
23524        // `self.membros().is_empty()` refusal probe (which must trip
23525        // [`AplicacaoError::NoMembros`] when the accessor projects the
23526        // empty slice), the same method's per-member validate loop's
23527        // `for m in self.membros()` traversal (which must reach every
23528        // entry in the same order the accessor projects, so both the
23529        // per-entry empty-`:caixa` gate that trips
23530        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
23531        // detection `insert_first_seen` that trips
23532        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
23533        // projection), and the peer [`AplicacaoSpec::validate`]'s
23534        // `HashSet<&str>` name-set seed's
23535        // `self.membros().iter().map(Membro::nome).collect()` collect
23536        // input (which every `:contratos` `:de` / `:para` membership
23537        // lookup rejects an unknown name against) must all three key
23538        // off the lifted accessor, so any future rebrand on the typed
23539        // slot's reader shape lands at exactly one place. Pins the
23540        // three-site coherence by exercising each production consumer
23541        // end-to-end: (1) the `NoMembros` refusal under the empty
23542        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
23543        // second entry of a two-member cohort whose head is valid but
23544        // tail has an empty `:caixa` (which requires the loop to
23545        // reach the second entry through the accessor), and (3) the
23546        // `MembroDuplicate` refusal fires on the second entry of a
23547        // two-member cohort that shares a `:caixa` name (which
23548        // requires the loop to reach both entries through the
23549        // accessor for the dedup HashSet's second insert to collide).
23550        //
23551        // Peer of the sibling M2
23552        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23553        // (bc92bce) coherence pin on the per-`:supervisor` static-
23554        // child-list axis and the sibling M3
23555        // `validate_placement_reads_through_lifted_clusters_accessor`
23556        // (a6e18d7) coherence pin on the per-`:placement` distribution-
23557        // target-list axis — extends the slice-return-accessor
23558        // multi-consumer coherence discipline onto the outermost M3
23559        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
23560
23561        // (1) Pre-flight `.is_empty()` probe: the empty slice must
23562        // trip `NoMembros`.
23563        let mut spec = three_member_spec();
23564        spec.membros = Vec::new();
23565        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
23566        assert!(
23567            spec.membros().is_empty(),
23568            "the pre-flight refusal input must be the empty slice per \
23569             the accessor's projection",
23570        );
23571
23572        // (2) Per-member validate loop: a two-member cohort with an
23573        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
23574        // the tail — the loop must reach the second entry through
23575        // the accessor.
23576        let mut spec = three_member_spec();
23577        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
23578        assert_eq!(
23579            spec.validate().unwrap_err(),
23580            AplicacaoError::MembroCaixaEmpty,
23581        );
23582        assert_eq!(
23583            spec.membros().len(),
23584            2,
23585            "the per-member validate loop's traversal input must be \
23586             a two-element slice per the accessor's projection",
23587        );
23588
23589        // (3) Per-member validate loop: a two-member cohort that
23590        // shares a `:caixa` name must trip `MembroDuplicate` on the
23591        // second entry — the loop must reach both entries through the
23592        // accessor for the dedup HashSet's second insert to collide.
23593        let mut spec = three_member_spec();
23594        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
23595        match spec.validate().unwrap_err() {
23596            AplicacaoError::MembroDuplicate { caixa } => {
23597                assert_eq!(
23598                    caixa, "catalog",
23599                    "MembroDuplicate.caixa must carry the shared \
23600                     member name verbatim",
23601                );
23602            }
23603            other => panic!("expected MembroDuplicate, got {other:?}"),
23604        }
23605        assert_eq!(
23606            spec.membros().len(),
23607            2,
23608            "the per-member validate loop's traversal input must be \
23609             a two-element slice per the accessor's projection",
23610        );
23611    }
23612
23613    #[test]
23614    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
23615        // The canonical per-`:contratos` contract-list-slice-shape pin:
23616        // [`AplicacaoSpec::contratos`] must return the `:contratos`
23617        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
23618        // slice-view over the same backing buffer the raw
23619        // `self.contratos.as_slice()` field access borrows from, byte-
23620        // equal across every representative fixture in the accept-set —
23621        // the empty slice (the pre-validation "internal-only mesh" shape
23622        // an Aplicacao whose members exchange no typed edges renders
23623        // through), the singleton slice (the minimal one-edge Aplicacao
23624        // shape), and multi-entry cohorts (the peer multi-edge shapes
23625        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
23626        // of the application graph).
23627        //
23628        // Pins against a future silent detour that returned
23629        // `&Vec<WitContract>` (which would type-check but leak the
23630        // storage-side `Vec`'s grow/push/reserve surface no consumer of
23631        // the typed view reaches for), a fresh-allocated
23632        // `Vec<WitContract>` copy (which would type-check via a coercion
23633        // but silently break every downstream caller that relied on the
23634        // slice sharing the backing buffer's identity), or an out-of-
23635        // order or length-drifted projection (which would silently split
23636        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
23637        // seed's traversal input from the `detect_sync_cycles` per-edge
23638        // adjacency-list seed's traversal input from the
23639        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
23640        // BTreeMap grouping loop's traversal input from the
23641        // `feira app graph` per-contract print traversal's input).
23642        //
23643        // Peer of the immediately-adjacent sibling M3
23644        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
23645        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
23646        // node-list axis, the sibling M3
23647        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
23648        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
23649        // distribution-target-list axis, and the sibling M2
23650        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23651        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23652        // `:supervisor` static-child-list axis — extends the slice-
23653        // return-accessor byte-equal-projection discipline onto the
23654        // outermost M3 mesh-slot type's per-Aplicacao contract-list
23655        // `Vec`-carry axis, closing the last unlifted per-
23656        // `AplicacaoSpec` `Vec`-carry axis.
23657        let fixtures: Vec<Vec<WitContract>> = vec![
23658            Vec::new(),
23659            vec![contract_http("cart", "catalog", "/products/:id")],
23660            vec![
23661                contract_http("cart", "catalog", "/products/:id"),
23662                contract_http("cart", "payment", "/charge"),
23663            ],
23664            vec![
23665                contract_http("cart", "catalog", "/products/:id"),
23666                contract_http("cart", "payment", "/charge"),
23667                contract_http("payment", "catalog", "/audit"),
23668            ],
23669        ];
23670        for contratos in fixtures {
23671            let s = AplicacaoSpec {
23672                membros: vec![
23673                    membro("catalog", "^0.1"),
23674                    membro("cart", "^0.1"),
23675                    membro("payment", "^0.2"),
23676                ],
23677                contratos: contratos.clone(),
23678                politicas: MeshPolicy::default(),
23679                placement: Placement::default(),
23680                entrada: None,
23681            };
23682            assert_eq!(
23683                s.contratos(),
23684                contratos.as_slice(),
23685                "AplicacaoSpec::contratos must return :contratos verbatim \
23686                 (got {:?}, expected {:?})",
23687                s.contratos(),
23688                contratos.as_slice(),
23689            );
23690            assert_eq!(
23691                s.contratos(),
23692                s.contratos.as_slice(),
23693                "AplicacaoSpec::contratos accessor and \
23694                 .contratos.as_slice() field access must byte-equal — \
23695                 the accessor is the substrate-primitive typed dispatch \
23696                 every downstream contract-list consumer must route \
23697                 through",
23698            );
23699            assert_eq!(
23700                s.contratos().len(),
23701                s.contratos.len(),
23702                "AplicacaoSpec::contratos().len() must byte-equal \
23703                 self.contratos.len() — a length-drift would silently \
23704                 split the paired per-edge validate-loop's traversal \
23705                 input from the sync-cycle adjacency-list seed's \
23706                 traversal input from the cilium_network_policies \
23707                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
23708                 input from the `feira app graph` per-contract print \
23709                 traversal's input",
23710            );
23711        }
23712    }
23713
23714    #[test]
23715    fn validate_reads_through_lifted_contratos_accessor() {
23716        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
23717        // per-`:contratos` validate-loop's `for c in self.contratos()`
23718        // traversal (which must reach every entry in the same order the
23719        // accessor projects, so both the per-entry
23720        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
23721        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
23722        // dedup `HashSet` insert key off the accessor's projection),
23723        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
23724        // `for c in self.contratos()` adjacency-list seed (which drives
23725        // the sync-subgraph deadlock-detection gate via
23726        // [`AplicacaoError::SyncCycle`]), and the peer
23727        // [`caixa_mesh::cilium_network_policies`]'s
23728        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
23729        // grouping loop (which drives the per-CNP fan-out) must all
23730        // three key off the lifted accessor, so any future rebrand on
23731        // the typed slot's reader shape lands at exactly one place. Pins
23732        // the three-site coherence by exercising the two caixa-core
23733        // production consumers end-to-end: (1) the empty-`:contratos`
23734        // slice must validate without a per-edge diagnostic (the
23735        // per-edge loop is a no-op under the empty projection), (2) the
23736        // `ContratoMemberMissing` refusal fires on the second entry of a
23737        // two-edge cohort whose head references a valid member but tail
23738        // references a phantom name (which requires the loop to reach
23739        // the second entry through the accessor), and (3) the
23740        // `SyncCycle` refusal fires on a self-referential two-edge
23741        // cohort through the sync-cycle detector's peer projection
23742        // (which requires the detector to iterate the accessor's
23743        // projection to add the back-edge to its adjacency list).
23744        //
23745        // Peer of the sibling M3
23746        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23747        // three-consumer coherence pin on the per-`:membros` node-list
23748        // axis and the sibling M3
23749        // `validate_placement_reads_through_lifted_clusters_accessor`
23750        // (a6e18d7) coherence pin on the per-`:placement` distribution-
23751        // target-list axis — extends the slice-return-accessor multi-
23752        // consumer coherence discipline onto the outermost M3 mesh-slot
23753        // type's per-Aplicacao contract-list `Vec`-carry axis.
23754
23755        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
23756        // and no per-edge diagnostic surfaces. Validate succeeds on
23757        // the well-formed `:membros` head.
23758        let mut spec = three_member_spec();
23759        spec.contratos = Vec::new();
23760        assert!(
23761            spec.validate().is_ok(),
23762            "empty :contratos must validate — the per-edge loop is a \
23763             no-op under the accessor's empty projection",
23764        );
23765        assert!(
23766            spec.contratos().is_empty(),
23767            "the per-edge validate loop's traversal input must be the \
23768             empty slice per the accessor's projection",
23769        );
23770
23771        // (2) Per-edge validate loop: a two-edge cohort whose tail
23772        // references a phantom `:para` member must trip
23773        // `ContratoMemberMissing` on the tail — the loop must reach
23774        // the second entry through the accessor for the membership
23775        // lookup to fail on the phantom name.
23776        let mut spec = three_member_spec();
23777        spec.contratos = vec![
23778            contract_http("cart", "catalog", "/products/:id"),
23779            contract_http("cart", "phantom", "/x"),
23780        ];
23781        let err = spec.validate().unwrap_err();
23782        assert!(
23783            matches!(
23784                err,
23785                AplicacaoError::ContratoMemberMissing { ref caixa }
23786                    if caixa == "phantom"
23787            ),
23788            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
23789        );
23790        assert_eq!(
23791            spec.contratos().len(),
23792            2,
23793            "the per-edge validate loop's traversal input must be \
23794             a two-element slice per the accessor's projection",
23795        );
23796
23797        // (3) Sync-cycle detector: a two-edge synchronous cohort
23798        // whose second edge closes the sync-subgraph back onto the
23799        // first must trip [`AplicacaoError::ContratoCycle`] — the
23800        // detector must iterate the accessor's projection to add
23801        // both edges to its adjacency list, so a length-drift on
23802        // the accessor's projection would silently disagree with
23803        // the sync-cycle detector on which edge closes the loop.
23804        // Peer projection to the `validate` per-edge loop above:
23805        // the sync-cycle detector routes through the same lifted
23806        // accessor, so a rebrand of the reader shape lands at one
23807        // place. Uses a two-edge cohort (cart → catalog → cart)
23808        // because the per-edge `ContratoSelfLoop` gate fires before
23809        // the sync-cycle detector on a single self-referential edge
23810        // (`cart → cart`) — the cycle-detector's input must be a
23811        // multi-edge cohort for its per-edge traversal input to be
23812        // observably wider than the per-edge validate loop's input.
23813        let mut spec = three_member_spec();
23814        spec.contratos = vec![
23815            contract_http("cart", "catalog", "/products/:id"),
23816            contract_http("catalog", "cart", "/callback"),
23817        ];
23818        let err = spec.validate().unwrap_err();
23819        assert!(
23820            matches!(err, AplicacaoError::ContratoCycle { .. }),
23821            "expected ContratoCycle from the sync-cycle detector on a \
23822             two-edge back-edge cohort, got {err:?}",
23823        );
23824        assert_eq!(
23825            spec.contratos().len(),
23826            2,
23827            "the sync-cycle detector's traversal input must be a \
23828             two-element slice per the accessor's projection",
23829        );
23830    }
23831
23832    #[test]
23833    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
23834        // The canonical per-`:politicas` outer-composite-reference-shape
23835        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
23836        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
23837        // the same backing storage the raw `&self.politicas` field
23838        // access borrows from, byte-equal across every representative
23839        // fixture in the accept-set — the default `MeshPolicy` (the
23840        // author-empty "no policy on any axis" shape whose
23841        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
23842        // shapes carrying one axis at a time
23843        // (`{mtls_required, timeout, retries, circuit_breaker,
23844        // rate_limit}` — the minimal five-axis fan-out over the
23845        // per-axis lifted accessor family every downstream mesh-artifact
23846        // emitter dispatches on), and the multi-axis composite (the
23847        // canonical `three_member_spec` fixture's `{timeout, retries,
23848        // mtls_required}` triple — the load-bearing shape every
23849        // Aplicacao-scoped fixture in this suite constructs).
23850        //
23851        // Pins against a future silent detour that returned a fresh-
23852        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
23853        // impl but silently break every downstream caller that relied
23854        // on the reference sharing the composite's backing identity), a
23855        // reference to an operator-resolved overlay (the future
23856        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
23857        // acknowledges — its resolution must land at exactly this
23858        // accessor body, not silently divert the raw slot away from a
23859        // second consumer), or an axis-shuffled projection (a future
23860        // detour that swapped `timeout` and `retries` through the
23861        // accessor would silently split the paired `validate_politicas`
23862        // per-axis bracket-dispatch's traversal input from the peer
23863        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
23864        // emitter's fan-out input from the peer
23865        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
23866        // overlay emitter's fan-out input).
23867        //
23868        // Peer of the sibling M3
23869        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
23870        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
23871        // node-list `Vec`-carry axis and the sibling M3
23872        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
23873        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
23874        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
23875        // accessor byte-equal-projection discipline onto the outermost
23876        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
23877        // reference axis, the first `&Composite`-return accessor on the
23878        // outer [`AplicacaoSpec`] type.
23879        let fixtures: Vec<MeshPolicy> = vec![
23880            MeshPolicy::default(),
23881            MeshPolicy {
23882                mtls_required: Some(true),
23883                ..MeshPolicy::default()
23884            },
23885            MeshPolicy {
23886                mtls_required: Some(false),
23887                ..MeshPolicy::default()
23888            },
23889            MeshPolicy {
23890                timeout: Some(Duration::from_secs(30)),
23891                ..MeshPolicy::default()
23892            },
23893            MeshPolicy {
23894                retries: Some(3),
23895                ..MeshPolicy::default()
23896            },
23897            MeshPolicy {
23898                circuit_breaker: Some(CircuitBreaker {
23899                    max_failures: 5,
23900                    window: Duration::from_secs(30),
23901                }),
23902                ..MeshPolicy::default()
23903            },
23904            MeshPolicy {
23905                rate_limit: Some(RateLimit {
23906                    rate: 100,
23907                    window: Duration::from_secs(1),
23908                }),
23909                ..MeshPolicy::default()
23910            },
23911            MeshPolicy {
23912                timeout: Some(Duration::from_secs(30)),
23913                retries: Some(3),
23914                mtls_required: Some(true),
23915                ..MeshPolicy::default()
23916            },
23917        ];
23918        for politicas in fixtures {
23919            let s = AplicacaoSpec {
23920                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23921                contratos: Vec::new(),
23922                politicas: politicas.clone(),
23923                placement: Placement::default(),
23924                entrada: None,
23925            };
23926            assert_eq!(
23927                *s.politicas(),
23928                politicas,
23929                "AplicacaoSpec::politicas must return :politicas verbatim \
23930                 (got {:?}, expected {:?})",
23931                s.politicas(),
23932                politicas,
23933            );
23934            assert!(
23935                std::ptr::eq(s.politicas(), &s.politicas),
23936                "AplicacaoSpec::politicas accessor and &self.politicas \
23937                 field access must borrow the same backing storage — \
23938                 the accessor is the substrate-primitive typed dispatch \
23939                 every downstream mesh-policy composite consumer must \
23940                 route through, and a reference-identity split would \
23941                 silently break every consumer that relied on the \
23942                 borrow sharing the composite's storage",
23943            );
23944            assert_eq!(
23945                s.politicas().is_empty(),
23946                s.politicas.is_empty(),
23947                "AplicacaoSpec::politicas().is_empty() must byte-equal \
23948                 self.politicas.is_empty() — an emptiness-drift would \
23949                 silently split the paired `validate_politicas` \
23950                 per-axis bracket-dispatch's seed from the peer \
23951                 caixa-mesh CNP mTLS-overlay emitter's key from the \
23952                 peer caixa-mesh HTTPRoute timeout+retry overlay \
23953                 emitter's key",
23954            );
23955        }
23956    }
23957
23958    #[test]
23959    fn validate_politicas_reads_through_lifted_politicas_accessor() {
23960        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
23961        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
23962        // followed by the per-axis fan-out `p.timeout()` /
23963        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
23964        // the lifted axis-level accessor family) must key off the
23965        // lifted outer accessor, so any future rebrand on the typed
23966        // slot's outer-composite reader shape lands at exactly one
23967        // place. Pins the multi-axis coherence by exercising each
23968        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
23969        // a `Some(Duration::ZERO)` timeout under the outer accessor's
23970        // reference projection, (2) `PolicyRetriesZero` fires on a
23971        // `Some(0)` retries under the same projection, and (3) an
23972        // empty [`MeshPolicy::default`] passes `validate_politicas` —
23973        // the outer accessor's reference-projection reaches every
23974        // per-axis branch without silently short-circuiting any.
23975        //
23976        // Peer of the sibling M3
23977        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23978        // three-consumer coherence pin on the per-`:membros` node-list
23979        // axis and the sibling M3
23980        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
23981        // three-consumer coherence pin on the per-`:contratos`
23982        // edge-list axis — extends the multi-consumer coherence
23983        // discipline onto the outermost M3 mesh-slot type's per-
23984        // Aplicacao mesh-policy composite-reference axis, the first
23985        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
23986        // type.
23987
23988        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
23989        // reference projection: a `Some(Duration::ZERO)` timeout must
23990        // trip the zero-floor gate. The bracket-dispatch's first arm
23991        // reads `p.timeout()` on the reference returned by the outer
23992        // accessor.
23993        let mut spec = three_member_spec();
23994        spec.politicas.timeout = Some(Duration::ZERO);
23995        spec.politicas.retries = None;
23996        spec.politicas.circuit_breaker = None;
23997        spec.politicas.rate_limit = None;
23998        assert_eq!(
23999            spec.validate().unwrap_err(),
24000            AplicacaoError::PolicyTimeoutZero,
24001        );
24002        assert!(
24003            std::ptr::eq(spec.politicas(), &spec.politicas),
24004            "the `validate_politicas` per-axis bracket-dispatch's \
24005             traversal input must be the same backing composite the \
24006             accessor's reference projection borrows from",
24007        );
24008
24009        // (2) `PolicyRetriesZero` refusal under the outer accessor's
24010        // reference projection: a `Some(0)` retries must trip the
24011        // zero-floor gate. The bracket-dispatch's second arm reads
24012        // `p.retries()` on the reference returned by the outer accessor.
24013        let mut spec = three_member_spec();
24014        spec.politicas.timeout = None;
24015        spec.politicas.retries = Some(0);
24016        spec.politicas.circuit_breaker = None;
24017        spec.politicas.rate_limit = None;
24018        assert_eq!(
24019            spec.validate().unwrap_err(),
24020            AplicacaoError::PolicyRetriesZero,
24021        );
24022
24023        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
24024        // — every per-axis arm short-circuits on `None`, so the outer
24025        // accessor's reference projection reaches the fall-through
24026        // `Ok(())` without any per-axis refusal firing.
24027        let mut spec = three_member_spec();
24028        spec.politicas = MeshPolicy::default();
24029        assert!(
24030            spec.validate().is_ok(),
24031            "an empty `MeshPolicy` must pass `validate_politicas` — \
24032             every per-axis arm short-circuits on `None` under the \
24033             outer accessor's reference projection",
24034        );
24035        assert!(
24036            spec.politicas().is_empty(),
24037            "the outer accessor's reference projection must be the \
24038             empty composite per the `MeshPolicy::default()` fixture",
24039        );
24040    }
24041
24042    #[test]
24043    #[allow(clippy::too_many_lines)]
24044    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
24045        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
24046        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
24047        // must both key off the lifted axis-level accessors
24048        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
24049        // the peer `:circuit-breaker` / `:rate-limit` arms already
24050        // routing through [`MeshPolicy::circuit_breaker`] /
24051        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
24052        // per axis on the substrate primitive" shape at the fan-out
24053        // (four axes, four accessors, no raw-field-access site
24054        // anywhere on the bracket-dispatch). Pins the per-axis
24055        // coherence at the accept-set boundaries the bracket carves:
24056        //   1. accessor byte-equal to raw field on every representative
24057        //      accept-set value (`None`, sub-cap, at-cap, past-cap
24058        //      sentinel) — a future accessor drift that no longer
24059        //      shipped the raw slot verbatim would surface here,
24060        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
24061        //      routed through the accessor's projection, proving the
24062        //      first arm reads through the accessor rather than a
24063        //      silent-detour peer-axis field access,
24064        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
24065        //      through the accessor's projection, proving the second
24066        //      arm reads through the accessor,
24067        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
24068        //      passes validate under the accessor projection (paired
24069        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
24070        //      sibling axis), pinning the upper-boundary accept-arm
24071        //      also routes through the accessor.
24072        //
24073        // Peer of the sibling M3
24074        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24075        // outer-composite-reference coherence pin (which asserts the
24076        // `let p = self.politicas()` seed); extends the discipline onto
24077        // the per-axis fan-out layer that consumes the seed's
24078        // reference. Same shape as
24079        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24080        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24081        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
24082        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
24083
24084        // (1) Accessor byte-equal to raw field on the `:timeout` axis
24085        // across the accept-set boundaries the bracket dispatch's
24086        // three-arm gate carves out
24087        // ([`crate::render::require_positive_canonical_bounded_duration`]
24088        // — zero-floor + canonical-form + upper-cap).
24089        for timeout in [
24090            None,
24091            Some(Duration::ZERO),
24092            Some(Duration::from_millis(1)),
24093            Some(POLICY_TIMEOUT_MAX),
24094        ] {
24095            let p = MeshPolicy {
24096                timeout,
24097                ..MeshPolicy::default()
24098            };
24099            assert_eq!(
24100                p.timeout(),
24101                p.timeout,
24102                "MeshPolicy::timeout accessor must byte-equal the raw \
24103                 .timeout field across every accept-set boundary the \
24104                 validate_politicas :timeout arm carves out — a drift \
24105                 here would silently split the validate bracket's arm \
24106                 from the peer caixa-mesh HTTPRoute timeout-overlay \
24107                 emitter's read",
24108            );
24109        }
24110
24111        // (2) Accessor byte-equal to raw field on the `:retries` axis
24112        // across the accept-set boundaries the bracket dispatch's
24113        // two-arm gate carves out
24114        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
24115        // + upper-cap).
24116        for retries in [
24117            None,
24118            Some(0u32),
24119            Some(1u32),
24120            Some(POLICY_RETRIES_MAX),
24121            Some(POLICY_RETRIES_MAX + 1),
24122            Some(u32::MAX),
24123        ] {
24124            let p = MeshPolicy {
24125                retries,
24126                ..MeshPolicy::default()
24127            };
24128            assert_eq!(
24129                p.retries(),
24130                p.retries,
24131                "MeshPolicy::retries accessor must byte-equal the raw \
24132                 .retries field across every accept-set boundary the \
24133                 validate_politicas :retries arm carves out — a drift \
24134                 here would silently split the validate bracket's arm \
24135                 from the peer caixa-mesh HTTPRoute retry-overlay \
24136                 emitter's read",
24137            );
24138        }
24139
24140        // (3) `PolicyTimeoutZero` fires on the accessor-projected
24141        // zero-floor boundary. A silent detour that no longer read
24142        // through `p.timeout()` (a peer-axis field read, an accidental
24143        // Option::and-then chain that collapsed the None arm to Some,
24144        // an accessor rebrand that clamped the return through the
24145        // upper cap) would fail to refuse here.
24146        let mut spec = three_member_spec();
24147        spec.politicas.timeout = Some(Duration::ZERO);
24148        spec.politicas.retries = None;
24149        spec.politicas.circuit_breaker = None;
24150        spec.politicas.rate_limit = None;
24151        assert_eq!(
24152            spec.politicas().timeout(),
24153            Some(Duration::ZERO),
24154            "the accessor projection must reflect the fixture's \
24155             `Some(Duration::ZERO)` :timeout verbatim",
24156        );
24157        assert_eq!(
24158            spec.validate().unwrap_err(),
24159            AplicacaoError::PolicyTimeoutZero,
24160            "the validate_politicas :timeout zero-floor arm must fire \
24161             through the lifted accessor's projection — a silent \
24162             detour to a peer-axis field would fail to refuse",
24163        );
24164
24165        // (4) `PolicyRetriesZero` fires on the accessor-projected
24166        // zero-floor boundary on the sibling `:retries` axis.
24167        let mut spec = three_member_spec();
24168        spec.politicas.timeout = None;
24169        spec.politicas.retries = Some(0);
24170        spec.politicas.circuit_breaker = None;
24171        spec.politicas.rate_limit = None;
24172        assert_eq!(
24173            spec.politicas().retries(),
24174            Some(0),
24175            "the accessor projection must reflect the fixture's \
24176             `Some(0)` :retries verbatim",
24177        );
24178        assert_eq!(
24179            spec.validate().unwrap_err(),
24180            AplicacaoError::PolicyRetriesZero,
24181            "the validate_politicas :retries zero-floor arm must fire \
24182             through the lifted accessor's projection — a silent \
24183             detour to a peer-axis field would fail to refuse",
24184        );
24185
24186        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
24187        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
24188        // must pass validate under the accessor projection — pins the
24189        // upper-boundary accept-arm also routes through the lifted
24190        // accessor (a drift that clamped or short-circuited at the
24191        // upper boundary would fail the whole-spec validate here).
24192        let mut spec = three_member_spec();
24193        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
24194        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
24195        spec.politicas.circuit_breaker = None;
24196        spec.politicas.rate_limit = None;
24197        assert_eq!(
24198            spec.politicas().timeout(),
24199            Some(POLICY_TIMEOUT_MAX),
24200            "the accessor projection must reflect the fixture's \
24201             at-cap :timeout verbatim",
24202        );
24203        assert_eq!(
24204            spec.politicas().retries(),
24205            Some(POLICY_RETRIES_MAX),
24206            "the accessor projection must reflect the fixture's \
24207             at-cap :retries verbatim",
24208        );
24209        assert!(
24210            spec.validate().is_ok(),
24211            "at-cap :timeout + :retries must pass validate under the \
24212             accessor projection — the upper-boundary accept-arm on \
24213             both axes routes through the lifted accessor",
24214        );
24215    }
24216
24217    #[test]
24218    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
24219        // The canonical per-`:placement` outer-composite-reference-shape
24220        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
24221        // typed `Placement` verbatim as a `&Placement` reference over the
24222        // same backing storage the raw `&self.placement` field access
24223        // borrows from, byte-equal across every representative fixture in
24224        // the accept-set — the default `Placement` (the substrate seed
24225        // shape whose [`PlacementStrategy::default`] evaluates to
24226        // `SingleNode` with an empty `:clusters` pool and both
24227        // optional-scalar axes `None`), and every canonical strategy /
24228        // cluster-pool / optional-scalar combination the
24229        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
24230        // three [`PlacementStrategy`] variants — `SingleNode`,
24231        // `Replicated`, `Sharded` — cross-projected with a non-empty
24232        // `:clusters` pool and, on the `Sharded` arm, a non-empty
24233        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
24234        // canonical `three_member_spec` `Replicated` fixture's
24235        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
24236        //
24237        // Pins against a future silent detour that returned a fresh-
24238        // cloned `Placement` copy (which would type-check via a `Clone`
24239        // impl but silently break every downstream caller that relied on
24240        // the reference sharing the composite's backing identity), a
24241        // reference to an operator-resolved overlay (the future per-
24242        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
24243        // acknowledges — its resolution must land at exactly this
24244        // accessor body, not silently divert the raw slot away from a
24245        // second consumer), or an axis-shuffled projection (a future
24246        // detour that swapped `clusters` and `affinity` through the
24247        // accessor would silently split the paired `validate_placement`
24248        // per-axis bracket-dispatch's traversal input from the peer
24249        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
24250        // programs.yaml distribution-annotation emitter's fan-out input
24251        // from the peer `feira app graph` per-Aplicacao print line's
24252        // input).
24253        //
24254        // Peer of the sibling M3
24255        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24256        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
24257        // outer mesh-policy composite-reference axis, and of the sibling
24258        // slice-return `aplicacao_spec_membros_returns_membros_slice_
24259        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
24260        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
24261        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
24262        // the outer-accessor byte-equal-projection discipline onto the
24263        // outermost M3 mesh-slot type's per-Aplicacao distribution
24264        // composite-reference axis, the second `&Composite`-return
24265        // accessor on the outer [`AplicacaoSpec`] type.
24266        let fixtures: Vec<Placement> = vec![
24267            Placement::default(),
24268            Placement {
24269                estrategia: PlacementStrategy::SingleNode,
24270                clusters: vec!["rio".into()],
24271                affinity: None,
24272                shard_key: None,
24273            },
24274            Placement {
24275                estrategia: PlacementStrategy::Replicated,
24276                clusters: vec!["rio".into(), "mar".into()],
24277                affinity: None,
24278                shard_key: None,
24279            },
24280            Placement {
24281                estrategia: PlacementStrategy::Replicated,
24282                clusters: vec!["rio".into(), "mar".into()],
24283                affinity: Some("data-locality".into()),
24284                shard_key: None,
24285            },
24286            Placement {
24287                estrategia: PlacementStrategy::Sharded,
24288                clusters: vec!["rio".into(), "mar".into()],
24289                affinity: None,
24290                shard_key: Some("tenantId".into()),
24291            },
24292            Placement {
24293                estrategia: PlacementStrategy::Sharded,
24294                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
24295                affinity: Some("low-latency".into()),
24296                shard_key: Some("metadata.tenantId".into()),
24297            },
24298        ];
24299        for placement in fixtures {
24300            let s = AplicacaoSpec {
24301                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24302                contratos: Vec::new(),
24303                politicas: MeshPolicy::default(),
24304                placement: placement.clone(),
24305                entrada: None,
24306            };
24307            assert_eq!(
24308                *s.placement(),
24309                placement,
24310                "AplicacaoSpec::placement must return :placement verbatim \
24311                 (got {:?}, expected {:?})",
24312                s.placement(),
24313                placement,
24314            );
24315            assert!(
24316                std::ptr::eq(s.placement(), &s.placement),
24317                "AplicacaoSpec::placement accessor and &self.placement \
24318                 field access must borrow the same backing storage — the \
24319                 accessor is the substrate-primitive typed dispatch every \
24320                 downstream distribution-composite consumer must route \
24321                 through, and a reference-identity split would silently \
24322                 break every consumer that relied on the borrow sharing \
24323                 the composite's storage",
24324            );
24325            assert_eq!(
24326                s.placement().estrategia(),
24327                s.placement.estrategia,
24328                "AplicacaoSpec::placement().estrategia() must byte-equal \
24329                 self.placement.estrategia — a strategy-drift would \
24330                 silently split the paired `validate_placement` \
24331                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
24332                 peer caixa-mesh programs.yaml `placement.estrategia` \
24333                 emitter's key from the peer `feira app graph` printer's \
24334                 strategy label",
24335            );
24336            assert_eq!(
24337                s.placement().clusters(),
24338                s.placement.clusters.as_slice(),
24339                "AplicacaoSpec::placement().clusters() must byte-equal \
24340                 self.placement.clusters — a cluster-pool drift would \
24341                 silently split the paired `validate_placement` \
24342                 pre-flight `.is_empty()` refusal probe's traversal from \
24343                 the peer caixa-mesh programs.yaml `placement.clusters` \
24344                 emitter's fan-out from the peer `feira app graph` \
24345                 printer's cluster list",
24346            );
24347        }
24348    }
24349
24350    #[test]
24351    fn validate_placement_reads_through_lifted_placement_accessor() {
24352        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
24353        // per-axis bracket-dispatch seed (`let p = self.placement();`,
24354        // followed by the per-axis fan-out `p.clusters()` /
24355        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
24356        // lifted axis-level accessor family) must key off the lifted
24357        // outer accessor, so any future rebrand on the typed slot's
24358        // outer-composite reader shape lands at exactly one place. Pins
24359        // the multi-axis coherence by exercising each per-axis refusal
24360        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
24361        // `:clusters` pool under the outer accessor's reference
24362        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
24363        // strategy with a `None` `:shard-key` under the same projection,
24364        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
24365        // with a `Some` `:shard-key` under the same projection, and
24366        // (4) the canonical `three_member_spec` `Replicated` fixture
24367        // passes `validate_placement` under the outer accessor's
24368        // reference projection — the accessor's reference-projection
24369        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
24370        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
24371        // without silently short-circuiting any.
24372        //
24373        // Peer of the sibling M3
24374        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24375        // (534dc21) multi-axis coherence pin on the per-`:politicas`
24376        // outer mesh-policy composite-reference axis — extends the
24377        // multi-consumer coherence discipline onto the outermost M3
24378        // mesh-slot type's per-Aplicacao distribution composite-
24379        // reference axis, the second `&Composite`-return accessor on
24380        // the outer [`AplicacaoSpec`] type.
24381
24382        // (1) `PlacementWithoutClusters` refusal under the outer
24383        // accessor's reference projection: an empty `:clusters` pool
24384        // must trip the pre-flight refusal probe. The bracket-dispatch's
24385        // first arm reads `p.clusters()` on the reference returned by
24386        // the outer accessor.
24387        let mut spec = three_member_spec();
24388        spec.placement.clusters = Vec::new();
24389        assert_eq!(
24390            spec.validate().unwrap_err(),
24391            AplicacaoError::PlacementWithoutClusters {
24392                estrategia: PlacementStrategy::Replicated,
24393            },
24394        );
24395        assert!(
24396            std::ptr::eq(spec.placement(), &spec.placement),
24397            "the `validate_placement` per-axis bracket-dispatch's \
24398             traversal input must be the same backing composite the \
24399             accessor's reference projection borrows from",
24400        );
24401
24402        // (2) `ShardedWithoutKey` refusal under the outer accessor's
24403        // reference projection: a `Sharded` strategy with a `None`
24404        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
24405        // The bracket-dispatch's third arm reads `p.estrategia()` for
24406        // the match scrutinee then `p.shard_key()` for the cascade
24407        // scrutinee, both on the reference returned by the outer
24408        // accessor.
24409        let mut spec = three_member_spec();
24410        spec.placement.estrategia = PlacementStrategy::Sharded;
24411        spec.placement.shard_key = None;
24412        assert_eq!(
24413            spec.validate().unwrap_err(),
24414            AplicacaoError::ShardedWithoutKey,
24415        );
24416
24417        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
24418        // reference projection: a non-`Sharded` strategy with a `Some`
24419        // `:shard-key` must trip the declared-but-inert refusal. The
24420        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
24421        // + `p.estrategia()` for the diagnostic on the reference
24422        // returned by the outer accessor.
24423        let mut spec = three_member_spec();
24424        spec.placement.estrategia = PlacementStrategy::Replicated;
24425        spec.placement.shard_key = Some("tenantId".into());
24426        assert_eq!(
24427            spec.validate().unwrap_err(),
24428            AplicacaoError::ShardKeyOnNonSharded {
24429                estrategia: PlacementStrategy::Replicated,
24430                shard_key: "tenantId".into(),
24431            },
24432        );
24433
24434        // (4) Canonical `three_member_spec` `Replicated` fixture passes
24435        // `validate_placement` — every per-axis arm reaches the fall-
24436        // through `Ok(())` without any per-axis refusal firing under the
24437        // outer accessor's reference projection.
24438        let spec = three_member_spec();
24439        assert!(
24440            spec.validate().is_ok(),
24441            "the canonical Replicated placement fixture must pass \
24442             `validate_placement` — every per-axis arm short-circuits on \
24443             valid input under the outer accessor's reference projection",
24444        );
24445        assert_eq!(
24446            spec.placement().estrategia(),
24447            PlacementStrategy::Replicated,
24448            "the outer accessor's reference projection must be the \
24449             canonical Replicated fixture's strategy",
24450        );
24451        assert_eq!(
24452            spec.placement().clusters(),
24453            &["rio", "mar"],
24454            "the outer accessor's reference projection must be the \
24455             canonical Replicated fixture's cluster pool",
24456        );
24457    }
24458
24459    #[test]
24460    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
24461        // The canonical per-`:entrada` outer-composite-optional-
24462        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
24463        // the `:entrada` typed `Option<Entrada>` verbatim as an
24464        // `Option<&Entrada>` reference over the same backing storage
24465        // the raw `self.entrada.as_ref()` field access borrows from,
24466        // byte-equal across every representative fixture in the
24467        // accept-set — the author-omitted `None` shape (the
24468        // "internal-only mesh" partition every downstream external-
24469        // gateway emitter treats as "emit nothing"), the minimal
24470        // singleton `:entrada` composite (host + destination + empty
24471        // paths + default port), the paths-carrying composite (the
24472        // canonical `three_member_spec` fixture's ["/api" "/health"]
24473        // path-list shape every HTTPRoute per-rule fan-out emitter
24474        // reads), and the non-default port composite (the canonical
24475        // custom-port shape the port-fallback resolver reads).
24476        //
24477        // Pins against a future silent detour that returned a fresh-
24478        // cloned `Entrada` copy (which would type-check via a `Clone`
24479        // impl but silently break every downstream caller that
24480        // relied on the reference sharing the composite's backing
24481        // identity), a reference to an operator-resolved overlay
24482        // (the future per-cluster `:entrada-overrides` slot the
24483        // MESH-COMPOSITION §V federation roadmap acknowledges — its
24484        // resolution must land at exactly this accessor body, not
24485        // silently divert the raw slot away from a second consumer),
24486        // a `None` → `Some(Entrada::default)` cluster-default
24487        // projection (which would collapse the load-bearing
24488        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
24489        // the peer `gateway_routes` early-return + `feira app graph`
24490        // internal-only-mesh partition both read), or an axis-
24491        // shuffled projection (a future detour that swapped
24492        // `host` and `para` through the accessor would silently
24493        // split the paired `validate` per-`:entrada` shape-and-
24494        // membership gate's traversal input from the peer
24495        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
24496        // fan-out input from the peer `feira app graph` external-
24497        // gateway summary line).
24498        //
24499        // Peer of the sibling M3
24500        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24501        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
24502        // `:politicas` outer mesh-policy composite-reference axis
24503        // and of the sibling M3
24504        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
24505        // (9abb8f0) `&Placement` byte-equal pin on the per-
24506        // `:placement` outer distribution-composite composite-
24507        // reference axis — extends the outer-accessor byte-equal-
24508        // projection discipline onto the last unlifted outermost M3
24509        // mesh-slot type's per-Aplicacao external-gateway composite-
24510        // reference axis, the third and final `&Composite`-return
24511        // accessor on the outer [`AplicacaoSpec`] type.
24512        let fixtures: Vec<Option<Entrada>> = vec![
24513            None,
24514            Some(Entrada {
24515                host: "checkout.quero.cloud".into(),
24516                para: "cart".into(),
24517                paths: Vec::new(),
24518                port: DEFAULT_SERVICO_PORT,
24519            }),
24520            Some(Entrada {
24521                host: "checkout.quero.cloud".into(),
24522                para: "cart".into(),
24523                paths: vec!["/api".into(), "/health".into()],
24524                port: DEFAULT_SERVICO_PORT,
24525            }),
24526            Some(Entrada {
24527                host: "checkout.quero.cloud".into(),
24528                para: "cart".into(),
24529                paths: vec!["/api".into()],
24530                port: 9443,
24531            }),
24532        ];
24533        for entrada in fixtures {
24534            let s = AplicacaoSpec {
24535                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24536                contratos: Vec::new(),
24537                politicas: MeshPolicy::default(),
24538                placement: Placement::default(),
24539                entrada: entrada.clone(),
24540            };
24541            assert_eq!(
24542                s.entrada(),
24543                entrada.as_ref(),
24544                "AplicacaoSpec::entrada must return :entrada verbatim \
24545                 (got {:?}, expected {:?})",
24546                s.entrada(),
24547                entrada.as_ref(),
24548            );
24549            match (s.entrada(), s.entrada.as_ref()) {
24550                (Some(a), Some(b)) => assert!(
24551                    std::ptr::eq(a, b),
24552                    "AplicacaoSpec::entrada accessor and \
24553                     self.entrada.as_ref() field access must borrow \
24554                     the same backing storage — the accessor is the \
24555                     substrate-primitive typed dispatch every \
24556                     downstream external-gateway composite consumer \
24557                     must route through, and a reference-identity \
24558                     split would silently break every consumer that \
24559                     relied on the borrow sharing the composite's \
24560                     storage",
24561                ),
24562                (None, None) => {}
24563                _ => panic!(
24564                    "AplicacaoSpec::entrada presence bit must byte-\
24565                     equal self.entrada.is_some() — a presence-bit \
24566                     drift would silently split the paired `validate` \
24567                     per-`:entrada` shape-and-membership gate's \
24568                     traversal head from the peer \
24569                     caixa-mesh gateway_routes early-return partition \
24570                     from the peer `feira app graph` internal-only-\
24571                     mesh partition",
24572                ),
24573            }
24574            assert_eq!(
24575                s.entrada().is_some(),
24576                s.entrada.is_some(),
24577                "AplicacaoSpec::entrada().is_some() must byte-equal \
24578                 self.entrada.is_some() — a presence-bit drift would \
24579                 silently split every downstream `Option<&Entrada>` \
24580                 consumer's partition on the internal-only-mesh arm",
24581            );
24582        }
24583    }
24584
24585    #[test]
24586    fn validate_reads_through_lifted_entrada_accessor() {
24587        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
24588        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
24589        // self.entrada() { … }`, followed by the per-axis fan-out
24590        // `validate_entrada_para(&e.para)` /
24591        // `EntradaMemberMissing` membership lookup /
24592        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
24593        // per-`e.paths` `validate_entrada_path` traversal) must key
24594        // off the lifted outer accessor, so any future rebrand on
24595        // the typed slot's outer-composite reader shape lands at
24596        // exactly one place. Pins the multi-axis coherence by
24597        // exercising each per-axis refusal end-to-end: (1) the
24598        // author-omitted `None` shape short-circuits past every
24599        // per-`:entrada` refusal (the internal-only mesh partition
24600        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
24601        // fires on a well-shaped but phantom `:para` under the outer
24602        // accessor's reference projection, and (3) the canonical
24603        // `three_member_spec` `:entrada` fixture passes `validate`
24604        // under the outer accessor's reference projection.
24605        //
24606        // Peer of the sibling M3
24607        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24608        // (534dc21) multi-axis coherence pin on the per-`:politicas`
24609        // outer mesh-policy composite-reference axis and the sibling
24610        // M3
24611        // [`validate_placement_reads_through_lifted_placement_accessor`]
24612        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
24613        // outer distribution-composite composite-reference axis —
24614        // extends the multi-consumer coherence discipline onto the
24615        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
24616        // external-gateway composite-reference axis, the third and
24617        // final `&Composite`-return accessor on the outer
24618        // [`AplicacaoSpec`] type.
24619
24620        // (1) `None` :entrada — the internal-only-mesh partition
24621        // short-circuits past every per-`:entrada` refusal. The outer
24622        // accessor's reference projection reaches the fall-through
24623        // `Ok(())` on the `None` arm without any per-axis refusal
24624        // firing.
24625        let mut spec = three_member_spec();
24626        spec.entrada = None;
24627        assert!(
24628            spec.validate().is_ok(),
24629            "an author-omitted `:entrada` must pass `validate` — the \
24630             internal-only-mesh partition short-circuits past every \
24631             per-`:entrada` refusal under the outer accessor's \
24632             reference projection",
24633        );
24634        assert!(
24635            spec.entrada().is_none(),
24636            "the outer accessor's reference projection must name the \
24637             internal-only-mesh partition per the `None` fixture",
24638        );
24639
24640        // (2) `EntradaMemberMissing` refusal under the outer accessor's
24641        // reference projection: a well-shaped but phantom `:para` must
24642        // trip the membership-lookup refusal. The gate's second arm
24643        // reads `e.para` on the reference returned by the outer
24644        // accessor.
24645        let mut spec = three_member_spec();
24646        if let Some(e) = spec.entrada.as_mut() {
24647            e.para = "phantom".into();
24648        }
24649        assert_eq!(
24650            spec.validate().unwrap_err(),
24651            AplicacaoError::EntradaMemberMissing {
24652                para: "phantom".into(),
24653            },
24654        );
24655        match (spec.entrada(), spec.entrada.as_ref()) {
24656            (Some(a), Some(b)) => assert!(
24657                std::ptr::eq(a, b),
24658                "the `validate` per-`:entrada` gate's traversal head \
24659                 must be the same backing composite the accessor's \
24660                 reference projection borrows from",
24661            ),
24662            _ => panic!("fixture must carry Some(:entrada)"),
24663        }
24664
24665        // (3) Canonical `three_member_spec` `:entrada` fixture passes
24666        // `validate` — every per-axis arm reaches the fall-through
24667        // `Ok(())` without any per-axis refusal firing under the
24668        // outer accessor's reference projection.
24669        let spec = three_member_spec();
24670        assert!(
24671            spec.validate().is_ok(),
24672            "the canonical `:entrada` fixture must pass `validate` — \
24673             every per-axis arm short-circuits on valid input under \
24674             the outer accessor's reference projection",
24675        );
24676        assert!(
24677            spec.entrada().is_some(),
24678            "the outer accessor's reference projection must be the \
24679             canonical `:entrada` fixture's composite",
24680        );
24681    }
24682
24683    #[test]
24684    fn port_for_destination_reads_through_lifted_entrada_accessor() {
24685        // Peer coherence pin: the
24686        // [`AplicacaoSpec::port_for_destination`] per-destination
24687        // L4-port fallback resolver's composite-projection seed
24688        // (`self.entrada().filter(…).map_or(…)`) must key off the
24689        // lifted outer accessor. Pins the coherence by exercising
24690        // the resolver end-to-end: (1) the `None` `:entrada` shape
24691        // falls through to `DEFAULT_SERVICO_PORT` under the outer
24692        // accessor's reference projection, (2) a non-matching
24693        // destination falls through to `DEFAULT_SERVICO_PORT` under
24694        // the outer accessor's reference projection, and (3) the
24695        // matching destination resolves to the `:entrada :port`
24696        // value under the outer accessor's reference projection.
24697        //
24698        // Peer of the sibling
24699        // [`validate_reads_through_lifted_entrada_accessor`] multi-
24700        // consumer coherence pin on the same per-`:entrada` outer-
24701        // composite axis — extends the multi-consumer coherence
24702        // discipline onto the second per-`:entrada` production
24703        // consumer, the L4-port fallback resolver.
24704
24705        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
24706        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
24707        // arm under the outer accessor's reference projection.
24708        let mut spec = three_member_spec();
24709        spec.entrada = None;
24710        assert_eq!(
24711            spec.port_for_destination("cart"),
24712            DEFAULT_SERVICO_PORT,
24713            "the port-fallback resolver must fall through to \
24714             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
24715             under the outer accessor's reference projection",
24716        );
24717
24718        // (2) Non-matching destination — the resolver's `filter(…)`
24719        // arm rejects a mismatched destination and falls through
24720        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
24721        // reference projection.
24722        let mut spec = three_member_spec();
24723        if let Some(e) = spec.entrada.as_mut() {
24724            e.para = "cart".into();
24725            e.port = 9443;
24726        }
24727        assert_eq!(
24728            spec.port_for_destination("catalog"),
24729            DEFAULT_SERVICO_PORT,
24730            "the port-fallback resolver must fall through to \
24731             DEFAULT_SERVICO_PORT on a non-matching destination \
24732             under the outer accessor's reference projection",
24733        );
24734
24735        // (3) Matching destination — the resolver's `map_or(…)` arm
24736        // returns the `:entrada :port` value under the outer
24737        // accessor's reference projection.
24738        let mut spec = three_member_spec();
24739        if let Some(e) = spec.entrada.as_mut() {
24740            e.para = "cart".into();
24741            e.port = 9443;
24742        }
24743        assert_eq!(
24744            spec.port_for_destination("cart"),
24745            9443,
24746            "the port-fallback resolver must return the \
24747             `:entrada :port` value on a matching destination \
24748             under the outer accessor's reference projection",
24749        );
24750    }
24751
24752    #[test]
24753    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
24754        // The canonical per-`:politicas` `:mtls-required` mTLS-
24755        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
24756        // must return the `:politicas :mtls-required` typed bool
24757        // verbatim as an `Option<bool>`, byte-equal to the raw field
24758        // access across every value in the three-way accept-set —
24759        // `None` (cluster default applies), `Some(true)` (mTLS
24760        // handshake enforced — the sandboxing-by-default arm the
24761        // MeshPolicy's docstring names), `Some(false)` (handshake
24762        // skipped — the explicit debug-edge opt-out).
24763        //
24764        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
24765        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
24766        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
24767        // shape — first `Option<Copy-T>`-return accessor on the M3
24768        // mesh-slot family. Pins against a future silent detour that
24769        // re-derived the toggle from a peer axis (an accidental
24770        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
24771        // whenever a breaker is set), a `None` → `Some(false)` cluster-
24772        // default projection (the canonical `Option<bool>` → `bool`
24773        // collapse footgun the surrounding `is_empty()` predicate
24774        // guards on the peer emptiness axis), or a `Some(true)` /
24775        // `Some(false)` variant swap that landed on one consumer
24776        // without the other.
24777        for required in [None, Some(true), Some(false)] {
24778            let p = MeshPolicy {
24779                mtls_required: required,
24780                ..MeshPolicy::default()
24781            };
24782            assert_eq!(
24783                p.mtls_required(),
24784                required,
24785                "MeshPolicy::mtls_required must return :politicas \
24786                 :mtls-required verbatim (got {:?}, expected {required:?})",
24787                p.mtls_required(),
24788            );
24789            assert_eq!(
24790                p.mtls_required(),
24791                p.mtls_required,
24792                "MeshPolicy::mtls_required must byte-equal the raw \
24793                 .mtls_required field access across every value in the \
24794                 three-way accept-set",
24795            );
24796        }
24797    }
24798
24799    #[test]
24800    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
24801        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
24802        // arm must key off [`MeshPolicy::mtls_required`], not the raw
24803        // `.mtls_required` field access. Structurally: toggling ONLY
24804        // the `mtls_required` slot on an otherwise-default MeshPolicy
24805        // must flip `is_empty()` from `true` (all-`None`) to `false`
24806        // (one axis carries a value); the flip must be observed for
24807        // both `Some(true)` and `Some(false)` since the emptiness
24808        // semantic reads "any axis carries a value" — not "any axis
24809        // carries a truthy value" — the same non-collapsing shape the
24810        // sibling M2 [`crate::LimitsSpec::is_empty`] /
24811        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
24812        // peer `Option<T>`-typed slot surfaces.
24813        //
24814        // Pins against a future silent detour that re-derived the
24815        // emptiness predicate off a peer axis (an accidental
24816        // `.rate_limit.is_none()`-only chain that dropped the
24817        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
24818        // collapse to a truthy-only check (which would silently
24819        // classify `Some(false)` as empty), or an accessor-side
24820        // detour that no longer names the substrate-primitive typed
24821        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
24822        // == false` fallback in the accessor that would silently
24823        // classify both `None` and `Some(false)` as the same value).
24824        //
24825        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
24826        // (7cd2a28) accessor-composition pin on the sibling optional-
24827        // scalar axis — same "the emptiness / shape-gate predicate
24828        // must route through the substrate-primitive typed dispatch"
24829        // discipline extended onto the peer per-`:politicas` emptiness
24830        // predicate.
24831        let empty = MeshPolicy::default();
24832        assert!(
24833            empty.is_empty(),
24834            "MeshPolicy::default() must be is_empty() — every axis \
24835             defaults to None",
24836        );
24837        for required in [Some(true), Some(false)] {
24838            let p = MeshPolicy {
24839                mtls_required: required,
24840                ..MeshPolicy::default()
24841            };
24842            assert!(
24843                !p.is_empty(),
24844                "MeshPolicy::is_empty must return false when \
24845                 :mtls-required is {required:?} — the emptiness \
24846                 predicate reads \"any axis carries a value\", not \
24847                 \"any axis carries a truthy value\"",
24848            );
24849            assert_eq!(
24850                p.mtls_required().is_none(),
24851                p.is_empty(),
24852                "when :mtls-required is the only set axis, \
24853                 is_empty() must equal mtls_required().is_none() — \
24854                 the accessor and the emptiness predicate must \
24855                 route through the same substrate-primitive typed \
24856                 dispatch on the :mtls-required arm",
24857            );
24858        }
24859    }
24860
24861    #[test]
24862    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
24863        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
24864        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
24865        // accessor must return by value, not by reference. Peer of the
24866        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
24867        // borrow-invariant pin on the sibling `Option<String>` slot,
24868        // but extended onto the peer `Option<bool>` copy-invariant
24869        // shape — the accessor's returned `Option<bool>` must outlive
24870        // `&self` (multiple calls must return equal values from a
24871        // dropped-`&self` copy, since the returned Option carries no
24872        // borrow), and calling the accessor twice on the same
24873        // MeshPolicy must yield the same `Option<bool>` verbatim
24874        // (idempotent, no side effects on `&self`).
24875        //
24876        // Pins against a future silent detour that returned
24877        // `Option<&bool>` (which would type-check but silently break
24878        // every downstream caller — [`single_field_overlay`]'s first
24879        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
24880        // detached copy at the call site), an accidental
24881        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
24882        // would also type-check but return `Option<&bool>`), or a
24883        // one-arm-only accessor that reads `Some(*b)` in the Some arm
24884        // but reads a fresh Default::default() in the None arm.
24885        for required in [None, Some(true), Some(false)] {
24886            let p = MeshPolicy {
24887                mtls_required: required,
24888                ..MeshPolicy::default()
24889            };
24890            let first = p.mtls_required();
24891            let second = p.mtls_required();
24892            assert_eq!(
24893                first, second,
24894                "MeshPolicy::mtls_required must be idempotent — two \
24895                 successive calls on the same &self must return the \
24896                 same Option<bool>",
24897            );
24898            assert_eq!(
24899                first, required,
24900                "MeshPolicy::mtls_required must return :politicas \
24901                 :mtls-required verbatim by copy — got {first:?}, \
24902                 expected {required:?}",
24903            );
24904        }
24905    }
24906
24907    #[test]
24908    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
24909        // The canonical per-`:politicas` `:retries` transient-failure-
24910        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
24911        // the `:politicas :retries` typed `u32` verbatim as an
24912        // `Option<u32>`, byte-equal to the raw field access across every
24913        // representative value in the accept-set — `None` (cluster
24914        // default applies — typically "no retries beyond a single
24915        // dispatch attempt" the caixa-mesh `retry_overlay` builder
24916        // documents), `Some(1)` (the lower boundary of the
24917        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
24918        // `AplicacaoSpec::validate_politicas` gate carves out on the
24919        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
24920        // (the upper boundary the same gate carves out on the sibling
24921        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
24922        // past-the-guard sentinel that pins the accessor doesn't perform
24923        // a silent bounds-collapse at the return path).
24924        //
24925        // Sibling of the peer per-`:politicas`
24926        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
24927        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
24928        // peer per-`:politicas` `Option<u32>` shape — second
24929        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
24930        // Pins against a future silent detour that re-derived the retry
24931        // cap from a peer axis (an accidental `.circuit_breaker
24932        // .as_ref().map(|b| b.max_failures)` collapse that read the
24933        // breaker's max-failure count as a retry budget), a
24934        // `None → Some(0)` cluster-default projection (which would
24935        // silently re-introduce the `PolicyRetriesZero` refusal case at
24936        // the emit boundary), or a bounds-collapsing accessor that
24937        // clamped the return through `POLICY_RETRIES_MAX` (the
24938        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
24939        // must ship the raw slot verbatim so a validate-time gate
24940        // regression surfaces at the emit boundary rather than being
24941        // silently absorbed).
24942        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
24943            let p = MeshPolicy {
24944                retries,
24945                ..MeshPolicy::default()
24946            };
24947            assert_eq!(
24948                p.retries(),
24949                retries,
24950                "MeshPolicy::retries must return :politicas :retries \
24951                 verbatim (got {:?}, expected {retries:?})",
24952                p.retries(),
24953            );
24954            assert_eq!(
24955                p.retries(),
24956                p.retries,
24957                "MeshPolicy::retries must byte-equal the raw .retries \
24958                 field access across every value in the accept-set",
24959            );
24960        }
24961    }
24962
24963    #[test]
24964    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
24965        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
24966        // must key off [`MeshPolicy::retries`], not the raw `.retries`
24967        // field access. Structurally: toggling ONLY the `retries` slot
24968        // on an otherwise-default MeshPolicy must flip `is_empty()`
24969        // from `true` (all-`None`) to `false` (one axis carries a
24970        // value); the flip must be observed for every value in the
24971        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
24972        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
24973        // the emptiness semantic reads "any axis carries a value" —
24974        // not "any axis carries a value the validate gate accepts" —
24975        // the same non-collapsing shape the peer M2
24976        // [`crate::LimitsSpec::is_empty`] /
24977        // [`crate::BehaviorSpec::is_empty`] predicates carry.
24978        //
24979        // Pins against a future silent detour that re-derived the
24980        // emptiness predicate off a peer axis (an accidental
24981        // `.rate_limit.is_none()`-only chain that dropped the
24982        // `retries` arm entirely), a `retries == Some(_)` collapse
24983        // that key-off a validate-gate-clamped bounds check (which
24984        // would silently classify a past-the-guard `Some(u32::MAX)`
24985        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
24986        // check), or an accessor-side detour that no longer names the
24987        // substrate-primitive typed dispatch.
24988        //
24989        // Sibling of the peer per-`:politicas`
24990        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
24991        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
24992        // same "the emptiness predicate must route through the
24993        // substrate-primitive typed dispatch" discipline extended onto
24994        // the peer per-`:politicas` `Option<u32>` axis.
24995        let empty = MeshPolicy::default();
24996        assert!(
24997            empty.is_empty(),
24998            "MeshPolicy::default() must be is_empty() — every axis \
24999             defaults to None",
25000        );
25001        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
25002            let p = MeshPolicy {
25003                retries,
25004                ..MeshPolicy::default()
25005            };
25006            assert!(
25007                !p.is_empty(),
25008                "MeshPolicy::is_empty must return false when \
25009                 :retries is {retries:?} — the emptiness \
25010                 predicate reads \"any axis carries a value\", not \
25011                 \"any axis carries a value the validate gate \
25012                 accepts\"",
25013            );
25014            assert_eq!(
25015                p.retries().is_none(),
25016                p.is_empty(),
25017                "when :retries is the only set axis, is_empty() \
25018                 must equal retries().is_none() — the accessor and \
25019                 the emptiness predicate must route through the same \
25020                 substrate-primitive typed dispatch on the :retries \
25021                 arm",
25022            );
25023        }
25024    }
25025
25026    #[test]
25027    fn mesh_policy_retries_projects_option_u32_by_copy() {
25028        // The by-copy pin: [`MeshPolicy::retries`] returns
25029        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
25030        // accessor must return by value, not by reference. Sibling of
25031        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
25032        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
25033        // extended onto the sibling `Option<u32>` copy-invariant
25034        // shape — the accessor's returned `Option<u32>` must outlive
25035        // `&self` (multiple calls must return equal values from a
25036        // dropped-`&self` copy, since the returned Option carries no
25037        // borrow), and calling the accessor twice on the same
25038        // MeshPolicy must yield the same `Option<u32>` verbatim
25039        // (idempotent, no side effects on `&self`).
25040        //
25041        // Pins against a future silent detour that returned
25042        // `Option<&u32>` (which would type-check but silently break
25043        // every downstream caller — [`crate::render::single_field_overlay`]'s
25044        // first parameter is `Option<T: Clone>`, and `&u32` would
25045        // fold to a detached copy at the call site), an accidental
25046        // `Option::as_ref()` projection (`self.retries.as_ref()` would
25047        // also type-check but return `Option<&u32>`), or a one-arm-
25048        // only accessor that reads `Some(*n)` in the Some arm but
25049        // reads a fresh `Default::default()` (`0_u32`) in the None
25050        // arm.
25051        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
25052            let p = MeshPolicy {
25053                retries,
25054                ..MeshPolicy::default()
25055            };
25056            let first = p.retries();
25057            let second = p.retries();
25058            assert_eq!(
25059                first, second,
25060                "MeshPolicy::retries must be idempotent — two \
25061                 successive calls on the same &self must return the \
25062                 same Option<u32>",
25063            );
25064            assert_eq!(
25065                first, retries,
25066                "MeshPolicy::retries must return :politicas :retries \
25067                 verbatim by copy — got {first:?}, expected {retries:?}",
25068            );
25069        }
25070    }
25071
25072    #[test]
25073    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
25074        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
25075        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
25076        // return the `:politicas :timeout` typed [`Duration`] verbatim
25077        // as an `Option<Duration>`, byte-equal to the raw field access
25078        // across every representative value in the accept-set — `None`
25079        // (cluster default applies — typically the gateway class's
25080        // implementation-side per-request wall-clock cap the caixa-mesh
25081        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
25082        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
25083        // set the surrounding `AplicacaoSpec::validate_politicas` gate
25084        // carves out on the sibling `PolicyTimeoutZero` /
25085        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
25086        // (the upper boundary the same gate carves out on the sibling
25087        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
25088        // (a past-the-guard sentinel that pins the accessor doesn't
25089        // perform a silent bounds-collapse into `None` on the zero-
25090        // Duration arm — validate rejects zero but the accessor must
25091        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
25092        // past-the-guard sentinel that pins the accessor doesn't
25093        // perform a silent bounds-collapse at the return path).
25094        //
25095        // Sibling of the peer per-`:politicas`
25096        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
25097        // `Option<u32>` optional-scalar axis and the peer per-
25098        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
25099        // pin on the sibling `Option<bool>` optional-scalar axis,
25100        // extended onto the peer per-`:politicas` `Option<Duration>`
25101        // shape — third `Option<Copy-T>`-return accessor on the M3
25102        // mesh-slot family. Pins against a future silent detour that
25103        // re-derived the per-call cap from a peer axis (an accidental
25104        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
25105        // read the breaker's rolling-window duration as a per-call
25106        // deadline), a `None → Some(Duration::MAX)` cluster-default
25107        // projection (which would silently re-introduce the
25108        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
25109        // blocking" arm at the emit boundary), or a bounds-collapsing
25110        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
25111        // (the `AplicacaoSpec::validate` gate owns the bounds; the
25112        // accessor must ship the raw slot verbatim so a validate-time
25113        // gate regression surfaces at the emit boundary rather than
25114        // being silently absorbed).
25115        for timeout in [
25116            None,
25117            Some(Duration::from_millis(1)),
25118            Some(POLICY_TIMEOUT_MAX),
25119            Some(Duration::ZERO),
25120            Some(Duration::MAX),
25121        ] {
25122            let p = MeshPolicy {
25123                timeout,
25124                ..MeshPolicy::default()
25125            };
25126            assert_eq!(
25127                p.timeout(),
25128                timeout,
25129                "MeshPolicy::timeout must return :politicas :timeout \
25130                 verbatim (got {:?}, expected {timeout:?})",
25131                p.timeout(),
25132            );
25133            assert_eq!(
25134                p.timeout(),
25135                p.timeout,
25136                "MeshPolicy::timeout must byte-equal the raw .timeout \
25137                 field access across every value in the accept-set",
25138            );
25139        }
25140    }
25141
25142    #[test]
25143    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
25144        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
25145        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
25146        // field access. Structurally: toggling ONLY the `timeout` slot
25147        // on an otherwise-default MeshPolicy must flip `is_empty()`
25148        // from `true` (all-`None`) to `false` (one axis carries a
25149        // value); the flip must be observed for every value in the
25150        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25151        // gate accepts (`Some(Duration::from_millis(1))`,
25152        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
25153        // reads "any axis carries a value" — not "any axis carries a
25154        // value the validate gate accepts" — the same non-collapsing
25155        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
25156        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25157        //
25158        // Pins against a future silent detour that re-derived the
25159        // emptiness predicate off a peer axis (an accidental
25160        // `.rate_limit.is_none()`-only chain that dropped the
25161        // `timeout` arm entirely), a `timeout == Some(_)` collapse
25162        // that key-off a validate-gate-clamped bounds check (which
25163        // would silently classify a past-the-guard `Some(Duration::MAX)`
25164        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
25165        // check), or an accessor-side detour that no longer names the
25166        // substrate-primitive typed dispatch.
25167        //
25168        // Sibling of the peer per-`:politicas`
25169        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
25170        // the sibling `Option<u32>` optional-scalar axis and the peer
25171        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25172        // accessor-composition pin on the sibling `Option<bool>`
25173        // optional-scalar axis — same "the emptiness predicate must
25174        // route through the substrate-primitive typed dispatch"
25175        // discipline extended onto the peer per-`:politicas`
25176        // `Option<Duration>` axis.
25177        let empty = MeshPolicy::default();
25178        assert!(
25179            empty.is_empty(),
25180            "MeshPolicy::default() must be is_empty() — every axis \
25181             defaults to None",
25182        );
25183        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
25184            let p = MeshPolicy {
25185                timeout,
25186                ..MeshPolicy::default()
25187            };
25188            assert!(
25189                !p.is_empty(),
25190                "MeshPolicy::is_empty must return false when \
25191                 :timeout is {timeout:?} — the emptiness \
25192                 predicate reads \"any axis carries a value\", not \
25193                 \"any axis carries a value the validate gate \
25194                 accepts\"",
25195            );
25196            assert_eq!(
25197                p.timeout().is_none(),
25198                p.is_empty(),
25199                "when :timeout is the only set axis, is_empty() \
25200                 must equal timeout().is_none() — the accessor and \
25201                 the emptiness predicate must route through the same \
25202                 substrate-primitive typed dispatch on the :timeout \
25203                 arm",
25204            );
25205        }
25206    }
25207
25208    #[test]
25209    fn mesh_policy_timeout_projects_option_duration_by_copy() {
25210        // The by-copy pin: [`MeshPolicy::timeout`] returns
25211        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
25212        // and the accessor must return by value, not by reference.
25213        // Sibling of the peer per-`:politicas`
25214        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
25215        // sibling `Option<u32>` optional-scalar axis and the peer
25216        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25217        // by-copy pin on the sibling `Option<bool>` optional-scalar
25218        // axis, extended onto the peer per-`:politicas`
25219        // `Option<Duration>` copy-invariant shape — the accessor's
25220        // returned `Option<Duration>` must outlive `&self` (multiple
25221        // calls must return equal values from a dropped-`&self`
25222        // copy, since the returned Option carries no borrow), and
25223        // calling the accessor twice on the same MeshPolicy must
25224        // yield the same `Option<Duration>` verbatim (idempotent, no
25225        // side effects on `&self`).
25226        //
25227        // Pins against a future silent detour that returned
25228        // `Option<&Duration>` (which would type-check but silently
25229        // break every downstream caller — [`crate::render::single_field_overlay`]'s
25230        // first parameter is `Option<T: Clone>`, and `&Duration`
25231        // would fold to a detached copy at the call site), an
25232        // accidental `Option::as_ref()` projection
25233        // (`self.timeout.as_ref()` would also type-check but return
25234        // `Option<&Duration>`), or a one-arm-only accessor that
25235        // reads `Some(*d)` in the Some arm but reads a fresh
25236        // `Default::default()` (`Duration::ZERO`) in the None arm
25237        // (which would silently re-classify every unset `:timeout`
25238        // as the `PolicyTimeoutZero`-refused zero-Duration value at
25239        // the accessor boundary).
25240        for timeout in [
25241            None,
25242            Some(Duration::from_millis(1)),
25243            Some(POLICY_TIMEOUT_MAX),
25244            Some(Duration::ZERO),
25245            Some(Duration::MAX),
25246        ] {
25247            let p = MeshPolicy {
25248                timeout,
25249                ..MeshPolicy::default()
25250            };
25251            let first = p.timeout();
25252            let second = p.timeout();
25253            assert_eq!(
25254                first, second,
25255                "MeshPolicy::timeout must be idempotent — two \
25256                 successive calls on the same &self must return the \
25257                 same Option<Duration>",
25258            );
25259            assert_eq!(
25260                first, timeout,
25261                "MeshPolicy::timeout must return :politicas :timeout \
25262                 verbatim by copy — got {first:?}, expected {timeout:?}",
25263            );
25264        }
25265    }
25266
25267    #[test]
25268    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
25269        // The canonical per-`:politicas` `:rate-limit` Envoy-
25270        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
25271        // [`MeshPolicy::rate_limit`] must return the `:politicas
25272        // :rate-limit` typed [`RateLimit`] verbatim as an
25273        // `Option<RateLimit>`, byte-equal to the raw field access
25274        // across every representative value in the accept-set — `None`
25275        // (cluster default applies — no per-Aplicacao rate declaration,
25276        // the gateway-class per-listener default arm the future caixa-
25277        // mesh `local_rate_limit_overlay` emitter documents),
25278        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
25279        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
25280        // accept-set the surrounding
25281        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25282        // sibling `PolicyRateLimitZero` refusal, paired with the
25283        // canonical-window "1 second" arm of the three-unit
25284        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
25285        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
25286        // (the upper boundary the same gate carves out on the sibling
25287        // `PolicyRateLimitExceedsCap` refusal, paired with the
25288        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
25289        // (a past-the-guard sentinel that pins the accessor doesn't
25290        // perform a silent bounds-collapse into `None` on the
25291        // zero-rate/zero-window arm — validate rejects zero but the
25292        // accessor must ship the raw slot verbatim so a validate-time
25293        // gate regression surfaces at the emit boundary rather than
25294        // being silently absorbed), and
25295        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
25296        // (a past-the-guard sentinel that pins the accessor doesn't
25297        // perform a silent bounds-collapse at the return path).
25298        //
25299        // First `Option<Copy-composite-T>`-return accessor pin on the
25300        // M3 mesh-slot family (peer of the sibling per-`:politicas`
25301        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
25302        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
25303        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
25304        // Copy accessor pins, extended onto the peer per-`:politicas`
25305        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
25306        // and the accessor returns by value). Pins against a future
25307        // silent detour that re-derived the rate declaration from a
25308        // peer axis (an accidental
25309        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
25310        // collapse that read the breaker's trip threshold + rolling
25311        // window as a rate declaration), a `None → Some(default())`
25312        // cluster-default projection (which would silently re-
25313        // introduce a "cluster default is 0/s" arm the emit boundary
25314        // would take as "declared but inert" — the canonical
25315        // declared-but-inert footgun the sibling
25316        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
25317        // amplification-shape axis), a bounds-collapsing accessor
25318        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
25319        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
25320        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
25321        // accessor must ship the raw slot verbatim), or a
25322        // by-reference detour (`Option<&RateLimit>`) that broke every
25323        // downstream consumer keying off `Option<RateLimit>` by-copy.
25324        for rl in [
25325            None,
25326            Some(RateLimit {
25327                rate: 1,
25328                window: Duration::from_secs(1),
25329            }),
25330            Some(RateLimit {
25331                rate: POLICY_RATE_LIMIT_MAX,
25332                window: Duration::from_secs(3600),
25333            }),
25334            Some(RateLimit {
25335                rate: 0,
25336                window: Duration::ZERO,
25337            }),
25338            Some(RateLimit {
25339                rate: u32::MAX,
25340                window: Duration::MAX,
25341            }),
25342        ] {
25343            let p = MeshPolicy {
25344                rate_limit: rl,
25345                ..MeshPolicy::default()
25346            };
25347            assert_eq!(
25348                p.rate_limit(),
25349                rl,
25350                "MeshPolicy::rate_limit must return :politicas :rate-limit \
25351                 verbatim (got {:?}, expected {rl:?})",
25352                p.rate_limit(),
25353            );
25354            assert_eq!(
25355                p.rate_limit(),
25356                p.rate_limit,
25357                "MeshPolicy::rate_limit must byte-equal the raw \
25358                 .rate_limit field access across every value in the \
25359                 accept-set",
25360            );
25361        }
25362    }
25363
25364    #[test]
25365    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
25366        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
25367        // must key off [`MeshPolicy::rate_limit`], not the raw
25368        // `.rate_limit` field access. Structurally: toggling ONLY the
25369        // `rate_limit` slot on an otherwise-default MeshPolicy must
25370        // flip `is_empty()` from `true` (all-`None`) to `false` (one
25371        // axis carries a value); the flip must be observed for every
25372        // representative value in the accept-set the surrounding
25373        // [`AplicacaoSpec::validate_politicas`] gate accepts
25374        // (`Some(RateLimit { rate: 1, window: 1s })`,
25375        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
25376        // since the emptiness semantic reads "any axis carries a
25377        // value" — not "any axis carries a value the validate gate
25378        // accepts" — the same non-collapsing shape the peer M2
25379        // [`crate::LimitsSpec::is_empty`] /
25380        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25381        //
25382        // Pins against a future silent detour that re-derived the
25383        // emptiness predicate off a peer axis (an accidental
25384        // `.timeout.is_none()`-only chain that dropped the
25385        // `rate_limit` arm entirely — the last unlifted inline field
25386        // access on `is_empty` before this lift), a `rate_limit ==
25387        // Some(_)` collapse that key-off a validate-gate-clamped
25388        // bounds check (which would silently classify a past-the-
25389        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
25390        // because it fails the value-shape gate), or an accessor-
25391        // side detour that no longer names the substrate-primitive
25392        // typed dispatch.
25393        //
25394        // Fourth "the emptiness predicate must route through the
25395        // substrate-primitive typed dispatch" composition pin on the
25396        // M3 mesh-slot family — closes the last unlifted composition
25397        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
25398        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
25399        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
25400        // 7073d0f is_empty-composition pins on the sibling primitive-
25401        // Copy axes, extended onto the peer per-`:politicas`
25402        // composite-Copy `Option<RateLimit>` axis).
25403        let empty = MeshPolicy::default();
25404        assert!(
25405            empty.is_empty(),
25406            "MeshPolicy::default() must be is_empty() — every axis \
25407             defaults to None",
25408        );
25409        for rl in [
25410            RateLimit {
25411                rate: 1,
25412                window: Duration::from_secs(1),
25413            },
25414            RateLimit {
25415                rate: POLICY_RATE_LIMIT_MAX,
25416                window: Duration::from_secs(3600),
25417            },
25418        ] {
25419            let p = MeshPolicy {
25420                rate_limit: Some(rl),
25421                ..MeshPolicy::default()
25422            };
25423            assert!(
25424                !p.is_empty(),
25425                "MeshPolicy::is_empty must return false when \
25426                 :rate-limit is {rl:?} — the emptiness predicate \
25427                 reads \"any axis carries a value\", not \"any axis \
25428                 carries a value the validate gate accepts\"",
25429            );
25430            assert_eq!(
25431                p.rate_limit().is_none(),
25432                p.is_empty(),
25433                "when :rate-limit is the only set axis, is_empty() \
25434                 must equal rate_limit().is_none() — the accessor \
25435                 and the emptiness predicate must route through the \
25436                 same substrate-primitive typed dispatch on the \
25437                 :rate-limit arm",
25438            );
25439        }
25440    }
25441
25442    #[test]
25443    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
25444        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25445        // `:rate-limit` value-shape gate must key off
25446        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
25447        // field bind. Structurally: a `MeshPolicy` whose only set
25448        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
25449        // the `PolicyRateLimitZero` refusal exactly, and the same
25450        // MeshPolicy with the rate at the canonical lower boundary
25451        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
25452        // The pair jointly pins the accessor + validate-gate
25453        // composition: any future silent detour that had the accessor
25454        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
25455        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
25456        // silently absorb the `PolicyRateLimitZero` refusal at the
25457        // accessor boundary — the composition pin catches that at
25458        // caixa-core build time.
25459        //
25460        // Sibling of the peer [`validate_politicas`]
25461        // `:mtls-required` / `:retries` / `:timeout` composition pins
25462        // on the sibling primitive-Copy optional-scalar axes — same
25463        // "the validate / shape-gate predicate must route through the
25464        // substrate-primitive typed dispatch" discipline extended
25465        // onto the peer per-`:politicas` composite-Copy
25466        // `Option<RateLimit>` axis. Second composition-with-accessor
25467        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
25468        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
25469        let mut spec = three_member_spec();
25470        spec.politicas = MeshPolicy {
25471            rate_limit: Some(RateLimit {
25472                rate: 0,
25473                window: Duration::from_secs(1),
25474            }),
25475            ..MeshPolicy::default()
25476        };
25477        assert!(
25478            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
25479            "validate_politicas must reject rate == 0 with \
25480             PolicyRateLimitZero — the accessor and the validate gate \
25481             must route through the same substrate-primitive typed \
25482             dispatch on the :rate-limit zero-floor arm",
25483        );
25484        spec.politicas = MeshPolicy {
25485            rate_limit: Some(RateLimit {
25486                rate: 1,
25487                window: Duration::from_secs(1),
25488            }),
25489            ..MeshPolicy::default()
25490        };
25491        assert!(
25492            spec.validate().is_ok(),
25493            "validate_politicas must accept rate == 1 (the canonical \
25494             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
25495             set) with a canonical 1s window",
25496        );
25497    }
25498
25499    #[test]
25500    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
25501        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
25502        // `outlier_detection`-mesh consecutive-failure-ejection scalar
25503        // pin: [`MeshPolicy::circuit_breaker`] must return the
25504        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
25505        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
25506        // raw field access across every representative value in the
25507        // accept-set — `None` (cluster default applies — no
25508        // per-Aplicacao breaker declaration, the gateway-class per-
25509        // listener default arm the future caixa-mesh
25510        // `outlier_detection_overlay` emitter documents),
25511        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
25512        // (the lower boundary of the accept-set the surrounding
25513        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25514        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
25515        // refusals),
25516        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
25517        // (the upper boundary the same gate carves out on the sibling
25518        // `PolicyBreakerMaxFailuresExceedsCap` /
25519        // `PolicyBreakerWindowExceedsCap` refusals),
25520        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
25521        // (a past-the-guard sentinel that pins the accessor doesn't
25522        // perform a silent bounds-collapse into `None` on the
25523        // zero-failures/zero-window arm — validate rejects zero but
25524        // the accessor must ship the raw slot verbatim so a validate-
25525        // time gate regression surfaces at the emit boundary rather
25526        // than being silently absorbed), and
25527        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
25528        // (a past-the-guard sentinel that pins the accessor doesn't
25529        // perform a silent bounds-collapse at the return path).
25530        //
25531        // Second `Option<Copy-composite-T>`-return accessor pin on the
25532        // M3 mesh-slot family (peer of the sibling per-`:politicas`
25533        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
25534        // composite-Copy accessor pin, and of the sibling per-
25535        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
25536        // [`MeshPolicy::retries`] bdfb399 /
25537        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
25538        // accessor pins). Pins against a future silent detour that
25539        // re-derived the breaker declaration from a peer axis (an
25540        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
25541        // collapse that read the rate-limit's bucket capacity + refill
25542        // period as a breaker declaration), a `None → Some(default())`
25543        // cluster-default projection (which would silently re-
25544        // introduce the `PolicyBreakerZeroFailures` /
25545        // `PolicyBreakerZeroWindow` refusal cases at the emit
25546        // boundary), a bounds-collapsing accessor that clamped
25547        // `cb.max_failures` through
25548        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
25549        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
25550        // [`AplicacaoSpec::validate`] gate owns the bounds; the
25551        // accessor must ship the raw slot verbatim), or a
25552        // by-reference detour (`Option<&CircuitBreaker>`) that broke
25553        // every downstream consumer keying off `Option<CircuitBreaker>`
25554        // by-copy.
25555        for cb in [
25556            None,
25557            Some(CircuitBreaker {
25558                max_failures: 1,
25559                window: Duration::from_millis(1),
25560            }),
25561            Some(CircuitBreaker {
25562                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25563                window: POLICY_BREAKER_WINDOW_MAX,
25564            }),
25565            Some(CircuitBreaker {
25566                max_failures: 0,
25567                window: Duration::ZERO,
25568            }),
25569            Some(CircuitBreaker {
25570                max_failures: u32::MAX,
25571                window: Duration::MAX,
25572            }),
25573        ] {
25574            let p = MeshPolicy {
25575                circuit_breaker: cb,
25576                ..MeshPolicy::default()
25577            };
25578            assert_eq!(
25579                p.circuit_breaker(),
25580                cb,
25581                "MeshPolicy::circuit_breaker must return :politicas \
25582                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
25583                p.circuit_breaker(),
25584            );
25585            assert_eq!(
25586                p.circuit_breaker(),
25587                p.circuit_breaker,
25588                "MeshPolicy::circuit_breaker must byte-equal the raw \
25589                 .circuit_breaker field access across every value in \
25590                 the accept-set",
25591            );
25592        }
25593    }
25594
25595    #[test]
25596    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
25597        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
25598        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
25599        // `.circuit_breaker` field access. Structurally: toggling ONLY
25600        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
25601        // must flip `is_empty()` from `true` (all-`None`) to `false`
25602        // (one axis carries a value); the flip must be observed for
25603        // every representative value in the accept-set the surrounding
25604        // [`AplicacaoSpec::validate_politicas`] gate accepts
25605        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
25606        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
25607        // since the emptiness semantic reads "any axis carries a
25608        // value" — not "any axis carries a value the validate gate
25609        // accepts" — the same non-collapsing shape the peer M2
25610        // [`crate::LimitsSpec::is_empty`] /
25611        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25612        //
25613        // Pins against a future silent detour that re-derived the
25614        // emptiness predicate off a peer axis (an accidental
25615        // `.rate_limit.is_none()`-only chain that dropped the
25616        // `circuit_breaker` arm entirely — the last unlifted inline
25617        // field access on `is_empty` before this lift), a
25618        // `circuit_breaker == Some(_)` collapse that key-off a
25619        // validate-gate-clamped bounds check (which would silently
25620        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
25621        // 0, window: 0s })` as empty because it fails the value-shape
25622        // gate), or an accessor-side detour that no longer names the
25623        // substrate-primitive typed dispatch.
25624        //
25625        // Fifth "the emptiness predicate must route through the
25626        // substrate-primitive typed dispatch" composition pin on the
25627        // M3 mesh-slot family — closes the last unlifted composition
25628        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
25629        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
25630        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
25631        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
25632        // composition pins on the sibling primitive-Copy + composite-
25633        // Copy axes, extended onto the peer per-`:politicas`
25634        // composite-Copy `Option<CircuitBreaker>` axis).
25635        let empty = MeshPolicy::default();
25636        assert!(
25637            empty.is_empty(),
25638            "MeshPolicy::default() must be is_empty() — every axis \
25639             defaults to None",
25640        );
25641        for cb in [
25642            CircuitBreaker {
25643                max_failures: 1,
25644                window: Duration::from_millis(1),
25645            },
25646            CircuitBreaker {
25647                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25648                window: POLICY_BREAKER_WINDOW_MAX,
25649            },
25650        ] {
25651            let p = MeshPolicy {
25652                circuit_breaker: Some(cb),
25653                ..MeshPolicy::default()
25654            };
25655            assert!(
25656                !p.is_empty(),
25657                "MeshPolicy::is_empty must return false when \
25658                 :circuit-breaker is {cb:?} — the emptiness predicate \
25659                 reads \"any axis carries a value\", not \"any axis \
25660                 carries a value the validate gate accepts\"",
25661            );
25662            assert_eq!(
25663                p.circuit_breaker().is_none(),
25664                p.is_empty(),
25665                "when :circuit-breaker is the only set axis, \
25666                 is_empty() must equal circuit_breaker().is_none() — \
25667                 the accessor and the emptiness predicate must route \
25668                 through the same substrate-primitive typed dispatch \
25669                 on the :circuit-breaker arm",
25670            );
25671        }
25672    }
25673
25674    #[test]
25675    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
25676        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25677        // `:circuit-breaker` value-shape gate must key off
25678        // [`MeshPolicy::circuit_breaker`], not the raw
25679        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
25680        // whose only set axis is a `Some(CircuitBreaker { max_failures:
25681        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
25682        // refusal exactly, and the same MeshPolicy with the breaker at
25683        // the canonical lower boundary
25684        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
25685        // pass validate. The pair jointly pins the accessor +
25686        // validate-gate composition: any future silent detour that had
25687        // the accessor omit the `Some(CircuitBreaker { max_failures:
25688        // 0, .. })` arm (a
25689        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
25690        // collapse) would silently absorb the
25691        // `PolicyBreakerZeroFailures` refusal at the accessor
25692        // boundary — the composition pin catches that at caixa-core
25693        // build time.
25694        //
25695        // Sibling of the peer [`validate_politicas`]
25696        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
25697        // composition pins on the sibling primitive-Copy + composite-
25698        // Copy optional-scalar axes — same "the validate / shape-gate
25699        // predicate must route through the substrate-primitive typed
25700        // dispatch" discipline extended onto the peer per-`:politicas`
25701        // composite-Copy `Option<CircuitBreaker>` axis. Second
25702        // composition-with-accessor pin on the M3 mesh-slot
25703        // `Option<CircuitBreaker>` arm alongside the
25704        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
25705        let mut spec = three_member_spec();
25706        spec.politicas = MeshPolicy {
25707            circuit_breaker: Some(CircuitBreaker {
25708                max_failures: 0,
25709                window: Duration::from_millis(1),
25710            }),
25711            ..MeshPolicy::default()
25712        };
25713        assert!(
25714            matches!(
25715                spec.validate(),
25716                Err(AplicacaoError::PolicyBreakerZeroFailures)
25717            ),
25718            "validate_politicas must reject max_failures == 0 with \
25719             PolicyBreakerZeroFailures — the accessor and the validate \
25720             gate must route through the same substrate-primitive \
25721             typed dispatch on the :circuit-breaker zero-floor arm",
25722        );
25723        spec.politicas = MeshPolicy {
25724            circuit_breaker: Some(CircuitBreaker {
25725                max_failures: 1,
25726                window: Duration::from_millis(1),
25727            }),
25728            ..MeshPolicy::default()
25729        };
25730        assert!(
25731            spec.validate().is_ok(),
25732            "validate_politicas must accept a CircuitBreaker at the \
25733             canonical lower boundary (max_failures = 1, window = \
25734             1ms) — the accessor and the validate gate must route \
25735             through the same substrate-primitive typed dispatch on \
25736             the :circuit-breaker arm",
25737        );
25738    }
25739
25740    #[test]
25741    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
25742        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
25743        // Envoy-outlier-detection trip-threshold scalar pin:
25744        // [`CircuitBreaker::max_failures`] must return the
25745        // `:politicas :circuit-breaker :max-failures` typed `u32`
25746        // verbatim, byte-equal to the raw field access across every
25747        // representative value in the accept-set — `1` (the lower
25748        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
25749        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
25750        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
25751        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
25752        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
25753        // refusal), `0` (a past-the-guard sentinel that pins the accessor
25754        // doesn't perform a silent bounds-collapse into `1` on the zero
25755        // arm — validate rejects zero but the accessor must ship the
25756        // raw slot verbatim so a validate-time gate regression surfaces
25757        // at the emit boundary rather than being silently absorbed),
25758        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
25759        // doesn't perform a silent bounds-collapse through
25760        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
25761        //
25762        // First sub-struct required-scalar accessor pin on the M3
25763        // mesh-slot family — sibling in shape to the peer per-`:membros`
25764        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
25765        // (a40b0e3) required-`String`-carry accessor pins and the peer
25766        // per-`:contratos` [`WitContract::source`] /
25767        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
25768        // accessor pins, extended onto the peer per-`CircuitBreaker`
25769        // required-`u32` scalar-value axis. Pins against a future silent
25770        // detour that re-derived the trip threshold from a peer axis (an
25771        // accidental `self.window.as_secs() as u32` collapse that read
25772        // the breaker's rolling-window duration as a failure count), a
25773        // `0 → 1` cluster-default projection (which would silently absorb
25774        // the `PolicyBreakerZeroFailures` refusal case at the accessor
25775        // boundary), or a bounds-collapsing accessor that clamped the
25776        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
25777        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25778        // must ship the raw slot verbatim).
25779        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
25780            let cb = CircuitBreaker {
25781                max_failures,
25782                window: Duration::from_secs(60),
25783            };
25784            assert_eq!(
25785                cb.max_failures(),
25786                max_failures,
25787                "CircuitBreaker::max_failures must return :politicas \
25788                 :circuit-breaker :max-failures verbatim (got {}, \
25789                 expected {max_failures})",
25790                cb.max_failures(),
25791            );
25792            assert_eq!(
25793                cb.max_failures(),
25794                cb.max_failures,
25795                "CircuitBreaker::max_failures must byte-equal the raw \
25796                 .max_failures field access across every value in the \
25797                 u32 accept-set",
25798            );
25799        }
25800    }
25801
25802    #[test]
25803    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
25804        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25805        // `:circuit-breaker :max-failures` zero-floor arm must key off
25806        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
25807        // field access. Structurally: a `CircuitBreaker { max_failures:
25808        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
25809        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
25810        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
25811        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
25812        // pass validate. The pair jointly pins the accessor +
25813        // validate-gate composition: any future silent detour that had
25814        // the accessor return a fresh `1` on the zero arm (a
25815        // `.max_failures().max(1)` collapse) would silently absorb the
25816        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
25817        // and the validate gate would accept a struct-literal
25818        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
25819        // catches that at caixa-core build time.
25820        //
25821        // Peer of the sibling per-`:politicas`
25822        // [`MeshPolicy::mtls_required`] (c0110f1) /
25823        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
25824        // (7073d0f) accessor-composition pins on the sibling optional-
25825        // scalar axes — same "the validate / shape-gate predicate must
25826        // route through the substrate-primitive typed dispatch"
25827        // discipline extended onto the peer per-`CircuitBreaker`
25828        // required-scalar composition axis.
25829        let mut spec = three_member_spec();
25830        spec.politicas = MeshPolicy {
25831            circuit_breaker: Some(CircuitBreaker {
25832                max_failures: 0,
25833                window: Duration::from_secs(60),
25834            }),
25835            ..MeshPolicy::default()
25836        };
25837        assert!(
25838            matches!(
25839                spec.validate(),
25840                Err(AplicacaoError::PolicyBreakerZeroFailures)
25841            ),
25842            "validate_politicas must reject max_failures == 0 with \
25843             PolicyBreakerZeroFailures — the accessor and the validate \
25844             gate must route through the same substrate-primitive typed \
25845             dispatch on the :max-failures zero-floor arm",
25846        );
25847        spec.politicas = MeshPolicy {
25848            circuit_breaker: Some(CircuitBreaker {
25849                max_failures: 1,
25850                window: Duration::from_secs(60),
25851            }),
25852            ..MeshPolicy::default()
25853        };
25854        assert!(
25855            spec.validate().is_ok(),
25856            "validate_politicas must accept max_failures == 1 (the \
25857             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
25858             accept-set)",
25859        );
25860    }
25861
25862    #[test]
25863    fn circuit_breaker_max_failures_projects_u32_by_copy() {
25864        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
25865        // `u32` by copy — `u32` is `Copy` and the accessor must return
25866        // by value, not by reference. Peer of the sibling
25867        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
25868        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
25869        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
25870        // optional-scalar axes, extended onto the peer
25871        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
25872        // the accessor's returned `u32` must outlive `&self` (multiple
25873        // calls must return equal values from a dropped-`&self` copy,
25874        // since the returned scalar carries no borrow), and calling
25875        // the accessor twice on the same CircuitBreaker must yield the
25876        // same `u32` verbatim (idempotent, no side effects on `&self`).
25877        //
25878        // Pins against a future silent detour that returned `&u32`
25879        // (which would type-check but silently break every downstream
25880        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
25881        // first parameter is `u32`, and `&u32` would fold to a detached
25882        // copy at the call site with a `*` deref the sibling accessors
25883        // don't need), an accidental `.max_failures.wrapping_add(0)`
25884        // detour that returned a fresh copy through an arithmetic
25885        // no-op (breaking a future `const fn` regression), or a
25886        // one-arm-only accessor that returned a saturating value on
25887        // some sentinel input (breaking the pass-through invariant the
25888        // sibling required-scalar accessors carry).
25889        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
25890            let cb = CircuitBreaker {
25891                max_failures,
25892                window: Duration::from_secs(60),
25893            };
25894            let first = cb.max_failures();
25895            let second = cb.max_failures();
25896            assert_eq!(
25897                first, second,
25898                "CircuitBreaker::max_failures must be idempotent — two \
25899                 successive calls on the same &self must return the \
25900                 same u32",
25901            );
25902            assert_eq!(
25903                first, max_failures,
25904                "CircuitBreaker::max_failures must return :politicas \
25905                 :circuit-breaker :max-failures verbatim by copy — \
25906                 got {first}, expected {max_failures}",
25907            );
25908        }
25909    }
25910
25911    #[test]
25912    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
25913        // The canonical per-`:politicas :circuit-breaker` `:window`
25914        // Envoy-outlier-detection rolling-observation-interval scalar
25915        // pin: [`CircuitBreaker::window`] must return the
25916        // `:politicas :circuit-breaker :window` typed `Duration`
25917        // verbatim, byte-equal to the raw field access across every
25918        // representative value in the accept-set — `Duration::from_millis(1)`
25919        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
25920        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
25921        // gate carves out on the sibling `PolicyBreakerZeroWindow`
25922        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
25923        // same gate carves out on the sibling
25924        // `PolicyBreakerWindowExceedsCap` refusal),
25925        // `Duration::ZERO` (a past-the-guard sentinel that pins the
25926        // accessor doesn't perform a silent bounds-collapse into
25927        // `Duration::from_millis(1)` on the zero arm — validate rejects
25928        // zero but the accessor must ship the raw slot verbatim so a
25929        // validate-time gate regression surfaces at the emit boundary
25930        // rather than being silently absorbed),
25931        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
25932        // far above the 1h cap — that pins the accessor doesn't perform
25933        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
25934        // at the return path).
25935        //
25936        // Second sub-struct required-scalar accessor pin on the M3
25937        // mesh-slot family — sibling in shape to the just-landed
25938        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
25939        // (3a74062) required-`u32` accessor pin on the peer
25940        // per-`CircuitBreaker` required-axis, extended onto the
25941        // per-sub-struct required-`Duration` axis. Pins against a
25942        // future silent detour that re-derived the observation window
25943        // from a peer axis (an accidental
25944        // `Duration::from_secs(self.max_failures as u64)` collapse that
25945        // read the breaker's trip count as an observation-interval
25946        // duration), a `Duration::ZERO → Duration::from_millis(1)`
25947        // cluster-default projection (which would silently absorb the
25948        // `PolicyBreakerZeroWindow` refusal case at the accessor
25949        // boundary), or a bounds-collapsing accessor that clamped the
25950        // return through `POLICY_BREAKER_WINDOW_MAX` (the
25951        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25952        // must ship the raw slot verbatim).
25953        for window in [
25954            Duration::from_millis(1),
25955            POLICY_BREAKER_WINDOW_MAX,
25956            Duration::ZERO,
25957            Duration::from_secs(86_400),
25958        ] {
25959            let cb = CircuitBreaker {
25960                max_failures: 5,
25961                window,
25962            };
25963            assert_eq!(
25964                cb.window(),
25965                window,
25966                "CircuitBreaker::window must return :politicas \
25967                 :circuit-breaker :window verbatim (got {:?}, \
25968                 expected {window:?})",
25969                cb.window(),
25970            );
25971            assert_eq!(
25972                cb.window(),
25973                cb.window,
25974                "CircuitBreaker::window must byte-equal the raw \
25975                 .window field access across every value in the \
25976                 Duration accept-set",
25977            );
25978        }
25979    }
25980
25981    #[test]
25982    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
25983        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25984        // `:circuit-breaker :window` zero-floor arm must key off
25985        // [`CircuitBreaker::window`], not the raw `.window` field
25986        // access. Structurally: a `CircuitBreaker { window:
25987        // Duration::ZERO, .. }` embedded in a
25988        // `:politicas :circuit-breaker` slot must surface the
25989        // `PolicyBreakerZeroWindow` refusal exactly, and a
25990        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
25991        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
25992        // accept-set) must pass validate. The pair jointly pins the
25993        // accessor + validate-gate composition: any future silent
25994        // detour that had the accessor return a fresh
25995        // `Duration::from_millis(1)` on the zero arm (a
25996        // `.window().max(Duration::from_millis(1))` collapse) would
25997        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
25998        // accessor boundary and the validate gate would accept a
25999        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
26000        // — the composition pin catches that at caixa-core build time.
26001        //
26002        // Peer of the sibling per-`CircuitBreaker`
26003        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
26004        // pin on the peer required-scalar `:max-failures` axis — same
26005        // "the validate / shape-gate predicate must route through the
26006        // substrate-primitive typed dispatch" discipline extended onto
26007        // the peer per-`CircuitBreaker` required-`Duration` composition
26008        // axis.
26009        let mut spec = three_member_spec();
26010        spec.politicas = MeshPolicy {
26011            circuit_breaker: Some(CircuitBreaker {
26012                max_failures: 5,
26013                window: Duration::ZERO,
26014            }),
26015            ..MeshPolicy::default()
26016        };
26017        assert!(
26018            matches!(
26019                spec.validate(),
26020                Err(AplicacaoError::PolicyBreakerZeroWindow)
26021            ),
26022            "validate_politicas must reject window == Duration::ZERO \
26023             with PolicyBreakerZeroWindow — the accessor and the \
26024             validate gate must route through the same substrate-\
26025             primitive typed dispatch on the :window zero-floor arm",
26026        );
26027        spec.politicas = MeshPolicy {
26028            circuit_breaker: Some(CircuitBreaker {
26029                max_failures: 5,
26030                window: Duration::from_millis(1),
26031            }),
26032            ..MeshPolicy::default()
26033        };
26034        assert!(
26035            spec.validate().is_ok(),
26036            "validate_politicas must accept window == \
26037             Duration::from_millis(1) (the lower boundary of the \
26038             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
26039        );
26040    }
26041
26042    #[test]
26043    fn circuit_breaker_window_projects_duration_by_copy() {
26044        // The by-copy pin: [`CircuitBreaker::window`] returns
26045        // `Duration` by copy — `Duration` is `Copy` and the accessor
26046        // must return by value, not by reference. Peer of the sibling
26047        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
26048        // (3a74062) by-copy pin on the peer required-scalar
26049        // `:max-failures` axis, extended onto the peer
26050        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
26051        // — the accessor's returned `Duration` must outlive `&self`
26052        // (multiple calls must return equal values from a
26053        // dropped-`&self` copy, since the returned scalar carries no
26054        // borrow), and calling the accessor twice on the same
26055        // CircuitBreaker must yield the same `Duration` verbatim
26056        // (idempotent, no side effects on `&self`).
26057        //
26058        // Pins against a future silent detour that returned
26059        // `&Duration` (which would type-check but silently break every
26060        // downstream `Duration`-by-value consumer —
26061        // [`crate::render::require_positive_canonical_bounded_duration`]'s
26062        // first parameter is `Duration`, and `&Duration` would fold to
26063        // a detached copy at the call site with a `*` deref the sibling
26064        // accessors don't need), an accidental `.window + Duration::ZERO`
26065        // detour that returned a fresh copy through an arithmetic
26066        // no-op (breaking a future `const fn` regression), or a
26067        // one-arm-only accessor that returned a saturating value on
26068        // some sentinel input (breaking the pass-through invariant the
26069        // sibling required-scalar accessors carry).
26070        for window in [
26071            Duration::from_millis(1),
26072            POLICY_BREAKER_WINDOW_MAX,
26073            Duration::ZERO,
26074            Duration::from_secs(86_400),
26075        ] {
26076            let cb = CircuitBreaker {
26077                max_failures: 5,
26078                window,
26079            };
26080            let first = cb.window();
26081            let second = cb.window();
26082            assert_eq!(
26083                first, second,
26084                "CircuitBreaker::window must be idempotent — two \
26085                 successive calls on the same &self must return the \
26086                 same Duration",
26087            );
26088            assert_eq!(
26089                first, window,
26090                "CircuitBreaker::window must return :politicas \
26091                 :circuit-breaker :window verbatim by copy — \
26092                 got {first:?}, expected {window:?}",
26093            );
26094        }
26095    }
26096
26097    #[test]
26098    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
26099        // Apex-identity pair-invariant pin composing both substrate-
26100        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
26101        // and [`WitContract::destination`] — at the emit-side call shape
26102        // every per-`(:de, :para)` CNP L4 port reader now takes. The
26103        // invariant, evaluated per-edge:
26104        //
26105        //   spec.port_for_destination(c.destination()) == expected_port
26106        //
26107        // where `expected_port` is `entrada.port` when
26108        // `c.destination() == entrada.destination()` and
26109        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
26110        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
26111        // pin on the per-`:entrada` axis — that pin encodes the apex
26112        // ingress L4 identity via `entrada.destination()`; this pin
26113        // encodes the per-edge L4 identity via `c.destination()`, and
26114        // both compose on the same substrate-primitive resolver so a
26115        // future refactor that silently split either accessor's apex
26116        // behavior surfaces at caixa-core build time.
26117        let mut spec = three_member_spec();
26118        if let Some(e) = spec.entrada.as_mut() {
26119            e.para = "cart".into();
26120            e.port = 8443;
26121        }
26122        let apex_contract = WitContract {
26123            de: "checkout".into(),
26124            para: "cart".into(),
26125            wit: "wasi:http/proxy".into(),
26126            endpoint: Some("/hello".into()),
26127            subject: None,
26128            slot: None,
26129        };
26130        assert_eq!(
26131            spec.port_for_destination(apex_contract.destination()),
26132            8443,
26133            "`spec.port_for_destination(c.destination())` must equal \
26134             `entrada.port` when the contract callee names the ingress \
26135             apex — the CNP per-edge L4 port and the HTTPRoute apex \
26136             backendRef port share this substrate-primitive resolver.",
26137        );
26138        let non_apex_contract = WitContract {
26139            de: "cart".into(),
26140            para: "payment".into(),
26141            wit: "wasi:http/proxy".into(),
26142            endpoint: Some("/charge".into()),
26143            subject: None,
26144            slot: None,
26145        };
26146        assert_eq!(
26147            spec.port_for_destination(non_apex_contract.destination()),
26148            DEFAULT_SERVICO_PORT,
26149            "`spec.port_for_destination(c.destination())` must fall back \
26150             to the substrate-canonical port floor when the contract \
26151             callee is not the ingress apex — the resolver's non-apex \
26152             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
26153        );
26154    }
26155
26156    #[test]
26157    fn membro_key_consts_are_lower_camel_case_shape() {
26158        // Shape-pin: every `MEMBRO_KEY_*` const must be a
26159        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26160        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26161        // leading capital, no whitespace / dots) — the canonical shape
26162        // the `#[serde(rename_all = "camelCase")]` derive produces on
26163        // [`Membro`]. A future flip to a non-camelCase attribute at
26164        // the derive surfaces both here (this test fails on the
26165        // stale-constant shape) and at
26166        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
26167        // fails on the mismatch between const and derive). Peer with
26168        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
26169        // on the sibling `SupervisorSpec` top-level axis.
26170        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
26171            assert!(
26172                !key.is_empty(),
26173                "MEMBRO_KEY_* must be non-empty (got {key:?})"
26174            );
26175            let first = key.chars().next().unwrap();
26176            assert!(
26177                first.is_ascii_lowercase(),
26178                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
26179                 (got {key:?}, leads with {first:?})",
26180            );
26181            assert!(
26182                key.chars().all(|c| c.is_ascii_alphanumeric()),
26183                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
26184                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26185            );
26186        }
26187    }
26188
26189    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
26190
26191    #[test]
26192    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
26193        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
26194        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
26195        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
26196        // keys the `#[serde(rename_all = "camelCase")]` attribute on
26197        // [`WitContract`] emits for the required-triad. The three
26198        // sibling payload-arm keys already pin under
26199        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
26200        // `STORE_FIELD_NAME` — pin all six alongside so a future
26201        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26202        // verbatim-field-name flip at the derive attribute (any of which
26203        // would silently break every downstream JSON consumer that
26204        // reaches for one of the six via `Value::get(...)`) surfaces
26205        // here as a build-time test failure at `aplicacao.rs`, not as an
26206        // apply-time `.get(<stale-canonical-const>)` returning `None`
26207        // far from the derive-attr drift's commit. Peer with the sibling
26208        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26209        // pin on the M3 `:membros` per-entry axis — same discipline the
26210        // `Membro` per-entry lift established, extended here to the
26211        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
26212        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
26213        // axis on the Aplicacao surface without a lifted serde-key peer.
26214        let c = WitContract {
26215            de: "cart".into(),
26216            para: "catalog".into(),
26217            wit: "wasi:http/proxy".into(),
26218            endpoint: Some("/lookup".into()),
26219            subject: None,
26220            slot: None,
26221        };
26222        let json = serde_json::to_string(&c).unwrap();
26223        for key in [
26224            crate::CONTRATO_KEY_DE,
26225            crate::CONTRATO_KEY_PARA,
26226            crate::CONTRATO_KEY_WIT,
26227            WitTarget::HTTP_FIELD_NAME,
26228        ] {
26229            let quoted = format!("\"{key}\"");
26230            assert!(
26231                json.contains(&quoted),
26232                "serialized WitContract must carry the lifted \
26233                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
26234                 {quoted} verbatim in the JSON emission (got: {json})",
26235            );
26236        }
26237
26238        // Pin the two remaining payload-arm keys by round-tripping a
26239        // `WitContract` under each payload-shape (pub-sub, store) — the
26240        // required-triad appears on every emission but the payload arms
26241        // only surface when their `Option<String>` field is `Some`.
26242        let pubsub = WitContract {
26243            de: "cart".into(),
26244            para: "events".into(),
26245            wit: "nats:pub-sub".into(),
26246            endpoint: None,
26247            subject: Some("orders.placed".into()),
26248            slot: None,
26249        };
26250        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
26251        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
26252        assert!(
26253            pubsub_json.contains(&pubsub_quoted),
26254            "serialized pub-sub WitContract must carry the lifted \
26255             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
26256             verbatim in the JSON emission (got: {pubsub_json})",
26257        );
26258        let store = WitContract {
26259            de: "cart".into(),
26260            para: "sessions".into(),
26261            wit: "wasi:keyvalue/store".into(),
26262            endpoint: None,
26263            subject: None,
26264            slot: Some("cart/$id".into()),
26265        };
26266        let store_json = serde_json::to_string(&store).unwrap();
26267        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
26268        assert!(
26269            store_json.contains(&store_quoted),
26270            "serialized store WitContract must carry the lifted \
26271             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
26272             verbatim in the JSON emission (got: {store_json})",
26273        );
26274    }
26275
26276    #[test]
26277    fn contrato_key_consts_are_pairwise_distinct() {
26278        // Cross-axis drift-detection pin: a future collapse of the six
26279        // canonical [`WitContract`] per-entry byte-strings onto the same
26280        // value (e.g. an accidental copy-paste flip of
26281        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
26282        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
26283        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
26284        // every downstream probe on one axis onto the sibling axis's
26285        // overlay entry and pass every propagation-probe test that
26286        // expected only the stale axis's value. Peer of the sibling
26287        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
26288        // widened here to the six-way axis the `WitContract`
26289        // required-triad + `WitTarget` payload-triad jointly cover.
26290        let all = [
26291            crate::CONTRATO_KEY_DE,
26292            crate::CONTRATO_KEY_PARA,
26293            crate::CONTRATO_KEY_WIT,
26294            WitTarget::HTTP_FIELD_NAME,
26295            WitTarget::PUBSUB_FIELD_NAME,
26296            WitTarget::STORE_FIELD_NAME,
26297        ];
26298        for (i, a) in all.iter().enumerate() {
26299            for b in all.iter().skip(i + 1) {
26300                assert_ne!(
26301                    a, b,
26302                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
26303                     must be pairwise-distinct canonical byte-sequences \
26304                     — got `{a}` == `{b}`",
26305                );
26306            }
26307        }
26308    }
26309
26310    #[test]
26311    fn contrato_key_consts_are_lower_camel_case_shape() {
26312        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
26313        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
26314        // byte-sequence (no `snake_case` underscores, no `kebab-case`
26315        // hyphens, no leading colon, no `PascalCase` leading capital, no
26316        // whitespace / dots) — the canonical shape the
26317        // `#[serde(rename_all = "camelCase")]` derive produces on
26318        // [`WitContract`]. A future flip to a non-camelCase attribute at
26319        // the derive surfaces both here (this test fails on the
26320        // stale-constant shape) and at
26321        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26322        // (that test fails on the mismatch between const and derive).
26323        // Peer with `membro_key_consts_are_lower_camel_case_shape`
26324        // (ce80ca0) on the sibling `Membro` per-entry axis.
26325        for key in [
26326            crate::CONTRATO_KEY_DE,
26327            crate::CONTRATO_KEY_PARA,
26328            crate::CONTRATO_KEY_WIT,
26329            WitTarget::HTTP_FIELD_NAME,
26330            WitTarget::PUBSUB_FIELD_NAME,
26331            WitTarget::STORE_FIELD_NAME,
26332        ] {
26333            assert!(
26334                !key.is_empty(),
26335                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26336                 non-empty (got {key:?})"
26337            );
26338            let first = key.chars().next().unwrap();
26339            assert!(
26340                first.is_ascii_lowercase(),
26341                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
26342                 with an ASCII-lowercase byte (got {key:?}, leads with \
26343                 {first:?})",
26344            );
26345            assert!(
26346                key.chars().all(|c| c.is_ascii_alphanumeric()),
26347                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26348                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
26349                 whitespace (got {key:?})",
26350            );
26351        }
26352    }
26353
26354    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
26355
26356    #[test]
26357    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
26358        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
26359        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
26360        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
26361        // name the exact camelCase JSON keys the
26362        // `#[serde(rename_all = "camelCase")]` attribute on
26363        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
26364        // pin that each canonical byte-sequence appears verbatim in the
26365        // JSON — a future accidental `rename_all = "snake_case"` /
26366        // `"kebab-case"` / verbatim-field-name flip at the derive
26367        // attribute (any of which would silently break every downstream
26368        // JSON consumer that reaches for one of the four consts via
26369        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
26370        // emitter's per-Aplicacao hostname/paths/port projection, the
26371        // future `app-operator` reconciler's per-Aplicacao ingress
26372        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
26373        // materializer's admission-time cross-check) surfaces here as
26374        // a build-time test failure at `aplicacao.rs`, not as an
26375        // apply-time `.get(<stale-canonical-const>)` returning `None`
26376        // far from the derive-attr drift's commit. Peer with the
26377        // sibling
26378        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26379        // (ca463a4) and
26380        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26381        // pins on the M3 collection-slot atom axes — same discipline
26382        // both collection-slot lifts established, extended here to the
26383        // singleton `:entrada` mesh-slot atom axis, the last M3
26384        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
26385        // axis on the Aplicacao surface without a lifted serde-key
26386        // peer.
26387        let e = Entrada {
26388            host: "checkout.quero.cloud".into(),
26389            para: "cart".into(),
26390            paths: vec!["/cart".into()],
26391            port: 8080,
26392        };
26393        let json = serde_json::to_string(&e).unwrap();
26394        for key in [
26395            crate::ENTRADA_KEY_HOST,
26396            crate::ENTRADA_KEY_PARA,
26397            crate::ENTRADA_KEY_PATHS,
26398            crate::ENTRADA_KEY_PORT,
26399        ] {
26400            let quoted = format!("\"{key}\"");
26401            assert!(
26402                json.contains(&quoted),
26403                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
26404                 byte-sequence {quoted} verbatim in the JSON emission \
26405                 (got: {json})",
26406            );
26407        }
26408    }
26409
26410    #[test]
26411    fn entrada_key_consts_are_pairwise_distinct() {
26412        // Cross-axis drift-detection pin: a future collapse of the four
26413        // canonical [`Entrada`] singleton byte-strings onto the same
26414        // value (e.g. an accidental copy-paste flip of
26415        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
26416        // silently reroute every downstream probe on one axis onto the
26417        // sibling axis's overlay entry and pass every propagation-probe
26418        // test that expected only the stale axis's value — the
26419        // Gateway/HTTPRoute emitter would read the hostname string
26420        // where the destination-Servico name was expected (or vice
26421        // versa), the admission-webhook cross-check would compare the
26422        // wrong pair of values, and the resulting Gateway resource
26423        // would either be admitted with garbage or rejected at the
26424        // controller far from the rebrand commit's source. Peer of the
26425        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
26426        // tetrad (40cc4e5), the two-way distinct pin on the
26427        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
26428        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
26429        // triad (ca463a4).
26430        let all = [
26431            crate::ENTRADA_KEY_HOST,
26432            crate::ENTRADA_KEY_PARA,
26433            crate::ENTRADA_KEY_PATHS,
26434            crate::ENTRADA_KEY_PORT,
26435        ];
26436        for (i, a) in all.iter().enumerate() {
26437            for b in all.iter().skip(i + 1) {
26438                assert_ne!(
26439                    a, b,
26440                    "ENTRADA_KEY_* consts must be pairwise-distinct \
26441                     canonical byte-sequences — got `{a}` == `{b}`",
26442                );
26443            }
26444        }
26445    }
26446
26447    #[test]
26448    fn entrada_key_consts_are_lower_camel_case_shape() {
26449        // Shape-pin: every `ENTRADA_KEY_*` const must be a
26450        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26451        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26452        // leading capital, no whitespace / dots) — the canonical shape
26453        // the `#[serde(rename_all = "camelCase")]` derive produces on
26454        // [`Entrada`]. A future flip to a non-camelCase attribute at
26455        // the derive surfaces both here (this test fails on the
26456        // stale-constant shape) and at
26457        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
26458        // test fails on the mismatch between const and derive). Peer
26459        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
26460        // and `contrato_key_consts_are_lower_camel_case_shape`
26461        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
26462        // entry axes.
26463        for key in [
26464            crate::ENTRADA_KEY_HOST,
26465            crate::ENTRADA_KEY_PARA,
26466            crate::ENTRADA_KEY_PATHS,
26467            crate::ENTRADA_KEY_PORT,
26468        ] {
26469            assert!(
26470                !key.is_empty(),
26471                "ENTRADA_KEY_* must be non-empty (got {key:?})"
26472            );
26473            let first = key.chars().next().unwrap();
26474            assert!(
26475                first.is_ascii_lowercase(),
26476                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
26477                 (got {key:?}, leads with {first:?})",
26478            );
26479            assert!(
26480                key.chars().all(|c| c.is_ascii_alphanumeric()),
26481                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
26482                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26483            );
26484        }
26485    }
26486
26487    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
26488
26489    #[test]
26490    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
26491        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
26492        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
26493        // [`crate::POLITICAS_KEY_RETRIES`] /
26494        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
26495        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
26496        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
26497        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
26498        // on [`MeshPolicy`] emits. Three of the five axes
26499        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
26500        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
26501        // camelCase transforms — the derive-attribute is load-bearing
26502        // on those, unlike the sibling `Entrada` / `Membro` /
26503        // `WitContract` structs whose fields are all lowercase-single-
26504        // word and where the derive is a no-op on every axis.
26505        // Serialize a fully-populated [`MeshPolicy`] (every axis
26506        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
26507        // on none of the five slots) and pin that each canonical
26508        // byte-sequence appears verbatim in the JSON — a future
26509        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26510        // verbatim-field-name flip at the derive attribute (any of
26511        // which would silently break every downstream JSON consumer
26512        // that reaches for one of the five consts via
26513        // `Value::get(...)` — the future M4 per-edge `:politicas`
26514        // overlay projection onto Cilium `L7Rules` and Gateway API
26515        // `HTTPRoute` backend timeouts, the future
26516        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26517        // admission-time mesh-policy cross-check, the future
26518        // `feira lint` per-`:politicas` bound-check gate) surfaces here
26519        // as a build-time test failure at `aplicacao.rs`, not as an
26520        // apply-time `.get(<stale-canonical-const>)` returning `None`
26521        // far from the derive-attr drift's commit. Peer with the
26522        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
26523        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26524        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
26525        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
26526        // atom axes — same discipline every M3 sibling lift
26527        // established, extended here to the singleton `:politicas`
26528        // mesh-slot atom axis, closing the last M3 typed-struct
26529        // top-level `#[serde(rename_all = "camelCase")]` axis on the
26530        // Aplicacao surface without a lifted serde-key peer.
26531        let p = MeshPolicy {
26532            timeout: Some(Duration::from_secs(30)),
26533            retries: Some(3),
26534            circuit_breaker: Some(CircuitBreaker {
26535                max_failures: 5,
26536                window: Duration::from_secs(60),
26537            }),
26538            mtls_required: Some(true),
26539            rate_limit: Some(RateLimit {
26540                rate: 100,
26541                window: Duration::from_secs(1),
26542            }),
26543        };
26544        let json = serde_json::to_string(&p).unwrap();
26545        for key in [
26546            crate::POLITICAS_KEY_TIMEOUT,
26547            crate::POLITICAS_KEY_RETRIES,
26548            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26549            crate::POLITICAS_KEY_MTLS_REQUIRED,
26550            crate::POLITICAS_KEY_RATE_LIMIT,
26551        ] {
26552            let quoted = format!("\"{key}\"");
26553            assert!(
26554                json.contains(&quoted),
26555                "serialized MeshPolicy must carry the lifted \
26556                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
26557                 JSON emission (got: {json})",
26558            );
26559        }
26560    }
26561
26562    #[test]
26563    fn politicas_key_consts_are_pairwise_distinct() {
26564        // Cross-axis drift-detection pin: a future collapse of the five
26565        // canonical [`MeshPolicy`] singleton byte-strings onto the same
26566        // value (e.g. an accidental copy-paste flip of
26567        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
26568        // would silently reroute every downstream probe on one axis
26569        // onto the sibling axis's overlay entry and pass every
26570        // propagation-probe test that expected only the stale axis's
26571        // value — the M4 per-edge `:politicas` overlay projection would
26572        // read the retry-count string where the timeout duration was
26573        // expected (or vice versa), the CR materializer's admission
26574        // cross-check would compare the wrong pair of values, and the
26575        // resulting mesh reconciler would either bind the wrong axis
26576        // or reject the resource at reconcile far from the rebrand
26577        // commit's source. Peer of the sibling four-way distinct pin
26578        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
26579        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
26580        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
26581        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
26582        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26583        let all = [
26584            crate::POLITICAS_KEY_TIMEOUT,
26585            crate::POLITICAS_KEY_RETRIES,
26586            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26587            crate::POLITICAS_KEY_MTLS_REQUIRED,
26588            crate::POLITICAS_KEY_RATE_LIMIT,
26589        ];
26590        for (i, a) in all.iter().enumerate() {
26591            for b in all.iter().skip(i + 1) {
26592                assert_ne!(
26593                    a, b,
26594                    "POLITICAS_KEY_* consts must be pairwise-distinct \
26595                     canonical byte-sequences — got `{a}` == `{b}`",
26596                );
26597            }
26598        }
26599    }
26600
26601    #[test]
26602    fn politicas_key_consts_are_lower_camel_case_shape() {
26603        // Shape-pin: every `POLITICAS_KEY_*` const must be a
26604        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26605        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26606        // leading capital, no whitespace / dots) — the canonical shape
26607        // the `#[serde(rename_all = "camelCase")]` derive produces on
26608        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
26609        // at the derive surfaces both here (this test fails on the
26610        // stale-constant shape) and at
26611        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26612        // (that test fails on the mismatch between const and derive).
26613        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
26614        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26615        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26616        // (ca463a4) on the sibling M3 typed-struct axes.
26617        for key in [
26618            crate::POLITICAS_KEY_TIMEOUT,
26619            crate::POLITICAS_KEY_RETRIES,
26620            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26621            crate::POLITICAS_KEY_MTLS_REQUIRED,
26622            crate::POLITICAS_KEY_RATE_LIMIT,
26623        ] {
26624            assert!(
26625                !key.is_empty(),
26626                "POLITICAS_KEY_* must be non-empty (got {key:?})"
26627            );
26628            let first = key.chars().next().unwrap();
26629            assert!(
26630                first.is_ascii_lowercase(),
26631                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
26632                 byte (got {key:?}, leads with {first:?})",
26633            );
26634            assert!(
26635                key.chars().all(|c| c.is_ascii_alphanumeric()),
26636                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
26637                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26638            );
26639        }
26640    }
26641
26642    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
26643
26644    #[test]
26645    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
26646        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
26647        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
26648        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
26649        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
26650        // [`CircuitBreaker`] emits inside the
26651        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
26652        // two axes (`max_failures` → `maxFailures`) is a non-trivial
26653        // camelCase transform — the derive-attribute is load-bearing on
26654        // that axis, unlike the sibling `window` field where the derive
26655        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
26656        // pin that each canonical byte-sequence appears verbatim in the
26657        // JSON — a future accidental `rename_all = "snake_case"` /
26658        // `"kebab-case"` / verbatim-field-name flip at the derive
26659        // attribute (any of which would silently break every downstream
26660        // JSON consumer that reaches for one of the two consts via
26661        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
26662        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
26663        // per-edge `:politicas` overlay projection onto the mesh's
26664        // per-backend consecutive-failure-counter tripping threshold, the
26665        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26666        // admission-time breaker cross-check, the future `feira lint`
26667        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
26668        // here as a build-time test failure at `aplicacao.rs`, not as an
26669        // apply-time `.get(<stale-canonical-const>)` returning `None`
26670        // far from the derive-attr drift's commit. Peer with the sibling
26671        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26672        // (b55cca7) parent-axis pin — that test pins the outer
26673        // sub-block key the derive on [`MeshPolicy`] emits, this test
26674        // pins the inner keys the derive on the payload type emits, so
26675        // the two together lock the whole [`MeshPolicy`] breaker-tuning
26676        // shape end-to-end at build time.
26677        let cb = CircuitBreaker {
26678            max_failures: 5,
26679            window: Duration::from_secs(60),
26680        };
26681        let json = serde_json::to_string(&cb).unwrap();
26682        for key in [
26683            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26684            crate::CIRCUIT_BREAKER_KEY_WINDOW,
26685        ] {
26686            let quoted = format!("\"{key}\"");
26687            assert!(
26688                json.contains(&quoted),
26689                "serialized CircuitBreaker must carry the lifted \
26690                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
26691                 in the JSON emission (got: {json})",
26692            );
26693        }
26694    }
26695
26696    #[test]
26697    fn circuit_breaker_key_consts_are_pairwise_distinct() {
26698        // Cross-axis drift-detection pin: a future collapse of the two
26699        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
26700        // same value (e.g. an accidental copy-paste flip of
26701        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
26702        // `"maxFailures"`) would silently reroute every downstream
26703        // probe on one axis onto the sibling axis's overlay entry and
26704        // pass every propagation-probe test that expected only the
26705        // stale axis's value — the M4 per-edge `:politicas` overlay
26706        // projection would read the failure-count where the window
26707        // duration was expected (or vice versa), the CR materializer's
26708        // admission cross-check would compare the wrong pair of values,
26709        // and the resulting mesh reconciler would either bind the wrong
26710        // axis or reject the resource at reconcile far from the rebrand
26711        // commit's source. Peer of the sibling five-way distinct pin on
26712        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
26713        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
26714        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
26715        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
26716        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26717        let all = [
26718            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26719            crate::CIRCUIT_BREAKER_KEY_WINDOW,
26720        ];
26721        for (i, a) in all.iter().enumerate() {
26722            for b in all.iter().skip(i + 1) {
26723                assert_ne!(
26724                    a, b,
26725                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
26726                     canonical byte-sequences — got `{a}` == `{b}`",
26727                );
26728            }
26729        }
26730    }
26731
26732    #[test]
26733    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
26734        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
26735        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26736        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26737        // leading capital, no whitespace / dots) — the canonical shape
26738        // the `#[serde(rename_all = "camelCase")]` derive produces on
26739        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
26740        // at the derive surfaces both here (this test fails on the
26741        // stale-constant shape) and at
26742        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
26743        // (that test fails on the mismatch between const and derive).
26744        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
26745        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
26746        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26747        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26748        // (ca463a4) on the sibling M3 typed-struct axes.
26749        for key in [
26750            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26751            crate::CIRCUIT_BREAKER_KEY_WINDOW,
26752        ] {
26753            assert!(
26754                !key.is_empty(),
26755                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
26756            );
26757            let first = key.chars().next().unwrap();
26758            assert!(
26759                first.is_ascii_lowercase(),
26760                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
26761                 byte (got {key:?}, leads with {first:?})",
26762            );
26763            assert!(
26764                key.chars().all(|c| c.is_ascii_alphanumeric()),
26765                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
26766                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26767            );
26768        }
26769    }
26770
26771    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
26772
26773    #[test]
26774    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
26775        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
26776        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
26777        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
26778        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
26779        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
26780        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
26781        // [`Placement`] emits. One of the four axes (`shard_key` →
26782        // `shardKey`) is a non-trivial camelCase transform — the
26783        // derive-attribute is load-bearing on that axis, unlike the
26784        // sibling `estrategia` / `clusters` / `affinity` axes whose
26785        // source-side field names carry no `_` and where the derive is a
26786        // no-op. Serialize a fully-populated [`Placement`] (both
26787        // `Option`-carrying axes `Some(_)` so
26788        // `skip_serializing_if = "Option::is_none"` fires on neither of
26789        // the two optional slots) and pin that each canonical
26790        // byte-sequence appears verbatim in the JSON — a future
26791        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26792        // verbatim-field-name flip at the derive attribute (any of which
26793        // would silently break every downstream consumer that reaches
26794        // for one of the four consts via
26795        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
26796        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
26797        // aggregator's per-cluster fanout filter keying off
26798        // `placement.clusters`, the M3 shard-pool dispatch materializer
26799        // keying off `placement.shardKey`, the M3 Adaptive compression
26800        // pass weighting off `placement.affinity`, every downstream
26801        // dispatcher branching on `placement.estrategia`, the future
26802        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26803        // admission-time placement cross-check, the future `feira lint`
26804        // per-`:placement` bound-check gate) surfaces here as a
26805        // build-time test failure at `aplicacao.rs`, not as an
26806        // apply-time `.get(<stale-canonical-const>)` returning `None`
26807        // far from the derive-attr drift's commit. Peer with the sibling
26808        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26809        // (b55cca7),
26810        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
26811        // (468e959),
26812        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
26813        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26814        // (ca463a4), and
26815        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26816        // pins on the M3 collection-slot / singleton-slot atom axes —
26817        // closes the last M3 typed-struct top-level
26818        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
26819        // surface without a drift-detection pin.
26820        let p = Placement {
26821            estrategia: PlacementStrategy::Sharded,
26822            clusters: vec!["rio".into(), "mar".into()],
26823            affinity: Some("data-locality".into()),
26824            shard_key: Some("$tenantId".into()),
26825        };
26826        let json = serde_json::to_string(&p).unwrap();
26827        for key in [
26828            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26829            crate::M3_PLACEMENT_KEY_CLUSTERS,
26830            crate::M3_PLACEMENT_KEY_AFFINITY,
26831            crate::M3_PLACEMENT_KEY_SHARD_KEY,
26832        ] {
26833            let quoted = format!("\"{key}\"");
26834            assert!(
26835                json.contains(&quoted),
26836                "serialized Placement must carry the lifted \
26837                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
26838                 the JSON emission (got: {json})",
26839            );
26840        }
26841    }
26842
26843    #[test]
26844    fn m3_placement_key_consts_are_pairwise_distinct() {
26845        // Cross-axis drift-detection pin: a future collapse of the four
26846        // canonical [`Placement`] sub-block byte-strings onto the same
26847        // value (e.g. an accidental copy-paste flip of
26848        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
26849        // `"affinity"`) would silently reroute every downstream probe on
26850        // one axis onto the sibling axis's overlay entry and pass every
26851        // propagation-probe test that expected only the stale axis's
26852        // value — the M3 shard-pool dispatch materializer would read the
26853        // affinity placement-hint where the shard-selection template was
26854        // expected (or vice versa), the M3 Adaptive compression pass's
26855        // cross-check would compare the wrong pair of values, and the
26856        // resulting placement engine would either bind the wrong axis or
26857        // reject the resource at reconcile far from the rebrand commit's
26858        // source. Peer of the sibling two-way distinct pin on the
26859        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
26860        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
26861        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
26862        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
26863        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
26864        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26865        let all = [
26866            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26867            crate::M3_PLACEMENT_KEY_CLUSTERS,
26868            crate::M3_PLACEMENT_KEY_AFFINITY,
26869            crate::M3_PLACEMENT_KEY_SHARD_KEY,
26870        ];
26871        for (i, a) in all.iter().enumerate() {
26872            for b in all.iter().skip(i + 1) {
26873                assert_ne!(
26874                    a, b,
26875                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
26876                     canonical byte-sequences — got `{a}` == `{b}`",
26877                );
26878            }
26879        }
26880    }
26881
26882    #[test]
26883    fn m3_placement_key_consts_are_lower_camel_case_shape() {
26884        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
26885        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26886        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26887        // leading capital, no whitespace / dots) — the canonical shape
26888        // the `#[serde(rename_all = "camelCase")]` derive produces on
26889        // [`Placement`]. A future flip to a non-camelCase attribute at
26890        // the derive surfaces both here (this test fails on the stale-
26891        // constant shape) and at
26892        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
26893        // (that test fails on the mismatch between const and derive).
26894        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
26895        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
26896        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
26897        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26898        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26899        // (ca463a4) on the sibling M3 typed-struct axes.
26900        for key in [
26901            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26902            crate::M3_PLACEMENT_KEY_CLUSTERS,
26903            crate::M3_PLACEMENT_KEY_AFFINITY,
26904            crate::M3_PLACEMENT_KEY_SHARD_KEY,
26905        ] {
26906            assert!(
26907                !key.is_empty(),
26908                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
26909            );
26910            let first = key.chars().next().unwrap();
26911            assert!(
26912                first.is_ascii_lowercase(),
26913                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
26914                 byte (got {key:?}, leads with {first:?})",
26915            );
26916            assert!(
26917                key.chars().all(|c| c.is_ascii_alphanumeric()),
26918                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
26919                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26920            );
26921        }
26922    }
26923
26924    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
26925    //    destination-facing L4 port resolver every per-Aplicacao renderer
26926    //    reaching for a per-destination Servico TCP port axis routes
26927    //    through. The four pin tests below fix the four-way accept-set
26928    //    the resolver must always honor: (:entrada-para-matches,
26929    //    :entrada-para-mismatches, :entrada-none-so-fallback,
26930    //    :entrada-port-non-default-honored) — drift on any arm surfaces
26931    //    at caixa-core build time rather than at cluster-apply time.
26932
26933    #[test]
26934    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
26935        // The typed `:entrada` block's `:para "cart"` matches the
26936        // queried destination, so the resolver returns the author-
26937        // declared `:port` scalar verbatim — the canonical "the
26938        // destination Servico IS the ingress apex, honor the typed
26939        // listener port" arm of the port-resolution dispatch.
26940        let mut spec = three_member_spec();
26941        if let Some(e) = spec.entrada.as_mut() {
26942            e.para = "cart".into();
26943            e.port = 9090;
26944        }
26945        assert_eq!(
26946            spec.port_for_destination("cart"),
26947            9090,
26948            "port_for_destination(entrada.para) must return entrada.port \
26949             verbatim, not the DEFAULT_SERVICO_PORT fallback"
26950        );
26951    }
26952
26953    #[test]
26954    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
26955        // The typed `:entrada` block names `:para "cart"`, but the
26956        // queried destination is `"payment"` — a Servico that
26957        // participates in the mesh graph but is not the ingress apex.
26958        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
26959        // canonical port floor, closing the "non-apex destination reads
26960        // the substrate default" arm. Same fixture the peer
26961        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
26962        // pin at caixa-mesh exercises through the CNP emit-side path;
26963        // this pin exercises the shared underlying resolver directly.
26964        let spec = three_member_spec();
26965        assert_eq!(
26966            spec.port_for_destination("payment"),
26967            DEFAULT_SERVICO_PORT,
26968            "port_for_destination(non-apex-destination) must route \
26969             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
26970        );
26971    }
26972
26973    #[test]
26974    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
26975        // Internal-only Aplicacao — no `:entrada` block declared. Every
26976        // per-destination port query falls back to the lifted
26977        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
26978        // the Aplicacao surface admits `:entrada None` (internal mesh
26979        // with no external gateway); every downstream renderer's per-
26980        // destination port axis must still resolve to a well-defined
26981        // scalar even without an ingress apex.
26982        let mut spec = three_member_spec();
26983        spec.entrada = None;
26984        assert_eq!(
26985            spec.port_for_destination("cart"),
26986            DEFAULT_SERVICO_PORT,
26987            "port_for_destination on an internal-only Aplicacao must \
26988             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
26989             every destination"
26990        );
26991        assert_eq!(
26992            spec.port_for_destination("payment"),
26993            DEFAULT_SERVICO_PORT,
26994            "port_for_destination on an internal-only Aplicacao must \
26995             fall back uniformly across every destination — the fallback \
26996             is not entrada-shape-conditional"
26997        );
26998    }
26999
27000    #[test]
27001    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
27002        // Structural pin against a hypothetical future refactor that
27003        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
27004        // the resolver (a "normalize to the default when the author's
27005        // port matches the substrate default" collapse) — that would
27006        // break renderer sites that carry meaning on the emitted port
27007        // value beyond bare equality (a future per-cluster listener-
27008        // audit that keys off the author-declared port, not the
27009        // resolved-with-fallback port). Pin that a non-default
27010        // entrada.port is returned verbatim so drift here surfaces at
27011        // caixa-core build time.
27012        let mut spec = three_member_spec();
27013        if let Some(e) = spec.entrada.as_mut() {
27014            e.para = "cart".into();
27015            e.port = 8443;
27016        }
27017        assert_ne!(
27018            8443, DEFAULT_SERVICO_PORT,
27019            "test fixture must probe a port distinct from \
27020             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
27021        );
27022        assert_eq!(
27023            spec.port_for_destination("cart"),
27024            8443,
27025            "port_for_destination(entrada.para) must return entrada.port \
27026             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
27027        );
27028    }
27029
27030    #[test]
27031    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
27032        // Apex-identity pair-invariant pin composing both substrate-
27033        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
27034        // and [`Entrada::destination`] — at the emit-side call shape
27035        // every per-Aplicacao renderer's ingress-apex L4 port reader
27036        // now takes. The invariant:
27037        //
27038        //   spec.port_for_destination(entrada.destination()) == entrada.port
27039        //
27040        // holds by construction under today's single-destination
27041        // `:entrada` slot (`destination()` returns `entrada.para`, and
27042        // the resolver's apex arm matches `para == destination` and
27043        // returns `entrada.port`), and every downstream consumer that
27044        // composes the two accessors at the ingress apex — the
27045        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
27046        // `backendRefs[0].port` emit-site path, the peer future M4 CR
27047        // materializer's admission-webhook that promotes the scalar to
27048        // a per-CR override overlay, every future per-Aplicacao snapshot
27049        // renderer's apex-facing L4 port reader — reaches through the
27050        // same composition. Pin the identity across four permutations
27051        // (`:para` × `:port` including a non-default port to exercise
27052        // the honor-verbatim arm and a non-cart `:para` to exercise
27053        // destination-agnostic identity) so a future refactor that
27054        // silently split either accessor's apex behavior surfaces at
27055        // caixa-core build time — a subtle `destination()` renaming
27056        // that returned `entrada.host.as_str()` instead of
27057        // `entrada.para.as_str()` would blow this pin loudly, closing
27058        // the last quiet failure mode the two lifts admit in composition.
27059        //
27060        // Peer discipline with the sibling caixa-mesh cross-crate pin
27061        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
27062        // on the two-renderer pair-invariant axis; this pin encodes the
27063        // same two-consumer coherence rule at the substrate-primitive
27064        // level so the invariant survives even if every renderer is
27065        // deleted.
27066        for (para, port) in [
27067            ("cart", DEFAULT_SERVICO_PORT),
27068            ("cart", 8443u16),
27069            ("payment", 9090u16),
27070            ("catalog", 443u16),
27071        ] {
27072            let mut spec = three_member_spec();
27073            if let Some(e) = spec.entrada.as_mut() {
27074                e.para = para.into();
27075                e.port = port;
27076            }
27077            let expected_port = spec
27078                .entrada()
27079                .expect("three_member_spec carries a typed `:entrada` block")
27080                .port();
27081            let composed_port = {
27082                let entrada = spec.entrada().expect("entrada present");
27083                spec.port_for_destination(entrada.destination())
27084            };
27085            assert_eq!(
27086                composed_port, expected_port,
27087                "`spec.port_for_destination(entrada.destination())` must \
27088                 equal `entrada.port` under today's single-destination \
27089                 `:entrada` slot — this is the apex-identity contract \
27090                 every downstream ingress-apex L4 port reader relies on. \
27091                 Input :entrada :para: {para:?}, :entrada :port: {port}"
27092            );
27093        }
27094    }
27095
27096    #[test]
27097    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
27098        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
27099        // per-`:entrada` apex-arm membership probe must key off
27100        // [`Entrada::destination`], not the raw `.para` field access.
27101        // Structurally: setting ONLY the `:entrada :para` field to a
27102        // fresh non-cart destination on an otherwise-well-formed
27103        // Aplicacao must (1) leave `e.destination()` byte-equal to
27104        // `e.para.as_str()` (the accessor is byte-projective by
27105        // definition), and (2) cause the resolver's apex arm to fire
27106        // and return `entrada.port` at exactly that new destination
27107        // while every other destination string falls through to
27108        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
27109        // membership check. Pins against a future silent detour that
27110        // (a) re-derived the apex-arm membership probe off
27111        // `e.para == destination` in `port_for_destination` instead of
27112        // `e.destination() == destination`, silently disagreeing with
27113        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
27114        // consumers (`entrada.destination()` at
27115        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
27116        // caixa-mesh/src/lib.rs:2739) that already reach through the
27117        // accessor, (b) accessor-side introduced a per-tenant alias
27118        // arm the caller was unaware of, silently rewriting an
27119        // author-declared `:para "cart"` value to a canary-aliased
27120        // form — the raw-field-access resolver would fall through to
27121        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
27122        // while the peer emit-site consumers landed on the aliased
27123        // destination, splitting the ingress-apex L4 port at
27124        // cluster-apply time.
27125        //
27126        // Peer of the sibling
27127        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
27128        // (d0de220) composition pin on the per-`:membros` refusal-arm
27129        // axis — same "the shape-gate predicate must route through the
27130        // substrate-primitive typed dispatch" discipline extended onto
27131        // the per-`:entrada` apex-arm membership-probe axis. Closes
27132        // the last unlifted `.para` production-code read site on
27133        // `Entrada` in `caixa-core` — after this converge every
27134        // `caixa-core` `.para` field access outside the accessor's own
27135        // body and outside the `WitContract` per-`:contratos` sibling
27136        // axis is either a test-side field-setter or a doc-comment
27137        // reference.
27138        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
27139            let mut spec = three_member_spec();
27140            if let Some(e) = spec.entrada.as_mut() {
27141                e.para = para.into();
27142                e.port = port;
27143            }
27144            let e = spec
27145                .entrada
27146                .as_ref()
27147                .expect("three_member_spec carries a typed `:entrada` block");
27148            assert_eq!(
27149                e.destination(),
27150                e.para.as_str(),
27151                "Entrada::destination must byte-equal the .para field \
27152                 access — an accessor-side detour that no longer \
27153                 projects the raw field would silently split this \
27154                 drift-detection test from the port_for_destination \
27155                 apex-arm membership probe",
27156            );
27157            assert_eq!(
27158                spec.port_for_destination(para),
27159                port,
27160                "port_for_destination must key off the accessor-projected \
27161                 destination and return `entrada.port` on the apex arm — \
27162                 input :entrada :para: {para:?}, :entrada :port: {port}",
27163            );
27164            assert_eq!(
27165                spec.port_for_destination("ghost-destination-never-a-member"),
27166                DEFAULT_SERVICO_PORT,
27167                "port_for_destination must fall through to \
27168                 DEFAULT_SERVICO_PORT on a non-matching destination \
27169                 under the accessor-projected membership check — input \
27170                 :entrada :para: {para:?}, :entrada :port: {port}",
27171            );
27172        }
27173    }
27174
27175    #[test]
27176    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
27177        // The canonical per-`:politicas :rate-limit` `:rate`
27178        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
27179        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
27180        // typed `u32` verbatim, byte-equal to the raw field access
27181        // across every representative value in the accept-set — `1` (the
27182        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
27183        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
27184        // carves out on the sibling `PolicyRateLimitZero` refusal),
27185        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
27186        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
27187        // `0` (a past-the-guard sentinel that pins the accessor doesn't
27188        // perform a silent bounds-collapse into `1` on the zero arm —
27189        // validate rejects zero but the accessor must ship the raw slot
27190        // verbatim so a validate-time gate regression surfaces at the
27191        // emit boundary rather than being silently absorbed), `u32::MAX`
27192        // (a past-the-guard sentinel that pins the accessor doesn't
27193        // perform a silent bounds-collapse through
27194        // `POLICY_RATE_LIMIT_MAX` at the return path).
27195        //
27196        // First sub-struct required-scalar accessor pin on the
27197        // `RateLimit` axis — sibling in shape to the peer
27198        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
27199        // required-`u32` accessor pin on the peer per-sub-struct
27200        // required-axis. Pins against a future silent detour that
27201        // re-derived the token capacity from a peer axis (an accidental
27202        // `self.window.as_secs() as u32` collapse that read the
27203        // rate-limit window duration as a token count), a `0 → 1`
27204        // cluster-default projection (which would silently absorb the
27205        // `PolicyRateLimitZero` refusal case at the accessor boundary),
27206        // or a bounds-collapsing accessor that clamped the return
27207        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
27208        // gate owns the bounds; the accessor must ship the raw slot
27209        // verbatim).
27210        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27211            let rl = RateLimit {
27212                rate,
27213                window: Duration::from_secs(1),
27214            };
27215            assert_eq!(
27216                rl.rate(),
27217                rate,
27218                "RateLimit::rate must return :politicas :rate-limit :rate \
27219                 verbatim (got {}, expected {rate})",
27220                rl.rate(),
27221            );
27222            assert_eq!(
27223                rl.rate(),
27224                rl.rate,
27225                "RateLimit::rate must byte-equal the raw .rate field \
27226                 access across every value in the u32 accept-set",
27227            );
27228        }
27229    }
27230
27231    #[test]
27232    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
27233        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27234        // `:rate-limit :rate` zero-floor arm must key off
27235        // [`RateLimit::rate`], not the raw `.rate` field access.
27236        // Structurally: a `RateLimit { rate: 0, window:
27237        // Duration::from_secs(1) }` embedded in a `:politicas
27238        // :rate-limit` slot must surface the `PolicyRateLimitZero`
27239        // refusal exactly, and a `RateLimit { rate: 1, window:
27240        // Duration::from_secs(1) }` (the lower boundary of the
27241        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
27242        // The pair jointly pins the accessor + validate-gate composition:
27243        // any future silent detour that had the accessor return a fresh
27244        // `1` on the zero arm (a `.rate().max(1)` collapse) would
27245        // silently absorb the `PolicyRateLimitZero` refusal at the
27246        // accessor boundary and the validate gate would accept a
27247        // struct-literal `RateLimit { rate: 0, .. }` — the composition
27248        // pin catches that at caixa-core build time.
27249        //
27250        // Peer of the sibling per-`CircuitBreaker`
27251        // [`CircuitBreaker::max_failures`] (3a74062) /
27252        // [`CircuitBreaker::window`] (373957f) accessor-composition
27253        // pins on the peer required-scalar axes — same "the validate /
27254        // shape-gate predicate must route through the substrate-primitive
27255        // typed dispatch" discipline extended onto the peer
27256        // per-`RateLimit` required-`u32` composition axis.
27257        let mut spec = three_member_spec();
27258        spec.politicas = MeshPolicy {
27259            rate_limit: Some(RateLimit {
27260                rate: 0,
27261                window: Duration::from_secs(1),
27262            }),
27263            ..MeshPolicy::default()
27264        };
27265        assert!(
27266            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
27267            "validate_politicas must reject rate == 0 with \
27268             PolicyRateLimitZero — the accessor and the validate gate \
27269             must route through the same substrate-primitive typed \
27270             dispatch on the :rate zero-floor arm",
27271        );
27272        spec.politicas = MeshPolicy {
27273            rate_limit: Some(RateLimit {
27274                rate: 1,
27275                window: Duration::from_secs(1),
27276            }),
27277            ..MeshPolicy::default()
27278        };
27279        assert!(
27280            spec.validate().is_ok(),
27281            "validate_politicas must accept rate == 1 (the lower \
27282             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
27283        );
27284    }
27285
27286    #[test]
27287    fn rate_limit_rate_projects_u32_by_copy() {
27288        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
27289        // `u32` is `Copy` and the accessor must return by value, not by
27290        // reference. Peer of the sibling per-`CircuitBreaker`
27291        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
27292        // peer required-scalar `:max-failures` axis, extended onto the
27293        // peer per-`RateLimit` required-`u32` copy-invariant shape —
27294        // the accessor's returned `u32` must outlive `&self` (multiple
27295        // calls must return equal values from a dropped-`&self` copy,
27296        // since the returned scalar carries no borrow), and calling the
27297        // accessor twice on the same RateLimit must yield the same
27298        // `u32` verbatim (idempotent, no side effects on `&self`).
27299        //
27300        // Pins against a future silent detour that returned `&u32`
27301        // (which would type-check but silently break every downstream
27302        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
27303        // first parameter is `u32`, and `&u32` would fold to a detached
27304        // copy at the call site with a `*` deref the sibling accessors
27305        // don't need), an accidental `.rate.wrapping_add(0)` detour that
27306        // returned a fresh copy through an arithmetic no-op (breaking a
27307        // future `const fn` regression), or a one-arm-only accessor
27308        // that returned a saturating value on some sentinel input
27309        // (breaking the pass-through invariant the sibling required-
27310        // scalar accessors carry).
27311        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27312            let rl = RateLimit {
27313                rate,
27314                window: Duration::from_secs(1),
27315            };
27316            let first = rl.rate();
27317            let second = rl.rate();
27318            assert_eq!(
27319                first, second,
27320                "RateLimit::rate must be idempotent — two successive \
27321                 calls on the same &self must return the same u32",
27322            );
27323            assert_eq!(
27324                first, rate,
27325                "RateLimit::rate must return :politicas :rate-limit :rate \
27326                 verbatim by copy — got {first}, expected {rate}",
27327            );
27328        }
27329    }
27330
27331    #[test]
27332    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
27333        // The canonical per-`:politicas :rate-limit` `:window`
27334        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
27335        // pin: [`RateLimit::window`] must return the
27336        // `:politicas :rate-limit :window` typed `Duration` verbatim,
27337        // byte-equal to the raw field access across every
27338        // representative value in the accept-set — `Duration::from_secs(1)`
27339        // (the `"s"` canonical window, the lower row of
27340        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
27341        // [`AplicacaoSpec::validate_politicas`] gate accepts via
27342        // [`is_canonical_rate_limit_window`]),
27343        // `Duration::from_secs(60)` (the `"m"` canonical window, the
27344        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
27345        // window, the upper row), `Duration::ZERO` (a past-the-guard
27346        // sentinel that pins the accessor doesn't perform a silent
27347        // bounds-collapse into `Duration::from_secs(1)` on the zero
27348        // arm — validate rejects an off-set window through
27349        // `PolicyRateLimitWindowNotCanonical` but the accessor must
27350        // ship the raw slot verbatim so a validate-time gate
27351        // regression surfaces at the emit boundary rather than being
27352        // silently absorbed), `Duration::from_millis(500)` (a
27353        // sub-canonical past-the-guard sentinel that pins the accessor
27354        // doesn't silently normalize a non-canonical fractional
27355        // magnitude onto the nearest canonical row).
27356        //
27357        // Second sub-struct required-scalar accessor pin on the
27358        // `RateLimit` axis — sibling in shape to the just-landed
27359        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
27360        // accessor pin on the peer per-sub-struct required-axis,
27361        // extended onto the per-`RateLimit` required-`Duration` axis.
27362        // Pins against a future silent detour that re-derived the
27363        // refill period from a peer axis (an accidental
27364        // `Duration::from_secs(self.rate as u64)` collapse that read
27365        // the rate-limit token capacity as a refill-interval
27366        // duration), a `Duration::ZERO → Duration::from_secs(1)`
27367        // canonical-default projection (which would silently absorb
27368        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
27369        // accessor boundary), or a canonical-set-collapsing accessor
27370        // that clamped the return through [`rate_limit_window_unit`]
27371        // (the `AplicacaoSpec::validate` gate owns the canonical-set
27372        // membership; the accessor must ship the raw slot verbatim).
27373        for window in [
27374            Duration::from_secs(1),
27375            Duration::from_secs(60),
27376            Duration::from_secs(3600),
27377            Duration::ZERO,
27378            Duration::from_millis(500),
27379        ] {
27380            let rl = RateLimit { rate: 100, window };
27381            assert_eq!(
27382                rl.window(),
27383                window,
27384                "RateLimit::window must return :politicas :rate-limit :window \
27385                 verbatim (got {:?}, expected {window:?})",
27386                rl.window(),
27387            );
27388            assert_eq!(
27389                rl.window(),
27390                rl.window,
27391                "RateLimit::window must byte-equal the raw .window field \
27392                 access across every value in the Duration accept-set",
27393            );
27394        }
27395    }
27396
27397    #[test]
27398    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
27399        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27400        // `:rate-limit :window` canonical-set arm must key off
27401        // [`RateLimit::window`], not the raw `.window` field access.
27402        // Structurally: a `RateLimit { window: Duration::from_millis(500),
27403        // .. }` embedded in a `:politicas :rate-limit` slot must
27404        // surface the `PolicyRateLimitWindowNotCanonical` refusal
27405        // exactly (with the sub-canonical `Duration::from_millis(500)`
27406        // magnitude carried through verbatim), and a `RateLimit
27407        // { window: Duration::from_secs(1), .. }` (the lower row of
27408        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
27409        // The pair jointly pins the accessor + validate-gate
27410        // composition: any future silent detour that had the accessor
27411        // normalize the off-set window to the nearest canonical row
27412        // (a `.window().max(Duration::from_secs(1))` collapse, or a
27413        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
27414        // collapse) would silently absorb the
27415        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
27416        // boundary — including a drift in the error's `window` payload
27417        // (the emit-side diagnostic reader keys off the offending
27418        // magnitude verbatim, so a normalization at the accessor
27419        // boundary would silently pin the wrong magnitude in the
27420        // refusal). The composition pin catches that at caixa-core
27421        // build time.
27422        //
27423        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
27424        // (7f81a60) accessor-composition pin on the peer required-
27425        // scalar `:rate` axis — same "the validate / shape-gate
27426        // predicate must route through the substrate-primitive typed
27427        // dispatch, and the error payload must project through the
27428        // same accessor" discipline extended onto the peer
27429        // per-`RateLimit` required-`Duration` composition axis.
27430        let mut spec = three_member_spec();
27431        spec.politicas = MeshPolicy {
27432            rate_limit: Some(RateLimit {
27433                rate: 100,
27434                window: Duration::from_millis(500),
27435            }),
27436            ..MeshPolicy::default()
27437        };
27438        match spec.validate() {
27439            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
27440                assert_eq!(
27441                    window,
27442                    Duration::from_millis(500),
27443                    "PolicyRateLimitWindowNotCanonical must carry the \
27444                     offending :window magnitude verbatim through the \
27445                     accessor — got {window:?}, expected 500ms",
27446                );
27447            }
27448            other => panic!(
27449                "validate_politicas must reject non-canonical :window \
27450                 with PolicyRateLimitWindowNotCanonical — the accessor \
27451                 and the validate gate must route through the same \
27452                 substrate-primitive typed dispatch on the :window \
27453                 canonical-set arm; got {other:?}",
27454            ),
27455        }
27456        spec.politicas = MeshPolicy {
27457            rate_limit: Some(RateLimit {
27458                rate: 100,
27459                window: Duration::from_secs(1),
27460            }),
27461            ..MeshPolicy::default()
27462        };
27463        assert!(
27464            spec.validate().is_ok(),
27465            "validate_politicas must accept window == Duration::from_secs(1) \
27466             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
27467        );
27468    }
27469
27470    #[test]
27471    fn rate_limit_window_projects_duration_by_copy() {
27472        // The by-copy pin: [`RateLimit::window`] returns `Duration`
27473        // by copy — `Duration` is `Copy` and the accessor must return
27474        // by value, not by reference. Peer of the sibling per-`RateLimit`
27475        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
27476        // required-scalar `:rate` axis, extended onto the peer
27477        // per-`RateLimit` required-`Duration` copy-invariant shape —
27478        // the accessor's returned `Duration` must outlive `&self`
27479        // (multiple calls must return equal values from a
27480        // dropped-`&self` copy, since the returned scalar carries no
27481        // borrow), and calling the accessor twice on the same
27482        // RateLimit must yield the same `Duration` verbatim
27483        // (idempotent, no side effects on `&self`).
27484        //
27485        // Pins against a future silent detour that returned
27486        // `&Duration` (which would type-check but silently break every
27487        // downstream `Duration`-by-value consumer —
27488        // [`is_canonical_rate_limit_window`]'s first parameter is
27489        // `Duration`, and `&Duration` would fold to a detached copy at
27490        // the call site with a `*` deref the sibling accessors don't
27491        // need), an accidental `.window + Duration::ZERO` detour that
27492        // returned a fresh copy through an arithmetic no-op (breaking
27493        // a future `const fn` regression), or a one-arm-only accessor
27494        // that returned a canonical fallback on some sentinel input
27495        // (breaking the pass-through invariant the sibling required-
27496        // scalar accessors carry).
27497        for window in [
27498            Duration::from_secs(1),
27499            Duration::from_secs(60),
27500            Duration::from_secs(3600),
27501            Duration::ZERO,
27502            Duration::from_millis(500),
27503        ] {
27504            let rl = RateLimit { rate: 100, window };
27505            let first = rl.window();
27506            let second = rl.window();
27507            assert_eq!(
27508                first, second,
27509                "RateLimit::window must be idempotent — two successive \
27510                 calls on the same &self must return the same Duration",
27511            );
27512            assert_eq!(
27513                first, window,
27514                "RateLimit::window must return :politicas :rate-limit :window \
27515                 verbatim by copy — got {first:?}, expected {window:?}",
27516            );
27517        }
27518    }
27519
27520    #[test]
27521    fn placement_estrategia_default_pins_m3_canonical_value() {
27522        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
27523        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
27524        // active-active-across-every-named-cluster arm, the closest
27525        // canonical M3 production reference the substrate carries and
27526        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
27527        // for every un-`:placement`-declared Aplicacao. Pinning the arm
27528        // here surfaces a future rebrand of the M3-canonical
27529        // distribution default (a widening to `Sharded` once the
27530        // substrate discovers hash-keyed distribution as the more
27531        // common production shape, a tightening to `SingleNode` for
27532        // stateful Erlang/OTP distributed-app-takeover semantics
27533        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
27534        // operator pins through a future `:placement-overrides` slot)
27535        // as a deliberate test edit, not a silent contract migration.
27536        // Peer of the sibling M2 per-supervisor value pins
27537        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
27538        // /
27539        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
27540        // extended onto the M3 mesh-primitive-defining `:placement
27541        // :estrategia` axis.
27542        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
27543    }
27544
27545    #[test]
27546    fn placement_strategy_default_routes_through_lifted_default() {
27547        // Composition pin: the [`Default for PlacementStrategy`] impl's
27548        // return arm must route through the substrate-canonical
27549        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
27550        // a raw `Self::Replicated` arm. Prior to the lift the impl
27551        // carried an inline `Self::Replicated` arm with no compile-time
27552        // link back to the shared M3-canonical `Replicated` arm the
27553        // paired [`Default for Placement`] impl's struct-literal
27554        // `estrategia` field, the serde-side `#[serde(default)]` on
27555        // [`Placement::estrategia`] that resolves an author-omitted
27556        // wire-form `:placement :estrategia` scalar through the impl,
27557        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
27558        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
27559        // routes through [`Placement::default`] which routes through the
27560        // strategy default) all key off — so a future rebrand of the
27561        // M3-canonical distribution default would have had to be threaded
27562        // through the `Default` impl and the three peer routes in
27563        // lockstep or the four consumers would silently split. Byte-
27564        // parity against the lifted constant closes the split. Peer of
27565        // the sibling
27566        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
27567        // /
27568        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
27569        // composition pins on the M2 per-supervisor axes.
27570        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
27571    }
27572
27573    #[test]
27574    fn placement_default_estrategia_routes_through_lifted_default() {
27575        // Composition pin: the [`Default for Placement`] impl's
27576        // struct-literal `estrategia` field must route through the
27577        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
27578        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
27579        // impl that the sibling
27580        // `placement_strategy_default_routes_through_lifted_default` pin
27581        // already routes onto the constant). Structurally: every
27582        // `Placement::default()` call must yield an `estrategia` field
27583        // byte-equal to the lifted constant so the two paired defaults —
27584        // the [`Default for PlacementStrategy`] impl arm and the
27585        // struct-literal default arm here — cannot silently split on any
27586        // future M3-canonical distribution-default rebrand. Peer of the
27587        // sibling M2
27588        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
27589        // byte-parity pin on the [`Default for SupervisorSpec`]
27590        // struct-literal `estrategia` field extended onto the M3
27591        // mesh-primitive-defining slot family.
27592        assert_eq!(
27593            Placement::default().estrategia,
27594            PLACEMENT_ESTRATEGIA_DEFAULT,
27595        );
27596    }
27597
27598    #[test]
27599    fn placement_serde_default_estrategia_routes_through_lifted_default() {
27600        // Composition pin: the serde-side `#[serde(default)]` on
27601        // [`Placement::estrategia`] — the wire-format author-omitted
27602        // `:placement :estrategia` arm — must resolve onto the substrate-
27603        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
27604        // (via the [`Default for PlacementStrategy`] impl the sibling
27605        // `placement_strategy_default_routes_through_lifted_default` pin
27606        // already routes onto the constant). Structurally: a `Placement`
27607        // deserialized from a payload that omits the `estrategia` key
27608        // must yield an `estrategia` field byte-equal to the lifted
27609        // constant, so the wire-format author-omitted arm and the
27610        // [`PlacementStrategy::default`] impl arm cannot silently split
27611        // on any future M3-canonical distribution-default rebrand. Peer
27612        // of the sibling M2
27613        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
27614        // byte-parity pin on the wire-format author-omitted `:children
27615        // :restart` scalar extended onto the M3 mesh-primitive-defining
27616        // slot family.
27617        let omitted: Placement = serde_json::from_str("{}")
27618            .expect("Placement must deserialize with the estrategia key omitted");
27619        assert_eq!(
27620            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
27621            "an author-omitted :placement :estrategia slot must degrade onto \
27622             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
27623             {:?}, expected {:?})",
27624            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
27625        );
27626    }
27627}