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 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 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 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 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 target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
11828        // Load-bearing contract pin: on every canonical
11829        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
11830        // [`WitContract::target_projected`] returns byte-equal to
11831        // [`WitContract::target`]`().unwrap()` — the post-validation
11832        // projection accessor is a thin panicking wrapper over the
11833        // pre-validation validator, no extra work in the projection
11834        // path. Any future divergence (a validator-side normalization
11835        // the projection doesn't route through, an accessor-side
11836        // caching layer the validator doesn't populate) would surface
11837        // here at caixa-core build time rather than a silent per-consumer
11838        // split at renderer emit time. Sweeps the closed 4-arm
11839        // [`WitTarget`] partition ([`WitTarget::Http`] /
11840        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
11841        // [`WitTarget::Capability`]) so every arm carries a byte-equality
11842        // pin on the two-accessor pair.
11843        for (wit, endpoint, subject, slot) in [
11844            ("wasi:http/proxy", Some("/x"), None, None),
11845            ("nats:pub-sub", None, Some("events.x"), None),
11846            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
11847            ("custom:capability-only", None, None, None),
11848        ] {
11849            let c = WitContract {
11850                de: "cart".into(),
11851                para: "catalog".into(),
11852                wit: wit.into(),
11853                endpoint: endpoint.map(str::to_string),
11854                subject: subject.map(str::to_string),
11855                slot: slot.map(str::to_string),
11856            };
11857            assert_eq!(
11858                c.target_projected(),
11859                c.target().unwrap(),
11860                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
11861            );
11862        }
11863    }
11864
11865    #[test]
11866    #[should_panic(expected = "validated by typed_view")]
11867    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
11868        // Panic-path pin: [`WitContract::target_projected`] threads the
11869        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
11870        // through its expect-panic when called on a contract whose
11871        // (`:wit`, payload) shape has not been crossed by
11872        // [`AplicacaoSpec::validate`] — a contract with a structurally-
11873        // invalid `:wit` (hyphen-for-colon typo) that would surface
11874        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
11875        // A future rebrand on the panic-message axis would land at one
11876        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
11877        // and this pin's [`should_panic(expected = …)`] literal would
11878        // migrate alongside — the pin catches drift between the const
11879        // and the accessor's `expect(…)` call by construction.
11880        let c = WitContract {
11881            de: "cart".into(),
11882            para: "catalog".into(),
11883            // Hyphen-for-colon typo: `WitContract::target` returns
11884            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
11885            // driving the [`WitContract::target_projected`] expect-panic.
11886            wit: "wasi-http/proxy".into(),
11887            endpoint: Some("/x".into()),
11888            subject: None,
11889            slot: None,
11890        };
11891        let _ = c.target_projected();
11892    }
11893
11894    #[test]
11895    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
11896        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
11897        // carries the exact byte-string the two prior open-coded
11898        // `.target().expect("validated by typed_view")` production
11899        // consumers threaded through inline before this lift converged
11900        // them onto [`WitContract::target_projected`] — the caixa-mesh
11901        // per-`(:de, :para)` CNP L7 introspection branch at
11902        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
11903        // graph` per-`:contratos` payload-column printer at
11904        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
11905        // byte-string load-bearing so a well-meaning const-side rebrand
11906        // that didn't carry a matched pin migration would surface here
11907        // at caixa-core build time rather than a silent per-consumer
11908        // panic-message drift at cluster-apply time. Peer of the
11909        // sibling [`WitTarget::CAPABILITY_LABEL`] /
11910        // [`WitTarget::CAPABILITY_EXPECTED`] /
11911        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
11912        // the paired payload-less-arm scalar-const family.
11913        assert_eq!(
11914            WitContract::PROJECTED_INVARIANT_MSG,
11915            "validated by typed_view"
11916        );
11917    }
11918
11919    #[test]
11920    fn empty_wit_takes_precedence_over_invalid() {
11921        // Ordering pin: `EmptyWit` is the more self-locating
11922        // diagnostic on `""` and must lead — the value-shape gate is
11923        // only reached after the empty-check fires. Mirrors
11924        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
11925        // the peer payload axis.
11926        let mut s = three_member_spec();
11927        s.contratos.push(WitContract {
11928            de: "payment".into(),
11929            para: "catalog".into(),
11930            wit: String::new(),
11931            endpoint: None,
11932            subject: None,
11933            slot: None,
11934        });
11935        let err = s.validate().unwrap_err();
11936        assert!(
11937            matches!(err, AplicacaoError::EmptyWit { .. }),
11938            "got {err:?}"
11939        );
11940    }
11941
11942    #[test]
11943    fn wit_invalid_fires_before_payload_shape_arm() {
11944        // Ordering pin: a malformed `:wit` surfaces *its own*
11945        // diagnostic (which names the offending wit verbatim) before
11946        // any payload-field check — a contrato whose wit is
11947        // structurally invalid AND carries a wrong target field
11948        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
11949        // because the dispatch on the wit is what decides which
11950        // payload field is "right" in the first place. Without this
11951        // ordering, the author would see "wrong target field" for a
11952        // wit that hasn't even been parsed, which doesn't name the
11953        // root cause.
11954        let mut s = three_member_spec();
11955        s.contratos.push(WitContract {
11956            de: "payment".into(),
11957            para: "catalog".into(),
11958            // Hyphen-for-colon typo + endpoint set: pre-gate this
11959            // raised `ContratoWrongTarget { expected: "none" }` (the
11960            // Capability arm rejecting the endpoint), masking the
11961            // real authoring mistake (the wit isn't `wasi:http/proxy`).
11962            wit: "wasi-http/proxy".into(),
11963            endpoint: Some("/x".into()),
11964            subject: None,
11965            slot: None,
11966        });
11967        let err = s.validate().unwrap_err();
11968        assert!(
11969            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
11970                if wit == "wasi-http/proxy"),
11971            "got {err:?}"
11972        );
11973    }
11974
11975    #[test]
11976    fn wit_invalid_diagnostic_carries_offending_wit() {
11977        // Diagnostic-shape pin — the offending `:wit` + `:de` +
11978        // `:para` + a non-empty reason flow through verbatim so the
11979        // author can grep their caixa.lisp for the offending contrato
11980        // block and fix it in one edit. Same shape as
11981        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
11982        let err = contrato_wit_err("WASI:HTTP/proxy");
11983        match err {
11984            AplicacaoError::ContratoWitInvalid {
11985                de,
11986                para,
11987                wit,
11988                reason,
11989            } => {
11990                assert_eq!(de, "payment");
11991                assert_eq!(para, "catalog");
11992                assert_eq!(wit, "WASI:HTTP/proxy");
11993                assert!(!reason.is_empty(), "reason field must be non-empty");
11994            }
11995            other => panic!("expected ContratoWitInvalid, got {other:?}"),
11996        }
11997    }
11998
11999    // ── :contratos :subject value-shape gate ─────────────────────────────
12000    //
12001    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
12002    // suites on the peer payload axes. Until this gate landed
12003    // `WitContract::target()` only refused the empty string; a
12004    // structurally invalid subject silently passed validate and the
12005    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
12006    // Subject'` on publish / subscribe, or as a silent message drop,
12007    // far from the source caixa.lisp. Every authoring footgun the
12008    // NATS server's subject parser would catch on admission now
12009    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
12010    // offending `:subject` + `:de` + `:para` named verbatim. Same
12011    // diagnostic shape as `ContratoEndpointInvalid` /
12012    // `ContratoWitInvalid` on the peer payload axes; same shared
12013    // predicate (`crate::render::is_nats_subject`) ensures drift
12014    // between any two axes' rule enforcement is a build error at the
12015    // predicate, not piecemeal across renderers.
12016
12017    fn contrato_subject_err(subject: &str) -> AplicacaoError {
12018        // Fresh spec per call so the new contract doesn't collide on
12019        // identity with `three_member_spec`'s pre-existing entries.
12020        // The new edge uses `(payment, catalog)` — a pair the fixture
12021        // doesn't already declare — with `:wit "nats:pub-sub"` and the
12022        // varying `:subject`, so the subject-shape gate fires cleanly
12023        // after the wit-shape gate (which `"nats:pub-sub"` passes).
12024        let mut s = three_member_spec();
12025        s.contratos.push(WitContract {
12026            de: "payment".into(),
12027            para: "catalog".into(),
12028            wit: "nats:pub-sub".into(),
12029            endpoint: None,
12030            subject: Some(subject.into()),
12031            slot: None,
12032        });
12033        s.validate().unwrap_err()
12034    }
12035
12036    #[test]
12037    fn rejects_pubsub_contrato_subject_with_whitespace() {
12038        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
12039        // landed at the NATS server as a malformed subject the parser
12040        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
12041        // source caixa.lisp.
12042        let err = contrato_subject_err("foo bar");
12043        assert!(
12044            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12045                if subject == "foo bar" && reason.contains("whitespace")),
12046            "got {err:?}"
12047        );
12048    }
12049
12050    #[test]
12051    fn rejects_pubsub_contrato_subject_with_control_char() {
12052        let err = contrato_subject_err("foo\x01bar");
12053        assert!(
12054            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12055                if subject == "foo\x01bar" && reason.contains("control character")),
12056            "got {err:?}"
12057        );
12058    }
12059
12060    #[test]
12061    fn rejects_pubsub_contrato_subject_with_non_ascii() {
12062        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12063        // the subject from a doc with smart quotes / accented
12064        // characters" footgun.
12065        let err = contrato_subject_err("foo.caf\u{e9}");
12066        assert!(
12067            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12068                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
12069            "got {err:?}"
12070        );
12071    }
12072
12073    #[test]
12074    fn rejects_pubsub_contrato_subject_with_leading_dot() {
12075        // Empty leading token — NATS rejects.
12076        let err = contrato_subject_err(".foo");
12077        assert!(
12078            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12079                if subject == ".foo" && reason.contains("must not start with `.`")),
12080            "got {err:?}"
12081        );
12082    }
12083
12084    #[test]
12085    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
12086        // Empty trailing token — NATS rejects. The remediation
12087        // (use `>` instead) is in the reason string.
12088        let err = contrato_subject_err("foo.");
12089        assert!(
12090            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12091                if subject == "foo." && reason.contains("must not end with `.`")),
12092            "got {err:?}"
12093        );
12094    }
12095
12096    #[test]
12097    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
12098        // The canonical "I forgot to fill in the middle segment"
12099        // typo — `"foo..bar"`. NATS rejects empty tokens.
12100        let err = contrato_subject_err("foo..bar");
12101        assert!(
12102            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12103                if subject == "foo..bar" && reason.contains("consecutive `.`")),
12104            "got {err:?}"
12105        );
12106    }
12107
12108    #[test]
12109    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
12110        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
12111        // as the final segment. Pre-gate this passed as a typed edge
12112        // and surfaced at runtime as a NATS subscribe rejection.
12113        let err = contrato_subject_err("foo.>.bar");
12114        assert!(
12115            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12116                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
12117            "got {err:?}"
12118        );
12119    }
12120
12121    #[test]
12122    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
12123        // `foo*.bar` — NATS wildcards are standalone tokens. The
12124        // remediation is in the reason string.
12125        let err = contrato_subject_err("foo*.bar");
12126        assert!(
12127            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12128                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
12129            "got {err:?}"
12130        );
12131    }
12132
12133    #[test]
12134    fn rejects_pubsub_contrato_subject_with_invalid_char() {
12135        // `foo,bar` — comma is not a valid NATS subject character.
12136        // Pinned separately from the wildcard arms so the invalid-
12137        // character diagnostic is in force.
12138        let err = contrato_subject_err("foo,bar");
12139        assert!(
12140            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12141                if subject == "foo,bar" && reason.contains("invalid character")),
12142            "got {err:?}"
12143        );
12144    }
12145
12146    #[test]
12147    fn rejects_pubsub_contrato_subject_too_long() {
12148        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
12149        // The legitimate-shape arms all pass (one all-`a` token, no
12150        // `.`, no wildcards); only the cap arm fires. Surfaces the
12151        // paste-from-binary / accidental-multi-line-blob landing
12152        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
12153        // on the peer axis.
12154        let big = "a".repeat(257);
12155        assert_eq!(big.len(), 257);
12156        let err = contrato_subject_err(&big);
12157        assert!(
12158            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12159                if subject == &big && reason.contains("max length of 256")),
12160            "got {err:?}"
12161        );
12162    }
12163
12164    #[test]
12165    fn pubsub_contrato_subject_max_length_validates() {
12166        // 256-byte subject — exactly the cap. Boundary pin: drift in
12167        // the cap surfaces here and at
12168        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
12169        // mirroring `http_contrato_endpoint_max_length_validates` and
12170        // `wit_max_length_validates` on the peer axes.
12171        let big = "a".repeat(256);
12172        assert_eq!(big.len(), 256);
12173        let mut s = three_member_spec();
12174        s.contratos.push(WitContract {
12175            de: "payment".into(),
12176            para: "catalog".into(),
12177            wit: "nats:pub-sub".into(),
12178            endpoint: None,
12179            subject: Some(big),
12180            slot: None,
12181        });
12182        s.validate().unwrap();
12183    }
12184
12185    #[test]
12186    fn pubsub_contrato_subject_accepts_canonical_forms() {
12187        // Positive-set sweep: every canonical NATS subject shape the
12188        // substrate-side `is_nats_subject` predicate accepts (the
12189        // multi-dot `events.order.charged`, the snake_case / kebab-
12190        // case / mixed-case tokens, the digit-bearing tokens, the
12191        // single-token wildcard `*` at every segment position, and
12192        // the trailing `>` multi-token wildcard) must remain a valid
12193        // contrato subject too. Drift between this list and the
12194        // substrate-side `nats_subject_accepts_canonical_forms` sweep
12195        // surfaces at the shared predicate — one source of truth.
12196        // Uses a fresh `(payment, catalog)` edge so none of the swept
12197        // subjects collide with the pre-existing entries in
12198        // `three_member_spec`.
12199        for subject in [
12200            "checkout.events.charge.failed",
12201            "rio.events.order.charged",
12202            "orders",
12203            "orders.123",
12204            "snake_case.token",
12205            "kebab-case.token",
12206            "MixedCase.Token",
12207            "orders.*.charged",
12208            "*.events.*",
12209            "orders.>",
12210        ] {
12211            let mut s = three_member_spec();
12212            s.contratos.push(WitContract {
12213                de: "payment".into(),
12214                para: "catalog".into(),
12215                wit: "nats:pub-sub".into(),
12216                endpoint: None,
12217                subject: Some(subject.into()),
12218                slot: None,
12219            });
12220            s.validate()
12221                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
12222        }
12223    }
12224
12225    #[test]
12226    fn contrato_subject_empty_takes_precedence_over_invalid() {
12227        // Ordering pin: `ContratoSubjectEmpty` is the more self-
12228        // locating diagnostic on `""` and must lead — the value-shape
12229        // gate is only reached after the empty-check fires. Mirrors
12230        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12231        // the peer payload axis.
12232        let mut s = three_member_spec();
12233        s.contratos.push(WitContract {
12234            de: "payment".into(),
12235            para: "catalog".into(),
12236            wit: "nats:pub-sub".into(),
12237            endpoint: None,
12238            subject: Some(String::new()),
12239            slot: None,
12240        });
12241        let err = s.validate().unwrap_err();
12242        assert!(
12243            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
12244            "got {err:?}"
12245        );
12246    }
12247
12248    #[test]
12249    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
12250        // Diagnostic-shape pin — the offending `:subject` + `:de` +
12251        // `:para` + a non-empty reason flow through verbatim so the
12252        // author can grep their caixa.lisp for the offending contrato
12253        // block and fix it in one edit. Same shape as
12254        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12255        // and `wit_invalid_diagnostic_carries_offending_wit`.
12256        let err = contrato_subject_err("foo..bar");
12257        match err {
12258            AplicacaoError::ContratoSubjectInvalid {
12259                de,
12260                para,
12261                subject,
12262                reason,
12263            } => {
12264                assert_eq!(de, "payment");
12265                assert_eq!(para, "catalog");
12266                assert_eq!(subject, "foo..bar");
12267                assert!(!reason.is_empty(), "reason field must be non-empty");
12268            }
12269            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
12270        }
12271    }
12272
12273    #[test]
12274    fn target_view_pubsub_subject_passes_through_to_typed_view() {
12275        // The compounding theorem on the pub-sub axis: every
12276        // `WitTarget::PubSub { subject }` returned by `target()` carries
12277        // a NATS-server-accepted subject. Renderers downstream of
12278        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
12279        // NATS Stream/Consumer CR emitter, the future `feira app graph`
12280        // view's subject labeller) can rely on this without re-checking
12281        // — the type system carries the proof. Mirrors
12282        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
12283        // on the peer axes.
12284        let nats = WitContract {
12285            de: "a".into(),
12286            para: "b".into(),
12287            wit: "nats:pub-sub".into(),
12288            endpoint: None,
12289            subject: Some("orders.events.*.charged".into()),
12290            slot: None,
12291        };
12292        match nats.target().unwrap() {
12293            WitTarget::PubSub { subject } => {
12294                assert_eq!(subject, "orders.events.*.charged");
12295            }
12296            other => panic!("expected PubSub, got {other:?}"),
12297        }
12298    }
12299
12300    // ── :contratos :slot value-shape gate ────────────────────────────────
12301    //
12302    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
12303    // (63e18a0) value-shape suites on the peer payload axes. Until this
12304    // gate landed `WitContract::target()` only refused the empty string
12305    // for the Store arm; a structurally invalid slot (raw whitespace,
12306    // control character, non-ASCII byte, paste-from-binary multi-line
12307    // blob) silently passed validate and surfaced at runtime as a
12308    // per-backend kv write rejection or a silent next-read corruption,
12309    // far from the source caixa.lisp with no field naming which
12310    // `:contratos` edge carried the typo. Every authoring footgun the
12311    // kv backend intersection-floor would catch on write now becomes a
12312    // caixa-build-time `ContratoSlotInvalid` with the offending
12313    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
12314    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
12315    // peer payload axes; same shared predicate
12316    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
12317    // any two axes' rule enforcement is a build error at the
12318    // predicate, not piecemeal across renderers. Closes the typed
12319    // payload-axis value-shape trajectory across all three legs of the
12320    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
12321
12322    fn contrato_slot_err(slot: &str) -> AplicacaoError {
12323        // Fresh spec per call so the new contract doesn't collide on
12324        // identity with `three_member_spec`'s pre-existing entries
12325        // and doesn't close a synchronous cycle the cycle detector
12326        // would reject before the slot-shape gate fires. The new edge
12327        // uses `(payment, catalog)` — a pair the fixture doesn't
12328        // already declare in either direction (the fixture carries
12329        // `cart -> catalog` and `cart -> payment`, so `payment ->
12330        // catalog` doesn't form a cycle on the sync subgraph) — with
12331        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
12332        // slot-shape gate fires cleanly after the wit-shape gate
12333        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
12334        // peer `contrato_subject_err` helper uses (63e18a0).
12335        let mut s = three_member_spec();
12336        s.contratos.push(WitContract {
12337            de: "payment".into(),
12338            para: "catalog".into(),
12339            wit: "wasi:keyvalue/store".into(),
12340            endpoint: None,
12341            subject: None,
12342            slot: Some(slot.into()),
12343        });
12344        s.validate().unwrap_err()
12345    }
12346
12347    #[test]
12348    fn rejects_store_contrato_slot_with_whitespace() {
12349        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
12350        // silently landed at the kv backend with whitespace whose
12351        // runtime behavior varies unpredictably across backends (etcd
12352        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
12353        // rejects on write). Now caught at the source caixa.lisp.
12354        let err = contrato_slot_err("check out/$order");
12355        assert!(
12356            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12357                if slot == "check out/$order" && reason.contains("whitespace")),
12358            "got {err:?}"
12359        );
12360    }
12361
12362    #[test]
12363    fn rejects_store_contrato_slot_with_tab() {
12364        // Tab byte arm-pinned separately from the space arm so a
12365        // future relaxation that admits one but not the other surfaces
12366        // here.
12367        let err = contrato_slot_err("check\tout");
12368        assert!(
12369            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12370                if slot == "check\tout" && reason.contains("whitespace")),
12371            "got {err:?}"
12372        );
12373    }
12374
12375    #[test]
12376    fn rejects_store_contrato_slot_with_control_char() {
12377        // SOH (0x01) — distinct from the whitespace arm. Redis admits
12378        // and corrupts on RESP protocol framing; DynamoDB rejects on
12379        // write.
12380        let err = contrato_slot_err("checkout/\x01order");
12381        assert!(
12382            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12383                if slot == "checkout/\x01order" && reason.contains("control character")),
12384            "got {err:?}"
12385        );
12386    }
12387
12388    #[test]
12389    fn rejects_store_contrato_slot_with_newline() {
12390        // Embedded newline — the canonical "the paste-from-binary slug
12391        // spans multiple lines" footgun. Distinct from the whitespace
12392        // arm because `\n` is a control character (0x0A).
12393        let err = contrato_slot_err("checkout\norder");
12394        assert!(
12395            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12396                if slot == "checkout\norder" && reason.contains("control character")),
12397            "got {err:?}"
12398        );
12399    }
12400
12401    #[test]
12402    fn rejects_store_contrato_slot_with_non_ascii() {
12403        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12404        // the slot from a doc with accented characters" footgun. Each
12405        // kv backend re-encodes non-ASCII differently (etcd preserves
12406        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
12407        // rejects), so the typed slot's value set is the intersection-
12408        // floor every backend admits identically (printable ASCII).
12409        let err = contrato_slot_err("ch\u{e9}ckout/$order");
12410        assert!(
12411            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12412                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
12413            "got {err:?}"
12414        );
12415    }
12416
12417    #[test]
12418    fn rejects_store_contrato_slot_too_long() {
12419        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
12420        // legitimate-shape arms all pass (a single all-`a` token, no
12421        // separators); only the cap arm fires. Surfaces the paste-
12422        // from-binary / accidental-multi-line-blob landing footgun.
12423        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
12424        // `rejects_http_contrato_endpoint_too_long` on the peer
12425        // payload axes.
12426        let big = "a".repeat(513);
12427        assert_eq!(big.len(), 513);
12428        let err = contrato_slot_err(&big);
12429        assert!(
12430            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12431                if slot == &big && reason.contains("max length of 512")),
12432            "got {err:?}"
12433        );
12434    }
12435
12436    #[test]
12437    fn store_contrato_slot_max_length_validates() {
12438        // 512-byte slot — exactly the cap. Boundary pin: drift in the
12439        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
12440        // simultaneously, mirroring
12441        // `pubsub_contrato_subject_max_length_validates` and
12442        // `http_contrato_endpoint_max_length_validates` on the peer
12443        // payload axes.
12444        let big = "a".repeat(512);
12445        assert_eq!(big.len(), 512);
12446        let mut s = three_member_spec();
12447        s.contratos.push(WitContract {
12448            de: "payment".into(),
12449            para: "catalog".into(),
12450            wit: "wasi:keyvalue/store".into(),
12451            endpoint: None,
12452            subject: None,
12453            slot: Some(big),
12454        });
12455        s.validate().unwrap();
12456    }
12457
12458    #[test]
12459    fn store_contrato_slot_accepts_canonical_forms() {
12460        // Positive-set sweep: every canonical kv slot template the
12461        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
12462        // (single-token identifiers, path-namespaced `$`-templates,
12463        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
12464        // snake_case / kebab-case / MixedCase tokens, digit-bearing
12465        // tokens, percent-encoded fragments) must remain valid
12466        // contrato slots too. Drift between this list and the
12467        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
12468        // surfaces at the shared predicate — one source of truth.
12469        // Uses a fresh `(payment, catalog)` edge so none of the swept
12470        // slots collide with the pre-existing entries in
12471        // `three_member_spec`.
12472        for slot in [
12473            "checkout",
12474            "checkout/$orderId",
12475            "users:{tenant}/{id}",
12476            "session.<sid>",
12477            "session.tokens.<sid>",
12478            "snake_case_key",
12479            "kebab-case-key",
12480            "MixedCase",
12481            "shard0",
12482            "v2/key",
12483            "users/caf%C3%A9",
12484        ] {
12485            let mut s = three_member_spec();
12486            s.contratos.push(WitContract {
12487                de: "payment".into(),
12488                para: "catalog".into(),
12489                wit: "wasi:keyvalue/store".into(),
12490                endpoint: None,
12491                subject: None,
12492                slot: Some(slot.into()),
12493            });
12494            s.validate()
12495                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
12496        }
12497    }
12498
12499    #[test]
12500    fn contrato_slot_empty_takes_precedence_over_invalid() {
12501        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
12502        // diagnostic on `""` and must lead — the value-shape gate is
12503        // only reached after the empty-check fires. Mirrors
12504        // `contrato_subject_empty_takes_precedence_over_invalid` and
12505        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12506        // the peer payload axes.
12507        let mut s = three_member_spec();
12508        s.contratos.push(WitContract {
12509            de: "payment".into(),
12510            para: "catalog".into(),
12511            wit: "wasi:keyvalue/store".into(),
12512            endpoint: None,
12513            subject: None,
12514            slot: Some(String::new()),
12515        });
12516        let err = s.validate().unwrap_err();
12517        assert!(
12518            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
12519            "got {err:?}"
12520        );
12521    }
12522
12523    #[test]
12524    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
12525        // Diagnostic-shape pin — the offending `:slot` + `:de` +
12526        // `:para` + a non-empty reason flow through verbatim so the
12527        // author can grep their caixa.lisp for the offending contrato
12528        // block and fix it in one edit. Same shape as
12529        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
12530        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12531        // on the peer payload axes.
12532        let err = contrato_slot_err("check out/$order");
12533        match err {
12534            AplicacaoError::ContratoSlotInvalid {
12535                de,
12536                para,
12537                slot,
12538                reason,
12539            } => {
12540                assert_eq!(de, "payment");
12541                assert_eq!(para, "catalog");
12542                assert_eq!(slot, "check out/$order");
12543                assert!(!reason.is_empty(), "reason field must be non-empty");
12544            }
12545            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
12546        }
12547    }
12548
12549    #[test]
12550    fn target_view_store_slot_passes_through_to_typed_view() {
12551        // The compounding theorem on the store axis: every
12552        // `WitTarget::Store { slot }` returned by `target()` carries a
12553        // kv-backend-accepted slot template. Renderers downstream of
12554        // `typed_view()` (the future per-Servico `:capabilities
12555        // wasi:keyvalue/store` axis emitter, the future `feira app
12556        // graph` view's slot labeller, the future kv-provider CR
12557        // materializer) can rely on this without re-checking — the
12558        // type system carries the proof. Mirrors
12559        // `target_view_pubsub_subject_passes_through_to_typed_view` on
12560        // the peer payload axis.
12561        let store = WitContract {
12562            de: "a".into(),
12563            para: "b".into(),
12564            wit: "wasi:keyvalue/store".into(),
12565            endpoint: None,
12566            subject: None,
12567            slot: Some("checkout/$orderId".into()),
12568        };
12569        match store.target().unwrap() {
12570            WitTarget::Store { slot } => {
12571                assert_eq!(slot, "checkout/$orderId");
12572            }
12573            other => panic!("expected Store, got {other:?}"),
12574        }
12575    }
12576
12577    #[test]
12578    fn rejects_self_loop_in_synchronous_contratos() {
12579        // A synchronous self-edge (`cart → cart` over HTTP) is now
12580        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
12581        // "this edge is degenerate" diagnostic — rather than incidentally
12582        // by the cycle detector framing it as a `["cart", "cart"]`
12583        // multi-node deadlock.
12584        let mut s = three_member_spec();
12585        s.contratos.push(contract_http("cart", "cart", "/loop"));
12586        let err = s.validate().unwrap_err();
12587        match err {
12588            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
12589                assert_eq!(caixa, "cart");
12590                assert_eq!(wit, "wasi:http/proxy");
12591            }
12592            other => panic!("expected ContratoSelfLoop, got {other:?}"),
12593        }
12594    }
12595
12596    #[test]
12597    fn rejects_self_loop_in_pubsub_contratos() {
12598        // The cycle detector excludes pub-sub edges (acyclic by
12599        // construction), so before the explicit gate a `nats:pub-sub`
12600        // self-edge silently validated and rendered a self-allow CNP.
12601        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
12602        let mut s = three_member_spec();
12603        s.contratos.push(WitContract {
12604            de: "payment".into(),
12605            para: "payment".into(),
12606            wit: "nats:pub-sub".into(),
12607            endpoint: None,
12608            subject: Some("rio.events.payment".into()),
12609            slot: None,
12610        });
12611        let err = s.validate().unwrap_err();
12612        match err {
12613            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
12614                assert_eq!(caixa, "payment");
12615                assert_eq!(wit, "nats:pub-sub");
12616            }
12617            other => panic!("expected ContratoSelfLoop, got {other:?}"),
12618        }
12619    }
12620
12621    #[test]
12622    fn self_loop_fires_before_payload_shape_check() {
12623        // The structural "this edge can't exist" error precedes the
12624        // narrower payload-shape diagnostics: a self-edge carrying an
12625        // otherwise-malformed endpoint still reports ContratoSelfLoop,
12626        // not ContratoEndpointInvalid.
12627        let mut s = three_member_spec();
12628        s.contratos.push(WitContract {
12629            de: "cart".into(),
12630            para: "cart".into(),
12631            wit: "wasi:http/proxy".into(),
12632            endpoint: Some("not-absolute".into()),
12633            subject: None,
12634            slot: None,
12635        });
12636        match s.validate().unwrap_err() {
12637            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
12638            other => panic!("expected ContratoSelfLoop, got {other:?}"),
12639        }
12640    }
12641
12642    #[test]
12643    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
12644        // A self-edge naming a non-member reports the more fundamental
12645        // ContratoMemberMissing first (the member doesn't exist), so the
12646        // self-loop gate is reached only once both endpoints resolve.
12647        let mut s = three_member_spec();
12648        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
12649        match s.validate().unwrap_err() {
12650            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
12651            other => panic!("expected ContratoMemberMissing, got {other:?}"),
12652        }
12653    }
12654
12655    #[test]
12656    fn rejects_two_node_synchronous_cycle() {
12657        let mut s = three_member_spec();
12658        // existing edges: cart → catalog, cart → payment
12659        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
12660        s.contratos
12661            .push(contract_http("catalog", "cart", "/refresh"));
12662        let err = s.validate().unwrap_err();
12663        match err {
12664            AplicacaoError::ContratoCycle { cycle } => {
12665                // Cycle traversal should mention both endpoints, with
12666                // the back-edge target appearing as both first and last
12667                // element to close the loop.
12668                assert!(cycle.len() >= 3);
12669                assert_eq!(cycle.first(), cycle.last());
12670                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
12671                assert!(body.contains("cart"));
12672                assert!(body.contains("catalog"));
12673            }
12674            other => panic!("expected ContratoCycle, got {other:?}"),
12675        }
12676    }
12677
12678    #[test]
12679    fn rejects_three_node_synchronous_cycle() {
12680        let mut s = three_member_spec();
12681        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
12682        s.contratos = vec![
12683            contract_http("catalog", "cart", "/x"),
12684            contract_http("cart", "payment", "/y"),
12685            contract_http("payment", "catalog", "/z"),
12686        ];
12687        let err = s.validate().unwrap_err();
12688        match err {
12689            AplicacaoError::ContratoCycle { cycle } => {
12690                assert_eq!(cycle.first(), cycle.last());
12691                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
12692                assert_eq!(body.len(), 3);
12693                assert!(body.contains("cart"));
12694                assert!(body.contains("catalog"));
12695                assert!(body.contains("payment"));
12696            }
12697            other => panic!("expected ContratoCycle, got {other:?}"),
12698        }
12699    }
12700
12701    #[test]
12702    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
12703        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
12704        // "acyclic by construction" — so a cycle whose closing edge
12705        // is pub-sub should NOT raise ContratoCycle.
12706        let mut s = three_member_spec();
12707        s.contratos = vec![
12708            contract_http("catalog", "cart", "/x"),
12709            contract_http("cart", "payment", "/y"),
12710            // Closing edge is pub-sub — async; not a sync deadlock.
12711            WitContract {
12712                de: "payment".into(),
12713                para: "catalog".into(),
12714                wit: "nats:pub-sub".into(),
12715                endpoint: None,
12716                subject: Some("checkout.events.charge.completed".into()),
12717                slot: None,
12718            },
12719        ];
12720        s.validate().expect("pub-sub edge breaks the sync cycle");
12721    }
12722
12723    #[test]
12724    fn store_edge_counts_as_synchronous_for_cycle_detection() {
12725        // wasi:keyvalue/store is request/response; a cycle through one
12726        // *is* a sync deadlock, just like HTTP.
12727        let mut s = three_member_spec();
12728        s.contratos = vec![
12729            contract_http("catalog", "cart", "/x"),
12730            WitContract {
12731                de: "cart".into(),
12732                para: "catalog".into(),
12733                wit: "wasi:keyvalue/store".into(),
12734                endpoint: None,
12735                subject: None,
12736                slot: Some("session/$id".into()),
12737            },
12738        ];
12739        let err = s.validate().unwrap_err();
12740        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
12741    }
12742
12743    #[test]
12744    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
12745        // Capability-only edges (unknown WIT shape, no payload) default
12746        // to synchronous — safer; authors with truly async capability
12747        // semantics can model them as pub-sub explicitly.
12748        let mut s = three_member_spec();
12749        s.contratos = vec![
12750            contract_http("catalog", "cart", "/x"),
12751            WitContract {
12752                de: "cart".into(),
12753                para: "catalog".into(),
12754                wit: "custom:exchange".into(),
12755                endpoint: None,
12756                subject: None,
12757                slot: None,
12758            },
12759        ];
12760        let err = s.validate().unwrap_err();
12761        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
12762    }
12763
12764    #[test]
12765    fn long_acyclic_chain_validates() {
12766        // A long sync chain (no back-edges) must validate even when
12767        // every node is reachable from the first.
12768        let mut s = three_member_spec();
12769        s.membros = vec![
12770            membro("a", "^0.1"),
12771            membro("b", "^0.1"),
12772            membro("c", "^0.1"),
12773            membro("d", "^0.1"),
12774            membro("e", "^0.1"),
12775        ];
12776        s.contratos = vec![
12777            contract_http("a", "b", "/1"),
12778            contract_http("b", "c", "/2"),
12779            contract_http("c", "d", "/3"),
12780            contract_http("d", "e", "/4"),
12781        ];
12782        s.entrada.as_mut().unwrap().para = "a".into();
12783        s.validate().unwrap();
12784    }
12785
12786    #[test]
12787    fn diamond_acyclic_validates() {
12788        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
12789        let mut s = three_member_spec();
12790        s.membros = vec![
12791            membro("a", "^0.1"),
12792            membro("b", "^0.1"),
12793            membro("c", "^0.1"),
12794            membro("d", "^0.1"),
12795        ];
12796        s.contratos = vec![
12797            contract_http("a", "b", "/1"),
12798            contract_http("a", "c", "/2"),
12799            contract_http("b", "d", "/3"),
12800            contract_http("c", "d", "/4"),
12801        ];
12802        s.entrada.as_mut().unwrap().para = "a".into();
12803        s.validate().unwrap();
12804    }
12805
12806    // ── duplicate-`:contratos` build-error gate ──────────────────────────
12807
12808    #[test]
12809    fn rejects_duplicate_http_contrato() {
12810        // Fail-before-pass-after pin: the fixture's `cart → catalog`
12811        // HTTP edge appears once. Push an identical entry — same
12812        // (de, para, wit, endpoint) — and validate() must reject it.
12813        // Until this gate landed the typed surface accepted the
12814        // duplicate silently and caixa-mesh's `cilium_network_policies`
12815        // emitted two ``CiliumNetworkPolicy`` objects with identical
12816        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
12817        // admission rejects on `kubectl apply` far from the source.
12818        let mut s = three_member_spec();
12819        s.contratos
12820            .push(contract_http("cart", "catalog", "/products/:id"));
12821        let err = s.validate().unwrap_err();
12822        assert!(
12823            matches!(
12824                err,
12825                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12826                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
12827            ),
12828            "got {err:?}"
12829        );
12830    }
12831
12832    #[test]
12833    fn rejects_duplicate_pubsub_contrato() {
12834        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
12835        // edges with identical (de, para, subject) are degenerate;
12836        // pin that the typed surface refuses both at validate time.
12837        let mut s = three_member_spec();
12838        let pubsub = WitContract {
12839            de: "payment".into(),
12840            para: "cart".into(),
12841            wit: "nats:pub-sub".into(),
12842            endpoint: None,
12843            subject: Some("checkout.events.charge.failed".into()),
12844            slot: None,
12845        };
12846        s.contratos.push(pubsub.clone());
12847        s.contratos.push(pubsub);
12848        let err = s.validate().unwrap_err();
12849        assert!(
12850            matches!(
12851                err,
12852                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12853                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
12854            ),
12855            "got {err:?}"
12856        );
12857    }
12858
12859    #[test]
12860    fn rejects_duplicate_store_contrato() {
12861        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
12862        // edges with identical (de, para, slot) collapse to one mesh-
12863        // policy edge; pin the build error.
12864        let mut s = three_member_spec();
12865        let store = WitContract {
12866            de: "cart".into(),
12867            para: "payment".into(),
12868            wit: "wasi:keyvalue/store".into(),
12869            endpoint: None,
12870            subject: None,
12871            slot: Some("checkout/$orderId".into()),
12872        };
12873        // Drop the conflicting HTTP `cart → payment` edge from the
12874        // fixture so the duplicate-store pair is the only one
12875        // distinguishable on this pair.
12876        s.contratos
12877            .retain(|c| !(c.de == "cart" && c.para == "payment"));
12878        s.contratos.push(store.clone());
12879        s.contratos.push(store);
12880        let err = s.validate().unwrap_err();
12881        assert!(
12882            matches!(
12883                err,
12884                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
12885                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
12886            ),
12887            "got {err:?}"
12888        );
12889    }
12890
12891    #[test]
12892    fn rejects_duplicate_capability_contrato() {
12893        // Same gate on the pure-capability axis (no payload selector).
12894        // Two contracts with identical (de, para, wit) and no
12895        // endpoint/subject/slot are duplicate edges; pin so a future
12896        // `target_label` change can't accidentally collapse the
12897        // capability arm into a None-shaped key that compares equal
12898        // to a populated one.
12899        let mut s = three_member_spec();
12900        let capability = WitContract {
12901            de: "cart".into(),
12902            para: "catalog".into(),
12903            wit: "pleme:cap/audit".into(),
12904            endpoint: None,
12905            subject: None,
12906            slot: None,
12907        };
12908        s.contratos.push(capability.clone());
12909        s.contratos.push(capability);
12910        let err = s.validate().unwrap_err();
12911        match err {
12912            AplicacaoError::ContratoDuplicate {
12913                de,
12914                para,
12915                wit,
12916                target,
12917            } => {
12918                assert_eq!(de, "cart");
12919                assert_eq!(para, "catalog");
12920                assert_eq!(wit, "pleme:cap/audit");
12921                assert!(
12922                    target.contains("capability"),
12923                    "capability-edge duplicate diagnostic must surface the \
12924                     no-payload shape (got target = {target:?})"
12925                );
12926            }
12927            other => panic!("expected ContratoDuplicate, got {other:?}"),
12928        }
12929    }
12930
12931    #[test]
12932    fn accepts_distinct_http_paths_between_same_pair() {
12933        // Negative pin: two HTTP contracts cart → catalog at distinct
12934        // endpoints (`/products/:id` and `/search`) are *not*
12935        // duplicates — they're distinct typed edges differing on the
12936        // payload axis. The duplicate-gate must not over-match here,
12937        // since the cart-calls-catalog-on-multiple-paths shape is the
12938        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
12939        // example: cart calls catalog at /products/:id, payment at
12940        // /charge — same shape extends to two paths on one para).
12941        let mut s = three_member_spec();
12942        s.contratos
12943            .push(contract_http("cart", "catalog", "/search"));
12944        s.validate()
12945            .expect("distinct endpoints between same (de, para) must validate");
12946    }
12947
12948    #[test]
12949    fn accepts_same_endpoint_on_different_pairs() {
12950        // Negative pin: the same `/charge` endpoint reused on two
12951        // different (de, para) pairs is two distinct edges, not a
12952        // duplicate. Pinning this shape so the gate's identity key
12953        // includes both `de` and `para` (not just `(wit, endpoint)`).
12954        let mut s = three_member_spec();
12955        s.contratos
12956            .push(contract_http("payment", "catalog", "/charge"));
12957        s.validate()
12958            .expect("same endpoint reused on distinct (de, para) must validate");
12959    }
12960
12961    #[test]
12962    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
12963        // Pin the diagnostic shape: the duplicate-edge error names
12964        // *which* target field carried the conflict, so the author
12965        // doesn't have to re-grep the source caixa.lisp to find it.
12966        // Same self-locating diagnostic discipline as
12967        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
12968        let mut s = three_member_spec();
12969        s.contratos
12970            .push(contract_http("cart", "catalog", "/products/:id"));
12971        let err = s.validate().unwrap_err();
12972        let msg = format!("{err}");
12973        assert!(
12974            msg.contains("\"/products/:id\""),
12975            "duplicate-contrato diagnostic must name the offending \
12976             :endpoint payload (got: {msg:?})"
12977        );
12978        assert!(
12979            msg.contains("cart") && msg.contains("catalog"),
12980            "diagnostic must name both endpoints of the duplicate edge \
12981             (got: {msg:?})"
12982        );
12983    }
12984
12985    #[test]
12986    fn duplicate_contrato_gate_runs_after_membership_check() {
12987        // Order pin: a duplicate contract whose `:de` is *also* not in
12988        // `:membros` surfaces the membership error first — the
12989        // missing-member diagnostic is more locating than the
12990        // duplicate-edge one (the author has to fix the membership
12991        // before the duplicate is meaningful). Same ordering
12992        // discipline as `membros_validation_runs_before_contratos_membership_check`.
12993        let mut s = three_member_spec();
12994        s.contratos.push(contract_http("phantom", "catalog", "/x"));
12995        s.contratos.push(contract_http("phantom", "catalog", "/x"));
12996        let err = s.validate().unwrap_err();
12997        assert!(
12998            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
12999            "membership-missing must fire before duplicate-edge (got {err:?})"
13000        );
13001    }
13002
13003    #[test]
13004    fn duplicate_contrato_gate_runs_after_target_shape_check() {
13005        // Order pin: a contract with a malformed target (e.g. an HTTP
13006        // wit world with an empty :endpoint) surfaces the target-shape
13007        // error first, not the duplicate one. Even when two such
13008        // malformed entries are identical, the per-contract `target()`
13009        // check fires inside the loop *before* the duplicate-key
13010        // insert, so the diagnostic remains the most-locating one.
13011        let mut s = three_member_spec();
13012        let malformed = WitContract {
13013            de: "cart".into(),
13014            para: "catalog".into(),
13015            wit: "wasi:http/proxy".into(),
13016            endpoint: Some(String::new()),
13017            subject: None,
13018            slot: None,
13019        };
13020        s.contratos.push(malformed.clone());
13021        s.contratos.push(malformed);
13022        let err = s.validate().unwrap_err();
13023        assert!(
13024            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
13025            "endpoint-empty must fire before duplicate-edge (got {err:?})"
13026        );
13027    }
13028
13029    #[test]
13030    fn wit_target_label_pins_per_variant_format() {
13031        // Label format is the single source of truth every duplicate-
13032        // `:contratos` diagnostic + every future `feira app graph`
13033        // consumer routes through. Pin the shape per variant so a
13034        // future edit to `WitTarget::label` (e.g. a JSON emitter that
13035        // strips the leading `:`, or a rename from `endpoint` →
13036        // `path`) surfaces as a red-red test rather than as a silent
13037        // downstream diagnostic drift. Together with the exhaustive
13038        // `match` on `WitTarget` inside `label()`, adding a future
13039        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
13040        // peer, per-edge WIT registry variants) is a compile error at
13041        // the label site — not a fall-through into the `Capability`
13042        // "no payload" default the prior raw-field-probe helper
13043        // silently landed on.
13044        assert_eq!(
13045            WitTarget::Http {
13046                endpoint: "/charge",
13047            }
13048            .label(),
13049            "\
13050:endpoint \"/charge\""
13051        );
13052        assert_eq!(
13053            WitTarget::PubSub {
13054                subject: "events.checkout.paid",
13055            }
13056            .label(),
13057            "\
13058:subject \"events.checkout.paid\""
13059        );
13060        assert_eq!(
13061            WitTarget::Store {
13062                slot: "checkout/$order",
13063            }
13064            .label(),
13065            "\
13066:slot \"checkout/$order\""
13067        );
13068        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
13069        // Capability-arm label routes through the lifted
13070        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
13071        // declaration per arm, next to the variant" discipline the
13072        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
13073        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13074        // consts already carry extends to the payload-less arm; the
13075        // byte-string equality pin below plus this label-routes-
13076        // through-the-const pin make a future rebrand on either the
13077        // const declaration or the `label()` template a build error
13078        // here rather than a downstream consumer surprise.
13079        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
13080        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
13081    }
13082
13083    #[test]
13084    fn wit_target_display_routes_through_label_helper() {
13085        // Fail-before-pass-after pin on the fourth (and only remaining)
13086        // typed-shape-discriminator axis to converge onto the
13087        // three-path-convergence discipline the sibling M3
13088        // [`PlacementStrategy`] (0a2f653) and M2
13089        // [`crate::supervisor::RestartStrategy`] /
13090        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
13091        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
13092        // through [`WitTarget::label`], so every consumer reaching for
13093        // `format!("{v}")` on a typed payload target lands on the same
13094        // stable author-facing byte-string [`WitTarget::label`] returns
13095        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
13096        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
13097        // `:contratos` gate seeds via [`WitTarget::label`] at
13098        // aplicacao.rs:5491 already threads through.
13099        //
13100        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
13101        // through to the `Debug` derive's structural output
13102        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
13103        // rather than the [`WitTarget::label`] helper's stable byte-
13104        // string (`:endpoint "/charge"` — the author-facing `:contratos`
13105        // keyword form). Every future consumer that reaches for
13106        // `format!("{target}")` — the canonical shape every user-facing
13107        // pretty-print site on the sibling typed-enum axes
13108        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
13109        // [`crate::supervisor::RestartPolicy`]) already uses — would
13110        // silently land under a different byte-string than the
13111        // [`WitTarget::label`] callers that the duplicate-`:contratos`
13112        // diagnostic already threads through, with the mismatch
13113        // surfacing as a downstream diagnostic / graph / audit line
13114        // reading one spelling while the substrate's own gate emitted
13115        // another.
13116        //
13117        // Pin the routing here so a future
13118        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
13119        // that hand-rolls the per-arm formatting instead of delegating
13120        // to [`WitTarget::label`] fails at caixa-core build time.
13121        for variant in [
13122            WitTarget::Http {
13123                endpoint: "/charge",
13124            },
13125            WitTarget::PubSub {
13126                subject: "events.checkout.paid",
13127            },
13128            WitTarget::Store {
13129                slot: "checkout/$order",
13130            },
13131            WitTarget::Capability,
13132        ] {
13133            assert_eq!(
13134                variant.to_string(),
13135                variant.label(),
13136                "WitTarget::{variant:?} Display must route through \
13137                 WitTarget::label (single source of truth: the lifted \
13138                 payload_pair 4-arm dispatch the label helper already \
13139                 threads through)"
13140            );
13141        }
13142    }
13143
13144    #[test]
13145    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
13146        // Consumer-side pin on the three-path convergence:
13147        // [`std::fmt::Display`] agrees byte-for-byte with the
13148        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
13149        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
13150        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
13151        // Pre-lift the two paths were structurally independent — the
13152        // substrate-side gate reached for `target_view.label()` while a
13153        // future downstream diagnostic / graph / audit line reaching
13154        // for `format!("{target}")` would silently land on the `Debug`
13155        // derive's structural output. Pin the two paths byte-for-byte
13156        // here so any future variant addition (M4 `Rest`/`Grpc` split
13157        // of [`WitTarget::Http`], `Queue`-shaped peer of
13158        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
13159        // match error at [`WitTarget::payload_pair`] rather than a
13160        // silent per-consumer dispatch miss.
13161        for variant in [
13162            WitTarget::Http {
13163                endpoint: "/charge",
13164            },
13165            WitTarget::PubSub {
13166                subject: "events.checkout.paid",
13167            },
13168            WitTarget::Store {
13169                slot: "checkout/$order",
13170            },
13171            WitTarget::Capability,
13172        ] {
13173            assert_eq!(
13174                format!("{variant}"),
13175                variant.label(),
13176                "WitTarget::{variant:?} Display byte-string must match \
13177                 the AplicacaoError::ContratoDuplicate `target:` carrier \
13178                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
13179                 seeds via WitTarget::label — three-path convergence: \
13180                 Display + label + payload_pair all resolve to the same \
13181                 per-arm byte-string"
13182            );
13183        }
13184    }
13185
13186    #[test]
13187    fn wit_target_payload_pair_pins_per_variant() {
13188        // Pin the per-arm `(field-name, payload)` pair single-sourced
13189        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
13190        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
13191        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
13192        // and [`WitTarget::field_name`] (returns the first component)
13193        // route through. Until this lift landed [`WitTarget::label`]
13194        // dispatched on the same three arms with a per-arm
13195        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
13196        // paired [`WitTarget::HTTP_FIELD_NAME`] /
13197        // [`WitTarget::PUBSUB_FIELD_NAME`] /
13198        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
13199        // canonical "same shape, written N times" duplication
13200        // THEORY.md §I.3.5 promotes to a build-time concern. A future
13201        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
13202        // [`WitTarget::Http`], `Queue`-shaped peer of
13203        // [`WitTarget::Store`]) is one match-arm edit at
13204        // [`WitTarget::payload_pair`], visible here as a compile-time
13205        // exhaustiveness error on both this pin and the label-format
13206        // pin above.
13207        assert_eq!(
13208            WitTarget::Http {
13209                endpoint: "/charge"
13210            }
13211            .payload_pair(),
13212            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
13213        );
13214        assert_eq!(
13215            WitTarget::PubSub {
13216                subject: "events.x",
13217            }
13218            .payload_pair(),
13219            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
13220        );
13221        assert_eq!(
13222            WitTarget::Store {
13223                slot: "checkout/$order",
13224            }
13225            .payload_pair(),
13226            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
13227        );
13228        assert_eq!(WitTarget::Capability.payload_pair(), None);
13229    }
13230
13231    #[test]
13232    fn wit_target_field_name_pins_per_variant() {
13233        // Pin the per-arm author-facing `:contratos` payload field
13234        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
13235        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13236        // + returned by [`WitTarget::field_name`]. Every downstream
13237        // consumer (the [`WitContract::target`] gate's `expected:`
13238        // scalar, the [`WitTarget::label`] template's keyword prefix,
13239        // the `feira app graph` verb's `endpoint=…` prefix) routes
13240        // through the same three peer consts, so a rename on the
13241        // author-surface `(defcaixa … :contratos ((:de … :para …
13242        // :wit … :endpoint …)))` field lands in exactly one place.
13243        assert_eq!(
13244            WitTarget::Http {
13245                endpoint: "/charge"
13246            }
13247            .field_name(),
13248            Some(WitTarget::HTTP_FIELD_NAME),
13249        );
13250        assert_eq!(
13251            WitTarget::PubSub {
13252                subject: "events.x",
13253            }
13254            .field_name(),
13255            Some(WitTarget::PUBSUB_FIELD_NAME),
13256        );
13257        assert_eq!(
13258            WitTarget::Store {
13259                slot: "checkout/$order",
13260            }
13261            .field_name(),
13262            Some(WitTarget::STORE_FIELD_NAME),
13263        );
13264        // Capability arm carries no payload field — the diagnostic
13265        // never reports `expected: "capability"` because the gate's
13266        // Capability arm accepts no payload at all (it fires the
13267        // "expected: none" WrongTarget error instead), so the field-
13268        // name method returns None here rather than a placeholder.
13269        assert_eq!(WitTarget::Capability.field_name(), None);
13270
13271        // Peer const scalar values pinned so a rename on either side
13272        // (author-surface field name in the `(defcaixa …)` DSL, or
13273        // the diagnostic's `expected:` scalar) can't drift without
13274        // failing here first.
13275        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
13276        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
13277        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
13278    }
13279
13280    #[test]
13281    fn wit_target_payload_pins_per_variant() {
13282        // Pin the per-arm payload scalar single-sourced onto the
13283        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
13284        // [`WitTarget::payload`] — the peer per-half projection to
13285        // [`WitTarget::field_name`] on the paired sub-selector axis. The
13286        // three payload-carrying arms round-trip their author-declared
13287        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
13288        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
13289        // the payload-less [`WitTarget::Capability`] arm returns `None`.
13290        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
13291        // (c6ec2af) pin on the Component-0 projection axis, extended
13292        // onto the Component-1 projection axis so both per-half readers
13293        // on the paired dispatch carry their own byte-shape pin.
13294        assert_eq!(
13295            WitTarget::Http {
13296                endpoint: "/charge",
13297            }
13298            .payload(),
13299            Some("/charge"),
13300        );
13301        assert_eq!(
13302            WitTarget::PubSub {
13303                subject: "events.x",
13304            }
13305            .payload(),
13306            Some("events.x"),
13307        );
13308        assert_eq!(
13309            WitTarget::Store {
13310                slot: "checkout/$order",
13311            }
13312            .payload(),
13313            Some("checkout/$order"),
13314        );
13315        assert_eq!(WitTarget::Capability.payload(), None);
13316    }
13317
13318    #[test]
13319    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
13320        // Per-variant equivalence pin: for every arm of [`WitTarget`],
13321        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
13322        // byte-for-byte. Guards the drift surface where a future refactor
13323        // that split one accessor off the shared match onto its own
13324        // dispatch — a well-meaning "inline the pair back into per-half
13325        // fields for one crate-internal caller who only wanted one half"
13326        // or a scratch `impl` shadowing the derived projection — would
13327        // silently desynchronize [`WitTarget::payload`] from the
13328        // authoritative [`WitTarget::payload_pair`] dispatch, and every
13329        // downstream consumer that thinks "the payload half of the pair"
13330        // would drift from the diagnostic / graph consumers reading the
13331        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
13332        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
13333        // per-half projection pin (`gitrefspec_ref_pair_projects_
13334        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
13335        // FluxCD source-controller `spec.ref.<field>` axis — same "one
13336        // paired dispatch, both per-half projections agree byte-for-
13337        // byte" discipline extended onto the M3 `:contratos` payload-
13338        // arm surface.
13339        for variant in [
13340            WitTarget::Http {
13341                endpoint: "/charge",
13342            },
13343            WitTarget::PubSub {
13344                subject: "events.checkout.paid",
13345            },
13346            WitTarget::Store {
13347                slot: "checkout/$order",
13348            },
13349            WitTarget::Capability,
13350        ] {
13351            let via_projection = variant.payload();
13352            let via_pair = variant.payload_pair().map(|(_, p)| p);
13353            assert_eq!(
13354                via_projection, via_pair,
13355                "WitTarget::{variant:?} payload() must equal \
13356                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
13357                 regression that splits the two per-half projections off \
13358                 their shared match would silently desynchronize the \
13359                 payload accessor from the paired dispatch every \
13360                 diagnostic / graph consumer reads through",
13361            );
13362        }
13363    }
13364
13365    #[test]
13366    fn wit_target_http_endpoint_pins_per_variant() {
13367        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
13368        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
13369        // substrate-primitive per-arm post-projection accessor every
13370        // L7-HTTP-facing consumer routes through, sibling to the peer
13371        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
13372        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
13373        // arm round-trips its author-declared endpoint verbatim as
13374        // `Some("/charge")`; the three sibling arms
13375        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
13376        // [`WitTarget::Capability`]) each return `None` because they
13377        // carry no HTTP endpoint by definition. Same fail-before-pass-
13378        // after per-variant discipline as the sibling
13379        // `wit_target_payload_pins_per_variant` (5d6dc92) /
13380        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
13381        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
13382        // the peer pan-arm / per-half projection axes — extended onto
13383        // the per-arm HTTP-shape post-projection axis so a future
13384        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
13385        // [`WitTarget::Http`], a `Queue`-shaped peer of
13386        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
13387        // error on the sibling [`WitTarget::http_endpoint`] match arms
13388        // whose payload the L7-HTTP-shape accept-set is meant to bound.
13389        assert_eq!(
13390            WitTarget::Http {
13391                endpoint: "/charge",
13392            }
13393            .http_endpoint(),
13394            Some("/charge"),
13395        );
13396        assert_eq!(
13397            WitTarget::PubSub {
13398                subject: "events.checkout.paid",
13399            }
13400            .http_endpoint(),
13401            None,
13402        );
13403        assert_eq!(
13404            WitTarget::Store {
13405                slot: "checkout/$order",
13406            }
13407            .http_endpoint(),
13408            None,
13409        );
13410        assert_eq!(WitTarget::Capability.http_endpoint(), None);
13411    }
13412
13413    #[test]
13414    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
13415        // Per-variant coherence pin: for every arm of [`WitTarget`],
13416        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
13417        // arm (both project the same author-declared request-path
13418        // scalar), and returns `None` on every sibling arm regardless of
13419        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
13420        // Store carry their own payload the pan-arm accessor surfaces,
13421        // but that payload is not an HTTP endpoint — the per-arm
13422        // accessor must not leak it through the HTTP-shape channel).
13423        // Guards the drift surface where a future refactor that
13424        // conflated the per-arm HTTP projection with the pan-arm
13425        // [`WitTarget::payload`] projection — a well-meaning "one
13426        // accessor for the L7 branch, one for the graph" collapse that
13427        // routes both through the same 4-arm dispatch — would silently
13428        // widen the L7-HTTP-shape accept-set onto pub-sub / store
13429        // payloads at the caixa-mesh L7 emit branch, admitting a
13430        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
13431        // rule with the operator-side apply-time symptom (Cilium's
13432        // eBPF data-plane rejects every ingress edge whose L7 filter
13433        // doesn't match the wire-format HTTP request line) far from
13434        // the source refactor. Sibling to the peer
13435        // `wit_target_payload_matches_payload_pair_second_component_
13436        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
13437        // extended onto the per-arm HTTP specialization axis so both
13438        // the pan-arm and the per-arm projections carry their own
13439        // byte-shape coherence witness against the substrate's typed
13440        // arm-family accept-set.
13441        for variant in [
13442            WitTarget::Http {
13443                endpoint: "/charge",
13444            },
13445            WitTarget::PubSub {
13446                subject: "events.checkout.paid",
13447            },
13448            WitTarget::Store {
13449                slot: "checkout/$order",
13450            },
13451            WitTarget::Capability,
13452        ] {
13453            let per_arm = variant.http_endpoint();
13454            let pan_arm = variant.payload();
13455            if variant.is_http() {
13456                assert_eq!(
13457                    per_arm, pan_arm,
13458                    "WitTarget::{variant:?} http_endpoint() must equal \
13459                     payload() on the Http arm — a per-arm-vs-pan-arm \
13460                     split would silently drift the L7 emit branch's \
13461                     path-scalar source from the graph verb's payload \
13462                     scalar source",
13463                );
13464            } else {
13465                assert_eq!(
13466                    per_arm, None,
13467                    "WitTarget::{variant:?} http_endpoint() must return \
13468                     None on non-Http arms — a leak that surfaced a \
13469                     pub-sub :subject or a key/value :slot through the \
13470                     HTTP-endpoint accessor would silently widen the \
13471                     Cilium L7 HTTP `path:` rule accept-set onto \
13472                     protocol shapes Cilium's eBPF data-plane can't \
13473                     introspect",
13474                );
13475            }
13476        }
13477    }
13478
13479    #[test]
13480    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
13481        // Per-variant coherence pin: for every arm of [`WitTarget`],
13482        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
13483        // drift surface where a future extension of the
13484        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
13485        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
13486        // accessor to cover both peers) landed without a paired
13487        // extension of the [`gen_platform::IsVariant`]-derived
13488        // `is_http()` predicate's accept-set, or vice versa — a
13489        // regression that split the "which arms count as HTTP-shaped
13490        // for L7-path emission?" answer between two dispatch surfaces
13491        // the substrate ships. Sibling to the peer
13492        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
13493        // on the paired dispatch axis — extended onto the per-arm
13494        // predicate-vs-accessor coherence axis so the gen-platform
13495        // IsVariant predicate and the substrate-lifted per-arm
13496        // accessor carry one shared answer to "is this the HTTP arm?".
13497        for variant in [
13498            WitTarget::Http {
13499                endpoint: "/charge",
13500            },
13501            WitTarget::PubSub {
13502                subject: "events.checkout.paid",
13503            },
13504            WitTarget::Store {
13505                slot: "checkout/$order",
13506            },
13507            WitTarget::Capability,
13508        ] {
13509            assert_eq!(
13510                variant.http_endpoint().is_some(),
13511                variant.is_http(),
13512                "WitTarget::{variant:?} http_endpoint().is_some() must \
13513                 equal is_http() — a drift would split the L7 emit \
13514                 branch's arm-set gate from the substrate-derived \
13515                 shape-discrimination predicate on the same axis",
13516            );
13517        }
13518    }
13519
13520    #[test]
13521    fn wit_target_pubsub_subject_pins_per_variant() {
13522        // Fail-before-pass-after pin: the substrate-canonical per-arm
13523        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
13524        // is the single dispatch every future pub-sub-facing consumer
13525        // routes through, sibling to the peer [`WitContract::subject`]
13526        // (63e18a0) pre-projection scalar accessor on the raw-field
13527        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
13528        // post-projection per-arm accessor on the sibling HTTP-shape
13529        // axis. The [`WitTarget::PubSub`] arm round-trips its
13530        // author-declared subject verbatim as
13531        // `Some("events.checkout.paid")`; the three sibling arms each
13532        // return `None` because they carry no NATS-shaped subject by
13533        // definition. Same fail-before-pass-after per-variant discipline
13534        // as the sibling `wit_target_http_endpoint_pins_per_variant`
13535        // pin on the peer per-arm axis — extended onto the per-arm
13536        // pub-sub-shape post-projection axis so a future [`WitTarget`]
13537        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
13538        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
13539        // compile-time exhaustiveness error on the sibling
13540        // [`WitTarget::pubsub_subject`] match arms whose payload the
13541        // pub-sub-shape accept-set is meant to bound.
13542        assert_eq!(
13543            WitTarget::PubSub {
13544                subject: "events.checkout.paid",
13545            }
13546            .pubsub_subject(),
13547            Some("events.checkout.paid"),
13548        );
13549        assert_eq!(
13550            WitTarget::Http {
13551                endpoint: "/charge",
13552            }
13553            .pubsub_subject(),
13554            None,
13555        );
13556        assert_eq!(
13557            WitTarget::Store {
13558                slot: "checkout/$order",
13559            }
13560            .pubsub_subject(),
13561            None,
13562        );
13563        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
13564    }
13565
13566    #[test]
13567    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
13568        // Per-variant coherence pin: for every arm of [`WitTarget`],
13569        // `.pubsub_subject()` equals `.payload()` on the
13570        // [`WitTarget::PubSub`] arm (both project the same
13571        // author-declared subject scalar), and returns `None` on every
13572        // sibling arm regardless of whether [`WitTarget::payload`]
13573        // itself returns `Some` (Http / Store carry their own payload
13574        // the pan-arm accessor surfaces, but that payload is not a
13575        // pub-sub subject — the per-arm accessor must not leak it
13576        // through the pub-sub-shape channel). Sibling to the peer
13577        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
13578        // coherence pin on the per-arm HTTP-shape axis — extended onto
13579        // the per-arm pub-sub specialization axis so both per-arm
13580        // projections carry their own byte-shape coherence witness
13581        // against the substrate's typed arm-family accept-set.
13582        for variant in [
13583            WitTarget::Http {
13584                endpoint: "/charge",
13585            },
13586            WitTarget::PubSub {
13587                subject: "events.checkout.paid",
13588            },
13589            WitTarget::Store {
13590                slot: "checkout/$order",
13591            },
13592            WitTarget::Capability,
13593        ] {
13594            let per_arm = variant.pubsub_subject();
13595            let pan_arm = variant.payload();
13596            if variant.is_pubsub() {
13597                assert_eq!(
13598                    per_arm, pan_arm,
13599                    "WitTarget::{variant:?} pubsub_subject() must equal \
13600                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
13601                     split would silently drift the pub-sub-shape emit \
13602                     branch's subject-scalar source from the graph verb's \
13603                     payload scalar source",
13604                );
13605            } else {
13606                assert_eq!(
13607                    per_arm, None,
13608                    "WitTarget::{variant:?} pubsub_subject() must return \
13609                     None on non-PubSub arms — a leak that surfaced an \
13610                     HTTP :endpoint or a key/value :slot through the \
13611                     pub-sub-subject accessor would silently widen the \
13612                     downstream NATS-shape accept-set onto protocol \
13613                     shapes NATS servers can't route",
13614                );
13615            }
13616        }
13617    }
13618
13619    #[test]
13620    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
13621        // Per-variant coherence pin: for every arm of [`WitTarget`],
13622        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
13623        // drift surface where a future extension of the
13624        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
13625        // without a paired extension of the [`gen_platform::IsVariant`]-
13626        // derived `is_pubsub()` predicate's accept-set, or vice versa
13627        // — a regression that split the "which arms count as pub-sub-
13628        // shaped for subject emission?" answer between two dispatch
13629        // surfaces the substrate ships. Sibling to the peer
13630        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
13631        // pin on the per-arm HTTP-shape axis — extended onto the
13632        // per-arm pub-sub predicate-vs-accessor coherence axis so the
13633        // gen-platform IsVariant predicate and the substrate-lifted
13634        // per-arm accessor carry one shared answer to "is this the
13635        // PubSub arm?".
13636        for variant in [
13637            WitTarget::Http {
13638                endpoint: "/charge",
13639            },
13640            WitTarget::PubSub {
13641                subject: "events.checkout.paid",
13642            },
13643            WitTarget::Store {
13644                slot: "checkout/$order",
13645            },
13646            WitTarget::Capability,
13647        ] {
13648            assert_eq!(
13649                variant.pubsub_subject().is_some(),
13650                variant.is_pubsub(),
13651                "WitTarget::{variant:?} pubsub_subject().is_some() must \
13652                 equal is_pubsub() — a drift would split the pub-sub \
13653                 emit branch's arm-set gate from the substrate-derived \
13654                 shape-discrimination predicate on the same axis",
13655            );
13656        }
13657    }
13658
13659    #[test]
13660    fn wit_target_store_slot_pins_per_variant() {
13661        // Fail-before-pass-after pin: the substrate-canonical per-arm
13662        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
13663        // is the single dispatch every future store-facing consumer
13664        // routes through, sibling to the peer [`WitContract::slot`]
13665        // pre-projection scalar accessor on the raw-field axis and to
13666        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
13667        // [`WitTarget::pubsub_subject`] post-projection per-arm
13668        // accessors on the sibling per-payload-arm axes. The
13669        // [`WitTarget::Store`] arm round-trips its author-declared
13670        // slot verbatim as `Some("checkout/$order")`; the three
13671        // sibling arms each return `None` because they carry no
13672        // WASI-key/value slot by definition. Same fail-before-pass-
13673        // after per-variant discipline as the sibling
13674        // `wit_target_http_endpoint_pins_per_variant` +
13675        // `wit_target_pubsub_subject_pins_per_variant` pins on the
13676        // peer per-arm axes — extended onto the per-arm store-shape
13677        // post-projection axis so a future [`WitTarget`] variant
13678        // addition trips a compile-time exhaustiveness error on the
13679        // sibling [`WitTarget::store_slot`] match arms whose payload
13680        // the store-shape accept-set is meant to bound.
13681        assert_eq!(
13682            WitTarget::Store {
13683                slot: "checkout/$order",
13684            }
13685            .store_slot(),
13686            Some("checkout/$order"),
13687        );
13688        assert_eq!(
13689            WitTarget::Http {
13690                endpoint: "/charge",
13691            }
13692            .store_slot(),
13693            None,
13694        );
13695        assert_eq!(
13696            WitTarget::PubSub {
13697                subject: "events.checkout.paid",
13698            }
13699            .store_slot(),
13700            None,
13701        );
13702        assert_eq!(WitTarget::Capability.store_slot(), None);
13703    }
13704
13705    #[test]
13706    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
13707        // Per-variant coherence pin: for every arm of [`WitTarget`],
13708        // `.store_slot()` equals `.payload()` on the
13709        // [`WitTarget::Store`] arm (both project the same
13710        // author-declared slot scalar), and returns `None` on every
13711        // sibling arm regardless of whether [`WitTarget::payload`]
13712        // itself returns `Some`. Sibling to the peer
13713        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
13714        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
13715        // pins on the per-arm HTTP and PubSub axes — closes the
13716        // per-arm-vs-pan-arm byte-shape coherence trio across all
13717        // three payload arms.
13718        for variant in [
13719            WitTarget::Http {
13720                endpoint: "/charge",
13721            },
13722            WitTarget::PubSub {
13723                subject: "events.checkout.paid",
13724            },
13725            WitTarget::Store {
13726                slot: "checkout/$order",
13727            },
13728            WitTarget::Capability,
13729        ] {
13730            let per_arm = variant.store_slot();
13731            let pan_arm = variant.payload();
13732            if variant.is_store() {
13733                assert_eq!(
13734                    per_arm, pan_arm,
13735                    "WitTarget::{variant:?} store_slot() must equal \
13736                     payload() on the Store arm — a per-arm-vs-pan-arm \
13737                     split would silently drift the store-shape emit \
13738                     branch's slot-scalar source from the graph verb's \
13739                     payload scalar source",
13740                );
13741            } else {
13742                assert_eq!(
13743                    per_arm, None,
13744                    "WitTarget::{variant:?} store_slot() must return \
13745                     None on non-Store arms — a leak that surfaced an \
13746                     HTTP :endpoint or a NATS :subject through the \
13747                     key/value-slot accessor would silently widen the \
13748                     downstream WASI-key/value slot accept-set onto \
13749                     protocol shapes the kv backends can't route",
13750                );
13751            }
13752        }
13753    }
13754
13755    #[test]
13756    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
13757        // Per-variant coherence pin: for every arm of [`WitTarget`],
13758        // `.store_slot().is_some()` iff `.is_store()`. Guards the
13759        // drift surface where a future extension of the
13760        // [`WitTarget::store_slot`] accessor's accept-set landed
13761        // without a paired extension of the [`gen_platform::IsVariant`]-
13762        // derived `is_store()` predicate's accept-set. Sibling to the
13763        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
13764        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
13765        // pins — closes the per-arm predicate-vs-accessor coherence
13766        // trio across all three payload arms so the gen-platform
13767        // IsVariant predicate and the substrate-lifted per-arm
13768        // accessor carry one shared answer to "is this the Store arm?".
13769        for variant in [
13770            WitTarget::Http {
13771                endpoint: "/charge",
13772            },
13773            WitTarget::PubSub {
13774                subject: "events.checkout.paid",
13775            },
13776            WitTarget::Store {
13777                slot: "checkout/$order",
13778            },
13779            WitTarget::Capability,
13780        ] {
13781            assert_eq!(
13782                variant.store_slot().is_some(),
13783                variant.is_store(),
13784                "WitTarget::{variant:?} store_slot().is_some() must \
13785                 equal is_store() — a drift would split the store-shape \
13786                 emit branch's arm-set gate from the substrate-derived \
13787                 shape-discrimination predicate on the same axis",
13788            );
13789        }
13790    }
13791
13792    #[test]
13793    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
13794        // Fail-before-pass-after cross-axis pin on the trio
13795        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
13796        // payload-carrying arm of [`WitTarget`], exactly one per-arm
13797        // accessor returns `Some(payload)` and the two peers return
13798        // `None`; and on the payload-less [`WitTarget::Capability`]
13799        // arm, all three return `None`. Guards the drift surface where
13800        // a future extension of one per-arm accessor's accept-set (e.g.
13801        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
13802        // that widened `http_endpoint` to cover both peers without
13803        // narrowing the peer `pubsub_subject` / `store_slot` accept-
13804        // sets to keep the partition mutually exclusive) landed without
13805        // threading through the peer per-arm accessors — the resulting
13806        // silent overlap would land the same edge's payload on two
13807        // downstream per-shape emit branches at once, or leak a
13808        // pub-sub subject through the store-slot channel, at renderer
13809        // emit time far from the substrate primitive's arm-widening
13810        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
13811        // 3-way pin on the payload-field-name axis — extended onto the
13812        // per-arm-accessor payload-projection axis so the substrate-
13813        // owned partition invariant is load-bearing at every per-arm
13814        // consumer's read site.
13815        let payload_variants = [
13816            (
13817                WitTarget::Http {
13818                    endpoint: "/charge",
13819                },
13820                "http",
13821            ),
13822            (
13823                WitTarget::PubSub {
13824                    subject: "events.checkout.paid",
13825                },
13826                "pubsub",
13827            ),
13828            (
13829                WitTarget::Store {
13830                    slot: "checkout/$order",
13831                },
13832                "store",
13833            ),
13834        ];
13835        for (variant, own_arm_label) in payload_variants {
13836            let own_arm_hit = match own_arm_label {
13837                "http" => variant.is_http(),
13838                "pubsub" => variant.is_pubsub(),
13839                "store" => variant.is_store(),
13840                other => panic!("unknown own-arm label {other:?}"),
13841            };
13842            let per_arm_results = [
13843                ("http_endpoint", variant.http_endpoint()),
13844                ("pubsub_subject", variant.pubsub_subject()),
13845                ("store_slot", variant.store_slot()),
13846            ];
13847            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
13848            assert_eq!(
13849                some_count, 1,
13850                "WitTarget::{variant:?} must land exactly one per-arm \
13851                 post-projection accessor's Some result — the trio \
13852                 (http_endpoint, pubsub_subject, store_slot) must \
13853                 partition the payload arm-set; got {per_arm_results:?}",
13854            );
13855            assert!(
13856                own_arm_hit,
13857                "WitTarget::{variant:?} own-arm gen-platform predicate \
13858                 must return true on its own arm — a partition failure \
13859                 upstream of this pin",
13860            );
13861            assert!(
13862                variant.payload().is_some(),
13863                "WitTarget::{variant:?} pan-arm payload() must return \
13864                 Some on every payload-carrying arm the trio partitions",
13865            );
13866        }
13867        // The payload-less Capability arm must return None on every
13868        // per-arm accessor — the partition's terminal-fallback shape.
13869        let cap = WitTarget::Capability;
13870        assert_eq!(cap.http_endpoint(), None);
13871        assert_eq!(cap.pubsub_subject(), None);
13872        assert_eq!(cap.store_slot(), None);
13873        assert_eq!(
13874            cap.payload(),
13875            None,
13876            "WitTarget::Capability pan-arm payload() must return None — \
13877             the trio's payload-less-arm coherence witness",
13878        );
13879    }
13880
13881    #[test]
13882    fn wit_target_field_names_are_pairwise_distinct() {
13883        // Distinctness pin: if any two of the three payload-field-name
13884        // scalars ever collapse (e.g. an accidental `endpoint` copy-
13885        // paste over the `subject` const), the [`WitContract::target`]
13886        // gate's diagnostic would point authors at the wrong field —
13887        // an "expected `:endpoint`" error on a pub-sub edge would
13888        // silently misroute the fix. Same cross-axis-distinctness
13889        // discipline as the peer M3 `:placement :estrategia` variant-
13890        // discriminator scalar-value pins (cc8f749) applied to the
13891        // payload-field-name axis.
13892        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
13893        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
13894        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
13895    }
13896
13897    #[test]
13898    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
13899        // Fail-before-pass-after pin: the graph-verb payload column's
13900        // per-arm `{field}={payload}` byte-string is derived through the
13901        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
13902        // payload-carrying arms, not through a hand-rolled per-arm match
13903        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
13904        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13905        // inline. A future variant addition — the M4-and-later per-edge
13906        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
13907        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
13908        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
13909        // and both [`WitTarget::label`] (duplicate-`:contratos`
13910        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
13911        // payload column) pick up the new arm from the same dispatch.
13912        // Prior to this lift the graph verb open-coded the 4-arm match
13913        // in caixa-feira, so a variant addition would have to be threaded
13914        // through both projections in lockstep or the graph verb would
13915        // silently drop the new arm to `(capability-only)`.
13916        for variant in [
13917            WitTarget::Http {
13918                endpoint: "/charge",
13919            },
13920            WitTarget::PubSub {
13921                subject: "events.checkout.paid",
13922            },
13923            WitTarget::Store {
13924                slot: "checkout/$order",
13925            },
13926        ] {
13927            let (field, payload) = variant
13928                .payload_pair()
13929                .expect("payload arm must expose (field, payload)");
13930            assert_eq!(
13931                variant.graph_label(),
13932                format!("{field}={payload}"),
13933                "WitTarget::{variant:?} graph_label must route the \
13934                 `{{field}}={{payload}}` template through payload_pair — \
13935                 a regression to a hand-rolled per-arm match at the graph \
13936                 verb would silently disagree with a future variant \
13937                 addition landed only at payload_pair"
13938            );
13939        }
13940    }
13941
13942    #[test]
13943    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
13944        // Fail-before-pass-after pin on the payload-less arm: the graph
13945        // verb's `(capability-only)` byte-string routes through the
13946        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
13947        // [`WitTarget::Capability`] arm, not through an inline
13948        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
13949        // per-`:contratos` payload column. Peer of the sibling
13950        // [`wit_target_label_pins_per_variant_format`] Capability-arm
13951        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
13952        // extended here onto the third payload-less-arm consumer axis
13953        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
13954        // axis and the wrong-target diagnostic axis).
13955        assert_eq!(
13956            WitTarget::Capability.graph_label(),
13957            WitTarget::CAPABILITY_GRAPH_LABEL,
13958        );
13959        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
13960    }
13961
13962    #[test]
13963    fn wit_target_capability_graph_label_distinct_from_capability_label() {
13964        // Cross-consumer-axis distinctness pin: the graph-verb
13965        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
13966        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
13967        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
13968        // payload)`) surface the payload-less arm on two distinct
13969        // consumer axes; a collapse (an accidental rebrand that lands
13970        // one spelling on both consts, a copy-paste that unifies them
13971        // "for consistency") would silently merge the two byte-strings
13972        // and lose the vocabulary distinction the graph verb's
13973        // compact-column form and the diagnostic's descriptive-clause
13974        // form each carry on purpose. Peer of the sibling 4-way
13975        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
13976        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
13977        // extended here onto the cross-consumer-axis distinctness of the
13978        // two payload-less-arm consts.
13979        assert_ne!(
13980            WitTarget::CAPABILITY_GRAPH_LABEL,
13981            WitTarget::CAPABILITY_LABEL,
13982            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
13983             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
13984             diagnostic) must remain distinct — a collapse would silently \
13985             merge two consumer axes onto one spelling"
13986        );
13987    }
13988
13989    #[test]
13990    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
13991        // 4-way distinctness pin extending the sibling
13992        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
13993        // (which covers only the HTTP / PubSub / Store payload arms)
13994        // onto the fourth scalar the shared
13995        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
13996        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
13997        // (`"none"`), the payload-less Capability-arm rejection scalar.
13998        //
13999        // All four [`WitTarget::HTTP_FIELD_NAME`] /
14000        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14001        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
14002        // dispatch surface [`WitContract::target`] writes onto the
14003        // `ContratoWrongTarget::expected` field — the same `&'static
14004        // str` axis authors read as "this WIT world's shape admits
14005        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
14006        // downstream consumers rely on: an `expected: "endpoint"`
14007        // diagnostic on a Capability-shaped edge tells the author to
14008        // add a `:endpoint "…"` slot to a WIT world that admits none,
14009        // silently misrouting the fix. Until this pin landed the three
14010        // payload-arm consts were distinctness-guarded by the sibling
14011        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
14012        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
14013        // author-facing vocabulary shift from `"none"` to `"endpoint"`
14014        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
14015        // into per-shape peers) would have silently landed one
14016        // Capability-arm rejection on a payload-arm's `expected:` byte-
14017        // string and desynchronized the diagnostic from the author's
14018        // typed shape.
14019        //
14020        // Same 4-way pairwise-distinctness pin discipline as the peer
14021        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
14022        // (cc8f749) applies on the sibling M3 closed-set typed-enum
14023        // scalar-value dispatch axis; extends the pin trajectory the
14024        // sibling `wit_target_field_names_are_pairwise_distinct`
14025        // 3-way pin opened to cover the last unguarded corner on the
14026        // `ContratoWrongTarget::expected` scalar-value axis.
14027        //
14028        // Fail-before-pass-after locally verified by mutating
14029        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
14030        // — this pin fires as expected; restoring passes.
14031        let all = [
14032            WitTarget::HTTP_FIELD_NAME,
14033            WitTarget::PUBSUB_FIELD_NAME,
14034            WitTarget::STORE_FIELD_NAME,
14035            WitTarget::CAPABILITY_EXPECTED,
14036        ];
14037        for (i, a) in all.iter().enumerate() {
14038            for (j, b) in all.iter().enumerate() {
14039                if i != j {
14040                    assert_ne!(
14041                        a, b,
14042                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
14043                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
14044                         pairwise distinct — got duplicate {a:?} at indices \
14045                         {i} and {j}; all four scalars thread through the \
14046                         shared `AplicacaoError::ContratoWrongTarget::expected` \
14047                         &'static str axis, so a collapse silently misdirects \
14048                         the diagnostic on which typed shape the WIT world admits",
14049                    );
14050                }
14051            }
14052        }
14053    }
14054
14055    #[test]
14056    fn wit_target_is_variant_predicates_partition_the_arm_set() {
14057        // Fail-before-pass-after pin on the
14058        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
14059        // each of the four variants exactly one of the generated
14060        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
14061        // predicates returns `true` and the other three return
14062        // `false`. Prior to this derive the only production
14063        // arm-discriminator on [`WitTarget`] — the sync-cycle
14064        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
14065        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
14066        // the variant that expressed no compile-time link back to
14067        // the closed-set typed dispatch a future fifth
14068        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
14069        // split of [`WitTarget::PubSub`] into shape-specific peers,
14070        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
14071        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
14072        // to thread through in lockstep or the DFS exclusion would
14073        // silently disagree with the peer diagnostic templates on
14074        // which arms carry sync-versus-async semantics. Peer of the
14075        // sibling [`crate::CaixaKind`] (f5bba80),
14076        // [`PlacementStrategy`] (766ec63),
14077        // [`crate::supervisor::RestartStrategy`],
14078        // [`crate::supervisor::RestartPolicy`], and
14079        // [`crate::upgrade::UpgradeInstruction`] (915a934)
14080        // `IsVariant` derives on the sibling closed-set typed-enum
14081        // discriminator axes — extends the same one-typed-dispatch-
14082        // per-variant discipline onto the last unlifted closed-set
14083        // typed-enum discriminator on the caixa surface (the M3
14084        // mesh-slot per-`:contratos` target-arm axis), closing the
14085        // arm-discriminator convergence trajectory across every
14086        // closed-set typed enum in caixa-core.
14087        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
14088            (
14089                WitTarget::Http { endpoint: "/x" },
14090                [true, false, false, false],
14091            ),
14092            (
14093                WitTarget::PubSub {
14094                    subject: "events.x",
14095                },
14096                [false, true, false, false],
14097            ),
14098            (
14099                WitTarget::Store { slot: "kv/x" },
14100                [false, false, true, false],
14101            ),
14102            (WitTarget::Capability, [false, false, false, true]),
14103        ];
14104        for (variant, expected) in rows {
14105            let observed = [
14106                variant.is_http(),
14107                variant.is_pubsub(),
14108                variant.is_store(),
14109                variant.is_capability(),
14110            ];
14111            assert_eq!(
14112                observed, expected,
14113                "WitTarget::{variant:?} is_* predicates must partition \
14114                 the arm set (http, pubsub, store, capability); got {observed:?}"
14115            );
14116        }
14117    }
14118
14119    #[test]
14120    fn wit_target_is_variant_predicates_are_const_fn() {
14121        // The [`gen_platform::IsVariant`] derive emits `const fn`
14122        // predicates on the peer [`crate::CaixaKind`] +
14123        // [`crate::upgrade::UpgradeInstruction`] +
14124        // [`crate::supervisor::RestartStrategy`] +
14125        // [`crate::supervisor::RestartPolicy`] +
14126        // [`PlacementStrategy`] closed-set typed enums — pin the
14127        // same posture on [`WitTarget`] so a future accidental
14128        // downgrade to non-`const` (an added runtime helper reachable
14129        // only from a non-`const` context, a manual hand-rolled
14130        // `impl` that shadows the derive-generated method) trips at
14131        // caixa-core build time rather than surfacing as a downstream
14132        // `const`-context regression far from the derive declaration.
14133        //
14134        // Unlike the peer unit-variant enums (`CaixaKind` /
14135        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
14136        // whose `const` constructors need no arguments, the three
14137        // payload-carrying [`WitTarget`] arms are const-constructed
14138        // through `&'static str` payloads — the same `'static`
14139        // lifetime the closed-set typed enum's four-arm partition
14140        // pin above already threads through.
14141        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
14142        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
14143        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
14144        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
14145        const IS_HTTP: bool = HTTP.is_http();
14146        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
14147        const IS_STORE: bool = STORE.is_store();
14148        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
14149        assert!(IS_HTTP);
14150        assert!(IS_PUBSUB);
14151        assert!(IS_STORE);
14152        assert!(IS_CAPABILITY);
14153    }
14154
14155    #[test]
14156    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
14157        // Consumer-side pin on the sole production converge site:
14158        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
14159        // edges from the synchronous-subgraph DFS via the lifted
14160        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
14161        // predicate (rebound from the prior raw
14162        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
14163        // variant). Byte-equivalent today (`is_pubsub` is the
14164        // derive-generated `matches!(self, Self::PubSub { .. })` by
14165        // construction, the `#[is_variant(name = "pubsub")]` override
14166        // aliasing the auto-derived `is_pub_sub` back to the sibling
14167        // [`WitContract::is_pubsub`] name); pin the behavior so a
14168        // future accidental drift (a rebind onto a peer arm
14169        // predicate, a manual hand-rolled `impl` that shadows the
14170        // derive-generated method with different semantics, a peer
14171        // arm rename that shifts which variant carries sync-versus-
14172        // async semantics) trips at caixa-core test time rather than
14173        // at some downstream operator's runtime dispatch far from the
14174        // rebind commit.
14175        //
14176        // The fixture constructs a two-Servico Aplicacao with one
14177        // pub-sub edge that would close a sync-cycle if the DFS did
14178        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
14179        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
14180        // edge, which is not a cycle. A regression in the converge
14181        // (a rebind that reads the pub-sub arm as sync) would report
14182        // `AplicacaoError::ContratoCycle`.
14183        let s = AplicacaoSpec {
14184            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
14185            contratos: vec![
14186                // Pub-sub edge: DFS must skip via is_pubsub().
14187                WitContract {
14188                    de: "a".into(),
14189                    para: "b".into(),
14190                    wit: "nats:pub-sub".into(),
14191                    endpoint: None,
14192                    subject: Some("events.x".into()),
14193                    slot: None,
14194                },
14195                // HTTP edge: DFS must include.
14196                WitContract {
14197                    de: "b".into(),
14198                    para: "a".into(),
14199                    wit: "wasi:http/proxy".into(),
14200                    endpoint: Some("/x".into()),
14201                    subject: None,
14202                    slot: None,
14203                },
14204            ],
14205            politicas: MeshPolicy::default(),
14206            placement: Placement {
14207                estrategia: PlacementStrategy::Replicated,
14208                clusters: vec!["rio".into()],
14209                affinity: None,
14210                shard_key: None,
14211            },
14212            entrada: None,
14213        };
14214        s.validate()
14215            .expect("pub-sub edge must be excluded from sync-cycle DFS");
14216    }
14217
14218    #[test]
14219    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
14220        // Consumer-side pin: the same three peer consts thread through
14221        // both the [`WitTarget::label`] template (leading-`:` keyword
14222        // prefix in the duplicate-`:contratos` diagnostic) and the
14223        // [`WitContract::target`] gate's [`AplicacaoError::
14224        // ContratoMissingTarget`] `expected:` scalar (the field the
14225        // author needs to add). Pin both routes at once so a future
14226        // refactor can't accidentally split them onto separate string
14227        // literals — the "one place, everywhere reaches for it"
14228        // invariant the peer const set carries.
14229        let http_label = WitTarget::Http { endpoint: "/x" }.label();
14230        assert!(
14231            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
14232            "label must lead with :{} keyword (got {http_label:?})",
14233            WitTarget::HTTP_FIELD_NAME,
14234        );
14235
14236        let mut s = three_member_spec();
14237        s.contratos.push(WitContract {
14238            de: "cart".into(),
14239            para: "catalog".into(),
14240            wit: "kafka:topic".into(),
14241            endpoint: None,
14242            subject: None,
14243            slot: None,
14244        });
14245        match s.validate().unwrap_err() {
14246            AplicacaoError::ContratoMissingTarget { expected, .. } => {
14247                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
14248            }
14249            other => panic!("expected ContratoMissingTarget, got {other:?}"),
14250        }
14251    }
14252
14253    #[test]
14254    fn duplicate_pubsub_diagnostic_names_offending_subject() {
14255        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
14256        // on the pub-sub target axis: the duplicate-edge diagnostic
14257        // must name the `:subject` payload verbatim (not just the
14258        // `(de, para, wit)` triple). Prior to lifting the label onto
14259        // [`WitTarget::label`] the diagnostic derived the label from
14260        // raw [`WitContract`] `Option<String>` probes — a future
14261        // `WitTarget` variant addition (M4 per-edge WIT registry)
14262        // would silently fall through to the `Capability` "no
14263        // payload" default without a compiler warning. Pinning the
14264        // pub-sub arm's format closes the second of three
14265        // payload-carrying `WitTarget` arms this diagnostic threads
14266        // through.
14267        let mut s = three_member_spec();
14268        let pubsub = WitContract {
14269            de: "payment".into(),
14270            para: "cart".into(),
14271            wit: "nats:pub-sub".into(),
14272            endpoint: None,
14273            subject: Some("events.checkout.paid".into()),
14274            slot: None,
14275        };
14276        s.contratos.push(pubsub.clone());
14277        s.contratos.push(pubsub);
14278        let err = s.validate().unwrap_err();
14279        let msg = format!("{err}");
14280        assert!(
14281            msg.contains(":subject \"events.checkout.paid\""),
14282            "duplicate-pubsub diagnostic must name the offending \
14283             :subject payload (got: {msg:?})"
14284        );
14285    }
14286
14287    #[test]
14288    fn duplicate_store_diagnostic_names_offending_slot() {
14289        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
14290        // key-value target axis: the diagnostic must name the `:slot`
14291        // payload verbatim. Third of three payload-carrying
14292        // `WitTarget` arms this diagnostic threads through, closing
14293        // the per-arm label pin trilogy (`Http` — 6841,
14294        // `PubSub` + `Store` — this test + peer above).
14295        let mut s = three_member_spec();
14296        let store = WitContract {
14297            de: "cart".into(),
14298            para: "payment".into(),
14299            wit: "wasi:keyvalue/store".into(),
14300            endpoint: None,
14301            subject: None,
14302            slot: Some("checkout/$orderId".into()),
14303        };
14304        s.contratos
14305            .retain(|c| !(c.de == "cart" && c.para == "payment"));
14306        s.contratos.push(store.clone());
14307        s.contratos.push(store);
14308        let err = s.validate().unwrap_err();
14309        let msg = format!("{err}");
14310        assert!(
14311            msg.contains(":slot \"checkout/$orderId\""),
14312            "duplicate-store diagnostic must name the offending :slot \
14313             payload (got: {msg:?})"
14314        );
14315    }
14316
14317    #[test]
14318    fn rejects_entrada_path_without_leading_slash() {
14319        let mut s = three_member_spec();
14320        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
14321        let err = s.validate().unwrap_err();
14322        assert!(
14323            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
14324            "got {err:?}"
14325        );
14326    }
14327
14328    #[test]
14329    fn rejects_empty_entrada_path() {
14330        let mut s = three_member_spec();
14331        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
14332        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14333    }
14334
14335    #[test]
14336    fn rejects_duplicate_entrada_paths() {
14337        let mut s = three_member_spec();
14338        s.entrada.as_mut().unwrap().paths = vec![
14339            "/api/cart".into(),
14340            "/api/products".into(),
14341            "/api/cart".into(),
14342        ];
14343        let err = s.validate().unwrap_err();
14344        assert!(
14345            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
14346            "got {err:?}"
14347        );
14348    }
14349
14350    #[test]
14351    fn rejects_zero_entrada_port() {
14352        let mut s = three_member_spec();
14353        s.entrada.as_mut().unwrap().port = 0;
14354        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
14355    }
14356
14357    // ── :entrada :paths value-shape gate ─────────────────────────────
14358    //
14359    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
14360    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
14361    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
14362    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
14363    // time now becomes a caixa-build-time `EntradaPathInvalid` with
14364    // the offending `:paths` entry named verbatim.
14365
14366    #[test]
14367    fn rejects_entrada_path_with_query() {
14368        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
14369        // silently passed validate and the Gateway API webhook
14370        // rejected it at apply time with no source citation.
14371        let mut s = three_member_spec();
14372        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
14373        let err = s.validate().unwrap_err();
14374        assert!(
14375            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14376                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
14377            "got {err:?}"
14378        );
14379    }
14380
14381    #[test]
14382    fn rejects_entrada_path_with_fragment() {
14383        let mut s = three_member_spec();
14384        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
14385        let err = s.validate().unwrap_err();
14386        assert!(
14387            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14388                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
14389            "got {err:?}"
14390        );
14391    }
14392
14393    #[test]
14394    fn rejects_entrada_path_with_space() {
14395        let mut s = three_member_spec();
14396        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
14397        let err = s.validate().unwrap_err();
14398        assert!(
14399            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14400                if path == "/api/my cart" && reason.contains("whitespace")),
14401            "got {err:?}"
14402        );
14403    }
14404
14405    #[test]
14406    fn rejects_entrada_path_with_tab() {
14407        let mut s = three_member_spec();
14408        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
14409        let err = s.validate().unwrap_err();
14410        assert!(
14411            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14412                if path == "/api/\tcart" && reason.contains("whitespace")),
14413            "got {err:?}"
14414        );
14415    }
14416
14417    #[test]
14418    fn rejects_entrada_path_with_control_char() {
14419        // 0x01 (SOH) — a non-whitespace control char surfaces the
14420        // distinct "control character" reason arm, separate from
14421        // the whitespace arm. Pinned so a future refactor that
14422        // collapses the two arms can't accidentally drop the more
14423        // self-locating diagnostic.
14424        let mut s = three_member_spec();
14425        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
14426        let err = s.validate().unwrap_err();
14427        assert!(
14428            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14429                if path == "/api/\x01cart" && reason.contains("control character")),
14430            "got {err:?}"
14431        );
14432    }
14433
14434    #[test]
14435    fn rejects_entrada_path_with_non_ascii() {
14436        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
14437        // unreserved-set rule rejects. The Gateway API webhook
14438        // rejects literal non-ASCII bytes; percent-encoding is the
14439        // only way to author non-ASCII in a path.
14440        let mut s = three_member_spec();
14441        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
14442        let err = s.validate().unwrap_err();
14443        assert!(
14444            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14445                if path == "/api/café" && reason.contains("non-ASCII")),
14446            "got {err:?}"
14447        );
14448    }
14449
14450    #[test]
14451    fn rejects_entrada_path_with_consecutive_slashes() {
14452        let mut s = three_member_spec();
14453        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
14454        let err = s.validate().unwrap_err();
14455        assert!(
14456            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14457                if path == "/api//cart" && reason.contains("consecutive `/`")),
14458            "got {err:?}"
14459        );
14460    }
14461
14462    #[test]
14463    fn rejects_entrada_path_with_dot_segment() {
14464        let mut s = three_member_spec();
14465        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
14466        let err = s.validate().unwrap_err();
14467        assert!(
14468            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14469                if path == "/api/./cart" && reason.contains("`.` segment")),
14470            "got {err:?}"
14471        );
14472    }
14473
14474    #[test]
14475    fn rejects_entrada_path_with_trailing_dot_segment() {
14476        // The bare `/.` and the trailing `/foo/.` are both rejected
14477        // by the Gateway API webhook; pinned separately so a future
14478        // narrowing that catches only the inner form surfaces here.
14479        let mut s = three_member_spec();
14480        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
14481        let err = s.validate().unwrap_err();
14482        assert!(
14483            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14484                if path == "/api/." && reason.contains("`.` segment")),
14485            "got {err:?}"
14486        );
14487    }
14488
14489    #[test]
14490    fn rejects_entrada_path_with_parent_segment() {
14491        let mut s = three_member_spec();
14492        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
14493        let err = s.validate().unwrap_err();
14494        assert!(
14495            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14496                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
14497            "got {err:?}"
14498        );
14499    }
14500
14501    #[test]
14502    fn rejects_entrada_path_with_trailing_parent_segment() {
14503        // Trailing `/..` — symmetric arm of the parent-segment rule,
14504        // pinned separately so a future relaxation that only checks
14505        // the inner form (`/../`) surfaces here.
14506        let mut s = three_member_spec();
14507        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
14508        let err = s.validate().unwrap_err();
14509        assert!(
14510            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14511                if path == "/api/.." && reason.contains("`..` parent-segment")),
14512            "got {err:?}"
14513        );
14514    }
14515
14516    #[test]
14517    fn rejects_entrada_path_too_long() {
14518        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
14519        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
14520        // ASCII-alphanumeric body so only the length rule fires.
14521        let mut s = three_member_spec();
14522        let big = format!("/api/{}", "a".repeat(1020));
14523        assert_eq!(big.len(), 1025);
14524        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
14525        let err = s.validate().unwrap_err();
14526        assert!(
14527            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14528                if path == &big && reason.contains("max length of 1024")),
14529            "got {err:?}"
14530        );
14531    }
14532
14533    #[test]
14534    fn entrada_path_max_length_validates() {
14535        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
14536        // maxLength cap. Boundary pin: drift in the cap surfaces here
14537        // and at `rejects_entrada_path_too_long` simultaneously.
14538        let mut s = three_member_spec();
14539        let big = format!("/api/{}", "a".repeat(1019));
14540        assert_eq!(big.len(), 1024);
14541        s.entrada.as_mut().unwrap().paths = vec![big];
14542        s.validate().unwrap();
14543    }
14544
14545    #[test]
14546    fn entrada_accepts_canonical_paths() {
14547        // Positive-control sweep — every form the Gateway API
14548        // apiserver accepts must round-trip through validate. Covers
14549        // the root catch-all, plain paths, dot-prefixed segments
14550        // (hidden-file-style, distinct from `.` and `..` segments
14551        // which are rejected), digit-bearing segments, the canonical
14552        // route-template `:param` form (`:` is RFC 3986 reserved-set
14553        // valid in paths), trailing-slash form, percent-encoded
14554        // segments, and an interior `..` *substring* (`/foo..bar` is
14555        // not the `..` segment and is allowed).
14556        for path in [
14557            "/",
14558            "/api/cart",
14559            "/healthz",
14560            "/api/.config",
14561            "/v1/products",
14562            "/products/:id",
14563            "/api/cart/",
14564            "/api/caf%C3%A9",
14565            "/foo..bar",
14566            "/...",
14567        ] {
14568            let mut s = three_member_spec();
14569            s.entrada.as_mut().unwrap().paths = vec![path.into()];
14570            s.validate()
14571                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
14572        }
14573    }
14574
14575    #[test]
14576    fn entrada_path_empty_takes_precedence_over_invalid() {
14577        // Ordering pin: `EntradaPathEmpty` is the more self-locating
14578        // diagnostic on `""` and must lead — `validate_entrada_path`
14579        // is only reached after the empty-check fires at the call
14580        // site. (The predicate itself defends against direct
14581        // invocation by returning the same error on `""`.)
14582        let mut s = three_member_spec();
14583        s.entrada.as_mut().unwrap().paths = vec!["".into()];
14584        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14585    }
14586
14587    #[test]
14588    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
14589        // Ordering pin: a path without a leading `/` surfaces the
14590        // narrower `EntradaPathNotAbsolute` diagnostic first; the
14591        // value-shape gate is only consulted on paths that already
14592        // satisfy the absolute-prefix invariant.
14593        let mut s = three_member_spec();
14594        // `bad path` would fire the whitespace rule under the
14595        // value-shape gate, but missing-leading-`/` is the more
14596        // self-locating diagnostic.
14597        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
14598        let err = s.validate().unwrap_err();
14599        assert!(
14600            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
14601            "got {err:?}"
14602        );
14603    }
14604
14605    #[test]
14606    fn entrada_path_invalid_fires_before_duplicate_check() {
14607        // Ordering pin: a malformed path on the *first* entry of a
14608        // would-be duplicate pair fires the value-shape gate before
14609        // the duplicate gate, mirroring the
14610        // `placement_cluster_invalid_fires_before_duplicate_check`
14611        // (6cbb900) pattern on the peer axis.
14612        let mut s = three_member_spec();
14613        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
14614        let err = s.validate().unwrap_err();
14615        assert!(
14616            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
14617            "got {err:?}"
14618        );
14619    }
14620
14621    #[test]
14622    fn entrada_path_diagnostic_carries_offending_path() {
14623        // Diagnostic-shape pin — the offending path + a non-empty
14624        // reason flow through verbatim so the author can grep their
14625        // caixa.lisp for `:paths` and fix it in one edit. Same shape
14626        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
14627        let mut s = three_member_spec();
14628        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
14629        let err = s.validate().unwrap_err();
14630        match err {
14631            AplicacaoError::EntradaPathInvalid { path, reason } => {
14632                assert_eq!(path, "/api?q=1");
14633                assert!(!reason.is_empty(), "reason field must be non-empty");
14634            }
14635            other => panic!("expected EntradaPathInvalid, got {other:?}"),
14636        }
14637    }
14638
14639    #[test]
14640    fn rejects_entrada_path_with_curly_brace_template_form() {
14641        // Per-axis pin on the shared `is_gateway_api_http_path`
14642        // reserved-byte arm: the canonical "I wrote an OpenAPI
14643        // path-template `{id}` instead of the Gateway API `:id` form"
14644        // footgun the K8s apiserver would otherwise catch at admission
14645        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
14646        // landing site, far from the caixa.lisp. Surfaces as
14647        // `EntradaPathInvalid` carrying the offending path verbatim
14648        // plus the canonical `%7B`/`%7D` percent-encoding remediation
14649        // — the substrate-side `gateway_api_http_path_rejects_every_
14650        // reserved_printable_ascii_byte` predicate-level sweep pins the
14651        // full eleven-byte set; this per-axis pin confirms the
14652        // diagnostic flows through to the `EntradaPathInvalid` variant.
14653        let mut s = three_member_spec();
14654        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
14655        let err = s.validate().unwrap_err();
14656        assert!(
14657            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14658                if path == "/api/cart/{id}"
14659                    && reason.contains("reserved character")
14660                    && reason.contains("'{'")
14661                    && reason.contains("%7B")),
14662            "got {err:?}"
14663        );
14664    }
14665
14666    #[test]
14667    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
14668        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
14669        // template_form` on the sibling `:contratos :endpoint` axis.
14670        // Same shared `is_gateway_api_http_path` reserved-byte arm
14671        // fires through `ContratoEndpointInvalid`, with the offending
14672        // endpoint + `:de` + `:para` + reason flowing through verbatim.
14673        // Pins that the lifted predicate's tightening lands on both
14674        // caller axes simultaneously — one source of truth for the
14675        // Gateway API HTTPPathMatch.value accepted set.
14676        let err = contrato_endpoint_err("/api/cart/{id}");
14677        assert!(
14678            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14679                if endpoint == "/api/cart/{id}"
14680                    && reason.contains("reserved character")
14681                    && reason.contains("'{'")
14682                    && reason.contains("%7B")),
14683            "got {err:?}"
14684        );
14685    }
14686
14687    // ── :entrada :host value-shape gate ──────────────────────────────
14688    //
14689    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
14690    // the sibling `:host` axis. Every authoring footgun the K8s
14691    // Gateway API v1 apiserver would catch at admission time becomes
14692    // a caixa-build-time `EntradaHostInvalid` with the offending
14693    // `:host` named verbatim. Same diagnostic shape as
14694    // `MembroVersaoInvalid` (9888b13).
14695
14696    #[test]
14697    fn rejects_entrada_host_with_scheme() {
14698        // Fail-before-pass-after pin — pre-gate codebases silently
14699        // accepted `https://…` and the apiserver rejected it at apply
14700        // time with no source citation.
14701        let mut s = three_member_spec();
14702        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
14703        let err = s.validate().unwrap_err();
14704        assert!(
14705            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14706                if host == "https://checkout.quero.cloud"),
14707            "got {err:?}"
14708        );
14709    }
14710
14711    #[test]
14712    fn rejects_entrada_host_with_port() {
14713        // The `:8080` port suffix is the canonical "I forgot the port
14714        // belongs in `:entrada :port`" footgun. The top-level `:` arm
14715        // (introduced after the per-label loop-only impl silently
14716        // surfaced a deep "label \"cloud:8080\" contains invalid
14717        // character ':'" leak) names the canonical fix verbatim — the
14718        // `:entrada :port` slot.
14719        let mut s = three_member_spec();
14720        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
14721        let err = s.validate().unwrap_err();
14722        assert!(
14723            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14724                if host == "checkout.quero.cloud:8080"
14725                && reason.contains(":entrada :port")),
14726            "got {err:?}"
14727        );
14728    }
14729
14730    #[test]
14731    fn rejects_entrada_host_with_trailing_colon() {
14732        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
14733        // edit) — the per-label loop would land it as a deep
14734        // "label \"com:\" must start and end with an alphanumeric"
14735        // / "contains invalid character ':'" leak. The top-level
14736        // `:` arm pre-empts with the canonical `:port` slot
14737        // diagnostic.
14738        let mut s = three_member_spec();
14739        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
14740        let err = s.validate().unwrap_err();
14741        assert!(
14742            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14743                if host == "checkout.quero.cloud:"
14744                && reason.contains(":entrada :port")),
14745            "got {err:?}"
14746        );
14747    }
14748
14749    #[test]
14750    fn rejects_entrada_host_unbracketed_ipv6_literal() {
14751        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
14752        // literals across the board (peer with `rejects_entrada_host_
14753        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
14754        // Before this top-level `:` arm landed the per-label loop
14755        // surfaced a single-label byte-class diagnostic that named the
14756        // `:` byte but not the IP-literal prohibition. The top-level
14757        // `:` arm names both the `:port` slot and the IP-literal
14758        // prohibition verbatim, so an author whose `:host "2001:..."`
14759        // value lands here gets a self-locating fix either way.
14760        let mut s = three_member_spec();
14761        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
14762        let err = s.validate().unwrap_err();
14763        assert!(
14764            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14765                if host == "2001:db8::1"
14766                && reason.contains("IPv6")),
14767            "got {err:?}"
14768        );
14769    }
14770
14771    #[test]
14772    fn rejects_entrada_host_wildcard_with_port() {
14773        // Wildcard host with port suffix — the `*.` strip and the
14774        // per-label loop on `["foo", "quero", "cloud:8080"]` would
14775        // surface the deep byte-class leak. The top-level `:` arm sits
14776        // upstream of the `*.` strip, so it names the canonical `:port`
14777        // fix verbatim regardless of whether the host is wildcard-led.
14778        let mut s = three_member_spec();
14779        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
14780        let err = s.validate().unwrap_err();
14781        assert!(
14782            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14783                if host == "*.quero.cloud:8080"
14784                && reason.contains(":entrada :port")),
14785            "got {err:?}"
14786        );
14787    }
14788
14789    #[test]
14790    fn rejects_entrada_host_with_path() {
14791        let mut s = three_member_spec();
14792        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
14793        let err = s.validate().unwrap_err();
14794        assert!(
14795            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14796                if host == "checkout.quero.cloud/api"),
14797            "got {err:?}"
14798        );
14799    }
14800
14801    #[test]
14802    fn rejects_entrada_host_with_uppercase() {
14803        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
14804        // rejected, not silently lower-cased.
14805        let mut s = three_member_spec();
14806        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
14807        let err = s.validate().unwrap_err();
14808        assert!(
14809            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14810                if reason.contains("uppercase")),
14811            "got {err:?}"
14812        );
14813    }
14814
14815    #[test]
14816    fn rejects_entrada_host_with_underscore() {
14817        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
14818        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
14819        let mut s = three_member_spec();
14820        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
14821        let err = s.validate().unwrap_err();
14822        assert!(
14823            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14824                if reason.contains('_')),
14825            "got {err:?}"
14826        );
14827    }
14828
14829    #[test]
14830    fn rejects_entrada_host_ipv4_literal() {
14831        // Gateway API v1 explicitly forbids IP literals as Hostnames.
14832        let mut s = three_member_spec();
14833        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
14834        let err = s.validate().unwrap_err();
14835        assert!(
14836            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14837                if reason.contains("IPv4")),
14838            "got {err:?}"
14839        );
14840    }
14841
14842    #[test]
14843    fn rejects_entrada_host_with_trailing_dot() {
14844        // The Gateway API regex anchors at end-of-string with no
14845        // trailing `.` allowance — the FQDN root-dot form is rejected.
14846        let mut s = three_member_spec();
14847        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
14848        let err = s.validate().unwrap_err();
14849        assert!(
14850            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14851                if host == "checkout.quero.cloud."),
14852            "got {err:?}"
14853        );
14854    }
14855
14856    #[test]
14857    fn rejects_entrada_host_with_leading_dot() {
14858        let mut s = three_member_spec();
14859        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
14860        let err = s.validate().unwrap_err();
14861        assert!(
14862            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14863                if reason.contains("empty label")),
14864            "got {err:?}"
14865        );
14866    }
14867
14868    #[test]
14869    fn rejects_entrada_host_with_consecutive_dots() {
14870        let mut s = three_member_spec();
14871        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
14872        let err = s.validate().unwrap_err();
14873        assert!(
14874            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14875                if reason.contains("empty label")),
14876            "got {err:?}"
14877        );
14878    }
14879
14880    #[test]
14881    fn rejects_entrada_host_with_leading_hyphen_label() {
14882        let mut s = three_member_spec();
14883        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
14884        let err = s.validate().unwrap_err();
14885        assert!(
14886            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14887                if reason.contains("alphanumeric")),
14888            "got {err:?}"
14889        );
14890    }
14891
14892    #[test]
14893    fn rejects_entrada_host_with_trailing_hyphen_label() {
14894        let mut s = three_member_spec();
14895        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
14896        let err = s.validate().unwrap_err();
14897        assert!(
14898            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14899                if reason.contains("alphanumeric")),
14900            "got {err:?}"
14901        );
14902    }
14903
14904    #[test]
14905    fn rejects_entrada_host_with_inner_wildcard() {
14906        // Gateway API allows `*` only as the first label (`*.foo`);
14907        // any inner or trailing `*` is rejected.
14908        let mut s = three_member_spec();
14909        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
14910        let err = s.validate().unwrap_err();
14911        assert!(
14912            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14913                if reason.contains("wildcard")),
14914            "got {err:?}"
14915        );
14916    }
14917
14918    #[test]
14919    fn rejects_entrada_host_bare_wildcard() {
14920        // `*.` with no domain is meaningless; Gateway API rejects it.
14921        let mut s = three_member_spec();
14922        s.entrada.as_mut().unwrap().host = "*.".into();
14923        let err = s.validate().unwrap_err();
14924        assert!(
14925            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14926                if reason.contains("wildcard")),
14927            "got {err:?}"
14928        );
14929    }
14930
14931    #[test]
14932    fn rejects_entrada_host_with_whitespace() {
14933        let mut s = three_member_spec();
14934        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
14935        let err = s.validate().unwrap_err();
14936        assert!(
14937            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
14938                if reason.contains("whitespace")),
14939            "got {err:?}"
14940        );
14941    }
14942
14943    #[test]
14944    fn rejects_entrada_host_space_names_offending_byte() {
14945        // Embedded space in the `:entrada :host` axis surfaces the
14946        // byte-naming diagnostic through the lifted
14947        // `find_ascii_whitespace_byte` predicate. Peer with the
14948        // sibling `parse_rejects_leading_whitespace` pins on
14949        // `supervisor::duration_codec` (a7ae622) — same "the
14950        // diagnostic carries the offending byte's `0x{b:02x}` shape"
14951        // discipline extended from the shared duration codec to the
14952        // Gateway API v1 Hostname axis.
14953        let mut s = three_member_spec();
14954        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
14955        let err = s.validate().unwrap_err();
14956        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14957            panic!("expected EntradaHostInvalid, got {err:?}");
14958        };
14959        assert!(
14960            reason.contains("ASCII whitespace byte"),
14961            "expected byte-naming diagnostic, got {reason:?}"
14962        );
14963        assert!(
14964            reason.contains("0x20"),
14965            "expected offending space byte 0x20, got {reason:?}"
14966        );
14967    }
14968
14969    #[test]
14970    fn rejects_entrada_host_tab_names_offending_byte() {
14971        // Embedded tab byte in the `:entrada :host` axis — the
14972        // canonical paste-from-YAML-block-scalar / paste-from-
14973        // indented-doc footgun. Pins that the lifted predicate covers
14974        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
14975        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
14976        // not just the leading-space case the pre-lift `.bytes().any`
14977        // arm's opaque "must not contain whitespace" reason already
14978        // covered. Peer with `parse_rejects_tab_byte` on
14979        // `supervisor::duration_codec` (a7ae622).
14980        let mut s = three_member_spec();
14981        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
14982        let err = s.validate().unwrap_err();
14983        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
14984            panic!("expected EntradaHostInvalid, got {err:?}");
14985        };
14986        assert!(
14987            reason.contains("ASCII whitespace byte"),
14988            "expected byte-naming diagnostic, got {reason:?}"
14989        );
14990        assert!(
14991            reason.contains("0x09"),
14992            "expected offending tab byte 0x09, got {reason:?}"
14993        );
14994    }
14995
14996    #[test]
14997    fn rejects_entrada_host_lf_names_offending_byte() {
14998        // Embedded LF byte in the `:entrada :host` axis — the
14999        // canonical paste-from-shell-heredoc / paste-from-multiline-
15000        // doc footgun the caixa-mesh YAML emitter would silently
15001        // reinterpret at the Gateway API v1 HTTPRoute admission
15002        // layer (an embedded LF byte in a YAML plain scalar either
15003        // truncates the value at the emitter or crashes the parser
15004        // on the k8s-apiserver side). Pins the third representative
15005        // of the full ASCII-whitespace set through the shared
15006        // predicate.
15007        let mut s = three_member_spec();
15008        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
15009        let err = s.validate().unwrap_err();
15010        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15011            panic!("expected EntradaHostInvalid, got {err:?}");
15012        };
15013        assert!(
15014            reason.contains("ASCII whitespace byte"),
15015            "expected byte-naming diagnostic, got {reason:?}"
15016        );
15017        assert!(
15018            reason.contains("0x0a"),
15019            "expected offending LF byte 0x0a, got {reason:?}"
15020        );
15021    }
15022
15023    #[test]
15024    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
15025        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
15026        // axis — the canonical paste-from-typography /
15027        // paste-from-word-processor footgun. Before the non-ASCII
15028        // Unicode `White_Space` scan lifted through the shared
15029        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
15030        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
15031        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
15032        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
15033        // with the far-from-source `label "…" must start and end
15034        // with an alphanumeric` diagnostic — burying the
15035        // paste-from-typography origin under a label-shape leak.
15036        // Peer with the sibling non-ASCII-whitespace pins at
15037        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
15038        // — 1b75b38), `limits::parse_duration`,
15039        // `limits::parse_millicores`, and the shared duration codec
15040        // — same "the diagnostic carries the offending Unicode
15041        // codepoint's `U+XXXX` shape" discipline extended from every
15042        // typed-magnitude codec to the Gateway API v1 Hostname axis.
15043        let mut s = three_member_spec();
15044        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
15045        let err = s.validate().unwrap_err();
15046        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15047            panic!("expected EntradaHostInvalid, got {err:?}");
15048        };
15049        assert!(
15050            reason.contains("non-ASCII Unicode whitespace character"),
15051            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15052        );
15053        assert!(
15054            reason.contains("U+00A0"),
15055            "expected offending NBSP codepoint U+00A0, got {reason:?}"
15056        );
15057    }
15058
15059    #[test]
15060    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
15061        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
15062        // `:entrada :host` axis — the canonical paste-from-web-doc /
15063        // paste-from-published-HTML footgun. `char::is_whitespace`
15064        // returns true for `U+2028` per the Unicode `White_Space`
15065        // property, so `str::trim` at any downstream site would
15066        // silently strip it — same drift class as NBSP but on a
15067        // different codepoint region. Pins the second representative
15068        // (non-Latin-1 `char::is_whitespace` member) through the
15069        // shared predicate. Peer with
15070        // `parse_byte_size_rejects_internal_line_separator` on
15071        // `limits::parse_byte_size` (1b75b38).
15072        let mut s = three_member_spec();
15073        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
15074        let err = s.validate().unwrap_err();
15075        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15076            panic!("expected EntradaHostInvalid, got {err:?}");
15077        };
15078        assert!(
15079            reason.contains("non-ASCII Unicode whitespace character"),
15080            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15081        );
15082        assert!(
15083            reason.contains("U+2028"),
15084            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
15085        );
15086    }
15087
15088    #[test]
15089    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
15090        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
15091        // labels in the `:entrada :host` axis — the canonical
15092        // paste-from-CJK-typography footgun (CJK IMEs default to
15093        // full-width whitespace when the space bar is pressed in
15094        // Japanese / Chinese input modes). Pins the third
15095        // representative of the non-ASCII Unicode `White_Space` set
15096        // through the shared predicate: the CJK block, distinct from
15097        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
15098        // SEPARATOR `U+2028` — covering the same axis breadth the
15099        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
15100        // (1b75b38) pins on `limits::parse_byte_size`.
15101        let mut s = three_member_spec();
15102        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
15103        let err = s.validate().unwrap_err();
15104        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15105            panic!("expected EntradaHostInvalid, got {err:?}");
15106        };
15107        assert!(
15108            reason.contains("non-ASCII Unicode whitespace character"),
15109            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15110        );
15111        assert!(
15112            reason.contains("U+3000"),
15113            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
15114        );
15115    }
15116
15117    #[test]
15118    fn rejects_entrada_host_too_long() {
15119        // Total length cap = 253; build a 254-byte host out of two
15120        // 63-byte labels + one 62-byte label + dots.
15121        let mut s = three_member_spec();
15122        let big = format!(
15123            "{}.{}.{}.{}",
15124            "a".repeat(63),
15125            "b".repeat(63),
15126            "c".repeat(63),
15127            "d".repeat(254 - 63 * 3 - 3)
15128        );
15129        assert_eq!(big.len(), 254);
15130        s.entrada.as_mut().unwrap().host = big;
15131        let err = s.validate().unwrap_err();
15132        assert!(
15133            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15134                if reason.contains("max length of 253")),
15135            "got {err:?}"
15136        );
15137    }
15138
15139    #[test]
15140    fn rejects_entrada_host_label_too_long() {
15141        let mut s = three_member_spec();
15142        // 64-byte label — one over the per-label cap.
15143        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
15144        let err = s.validate().unwrap_err();
15145        assert!(
15146            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15147                if reason.contains("label max length of 63")),
15148            "got {err:?}"
15149        );
15150    }
15151
15152    #[test]
15153    fn entrada_host_diagnostic_carries_offending_host() {
15154        // Diagnostic-shape pin — the offending host + a non-empty
15155        // reason flow through verbatim so the author can grep their
15156        // caixa.lisp for `:host "<host>"` and fix it in one edit.
15157        let mut s = three_member_spec();
15158        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
15159        let err = s.validate().unwrap_err();
15160        match err {
15161            AplicacaoError::EntradaHostInvalid { host, reason } => {
15162                assert_eq!(host, "checkout.quero.cloud:8080");
15163                assert!(!reason.is_empty(), "reason field must be non-empty");
15164            }
15165            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15166        }
15167    }
15168
15169    #[test]
15170    fn entrada_host_empty_takes_precedence_over_invalid() {
15171        // Ordering pin: `EmptyEntradaHost` is the more self-locating
15172        // diagnostic on `""` and must lead — `validate_entrada_host`
15173        // is only reached after the empty-check fires at the call
15174        // site. (The predicate itself defends against direct
15175        // invocation by returning the same error on `""`.)
15176        let mut s = three_member_spec();
15177        s.entrada.as_mut().unwrap().host = String::new();
15178        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
15179    }
15180
15181    #[test]
15182    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
15183        // Ordering pin: a missing :para member is the more
15184        // self-locating diagnostic and fires before the host gate.
15185        let mut s = three_member_spec();
15186        let e = s.entrada.as_mut().unwrap();
15187        e.para = "ghost".into();
15188        e.host = "BAD HOST".into();
15189        let err = s.validate().unwrap_err();
15190        assert!(
15191            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
15192            "got {err:?}"
15193        );
15194    }
15195
15196    #[test]
15197    fn entrada_host_invalid_fires_before_port_zero() {
15198        // Ordering pin: the host gate fires before the port gate so
15199        // a malformed host is named even when the port is also wrong.
15200        let mut s = three_member_spec();
15201        let e = s.entrada.as_mut().unwrap();
15202        e.host = "Checkout.quero.cloud".into();
15203        e.port = 0;
15204        let err = s.validate().unwrap_err();
15205        assert!(
15206            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15207                if host == "Checkout.quero.cloud"),
15208            "got {err:?}"
15209        );
15210    }
15211
15212    #[test]
15213    fn entrada_accepts_canonical_hosts() {
15214        // Positive-control sweep — every form the Gateway API
15215        // apiserver accepts must round-trip through validate. Covers
15216        // a plain DNS subdomain, a leading wildcard, a single-label
15217        // host (cluster-internal), a max-length-edge label, a
15218        // hyphen-bearing label, and a Punycode IDN label.
15219        for host in [
15220            "checkout.quero.cloud",
15221            "*.quero.cloud",
15222            "checkout",
15223            // 63-byte label — exactly the per-label cap.
15224            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
15225            "foo-bar.quero.cloud",
15226            // Punycode IDN — valid because the author pre-encoded.
15227            "xn--bcher-kva.example.com",
15228        ] {
15229            let mut s = three_member_spec();
15230            s.entrada.as_mut().unwrap().host = host.into();
15231            s.validate()
15232                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
15233        }
15234    }
15235
15236    #[test]
15237    fn entrada_host_max_length_validates() {
15238        // 253-byte host is the cap exactly — must validate. Build a
15239        // 253-byte host out of three 63-byte labels + one 61-byte
15240        // label + 3 dots = 252 bytes, then pad one byte to 253.
15241        let mut s = three_member_spec();
15242        let host = format!(
15243            "{}.{}.{}.{}",
15244            "a".repeat(63),
15245            "b".repeat(63),
15246            "c".repeat(63),
15247            "d".repeat(253 - 63 * 3 - 3)
15248        );
15249        assert_eq!(host.len(), 253);
15250        s.entrada.as_mut().unwrap().host = host;
15251        s.validate().unwrap();
15252    }
15253
15254    #[test]
15255    fn entrada_host_total_length_cap_threads_lifted_render_const() {
15256        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
15257        // total-length gate now reads the K8s Gateway API v1 Hostname
15258        // `maxLength: 253` cap from the lifted
15259        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
15260        // of truth — the same constant every future Gateway-API-Hostname
15261        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
15262        // materializer's per-host validator, the future per-`Certificate`
15263        // SAN emitter for cert-manager, the multi-`:entrada`
15264        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
15265        // from. Before the lift, the aplicacao-side reader consumed a
15266        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
15267        // 253-byte value as the peer render-side canonical bounds
15268        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
15269        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
15270        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
15271        // module boundary — a future 253-byte drift on either side would
15272        // silently split into two axes' worth of admission-schema mismatch
15273        // without a build-time signal. Pin the cap through a fresh 254-
15274        // byte host that hits the total-length arm, then read the reason
15275        // for the exact byte count the shared constant carries: any future
15276        // regression on the lift (a private alias reintroduced, a hard-
15277        // coded literal at the arm, a mismatch between the aplicacao-side
15278        // and render-side canonicals) surfaces as this pin's diagnostic
15279        // failing to match, not as a per-cluster admission rejection far
15280        // from the caixa.lisp source line.
15281        let mut s = three_member_spec();
15282        let over_cap = format!(
15283            "{}.{}.{}.{}",
15284            "a".repeat(63),
15285            "b".repeat(63),
15286            "c".repeat(63),
15287            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
15288        );
15289        assert_eq!(
15290            over_cap.len(),
15291            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
15292        );
15293        s.entrada.as_mut().unwrap().host = over_cap;
15294        let err = s.validate().unwrap_err();
15295        match err {
15296            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15297                let needle = format!(
15298                    "max length of {} bytes",
15299                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
15300                );
15301                assert!(
15302                    reason.contains(&needle),
15303                    "diagnostic must name the lifted \
15304                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
15305                );
15306            }
15307            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15308        }
15309    }
15310
15311    #[test]
15312    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
15313        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
15314        // on the per-label-cap axis. Before the lift, the aplicacao-side
15315        // per-label arm consumed a private const alias
15316        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
15317        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
15318        // split from it at the module boundary — every `.`-separated
15319        // label in a Gateway API v1 Hostname is a DNS-1123 label under
15320        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
15321        // so the private alias's 63 and the canonical const's 63 were
15322        // pinning the same underlying rule twice. Pin the cap through a
15323        // 64-byte label that hits the per-label arm, then read the reason
15324        // for the exact byte count the shared constant carries: any
15325        // future drift on either side (a private alias reintroduced, a
15326        // hard-coded literal at the arm, a mismatch between the two
15327        // 63-byte pins) surfaces at this pin's diagnostic rather than at
15328        // a per-cluster admission rejection whose "field is invalid"
15329        // opacity misframes the root cause.
15330        let mut s = three_member_spec();
15331        let over_cap_label = format!(
15332            "{}.quero.cloud",
15333            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
15334        );
15335        s.entrada.as_mut().unwrap().host = over_cap_label;
15336        let err = s.validate().unwrap_err();
15337        match err {
15338            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15339                let needle = format!(
15340                    "label max length of {} bytes",
15341                    crate::render::DNS_1123_LABEL_MAX_LEN,
15342                );
15343                assert!(
15344                    reason.contains(&needle),
15345                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
15346                     cap verbatim on the per-label arm, got: {reason:?}",
15347                );
15348            }
15349            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15350        }
15351    }
15352
15353    #[test]
15354    fn entrada_with_empty_paths_validates() {
15355        // Empty `:paths` is the documented "match every path" form;
15356        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
15357        let mut s = three_member_spec();
15358        s.entrada.as_mut().unwrap().paths = vec![];
15359        s.validate().unwrap();
15360    }
15361
15362    #[test]
15363    fn entrada_root_path_validates() {
15364        // The author-supplied bare-root `:entrada :paths` entry is the
15365        // same byte-shape the peer emit-side catch-all constant
15366        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
15367        // the author's `:paths` list is empty — sweeping the test-side
15368        // probe literal onto the lifted const closes the two-axis pin
15369        // (author-side admit + emit-side canonical fallback) around
15370        // one `&'static str`, so a future rebrand of the catch-all
15371        // reaches both consumers by construction. Peer to
15372        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
15373        // on the canonical-literal pin surface.
15374        let mut s = three_member_spec();
15375        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
15376        s.validate().unwrap();
15377    }
15378
15379    #[test]
15380    fn placement_strategy_variants_round_trip() {
15381        for s in [
15382            PlacementStrategy::SingleNode,
15383            PlacementStrategy::Replicated,
15384            PlacementStrategy::Sharded,
15385        ] {
15386            let p = Placement {
15387                estrategia: s,
15388                clusters: vec!["rio".into()],
15389                affinity: None,
15390                // Route the paired `:shard-key` fixture-builder through the
15391                // typed cross-slot invariant predicate
15392                // [`PlacementStrategy::requires_shard_key`] rather than the
15393                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
15394                // arm-identity predicate — the two answer the same
15395                // question under today's closed accept-set but a future
15396                // arm addition that consumed `:shard-key` under a
15397                // non-`Sharded` name would silently mis-attach the
15398                // fixture's `:shard-key` if the builder read through the
15399                // arm-identity predicate. The cross-slot-invariant
15400                // predicate migrates through one caixa-core edit on any
15401                // future arm addition; the fixture keeps producing a
15402                // `validate()`-passing round-trip by construction.
15403                shard_key: if s.requires_shard_key() {
15404                    Some("$key".into())
15405                } else {
15406                    None
15407                },
15408            };
15409            let json = serde_json::to_string(&p).unwrap();
15410            let back: Placement = serde_json::from_str(&json).unwrap();
15411            assert_eq!(back, p);
15412        }
15413    }
15414
15415    #[test]
15416    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
15417        // The fail-before-pass-after pin: pre-lift there was no
15418        // single-source binding between the [`PlacementStrategy`]
15419        // variant name the `Serialize` derive emits and the byte-
15420        // string every downstream cluster-side dispatcher (the
15421        // `lareira-fleet-programs` aggregator's per-entry strategy
15422        // branch, the future `app-operator` reconciler, the M3
15423        // Adaptive compression pass's per-strategy weighting) probes
15424        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
15425        // future `#[serde(rename_all = "kebab-case")]` attribute on
15426        // the enum — or a variant rename in the source — would
15427        // silently rebrand the emitted scalar under one spelling
15428        // while every downstream dispatcher still probed the other,
15429        // with the failure surfacing at the aggregator's dispatch
15430        // step or the operator's reconcile posture (workloads coming
15431        // up under the `default()` `Replicated` arm rather than the
15432        // typed slot's declared strategy) far from the source
15433        // rebrand commit and with no field naming the drift. Pinning
15434        // the two paths (the `Serialize` derive's serialized string
15435        // AND the [`PlacementStrategy::as_str`] helper) to the same
15436        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
15437        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15438        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
15439        // makes any future drift on either endpoint fail here at
15440        // caixa-core build time.
15441        for (variant, expected) in [
15442            (
15443                PlacementStrategy::SingleNode,
15444                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15445            ),
15446            (
15447                PlacementStrategy::Replicated,
15448                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15449            ),
15450            (
15451                PlacementStrategy::Sharded,
15452                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15453            ),
15454        ] {
15455            let json = serde_json::to_string(&variant).unwrap();
15456            assert_eq!(
15457                json,
15458                format!("\"{expected}\""),
15459                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
15460            );
15461            assert_eq!(
15462                variant.as_str(),
15463                expected,
15464                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
15465                 M3_PLACEMENT_ESTRATEGIA_* constant"
15466            );
15467        }
15468    }
15469
15470    #[test]
15471    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
15472        // Cross-arm drift-detection pin on the M3
15473        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
15474        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15475        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
15476        // scalar-value pentad: a future collapse of two canonical
15477        // variant byte-strings onto the same value (an accidental
15478        // copy-paste flip of
15479        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
15480        // read `"SingleNode"`, a per-arm rebrand that lands one const
15481        // without touching its paired peer) would silently reroute
15482        // every downstream operator's per-strategy dispatch onto the
15483        // sibling arm's reconcile branch and pass every
15484        // propagation-probe test that expected only the stale arm's
15485        // value — a `Replicated`-declared Aplicacao would come up
15486        // under the `SingleNode` primary-and-standby reconcile
15487        // posture, so every-cluster active-active workload would
15488        // silently collapse onto one-cluster-runs-at-a-time takeover
15489        // semantics against its declared strategy, with no field
15490        // naming the strategy-value drift root cause. Peer of the
15491        // sibling
15492        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
15493        // (09ffb2d) /
15494        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
15495        // (ccdf955) /
15496        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
15497        // (d739850) distinctness pins on the sibling OTP-shape /
15498        // caixa-kind closed-set typed-enum discriminator axes — the
15499        // fourth (and structurally the M3 mesh-primitive-defining)
15500        // closed-set typed-enum axis to converge on the same
15501        // "pairwise-distinct-by-construction" discipline.
15502        //
15503        // Fail-before-pass-after locally verified by mutating
15504        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
15505        // also read `"SingleNode"` — this pin fires as expected;
15506        // restoring passes.
15507        let all = [
15508            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15509            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15510            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15511        ];
15512        for (i, a) in all.iter().enumerate() {
15513            for (j, b) in all.iter().enumerate() {
15514                if i != j {
15515                    assert_ne!(
15516                        a, b,
15517                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
15518                         distinct — got duplicate {a:?} at indices {i} and {j}",
15519                    );
15520                }
15521            }
15522        }
15523    }
15524
15525    #[test]
15526    fn placement_strategy_display_routes_through_as_str_helper() {
15527        // The fail-before-pass-after pin: pre-lift the sibling
15528        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
15529        // / [`crate::supervisor::RestartPolicy`] both carried a stable
15530        // [`std::fmt::Display`] surface via their
15531        // `#[discriminant(also_display)]` gen-platform derive, but
15532        // [`PlacementStrategy`] did not — every consumer reaching for
15533        // a strategy byte-string past the wire format had to pick
15534        // between three paths ([`PlacementStrategy::as_str`], the
15535        // `Serialize` derive's serialized string, or `format!("{v:?}")`
15536        // on the `Debug` derive), any two of which a future variant
15537        // rename or `#[serde(rename_all = "kebab-case")]` attribute
15538        // would silently desynchronize. Wiring [`std::fmt::Display`]
15539        // through [`PlacementStrategy::as_str`] closes the third path:
15540        // every `format!("{v}")` call reaches the same lifted
15541        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
15542        // and the [`PlacementStrategy::as_str`] helper already route
15543        // through, so a future variant rename lands at exactly one
15544        // place. Pin the routing here so a future
15545        // `impl std::fmt::Display for PlacementStrategy` reimplementation
15546        // that hand-rolls the arms instead of delegating to
15547        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
15548        for variant in [
15549            PlacementStrategy::SingleNode,
15550            PlacementStrategy::Replicated,
15551            PlacementStrategy::Sharded,
15552        ] {
15553            assert_eq!(
15554                variant.to_string(),
15555                variant.as_str(),
15556                "PlacementStrategy::{variant:?} Display must route through \
15557                 PlacementStrategy::as_str (single source of truth: the lifted \
15558                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
15559            );
15560        }
15561    }
15562
15563    #[test]
15564    fn placement_strategy_display_matches_serialized_wire_byte_string() {
15565        // The fail-before-pass-after pin on the second half of the
15566        // three-path convergence: `Display` (user-facing text) agrees
15567        // byte-for-byte with the `Serialize` derive's wire format
15568        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
15569        // scalar) on every variant. Pre-lift the two paths were
15570        // structurally independent — a future
15571        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
15572        // would silently rebrand the emitted wire scalar
15573        // (`single-node`, `replicated`, `sharded`) while every consumer
15574        // that pretty-prints the strategy (the M3 diagnostic templates,
15575        // the future `feira app graph` per-Aplicacao strategy line,
15576        // the future M4 CR materializer's admission-webhook rejection
15577        // body) would still emit the TitleCase form the `as_str` /
15578        // `Display` route returns, with the mismatch surfacing at
15579        // consumer parse time / operator dispatch time far from the
15580        // source rebrand commit. Pin the two paths byte-for-byte here
15581        // so any future serde-attribute or variant-rename drift is a
15582        // caixa-core-build-time test failure at this call, not a
15583        // silent per-consumer dispatch miss.
15584        for variant in [
15585            PlacementStrategy::SingleNode,
15586            PlacementStrategy::Replicated,
15587            PlacementStrategy::Sharded,
15588        ] {
15589            let wire = serde_json::to_string(&variant).unwrap();
15590            // Strip the outer `"…"` the JSON string form carries — the
15591            // wire scalar the K8s / YAML apiserver consumes is the
15592            // enclosed byte-string, not the quote wrapper.
15593            let unquoted = wire
15594                .strip_prefix('"')
15595                .and_then(|s| s.strip_suffix('"'))
15596                .expect("serialized PlacementStrategy is a JSON string");
15597            assert_eq!(
15598                variant.to_string(),
15599                unquoted,
15600                "PlacementStrategy::{variant:?} Display byte-string must match the \
15601                 Serialize derive's wire byte-string (three-path convergence: \
15602                 Display + as_str + Serialize all resolve to the same \
15603                 M3_PLACEMENT_ESTRATEGIA_* const)"
15604            );
15605        }
15606    }
15607
15608    #[test]
15609    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
15610        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
15611        // derive on [`PlacementStrategy`]: for each of the three variants
15612        // exactly one of the generated `is_single_node` / `is_replicated`
15613        // / `is_sharded` predicates returns `true` and the other two
15614        // return `false`. Prior to this derive the three per-arm
15615        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
15616        // (the `placement_strategy_variants_round_trip` fixture, the
15617        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
15618        // fixture, and the
15619        // `validate_placement_reads_through_lifted_estrategia_accessor`
15620        // fixture) each open-coded a per-arm PartialEq compare against
15621        // the enum variant — three sites that expressed no compile-time
15622        // link back to the closed-set typed dispatch a future fourth
15623        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
15624        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
15625        // would have to thread through in lockstep or one fixture would
15626        // silently disagree with the others on which arms consume the
15627        // `:shard-key` axis. Peer of the sibling
15628        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
15629        // / [`crate::supervisor::RestartPolicy`] /
15630        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
15631        // the sibling closed-set typed-enum discriminator axes — extends
15632        // the same one-typed-dispatch-per-variant discipline onto the
15633        // fifth (and only remaining) closed-set typed-enum discriminator
15634        // on the caixa surface, closing the axis on the M3 mesh-slot
15635        // family.
15636        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
15637            (PlacementStrategy::SingleNode, [true, false, false]),
15638            (PlacementStrategy::Replicated, [false, true, false]),
15639            (PlacementStrategy::Sharded, [false, false, true]),
15640        ];
15641        for (variant, expected) in rows {
15642            let observed = [
15643                variant.is_single_node(),
15644                variant.is_replicated(),
15645                variant.is_sharded(),
15646            ];
15647            assert_eq!(
15648                observed, expected,
15649                "PlacementStrategy::{variant:?} is_* predicates must partition \
15650                 the arm set (single_node, replicated, sharded); got {observed:?}"
15651            );
15652        }
15653    }
15654
15655    #[test]
15656    fn placement_strategy_is_variant_predicates_are_const_fn() {
15657        // The [`gen_platform::IsVariant`] derive emits `const fn`
15658        // predicates on the peer [`crate::CaixaKind`] +
15659        // [`crate::upgrade::UpgradeInstruction`] +
15660        // [`crate::supervisor::RestartStrategy`] +
15661        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
15662        // pin the same posture on [`PlacementStrategy`] so a future
15663        // accidental downgrade to non-`const` (an added runtime helper
15664        // reachable only from a non-`const` context, a manual hand-rolled
15665        // `impl` that shadows the derive-generated method) trips at
15666        // caixa-core build time rather than surfacing as a downstream
15667        // `const`-context regression far from the derive declaration.
15668        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
15669        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
15670        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
15671        assert!(IS_SINGLE_NODE);
15672        assert!(IS_REPLICATED);
15673        assert!(IS_SHARDED);
15674    }
15675
15676    #[test]
15677    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
15678        // Fail-before-pass-after pin on the substrate-lifted
15679        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
15680        // per-arm predicate: for each variant in the closed accept-set the
15681        // predicate returns `true` iff the variant consumes the paired
15682        // [`Placement::shard_key`] axis under
15683        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
15684        // partition. Today the accept-set is the singleton `{Sharded}` —
15685        // `Sharded` is the Akka-style hash-keyed distribution arm
15686        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
15687        // §II.1) and `Replicated` (active-active) refuse the axis through
15688        // [`AplicacaoError::ShardKeyOnNonSharded`].
15689        //
15690        // Pins the per-arm truth-table so a future arm addition (an
15691        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
15692        // roadmap names, a `WeightedShard` promotion the future M5
15693        // adaptive-placement engine acknowledges) that landed a variant
15694        // without extending this predicate's arm-set would surface as a
15695        // caixa-core build-time exhaustiveness error at the
15696        // `match self { … }` arm-fan below rather than a silent per-consumer
15697        // mis-classification at renderer emit time. The paired
15698        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
15699        // predicate stays a distinct question — arm-identity (which the
15700        // sibling
15701        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
15702        // pin already locks) is not cross-slot-invariant consumption; today
15703        // they trip on the same singleton but the pair migrates through
15704        // one caixa-core edit on any future arm addition.
15705        //
15706        // Peer of the sibling per-arm classifier pins
15707        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
15708        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
15709        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
15710        // derived paired predicate on the post-projection typed-view axis
15711        // — same "per-arm semantic-classification predicate paired with
15712        // the arm-identity predicate the derive already emits" discipline
15713        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
15714        // `:placement :shard-key` cross-slot-invariant axis.
15715        let rows: [(PlacementStrategy, bool); 3] = [
15716            (PlacementStrategy::SingleNode, false),
15717            (PlacementStrategy::Replicated, false),
15718            (PlacementStrategy::Sharded, true),
15719        ];
15720        for (variant, expected) in rows {
15721            assert_eq!(
15722                variant.requires_shard_key(),
15723                expected,
15724                "PlacementStrategy::{variant:?}.requires_shard_key() must \
15725                 be {expected} (the substrate-canonical cross-slot invariant \
15726                 on the :placement :shard-key axis; today `Sharded` is the \
15727                 singleton consuming arm — MESH-COMPOSITION §II.4)",
15728            );
15729        }
15730    }
15731
15732    #[test]
15733    fn placement_strategy_requires_shard_key_is_const_fn() {
15734        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
15735        // invariant per-arm predicate is declared `#[must_use] pub const
15736        // fn` — pin the `const`-eval posture here so a future accidental
15737        // downgrade to non-`const` (an added runtime helper reachable
15738        // only from a non-`const` context, a manual hand-rolled `impl`
15739        // that shadows the current three-arm `match self { … }` dispatch)
15740        // trips at caixa-core build time rather than surfacing as a
15741        // downstream `const`-context regression far from the declaration.
15742        // Same shape as the sibling
15743        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
15744        // the peer [`gen_platform::IsVariant`]-derived arm-identity
15745        // predicate axis, but here the load-bearing assertions live in
15746        // module-scope `const _: () = assert!(…)` items so a violation
15747        // fails at compile time (const-eval trip) rather than test time —
15748        // strictly stronger than the runtime `assert!(CONST)` pattern the
15749        // sibling pin uses, and side-steps the
15750        // `clippy::assertions_on_constants` lint the runtime pattern
15751        // otherwise accumulates on the module baseline.
15752        //
15753        // The test body simply witnesses that the module-scope items
15754        // compiled and the runtime dispatch agrees with the const-eval
15755        // dispatch on every arm — the runtime read gives the test a
15756        // failure surface (rather than an empty test body clippy would
15757        // flag as a no-op).
15758        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
15759        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
15760        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
15761        assert_eq!(
15762            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
15763            [
15764                PlacementStrategy::SingleNode.requires_shard_key(),
15765                PlacementStrategy::Replicated.requires_shard_key(),
15766                PlacementStrategy::Sharded.requires_shard_key(),
15767            ],
15768            "runtime and const-eval dispatch on \
15769             PlacementStrategy::requires_shard_key must agree on every arm",
15770        );
15771    }
15772
15773    #[test]
15774    fn placement_estrategia_accessor_is_const_fn() {
15775        // The [`Placement::estrategia`] per-`:placement` distribution-
15776        // strategy `Copy`-return scalar accessor is declared
15777        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
15778        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
15779        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
15780        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
15781        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
15782        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
15783        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
15784        // [`RateLimit`], every one a `pub const fn`). Pin the
15785        // `const`-eval posture here so a future accidental downgrade to
15786        // non-`const` (an added runtime helper reachable only from a
15787        // non-`const` context, a slot promotion to a non-`Copy` return
15788        // that would silently drop the `const` qualifier, a manual
15789        // hand-rolled shadow) trips at caixa-core build time rather
15790        // than surfacing as a downstream `const`-context regression far
15791        // from the declaration.
15792        //
15793        // Same shape as the sibling
15794        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
15795        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
15796        // predicate axis — the load-bearing witness lives in the
15797        // module-scope `const fn` wrapper `estrategia_via_const_fn`
15798        // below: a body that calls [`Placement::estrategia`] under a
15799        // `const fn` signature is well-formed only when the callee is
15800        // itself `const fn`, so any future accidental downgrade of
15801        // [`Placement::estrategia`] to non-`const` fails at caixa-core
15802        // build time (const-eval E0015 / E0658 depending on the arm),
15803        // strictly stronger than a runtime `assert!(CONST)` and
15804        // side-stepping the destructor-in-const restriction that
15805        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
15806        // items on `Placement`'s `Vec<String>` / `Option<String>`
15807        // carriers.
15808        //
15809        // The runtime body witnesses that the const-eval-shaped
15810        // wrapper agrees with a direct call on every closed-set arm.
15811        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
15812            p.estrategia()
15813        }
15814        for estrategia in [
15815            PlacementStrategy::SingleNode,
15816            PlacementStrategy::Replicated,
15817            PlacementStrategy::Sharded,
15818        ] {
15819            let placement = Placement {
15820                estrategia,
15821                clusters: Vec::new(),
15822                affinity: None,
15823                shard_key: None,
15824            };
15825            assert_eq!(
15826                estrategia_via_const_fn(&placement),
15827                placement.estrategia(),
15828                "const-fn-wrapped and direct dispatch on \
15829                 Placement::estrategia must agree for {estrategia:?}",
15830            );
15831        }
15832    }
15833
15834    #[test]
15835    fn entrada_port_accessor_is_const_fn() {
15836        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
15837        // scalar accessor is declared `#[must_use] pub const fn` —
15838        // matching the peer M3 mesh-slot `Copy`-return accessor family
15839        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
15840        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
15841        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
15842        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
15843        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
15844        // [`RateLimit::window`] on the sibling [`RateLimit`], the
15845        // sibling per-`:placement` [`Placement::estrategia`] pinned by
15846        // [`placement_estrategia_accessor_is_const_fn`] above — every
15847        // one a `pub const fn`). Pin the `const`-eval posture here so
15848        // a future accidental downgrade to non-`const` (an added
15849        // runtime helper reachable only from a non-`const` context, an
15850        // `Option<u16>`-shape migration once the substrate grows
15851        // per-`:membros` heterogeneous listener ports that would
15852        // silently drop the `const` qualifier, a manual hand-rolled
15853        // shadow) trips at caixa-core build time rather than surfacing
15854        // as a downstream `const`-context regression far from the
15855        // declaration.
15856        //
15857        // Same shape as the sibling
15858        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
15859        // load-bearing witness lives in the module-scope `const fn`
15860        // wrapper `port_via_const_fn`: a body that calls
15861        // [`Entrada::port`] under a `const fn` signature is well-formed
15862        // only when the callee is itself `const fn`, side-stepping the
15863        // destructor-in-const restriction that would otherwise block a
15864        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
15865        // `String` / `Vec<String>` carriers.
15866        //
15867        // The runtime body sweeps a representative port set spanning
15868        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
15869        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
15870        // ceiling — the const-fn-wrapped call must agree with a direct
15871        // call on every fixture (a violation trips the test) and every
15872        // returned scalar must byte-equal the input `port` (a violation
15873        // means the accessor stopped being a raw field-return copy).
15874        const fn port_via_const_fn(e: &Entrada) -> u16 {
15875            e.port()
15876        }
15877        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
15878            let entrada = Entrada {
15879                host: String::new(),
15880                para: String::new(),
15881                port,
15882                paths: Vec::new(),
15883            };
15884            assert_eq!(
15885                port_via_const_fn(&entrada),
15886                entrada.port(),
15887                "const-fn-wrapped and direct dispatch on Entrada::port \
15888                 must agree for port={port}",
15889            );
15890            assert_eq!(
15891                entrada.port(),
15892                port,
15893                "Entrada::port must return the storage-side u16 verbatim \
15894                 for port={port}",
15895            );
15896        }
15897    }
15898
15899    #[test]
15900    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
15901        // Load-bearing cross-slot-partition pin closing the loop between
15902        // the substrate-lifted
15903        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
15904        // the closed-set typed enum and the actual
15905        // [`AplicacaoSpec::validate_placement`] runtime behavior across
15906        // the paired `:placement :shard-key` axis: every validated
15907        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
15908        // satisfies `placement.shard_key().is_some() ==
15909        // placement.estrategia().requires_shard_key()`. The four-cell
15910        // shape witness sweeps every combination of (variant in the
15911        // closed accept-set, `:shard-key` Some/None) and pins:
15912        //
15913        //   * variant.requires_shard_key() && shard_key.is_some() →
15914        //     validate() passes; the paired shape is the sole
15915        //     `requires_shard_key` arm-family accepted shape.
15916        //   * variant.requires_shard_key() && shard_key.is_none() →
15917        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
15918        //     the paired shape is the refused missing-key shape on
15919        //     Sharded-family arms.
15920        //   * !variant.requires_shard_key() && shard_key.is_some() →
15921        //     validate() fails with
15922        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
15923        //     is the refused declared-but-inert shape on non-Sharded-
15924        //     family arms.
15925        //   * !variant.requires_shard_key() && shard_key.is_none() →
15926        //     validate() passes; the paired shape is the sole
15927        //     non-`requires_shard_key` arm-family accepted shape.
15928        //
15929        // The compile-time-exhaustive `match p.estrategia()` dispatch at
15930        // [`AplicacaoSpec::validate_placement`] preserves its structural
15931        // arm-fan (a future arm addition still surfaces a build-time
15932        // exhaustiveness error there); this pin closes the semantic loop
15933        // between the arm-fan's shape-gate cascades and the substrate-
15934        // canonical predicate every downstream consumer of the paired
15935        // shape reads through. Fail-before-pass-after locally verified by
15936        // mutating the predicate's `Sharded => true` arm to `false` — the
15937        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
15938        // `validate() must pass` assertion; restoring passes. Same "close
15939        // the loop between the typed predicate and the runtime behavior"
15940        // discipline as the sibling
15941        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
15942        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
15943        // per-arm classifier axis.
15944        for variant in [
15945            PlacementStrategy::SingleNode,
15946            PlacementStrategy::Replicated,
15947            PlacementStrategy::Sharded,
15948        ] {
15949            for present in [false, true] {
15950                let mut spec = three_member_spec();
15951                spec.placement.estrategia = variant;
15952                spec.placement.shard_key = present.then(|| "tenantId".into());
15953                let expects_ok = variant.requires_shard_key() == present;
15954                let result = spec.validate();
15955                match (expects_ok, &result) {
15956                    (true, Ok(())) => {}
15957                    (false, Err(err)) => {
15958                        // Cross-check the refusal diagnostic names the
15959                        // right cell of the four-cell shape witness — the
15960                        // `requires_shard_key && !present` cell must trip
15961                        // [`AplicacaoError::ShardedWithoutKey`]; the
15962                        // `!requires_shard_key && present` cell must trip
15963                        // [`AplicacaoError::ShardKeyOnNonSharded`].
15964                        match (variant.requires_shard_key(), present, err) {
15965                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
15966                            (
15967                                false,
15968                                true,
15969                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
15970                            ) => {
15971                                assert_eq!(
15972                                    *e, variant,
15973                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
15974                                     the paired PlacementStrategy",
15975                                );
15976                            }
15977                            _ => panic!(
15978                                "unexpected refusal for estrategia={variant:?} \
15979                                 present={present}: {err:?}"
15980                            ),
15981                        }
15982                    }
15983                    (true, Err(err)) => panic!(
15984                        "validate() must pass for estrategia={variant:?} \
15985                         present={present} (requires_shard_key={} == present={present}), \
15986                         got {err:?}",
15987                        variant.requires_shard_key(),
15988                    ),
15989                    (false, Ok(())) => panic!(
15990                        "validate() must fail for estrategia={variant:?} \
15991                         present={present} (requires_shard_key={} != present={present})",
15992                        variant.requires_shard_key(),
15993                    ),
15994                }
15995            }
15996        }
15997    }
15998
15999    #[test]
16000    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
16001        // Pin the M3 diagnostic template routes through the typed
16002        // [`PlacementStrategy`] Display byte-string (rebound from the
16003        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
16004        // routes emitted identical bytes (the `Debug` derive on a
16005        // unit variant emits the variant name verbatim, exactly what
16006        // `as_str` returns), but the two paths were structurally
16007        // independent — a future `#[serde(rename_all = "…")]`
16008        // attribute or variant rename would coordinate the wire /
16009        // `Display` / `as_str` triple through the lifted const but
16010        // leave the `Debug` route on the compiler-derived variant name,
16011        // silently desynchronizing the diagnostic byte-string from the
16012        // wire byte-string. Rebinding the template onto `Display`
16013        // ties the diagnostic to the same lifted
16014        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
16015        // emits — drift becomes structurally impossible. Pin the
16016        // byte-string here so a future edit that reverts the template
16017        // to `{estrategia:?}` is caught at caixa-core test time, not
16018        // at consumer dispatch time.
16019        for (variant, expected_scalar) in [
16020            (
16021                PlacementStrategy::SingleNode,
16022                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16023            ),
16024            (
16025                PlacementStrategy::Replicated,
16026                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16027            ),
16028            (
16029                PlacementStrategy::Sharded,
16030                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16031            ),
16032        ] {
16033            let err = AplicacaoError::PlacementWithoutClusters {
16034                estrategia: variant,
16035            };
16036            let msg = err.to_string();
16037            assert!(
16038                msg.starts_with(&format!(":placement {expected_scalar} requires")),
16039                "PlacementWithoutClusters diagnostic for {variant:?} must open \
16040                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16041            );
16042        }
16043    }
16044
16045    #[test]
16046    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
16047        // Peer of
16048        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
16049        // on the second M3 diagnostic that carries the typed
16050        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
16051        // diagnostics now route the strategy scalar through the same
16052        // [`std::fmt::Display`] surface, tying the diagnostic
16053        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
16054        // const set the wire format also emits. The two non-Sharded
16055        // arms are exercised here (the diagnostic exists to flag a
16056        // `:shard-key` slot the current strategy will never consume);
16057        // the peer `Sharded` arm never reaches this diagnostic (the
16058        // `Sharded` strategy consumes `:shard-key` — the
16059        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
16060        // slot instead).
16061        for (variant, expected_scalar) in [
16062            (
16063                PlacementStrategy::SingleNode,
16064                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16065            ),
16066            (
16067                PlacementStrategy::Replicated,
16068                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16069            ),
16070        ] {
16071            let err = AplicacaoError::ShardKeyOnNonSharded {
16072                estrategia: variant,
16073                shard_key: "$tenantId".into(),
16074            };
16075            let msg = err.to_string();
16076            assert!(
16077                msg.starts_with(&format!(":placement {expected_scalar} carries")),
16078                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
16079                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16080            );
16081        }
16082    }
16083
16084    #[test]
16085    fn placement_strategy_all_enumerates_every_variant_once() {
16086        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
16087        // exhaustive-iteration surface: every variant appears exactly
16088        // once, and the slice length matches the arm count of the
16089        // closed set. Every consumer that walks the accepted-strategy
16090        // set (a future `feira app placement --list` CLI-side surfacing,
16091        // a future M4 admission-webhook's rejection body naming the
16092        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
16093        // reverse-projection consumers that iterate the accept-set for
16094        // a "did you mean" hint) reads through this slice, so a future
16095        // variant addition (an `Anycast` mesh-anycast arm the
16096        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
16097        // grows the enum but forgets to grow [`Self::ALL`] silently
16098        // truncates every downstream consumer's accept-set at the same
16099        // pre-addition boundary — this pin fails at caixa-core build
16100        // time on the pairwise-distinct + arm-count invariants.
16101        //
16102        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
16103        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
16104        // pins on the peer closed-set typed-enum axes.
16105        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
16106        assert_eq!(
16107            all.len(),
16108            3,
16109            "PlacementStrategy::ALL must enumerate every variant of the \
16110             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
16111        );
16112        for (i, a) in all.iter().enumerate() {
16113            for (j, b) in all.iter().enumerate() {
16114                if i != j {
16115                    assert_ne!(
16116                        a, b,
16117                        "PlacementStrategy::ALL must carry every variant exactly \
16118                         once — got duplicate {a:?} at indices {i} and {j}"
16119                    );
16120                }
16121            }
16122        }
16123        for variant in [
16124            PlacementStrategy::SingleNode,
16125            PlacementStrategy::Replicated,
16126            PlacementStrategy::Sharded,
16127        ] {
16128            assert!(
16129                all.contains(&variant),
16130                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
16131                 addition that grows the enum but forgets to grow the ALL slice \
16132                 silently truncates every downstream consumer's accept-set at the \
16133                 pre-addition boundary"
16134            );
16135        }
16136    }
16137
16138    #[test]
16139    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
16140        // Fail-before-pass-after pin on the forward accept-set of the
16141        // [`PlacementStrategy::from_wire`] reverse projection: every
16142        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
16143        // constant the [`PlacementStrategy::as_str`] emitter walks
16144        // parses back to its paired variant. Any future arm addition
16145        // that grows the emitter's `as_str` match but forgets to grow
16146        // the parser's `from_str` match silently splits the two halves
16147        // of the round-trip — the wire byte-string one non-serde
16148        // consumer parses from the one the emitter wrote — with the
16149        // failure surfacing at parse time far from the rebrand commit.
16150        // Pinning the three-arm accept-set here catches the drift at
16151        // caixa-core build time.
16152        //
16153        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
16154        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
16155        // closed-set typed-enum `str → Self` axes.
16156        for (wire, expected) in [
16157            (
16158                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16159                PlacementStrategy::SingleNode,
16160            ),
16161            (
16162                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16163                PlacementStrategy::Replicated,
16164            ),
16165            (
16166                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16167                PlacementStrategy::Sharded,
16168            ),
16169        ] {
16170            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16171                panic!(
16172                    "PlacementStrategy::from_wire({wire:?}) must accept every \
16173                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
16174                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
16175                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
16176                )
16177            });
16178            assert_eq!(
16179                parsed, expected,
16180                "PlacementStrategy::from_wire({wire:?}) must return \
16181                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
16182            );
16183        }
16184    }
16185
16186    #[test]
16187    fn placement_strategy_from_wire_round_trips_through_as_str() {
16188        // Fail-before-pass-after pin on the closed round-trip between
16189        // the forward [`PlacementStrategy::as_str`] emitter and the
16190        // reverse [`PlacementStrategy::from_wire`] parser: for every
16191        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
16192        // output must return exactly the same variant. Any per-arm
16193        // divergence — a future arm added to `as_str` but not
16194        // `from_str`, an accidental copy-paste flip in one but not the
16195        // other — silently splits the emit and parse halves and the
16196        // failure surfaces at consumer parse time far from the drift
16197        // site. The `ALL`-iterating shape means a future variant
16198        // addition picks up the coverage by construction.
16199        //
16200        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
16201        // [`crate::CaixaKind::from_wire`] and the
16202        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
16203        // sibling round-trip pin on [`RateLimitUnit`].
16204        for &variant in PlacementStrategy::ALL {
16205            let wire = variant.as_str();
16206            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16207                panic!(
16208                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16209                     must be Some({variant:?}) — the two halves of the round-trip \
16210                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
16211                     got None on wire byte-string {wire:?}"
16212                )
16213            });
16214            assert_eq!(
16215                parsed, variant,
16216                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16217                 must round-trip to the same variant; got {parsed:?}"
16218            );
16219        }
16220    }
16221
16222    #[test]
16223    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
16224        // Fail-before-pass-after pin on the closed-set refusal
16225        // discipline of [`PlacementStrategy::from_wire`]: every
16226        // byte-string outside the three-arm accept-set returns `None`
16227        // rather than silently collapsing onto the [`Default`]
16228        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
16229        // exercised here sweeps the load-bearing drift shapes: the
16230        // empty string (a stripped serde-attribute drift), an all-
16231        // whitespace string (the canonical text-editor accidental
16232        // padding shape), the lowercased kebab-case forms a future
16233        // `#[serde(rename_all = "kebab-case")]` attribute would emit
16234        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
16235        // coincidentally match the accepted canonical scalars, so only
16236        // `"single-node"` fires as a refusal, but pinning the case-
16237        // sensitivity of the accepted arms via the peer [`SingleNode`]
16238        // assertion in the round-trip pin makes the discipline
16239        // structurally clear), the lowercased single-word forms
16240        // (`"singlenode"`), the padded canonical scalar
16241        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
16242        // (`"Sharded\n"`), and a pointer-different `&'static str` that
16243        // happens to alias a canonical byte-string by content but not
16244        // by identity (validated implicitly by the emitter's routing
16245        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
16246        // identity a paired [`crate::assert_str_reexport_identity`] pin
16247        // in caixa-core's per-const declaration surface would catch).
16248        //
16249        // Peer of the sibling
16250        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
16251        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
16252        for bad in [
16253            "",
16254            " ",
16255            "\n",
16256            "\t",
16257            "single-node",
16258            "singlenode",
16259            "SingleNodes",
16260            "single_node",
16261            "single node",
16262            "SINGLENODE",
16263            "SingleNode ",
16264            " SingleNode",
16265            " Sharded ",
16266            "Sharded\n",
16267            "replicated ",
16268            "sharded",
16269            "REPLICATED",
16270            "Anycast",
16271            "Global",
16272            "?",
16273        ] {
16274            assert!(
16275                PlacementStrategy::from_wire(bad).is_none(),
16276                "PlacementStrategy::from_wire({bad:?}) must return None — the \
16277                 parser's accept-set is exactly the three PlacementStrategy::as_str \
16278                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
16279                 is outside that closed set"
16280            );
16281        }
16282    }
16283
16284    #[test]
16285    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
16286        // Fail-before-pass-after pin on the third path of the four-path
16287        // convergence: `from_str` (the reverse projection) inverts the
16288        // `Serialize` derive's wire byte-string on every variant.
16289        // Together with the pre-existing three-path convergence
16290        // (`Display` + `as_str` + `Serialize` all resolve to the same
16291        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
16292        // the peer
16293        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
16294        // this closes the round-trip: the wire byte-string the
16295        // `Serialize` derive emits parses back to the same variant
16296        // through `from_str`, so any future serde-attribute or variant-
16297        // rename drift on the emit half now surfaces as a matched drift
16298        // on the parse half at caixa-core build time — the two halves
16299        // migrate as a unit through the lifted consts on any future
16300        // rename, and the round-trip cannot silently split.
16301        //
16302        // Peer of the sibling
16303        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
16304        // wire-format pin — extends the three-path convergence
16305        // (`Display` + `as_str` + `Serialize`) onto the fourth path
16306        // (`from_str`), closing the `str ↔ Self` round-trip on the
16307        // M3 `:placement :estrategia` closed-set axis.
16308        for &variant in PlacementStrategy::ALL {
16309            let wire = serde_json::to_string(&variant).unwrap();
16310            let unquoted = wire
16311                .strip_prefix('"')
16312                .and_then(|s| s.strip_suffix('"'))
16313                .expect("serialized PlacementStrategy is a JSON string");
16314            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
16315                panic!(
16316                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
16317                     Serialize derive's wire byte-string for \
16318                     PlacementStrategy::{variant:?} — the four-path convergence \
16319                     (Display + as_str + Serialize + from_str) resolves through \
16320                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
16321                )
16322            });
16323            assert_eq!(
16324                parsed, variant,
16325                "PlacementStrategy::from_wire of the Serialize derive's wire \
16326                 byte-string for PlacementStrategy::{variant:?} must round-trip \
16327                 to the same variant; got {parsed:?}"
16328            );
16329        }
16330    }
16331
16332    #[test]
16333    fn rejects_zero_policy_timeout() {
16334        let mut s = three_member_spec();
16335        s.politicas.timeout = Some(Duration::ZERO);
16336        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
16337    }
16338
16339    #[test]
16340    fn rejects_zero_policy_retries() {
16341        let mut s = three_member_spec();
16342        s.politicas.retries = Some(0);
16343        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
16344    }
16345
16346    #[test]
16347    fn rejects_policy_retries_above_cap() {
16348        // The fail-before-pass-after pin: `Some(11)` is structurally
16349        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
16350        // passed validate on every pre-gate codebase because the
16351        // typed slot's only check was the zero-floor arm. The
16352        // thundering-herd amplification vector only surfaced at the
16353        // runtime substrate (Envoy / Cilium L7 retry overlay)
16354        // far from the source caixa.lisp with no field naming the
16355        // offending policy.
16356        let mut s = three_member_spec();
16357        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
16358        assert_eq!(
16359            s.validate().unwrap_err(),
16360            AplicacaoError::PolicyRetriesExceedsCap {
16361                retries: POLICY_RETRIES_MAX + 1
16362            }
16363        );
16364    }
16365
16366    #[test]
16367    fn rejects_policy_retries_far_above_cap() {
16368        // The `u32::MAX` worst case — the four-billion-retry policy
16369        // a typo (`(:retries 4294967295)`) or struct-literal
16370        // copy-paste lands in the slot. Pin the cap arm's coverage
16371        // explicitly across the full `u32` overflow so a future
16372        // relaxation that drops the upper bound surfaces here.
16373        let mut s = three_member_spec();
16374        s.politicas.retries = Some(u32::MAX);
16375        assert_eq!(
16376            s.validate().unwrap_err(),
16377            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
16378        );
16379    }
16380
16381    #[test]
16382    fn accepts_policy_retries_at_cap() {
16383        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
16384        // must validate. The cap is inclusive on the top edge,
16385        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16386        // discipline on the sibling [`crate::LimitsSpec::memory`]
16387        // axis. Pin the boundary explicitly so a future off-by-one
16388        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
16389        // surfaces here as a test failure rather than a silent
16390        // contract narrowing.
16391        let mut s = three_member_spec();
16392        s.politicas.retries = Some(POLICY_RETRIES_MAX);
16393        s.validate()
16394            .expect("retries == POLICY_RETRIES_MAX must validate");
16395    }
16396
16397    #[test]
16398    fn accepts_policy_retries_typical_values() {
16399        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
16400        // every value in the validated set must pass. The
16401        // Envoy / Istio production-playbook recommendation band
16402        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
16403        // (`maxRetries ≤ 10`) both lie within this set.
16404        for r in 1..=POLICY_RETRIES_MAX {
16405            let mut s = three_member_spec();
16406            s.politicas.retries = Some(r);
16407            s.validate()
16408                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
16409        }
16410    }
16411
16412    #[test]
16413    fn policy_retries_zero_takes_precedence_over_cap() {
16414        // The cross-arm ordering pin: `Some(0)` is structurally
16415        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
16416        // (cap), but the zero-floor diagnostic is the more
16417        // self-locating one (it directly names the omit-axis
16418        // remediation), so the validate gate must fire on zero
16419        // first. Pin the order so a future refactor that reorders
16420        // the arms surfaces here as a test failure rather than a
16421        // silent diagnostic regression. Same shape every other
16422        // zero-then-shape ordering on this surface uses
16423        // ([`AplicacaoError::PolicyTimeoutZero`] then
16424        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
16425        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
16426        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
16427        let mut s = three_member_spec();
16428        s.politicas.retries = Some(0);
16429        assert_eq!(
16430            s.validate().unwrap_err(),
16431            AplicacaoError::PolicyRetriesZero,
16432            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
16433        );
16434    }
16435
16436    #[test]
16437    fn policy_retries_cap_diagnostic_carries_offending_value() {
16438        // The diagnostic-shape pin: the offending `u32` is carried
16439        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
16440        // variant so the surfaced error message names the value the
16441        // author wrote (`":politicas :retries (47) exceeds the
16442        // mesh-policy ceiling …"`), not just the cap. Same
16443        // self-locating diagnostic shape every other typed-cap arm
16444        // on this surface carries
16445        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16446        // offending byte count verbatim).
16447        let mut s = three_member_spec();
16448        s.politicas.retries = Some(47);
16449        let err = s.validate().unwrap_err();
16450        assert!(
16451            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
16452            "got {err:?}"
16453        );
16454        let msg = err.to_string();
16455        assert!(
16456            msg.contains("47"),
16457            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
16458        );
16459    }
16460
16461    #[test]
16462    fn policy_retries_cap_is_aws_app_mesh_aligned() {
16463        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
16464        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
16465        // schema cap — the only upstream mesh-policy schema that
16466        // documents an explicit hard cap. Pinning the literal value
16467        // here surfaces a future drift (a relaxation to 20, a
16468        // tightening to 5) as a deliberate test edit, not a silent
16469        // contract narrowing.
16470        assert_eq!(POLICY_RETRIES_MAX, 10);
16471    }
16472
16473    #[test]
16474    fn rejects_circuit_breaker_zero_max_failures() {
16475        let mut s = three_member_spec();
16476        s.politicas.circuit_breaker = Some(CircuitBreaker {
16477            max_failures: 0,
16478            window: Duration::from_secs(60),
16479        });
16480        assert_eq!(
16481            s.validate().unwrap_err(),
16482            AplicacaoError::PolicyBreakerZeroFailures
16483        );
16484    }
16485
16486    #[test]
16487    fn rejects_circuit_breaker_max_failures_above_cap() {
16488        // The fail-before-pass-after pin: `1001` is structurally one
16489        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
16490        // silently passed validate on every pre-gate codebase
16491        // because the typed slot's only check was the zero-floor
16492        // arm. The breaker-no-op vector only surfaced at the runtime
16493        // substrate (Envoy / Cilium L7 outlier-detection overlay)
16494        // far from the source caixa.lisp with no field naming the
16495        // offending policy.
16496        let mut s = three_member_spec();
16497        s.politicas.circuit_breaker = Some(CircuitBreaker {
16498            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16499            window: Duration::from_secs(60),
16500        });
16501        assert_eq!(
16502            s.validate().unwrap_err(),
16503            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16504                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16505            }
16506        );
16507    }
16508
16509    #[test]
16510    fn rejects_circuit_breaker_max_failures_far_above_cap() {
16511        // The `u32::MAX` worst case — the four-billion-failure
16512        // threshold a typo (`(:max-failures 4294967295)`) or a
16513        // struct-literal copy-paste lands in the slot. Pin the cap
16514        // arm's coverage explicitly across the full `u32` overflow
16515        // so a future relaxation that drops the upper bound surfaces
16516        // here.
16517        let mut s = three_member_spec();
16518        s.politicas.circuit_breaker = Some(CircuitBreaker {
16519            max_failures: u32::MAX,
16520            window: Duration::from_secs(60),
16521        });
16522        assert_eq!(
16523            s.validate().unwrap_err(),
16524            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16525                max_failures: u32::MAX,
16526            }
16527        );
16528    }
16529
16530    #[test]
16531    fn accepts_circuit_breaker_max_failures_at_cap() {
16532        // The boundary value — exactly
16533        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
16534        // cap is inclusive on the top edge, matching the
16535        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16536        // discipline on the sibling capped axes. Pin the boundary
16537        // explicitly so a future off-by-one tightening
16538        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
16539        // surfaces here as a test failure rather than a silent
16540        // contract narrowing.
16541        let mut s = three_member_spec();
16542        s.politicas.circuit_breaker = Some(CircuitBreaker {
16543            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
16544            window: Duration::from_secs(60),
16545        });
16546        s.validate()
16547            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
16548    }
16549
16550    #[test]
16551    fn accepts_circuit_breaker_max_failures_typical_values() {
16552        // The documented production-playbook band positive-control
16553        // sweep — every value Hystrix / Istio / Envoy / Polly /
16554        // Resilience4j recommend (5..=50) must pass, plus a sweep
16555        // through the hyperscale band (100, 500, 1000) the cap
16556        // accepts. Pin the inclusive validated set explicitly so a
16557        // future tightening of the ceiling surfaces here.
16558        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
16559            let mut s = three_member_spec();
16560            s.politicas.circuit_breaker = Some(CircuitBreaker {
16561                max_failures: n,
16562                window: Duration::from_secs(60),
16563            });
16564            s.validate()
16565                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
16566        }
16567    }
16568
16569    #[test]
16570    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
16571        // The cross-arm ordering pin: `0` is structurally outside
16572        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
16573        // (cap), but the zero-floor diagnostic is the more
16574        // self-locating one (it directly names the omit-axis
16575        // remediation), so the validate gate must fire on zero
16576        // first. Same shape every other zero-then-shape ordering on
16577        // this surface uses
16578        // ([`AplicacaoError::PolicyRetriesZero`] then
16579        // [`AplicacaoError::PolicyRetriesExceedsCap`];
16580        // [`AplicacaoError::PolicyTimeoutZero`] then
16581        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
16582        let mut s = three_member_spec();
16583        s.politicas.circuit_breaker = Some(CircuitBreaker {
16584            max_failures: 0,
16585            window: Duration::from_secs(60),
16586        });
16587        assert_eq!(
16588            s.validate().unwrap_err(),
16589            AplicacaoError::PolicyBreakerZeroFailures,
16590            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
16591        );
16592    }
16593
16594    #[test]
16595    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
16596        // The cross-arm ordering pin between the cap and the
16597        // sibling `:window` gates (zero-window, canonical-window).
16598        // A breaker carrying both an over-cap `max_failures` AND a
16599        // structurally invalid window (zero, sub-ms) must surface
16600        // the cap diagnostic first — the cap arm is wired
16601        // immediately after the zero-failure arm and strictly
16602        // before the window arms, so the offending value the
16603        // diagnostic names matches the order the author would
16604        // discover the gates by reading top-to-bottom through
16605        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
16606        // future refactor that reorders the arms surfaces here as a
16607        // test failure rather than a silent diagnostic regression.
16608        let mut s = three_member_spec();
16609        s.politicas.circuit_breaker = Some(CircuitBreaker {
16610            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16611            window: Duration::ZERO,
16612        });
16613        assert_eq!(
16614            s.validate().unwrap_err(),
16615            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16616                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16617            },
16618            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
16619        );
16620    }
16621
16622    #[test]
16623    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
16624        // The diagnostic-shape pin: the offending `u32` is carried
16625        // verbatim into the
16626        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
16627        // variant so the surfaced error message names the value the
16628        // author wrote (`":politicas :circuit-breaker :max-failures
16629        // (50000) exceeds the mesh-policy ceiling …"`), not just
16630        // the cap. Same self-locating diagnostic shape every other
16631        // typed-cap arm on this surface carries
16632        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
16633        // offending retry count verbatim,
16634        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16635        // offending byte count verbatim).
16636        let mut s = three_member_spec();
16637        s.politicas.circuit_breaker = Some(CircuitBreaker {
16638            max_failures: 50_000,
16639            window: Duration::from_secs(60),
16640        });
16641        let err = s.validate().unwrap_err();
16642        assert!(
16643            matches!(
16644                err,
16645                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16646                    max_failures: 50_000
16647                }
16648            ),
16649            "got {err:?}"
16650        );
16651        let msg = err.to_string();
16652        assert!(
16653            msg.contains("50000"),
16654            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
16655        );
16656    }
16657
16658    #[test]
16659    fn policy_breaker_max_failures_cap_pins_canonical_value() {
16660        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
16661        // value at 1000 — an order of magnitude above every
16662        // documented production-playbook recommendation band
16663        // (Hystrix `requestVolumeThreshold` default 20, Istio
16664        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
16665        // `outlier_detection.consecutive_5xx` default 5, Polly /
16666        // Resilience4j typical 5..=50) and below the
16667        // clearly-pathological "effectively no protection" floor
16668        // (10_000, 100_000, u32::MAX). Pinning the literal value
16669        // here surfaces a future drift (a relaxation to 10_000, a
16670        // tightening to 100) as a deliberate test edit, not a
16671        // silent contract narrowing.
16672        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
16673    }
16674
16675    #[test]
16676    fn rejects_circuit_breaker_zero_window() {
16677        let mut s = three_member_spec();
16678        s.politicas.circuit_breaker = Some(CircuitBreaker {
16679            max_failures: 5,
16680            window: Duration::ZERO,
16681        });
16682        assert_eq!(
16683            s.validate().unwrap_err(),
16684            AplicacaoError::PolicyBreakerZeroWindow
16685        );
16686    }
16687
16688    #[test]
16689    fn rejects_zero_rate_limit() {
16690        let mut s = three_member_spec();
16691        s.politicas.rate_limit = Some(RateLimit {
16692            rate: 0,
16693            window: Duration::from_secs(1),
16694        });
16695        assert_eq!(
16696            s.validate().unwrap_err(),
16697            AplicacaoError::PolicyRateLimitZero
16698        );
16699    }
16700
16701    #[test]
16702    fn rejects_rate_limit_zero_window() {
16703        // `RateLimit { rate: 100, window: Duration::ZERO }` is
16704        // constructible programmatically (the typed `Duration` field
16705        // imposes no nonzero invariant) but renders through
16706        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
16707        // codec's `parse` rejects as `unknown rate-limit window unit
16708        // "0s"`. Until this validate-time gate landed the typed slot
16709        // accepted the value silently and the round-trip break only
16710        // surfaced at deserialize time (potentially in a downstream
16711        // consumer that never re-validates). Pin the rejection at
16712        // `AplicacaoSpec::validate` so the typed slot's valid set
16713        // matches the codec's round-trippable set structurally.
16714        let mut s = three_member_spec();
16715        s.politicas.rate_limit = Some(RateLimit {
16716            rate: 100,
16717            window: Duration::ZERO,
16718        });
16719        assert_eq!(
16720            s.validate().unwrap_err(),
16721            AplicacaoError::PolicyRateLimitWindowNotCanonical {
16722                window: Duration::ZERO
16723            }
16724        );
16725    }
16726
16727    #[test]
16728    fn rejects_rate_limit_arbitrary_seconds_window() {
16729        // 45 seconds is a valid `Duration` but not one of the three
16730        // canonical rate-limit windows the codec round-trips
16731        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
16732        // refuses on round-trip — same round-trip-break shape the
16733        // zero-window arm above pins, with a non-zero magnitude to
16734        // guard against a future "reject only zero" half-measure.
16735        let mut s = three_member_spec();
16736        let window = Duration::from_secs(45);
16737        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
16738        assert_eq!(
16739            s.validate().unwrap_err(),
16740            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16741        );
16742    }
16743
16744    #[test]
16745    fn rejects_rate_limit_two_minute_window() {
16746        // 120 seconds = 2 minutes is a "looks-canonical" but
16747        // not-canonical window: it's a clean integer multiple of the
16748        // minute unit, but the codec only round-trips the
16749        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
16750        // A `Duration::from_secs(120)` window renders as `"100/120s"`
16751        // which the parser rejects. Pinning this case rules out a
16752        // future "accept any clean multiple of s/m/h" relaxation
16753        // that would silently break the codec contract.
16754        let mut s = three_member_spec();
16755        let window = Duration::from_secs(120);
16756        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
16757        assert_eq!(
16758            s.validate().unwrap_err(),
16759            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16760        );
16761    }
16762
16763    #[test]
16764    fn rejects_rate_limit_subsecond_window() {
16765        // A sub-second window (e.g. 500ms) is a valid `Duration` but
16766        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
16767        // Pin the rejection so a future relaxation can't silently
16768        // admit fractional-second windows that the codec can't
16769        // round-trip.
16770        let mut s = three_member_spec();
16771        let window = Duration::from_millis(500);
16772        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
16773        assert_eq!(
16774            s.validate().unwrap_err(),
16775            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16776        );
16777    }
16778
16779    #[test]
16780    fn rejects_policy_rate_limit_above_cap() {
16781        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
16782        // is structurally one past the cap and silently passed
16783        // validate on every pre-gate codebase because the typed slot's
16784        // only `rate` check was the zero-floor arm. The no-op-limiter
16785        // shape only surfaced at the runtime substrate (Envoy's
16786        // `local_rate_limit.token_bucket.max_tokens`, the future
16787        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
16788        // with no field naming the offending policy.
16789        let mut s = three_member_spec();
16790        s.politicas.rate_limit = Some(RateLimit {
16791            rate: POLICY_RATE_LIMIT_MAX + 1,
16792            window: Duration::from_secs(1),
16793        });
16794        assert_eq!(
16795            s.validate().unwrap_err(),
16796            AplicacaoError::PolicyRateLimitExceedsCap {
16797                rate: POLICY_RATE_LIMIT_MAX + 1
16798            }
16799        );
16800    }
16801
16802    #[test]
16803    fn rejects_policy_rate_limit_far_above_cap() {
16804        // The `u32::MAX` worst case — the four-billion-token rate-limit
16805        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
16806        // copy-paste lands in the slot. Pin the cap arm's coverage
16807        // explicitly across the full `u32` overflow so a future
16808        // relaxation that drops the upper bound surfaces here. Peer to
16809        // `rejects_policy_retries_far_above_cap` on the sibling
16810        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
16811        // on the sibling `:max-failures` axis.
16812        let mut s = three_member_spec();
16813        s.politicas.rate_limit = Some(RateLimit {
16814            rate: u32::MAX,
16815            window: Duration::from_secs(1),
16816        });
16817        assert_eq!(
16818            s.validate().unwrap_err(),
16819            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
16820        );
16821    }
16822
16823    #[test]
16824    fn accepts_policy_rate_limit_at_cap() {
16825        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
16826        // must validate. The cap is inclusive on the top edge, matching
16827        // every other typed upper bound in this crate
16828        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
16829        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
16830        // across all three canonical windows so a future off-by-one
16831        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
16832        // window-conditional cap surfaces here as a test failure rather
16833        // than a silent contract narrowing.
16834        for secs in [1u64, 60, 3600] {
16835            let mut s = three_member_spec();
16836            s.politicas.rate_limit = Some(RateLimit {
16837                rate: POLICY_RATE_LIMIT_MAX,
16838                window: Duration::from_secs(secs),
16839            });
16840            s.validate().unwrap_or_else(|e| {
16841                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
16842            });
16843        }
16844    }
16845
16846    #[test]
16847    fn accepts_policy_rate_limit_typical_values() {
16848        // The documented production-playbook recommendation band —
16849        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
16850        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
16851        // Enterprise ~1M per-hour. Every value in the validated set
16852        // must pass; pin the band explicitly so a future tightening
16853        // surfaces here.
16854        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
16855            for secs in [1u64, 60, 3600] {
16856                let mut s = three_member_spec();
16857                s.politicas.rate_limit = Some(RateLimit {
16858                    rate,
16859                    window: Duration::from_secs(secs),
16860                });
16861                s.validate().unwrap_or_else(|e| {
16862                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
16863                });
16864            }
16865        }
16866    }
16867
16868    #[test]
16869    fn policy_rate_limit_zero_takes_precedence_over_cap() {
16870        // The cross-arm ordering pin: `rate == 0` is structurally
16871        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
16872        // (cap), but the zero-floor diagnostic is the more
16873        // self-locating one (it directly names the omit-axis
16874        // remediation). Pin the order so a future refactor that
16875        // reorders the arms surfaces here as a test failure rather
16876        // than a silent diagnostic regression. Same shape every other
16877        // zero-then-cap ordering on this surface uses
16878        // ([`AplicacaoError::PolicyRetriesZero`] then
16879        // [`AplicacaoError::PolicyRetriesExceedsCap`];
16880        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
16881        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
16882        let mut s = three_member_spec();
16883        s.politicas.rate_limit = Some(RateLimit {
16884            rate: 0,
16885            window: Duration::from_secs(1),
16886        });
16887        assert_eq!(
16888            s.validate().unwrap_err(),
16889            AplicacaoError::PolicyRateLimitZero,
16890            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
16891        );
16892    }
16893
16894    #[test]
16895    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
16896        // Two-axis-bad pin: rate above cap *and* window non-canonical.
16897        // The validate gate must fire on the rate cap first — the
16898        // amplification-shape (no-op limiter) diagnostic is the more
16899        // fundamental one; the window-canonical diagnostic is the
16900        // narrower codec-round-trip shape. Pin the ordering so a future
16901        // refactor that reorders the rate-then-window check arms
16902        // surfaces here as a test failure rather than a silent
16903        // diagnostic regression.
16904        let mut s = three_member_spec();
16905        s.politicas.rate_limit = Some(RateLimit {
16906            rate: POLICY_RATE_LIMIT_MAX + 1,
16907            window: Duration::from_secs(45),
16908        });
16909        assert_eq!(
16910            s.validate().unwrap_err(),
16911            AplicacaoError::PolicyRateLimitExceedsCap {
16912                rate: POLICY_RATE_LIMIT_MAX + 1
16913            },
16914            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
16915        );
16916    }
16917
16918    #[test]
16919    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
16920        // The diagnostic-shape pin: the offending `u32` is carried
16921        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
16922        // variant so the surfaced error message names the value the
16923        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
16924        // the mesh-policy ceiling …"`), not just the cap. Same
16925        // self-locating diagnostic shape every other typed-cap arm on
16926        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
16927        // carries the offending retries count verbatim,
16928        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
16929        // the offending failure count verbatim).
16930        let mut s = three_member_spec();
16931        s.politicas.rate_limit = Some(RateLimit {
16932            rate: 5_000_000,
16933            window: Duration::from_secs(1),
16934        });
16935        let err = s.validate().unwrap_err();
16936        assert!(
16937            matches!(
16938                err,
16939                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
16940            ),
16941            "got {err:?}"
16942        );
16943        let msg = err.to_string();
16944        assert!(
16945            msg.contains("5000000"),
16946            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
16947        );
16948    }
16949
16950    #[test]
16951    fn policy_rate_limit_cap_pins_canonical_value() {
16952        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
16953        // 1_000_000 — two-to-three orders of magnitude above every
16954        // documented production-playbook recommendation band (Envoy /
16955        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
16956        // Gateway 10_000..=100_000 per-minute) and below the
16957        // clearly-pathological "paste-from-binary blob" floor
16958        // (100_000_000, u32::MAX). Pinning the literal value here
16959        // surfaces a future drift (a relaxation to 10_000_000, a
16960        // tightening to 100_000) as a deliberate test edit, not a
16961        // silent contract narrowing.
16962        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
16963    }
16964
16965    #[test]
16966    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
16967        // Both axes are invalid here: rate == 0 *and* window is
16968        // non-canonical. The validate gate must fire on rate first
16969        // (matching the existing `rejects_zero_rate_limit` ordering),
16970        // so the existing diagnostic continues to lead with the
16971        // simpler "zero rate" framing. Pinning the order of checks
16972        // so a future refactor that reorders the arms surfaces here
16973        // as a test failure rather than a silent diagnostic
16974        // regression.
16975        let mut s = three_member_spec();
16976        s.politicas.rate_limit = Some(RateLimit {
16977            rate: 0,
16978            window: Duration::from_secs(45),
16979        });
16980        assert_eq!(
16981            s.validate().unwrap_err(),
16982            AplicacaoError::PolicyRateLimitZero
16983        );
16984    }
16985
16986    #[test]
16987    fn rate_limit_canonical_windows_validate() {
16988        // The three canonical windows the codec round-trips
16989        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
16990        // unchanged. Pin the full canonical set as a positive case
16991        // (the existing `rate_limit_round_trip_seconds` /
16992        // `rate_limit_round_trip_minutes` tests pin the
16993        // serialize-then-deserialize property at the codec layer; this
16994        // test pins the validate-side complement so a future tightening
16995        // of the canonical set — e.g. dropping `:hour` — surfaces here
16996        // as a test failure rather than a silent contract narrowing).
16997        for secs in [1u64, 60, 3600] {
16998            let mut s = three_member_spec();
16999            s.politicas.rate_limit = Some(RateLimit {
17000                rate: 100,
17001                window: Duration::from_secs(secs),
17002            });
17003            s.validate().expect("canonical window must validate");
17004        }
17005    }
17006
17007    #[test]
17008    fn rate_limit_validated_value_round_trips_through_codec() {
17009        // The structural property the validate gate enforces:
17010        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
17011        // losslessly through the `rate_limit_codec` (serialize → string
17012        // → deserialize → equal value). Pin this end-to-end so a future
17013        // change to either side (the validate gate's accepted window
17014        // set, the codec's parse/render unit set) that breaks the
17015        // alignment surfaces here. The previous-state shape (typed
17016        // slot accepts arbitrary `Duration`, codec only round-trips
17017        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
17018        // window — the validate gate now forecloses that.
17019        for secs in [1u64, 60, 3600] {
17020            let mut s = three_member_spec();
17021            s.politicas.rate_limit = Some(RateLimit {
17022                rate: 250,
17023                window: Duration::from_secs(secs),
17024            });
17025            s.validate().unwrap();
17026            let json = serde_json::to_string(&s.politicas).unwrap();
17027            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17028            assert_eq!(
17029                back.rate_limit, s.politicas.rate_limit,
17030                "every validated :rate-limit must round-trip losslessly through the codec"
17031            );
17032        }
17033    }
17034
17035    #[test]
17036    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
17037        // The hour-window canonical form (`"<n>/h"`) was missing from
17038        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
17039        // pair. Now that the validate gate pins 3600s as part of the
17040        // canonical set, pin its serialize-side render shape too so
17041        // the third leg of the s/m/h tripod is explicitly tested.
17042        let policy = MeshPolicy {
17043            rate_limit: Some(RateLimit {
17044                rate: 10000,
17045                window: Duration::from_secs(3600),
17046            }),
17047            ..Default::default()
17048        };
17049        let json = serde_json::to_string(&policy).unwrap();
17050        assert!(
17051            json.contains("\"10000/h\""),
17052            "hour-window canonical form must render with `h` suffix (got: {json})"
17053        );
17054        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17055        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
17056    }
17057
17058    #[test]
17059    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
17060        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
17061        // typed accessor's accepted-window set against the codec's
17062        // accepted set explicitly. A future addition to the codec
17063        // (e.g. accepting `:day`/`:week` as authoring units) must be
17064        // accompanied by a parallel addition here, and a regression
17065        // that drops one of the three canonical units from either
17066        // side surfaces as a test failure. The accessor is the
17067        // single source of truth for the canonical-window set —
17068        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
17069        // gate and [`rate_limit_codec::render`]'s canonical arm both
17070        // read through it — this test enshrines that its
17071        // `Duration → Option<RateLimitUnit>` projection matches the
17072        // codec's parse / render arms' accepted-window set exactly.
17073        //
17074        // Predecessor: this pin previously read the module-private
17075        // free helper `is_canonical_rate_limit_window` — a delegate
17076        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
17077        // — but the helper had no production consumers left after the
17078        // validate-gate migration onto [`RateLimit::canonical_unit`]
17079        // and was deleted; the closed-set arm-window bijection now
17080        // lives on exactly one typed dispatch on the substrate
17081        // primitive.
17082        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
17083            RateLimit { rate: 1, window }.canonical_unit()
17084        };
17085        assert!(canonical_unit(Duration::from_secs(1)).is_some());
17086        assert!(canonical_unit(Duration::from_secs(60)).is_some());
17087        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
17088        // Non-canonical windows the accessor rejects.
17089        assert!(canonical_unit(Duration::ZERO).is_none());
17090        assert!(canonical_unit(Duration::from_secs(2)).is_none());
17091        assert!(canonical_unit(Duration::from_secs(30)).is_none());
17092        assert!(canonical_unit(Duration::from_secs(120)).is_none());
17093        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
17094        // Sub-second windows: even `Duration::from_millis(1000)` is
17095        // exactly 1s and accepted; `Duration::from_millis(500)` is
17096        // sub-second and rejected.
17097        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
17098        assert!(canonical_unit(Duration::from_millis(500)).is_none());
17099        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
17100    }
17101
17102    #[test]
17103    fn rate_limit_unit_table_projections_are_mutual_inverses() {
17104        // Bidirection pin against the closed-set typed enum
17105        // [`RateLimitUnit`] arm-table (the canonical
17106        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
17107        // of the rate-limit unit surface reads from). The two
17108        // projection directions [`RateLimitUnit::from_suffix`] /
17109        // [`RateLimitUnit::window`] (str → Duration, exposed as one
17110        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
17111        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
17112        // (Duration → str, exposed as one typed dispatch through
17113        // [`RateLimit::canonical_unit`] composed with
17114        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
17115        // codec's parse arm ([`rate_limit_codec::parse`] via
17116        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
17117        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
17118        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
17119        // via [`RateLimit::canonical_unit`]) all key off. A future
17120        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
17121        // sub-second window) is one variant + one arm per method on the
17122        // closed-set enum; the compiler-enforced exhaustiveness on
17123        // every consumer's `match self` arms picks it up by
17124        // construction. This pin enshrines that both projection
17125        // directions agree on every canonical arm row and neither
17126        // leaks a spurious entry the other doesn't recognize.
17127        //
17128        // Predecessor: this test previously read the two vestigial
17129        // module-private free helpers `rate_limit_window_unit` and
17130        // `rate_limit_window_from_unit` on the `Duration → &str` and
17131        // `&str → Duration` axes; the former was deleted after its
17132        // sole production consumer ([`rate_limit_codec::render`])
17133        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
17134        // the latter is folded here into the substrate primitive
17135        // [`RateLimitUnit::window_from_suffix`] so both projection
17136        // directions live on the closed-set enum's arm-table.
17137        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
17138            let window = super::RateLimitUnit::window_from_suffix(unit)
17139                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
17140            assert_eq!(
17141                window,
17142                Duration::from_secs(secs),
17143                "unit {unit:?} must resolve to {secs}s"
17144            );
17145            let projected_suffix = RateLimit { rate: 1, window }
17146                .canonical_unit()
17147                .map(super::RateLimitUnit::as_suffix);
17148            assert_eq!(
17149                projected_suffix,
17150                Some(unit),
17151                "Duration({secs}s) must render as {unit:?} \
17152                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
17153            );
17154        }
17155        // Non-table units yield None on the `unit → Duration`
17156        // projection — a future `"d"` addition to the table would
17157        // flip this arm; today it pins the current three-row table's
17158        // rejection semantics.
17159        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
17160        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
17161        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
17162        // Non-table Durations yield None on the `Duration → unit`
17163        // projection — pins that the two projections agree on the
17164        // "not in the table" semantic too, so a drift where the
17165        // parse-side accepts a value the render-side can't emit is
17166        // a build error at the two-arm pair, not a silent codec
17167        // round-trip break.
17168        let projected_suffix = |window: Duration| -> Option<&'static str> {
17169            RateLimit { rate: 1, window }
17170                .canonical_unit()
17171                .map(super::RateLimitUnit::as_suffix)
17172        };
17173        assert!(projected_suffix(Duration::from_secs(2)).is_none());
17174        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
17175        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
17176    }
17177
17178    #[test]
17179    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
17180        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
17181        // substrate-primitive `&str → Duration` associated method the
17182        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
17183        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
17184        // to the same [`Duration`] the two-step composition
17185        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
17186        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
17187        // `"MIN"`) must project to [`None`] on both paths. A future
17188        // implementation of `window_from_suffix` that took a shortcut
17189        // through a per-suffix `match` table (bypassing the arm-table's
17190        // `Self::from_suffix` scan and the arm-table's `Self::window`
17191        // dispatch) would silently split the accept-set — the parse
17192        // arm would accept a suffix the enum's arm-table doesn't know,
17193        // or reject a suffix the enum's arm-table does; this pin
17194        // surfaces that drift at caixa-core build time rather than at a
17195        // downstream serde round-trip audit on a live `MeshPolicy`.
17196        //
17197        // Same byte-parity discipline the sibling
17198        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
17199        // pin carries on the peer `Duration → RateLimitUnit` axis via
17200        // [`RateLimit::canonical_unit`], and the peer
17201        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17202        // carries on the bidirectional arm-table axis — extended here
17203        // onto the fifth (and last unlifted) projection axis on the
17204        // closed-set enum's arm-table.
17205        let composition = |suffix: &str| -> Option<Duration> {
17206            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
17207        };
17208        for suffix in ["s", "m", "h"] {
17209            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17210            let via_composition = composition(suffix);
17211            assert_eq!(
17212                via_method, via_composition,
17213                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17214                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
17215                 method must delegate to the arm-table's two typed dispatches, \
17216                 not shortcut through a per-suffix match table"
17217            );
17218            assert!(
17219                via_method.is_some(),
17220                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
17221                 RateLimitUnit::window_from_suffix"
17222            );
17223        }
17224        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
17225            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17226            let via_composition = composition(suffix);
17227            assert_eq!(
17228                via_method, via_composition,
17229                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17230                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
17231                 axis too"
17232            );
17233            assert!(
17234                via_method.is_none(),
17235                "non-arm suffix {suffix:?} must project to None via \
17236                 RateLimitUnit::window_from_suffix — a future extension that \
17237                 accepted this suffix without a corresponding arm on the enum \
17238                 would split the codec's parse-accepted set from the enum's \
17239                 arm-table"
17240            );
17241        }
17242        // And the codec's parse arm now reads through this method: a
17243        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
17244        // the same `Duration` the method returns for its unit, closing
17245        // the two-consumer drift surface (the codec's parse arm and the
17246        // enum's arm-table) with one typed dispatch on the substrate
17247        // primitive.
17248        for suffix in ["s", "m", "h"] {
17249            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
17250            let mp: MeshPolicy = serde_json::from_str(&wire)
17251                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
17252            let parsed = mp.rate_limit().expect("rate_limit payload present");
17253            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
17254                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
17255            assert_eq!(
17256                parsed.window(),
17257                via_method,
17258                "codec parse arm on {wire:?} must resolve the window through \
17259                 RateLimitUnit::window_from_suffix, not a divergent path"
17260            );
17261        }
17262    }
17263
17264    #[test]
17265    fn rate_limit_unit_all_enumerates_every_arm_once() {
17266        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
17267        // enumerate every arm of the closed-set enum exactly once, in
17268        // the canonical shortest-to-longest window order (Second before
17269        // Minute before Hour) — the same order the sibling
17270        // [`crate::supervisor::RestartStrategy`] /
17271        // [`crate::supervisor::RestartPolicy`] /
17272        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
17273        // typed enums carry (the arm declared first is the arm listed
17274        // first). A future variant addition that extends the enum
17275        // without appending to [`RateLimitUnit::ALL`] leaves the
17276        // exhaustive iteration surface silently short one arm — the
17277        // codec's parse arm would then reject the new suffix even
17278        // though the enum knows it. This pin closes the drift.
17279        assert_eq!(
17280            super::RateLimitUnit::ALL,
17281            &[
17282                super::RateLimitUnit::Second,
17283                super::RateLimitUnit::Minute,
17284                super::RateLimitUnit::Hour,
17285            ],
17286            "RateLimitUnit::ALL must enumerate every arm exactly once, \
17287             in canonical shortest-to-longest window order"
17288        );
17289    }
17290
17291    #[test]
17292    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
17293        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
17294        // every arm's [`RateLimitUnit::as_suffix`] output must parse
17295        // back through [`RateLimitUnit::from_suffix`] to the same
17296        // variant. A future arm addition that lands `as_suffix` but
17297        // forgets `from_suffix` (`from_suffix` iterates
17298        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
17299        // is the load-bearing carrier of the round-trip; the sibling
17300        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
17301        // the `ALL` half) trips here at caixa-core build time rather
17302        // than surfacing as a codec round-trip miss (a `render` emit
17303        // that lands a suffix the paired `parse` cannot decode).
17304        for unit in super::RateLimitUnit::ALL {
17305            let suffix = unit.as_suffix();
17306            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
17307                panic!(
17308                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
17309                     RateLimitUnit::as_suffix output — got None for {unit:?}"
17310                )
17311            });
17312            assert_eq!(
17313                parsed, *unit,
17314                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
17315                 must return RateLimitUnit::{unit:?}"
17316            );
17317        }
17318    }
17319
17320    #[test]
17321    fn rate_limit_unit_from_window_and_window_round_trip() {
17322        // Total round-trip pin on the `(from_window, window)` pair:
17323        // every arm's [`RateLimitUnit::window`] output must parse back
17324        // through [`RateLimitUnit::from_window`] to the same variant.
17325        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
17326        // on the peer `Duration` axis — the two round-trip pins
17327        // together enshrine that both projections of the typed
17328        // canonical-unit bijection are total on the arm-set.
17329        for unit in super::RateLimitUnit::ALL {
17330            let window = unit.window();
17331            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
17332                panic!(
17333                    "RateLimitUnit::from_window({window:?}) must accept every \
17334                     RateLimitUnit::window output — got None for {unit:?}"
17335                )
17336            });
17337            assert_eq!(
17338                parsed, *unit,
17339                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17340                 must return RateLimitUnit::{unit:?}"
17341            );
17342        }
17343    }
17344
17345    #[test]
17346    fn rate_limit_unit_from_window_accessor_is_const_fn() {
17347        // Fail-before-pass-after pin: witnesses the
17348        // [`RateLimitUnit::from_window`] `const`-eval posture via a
17349        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
17350        // -> Option<RateLimitUnit>` whose body calls
17351        // `RateLimitUnit::from_window(window)`, well-formed only when
17352        // the callee is itself `const fn` (any future downgrade to
17353        // non-`const` fails at caixa-core build time with E0015 `cannot
17354        // call non-const function`, strictly stronger than a runtime
17355        // `assert!`, side-stepping the destructor-in-const restriction
17356        // that blocks direct `const _: Option<RateLimitUnit> =
17357        // RateLimitUnit::from_window(...)` items on `Duration`'s
17358        // carrier). The runtime body sweeps every closed-set
17359        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
17360        // rejection sample (`Duration::from_millis(500)` sub-second
17361        // residue) and asserts the wrapped and direct dispatches agree
17362        // — a violation means the wrapper stopped compiling under a
17363        // future `const`-posture downgrade, or the reverse resolver's
17364        // arm-set silently split from the peer `Self::window` emitter's
17365        // arm-set. Peer of the sibling
17366        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
17367        // (152c868) /
17368        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
17369        // (152c868) /
17370        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
17371        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
17372        // `const`-eval-surface pins on the peer M2 / M3 substrate-
17373        // primitive `Copy`-return accessor axes, extended onto the
17374        // reverse `Duration → RateLimitUnit` projection axis on the
17375        // M3 mesh-slot rate-limit closed-set typed enum.
17376        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
17377            super::RateLimitUnit::from_window(window)
17378        }
17379        for unit in super::RateLimitUnit::ALL {
17380            let window = unit.window();
17381            let via_wrapper = from_window_via_const_fn(window);
17382            let direct = super::RateLimitUnit::from_window(window);
17383            assert_eq!(
17384                via_wrapper, direct,
17385                "RateLimitUnit::from_window({window:?}) via const fn \
17386                 wrapper must agree with direct dispatch for {unit:?}"
17387            );
17388            assert_eq!(
17389                via_wrapper,
17390                Some(*unit),
17391                "RateLimitUnit::from_window({window:?}) via const fn \
17392                 wrapper must return Some({unit:?}) for the peer \
17393                 window() output"
17394            );
17395        }
17396        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
17397        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
17398    }
17399
17400    #[test]
17401    fn rate_limit_unit_from_window_composes_through_window_accessor() {
17402        // Composition-witness pin on the routing-through-peer discipline:
17403        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
17404        // through the peer `pub const fn` [`RateLimitUnit::window`]
17405        // canonical-`Duration` projection rather than a hand-authored
17406        // per-arm second-magnitude literal — a future arm-magnitude edit
17407        // on the sibling `window()` accessor (a `Second → 2s` typo, a
17408        // `Hour → 3599s` off-by-one) must therefore reach this reverse
17409        // resolver by construction. A pin that hard-coded the three
17410        // second-magnitudes here would silently split from the peer
17411        // emitter on any such edit; instead, this pin asserts the
17412        // composition invariant `from_window(u.window()) == Some(u)`
17413        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
17414        // arm — a violation means either the peer `Self::window`
17415        // accessor drifted (breaking every downstream consumer that
17416        // reads through it), or the reverse resolver stopped routing
17417        // through the peer (introducing a hand-authored literal that
17418        // silently disagrees with the emitter). Either failure is a
17419        // caixa-core-build-time surface, not a downstream renderer
17420        // round-trip regression.
17421        //
17422        // Peer of the sibling
17423        // [`crate::render::assert_str_reexport_identity`] discipline on
17424        // the substrate-primitive `&'static str` re-export axis and the
17425        // [`rate_limit_unit_from_window_and_window_round_trip`]
17426        // round-trip pin on the peer projection direction; extends the
17427        // one-canonical-dispatch-per-projection discipline onto the
17428        // reverse-resolver's per-arm probe axis.
17429        for unit in super::RateLimitUnit::ALL {
17430            let window_via_peer = unit.window();
17431            let resolved = super::RateLimitUnit::from_window(window_via_peer);
17432            assert_eq!(
17433                resolved,
17434                Some(*unit),
17435                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17436                 must return Some({unit:?}) — the reverse resolver's per-arm \
17437                 probes must route through the peer `Self::window` accessor \
17438                 so any future arm-magnitude edit reaches both projection \
17439                 directions by construction"
17440            );
17441        }
17442    }
17443
17444    #[test]
17445    fn rate_limit_canonical_unit_accessor_is_const_fn() {
17446        // Fail-before-pass-after pin: witnesses the
17447        // [`RateLimit::canonical_unit`] `const`-eval posture via a
17448        // `const fn` wrapper
17449        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
17450        // whose body calls `rl.canonical_unit()`, well-formed only when
17451        // the callee is itself `const fn` (any future downgrade to
17452        // non-`const` fails at caixa-core build time with E0015 `cannot
17453        // call non-const method`). The runtime body sweeps every
17454        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
17455        // constructs a typed [`RateLimit`] with the peer `Self::window`
17456        // canonical `Duration`, then asserts both the wrapper and the
17457        // direct dispatch agree and both return `Some(unit)`. Composes
17458        // with the sibling
17459        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
17460        // typed [`RateLimit`] projection layer's `const`-posture is
17461        // load-bearing on the reverse resolver's `const`-posture, and
17462        // both must migrate together (a downgrade of either surface
17463        // splits the paired `const`-eval-surface pass on the M3
17464        // mesh-slot rate-limit `Duration ↔ Self` bijection).
17465        const fn canonical_unit_via_const_fn(
17466            rl: &super::RateLimit,
17467        ) -> Option<super::RateLimitUnit> {
17468            rl.canonical_unit()
17469        }
17470        for unit in super::RateLimitUnit::ALL {
17471            let rl = super::RateLimit {
17472                rate: 1,
17473                window: unit.window(),
17474            };
17475            let via_wrapper = canonical_unit_via_const_fn(&rl);
17476            let direct = rl.canonical_unit();
17477            assert_eq!(
17478                via_wrapper, direct,
17479                "RateLimit::canonical_unit() via const fn wrapper must \
17480                 agree with direct dispatch for {unit:?}"
17481            );
17482            assert_eq!(
17483                via_wrapper,
17484                Some(*unit),
17485                "RateLimit::canonical_unit() via const fn wrapper must \
17486                 return Some({unit:?}) for a RateLimit whose window is \
17487                 the peer RateLimitUnit::{unit:?}.window() output"
17488            );
17489        }
17490    }
17491
17492    #[test]
17493    fn rate_limit_unit_projections_are_pairwise_distinct() {
17494        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
17495        // [`RateLimitUnit::window`] outputs must be pairwise distinct
17496        // across every arm — an accidental copy-paste flip that
17497        // reroutes one arm's suffix or window to also match another
17498        // silently collapses two arms onto one, so
17499        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
17500        // (both using `find` on `Self::ALL`) would return whichever
17501        // arm the linear scan lands on first — a match-arm-ordering-
17502        // dependent outcome the closed-set typed-enum shape is meant
17503        // to rule out structurally. Peer of the sibling
17504        // `caixa_kind_wire_consts_are_pairwise_distinct` /
17505        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
17506        // other closed-set typed-enum discriminator axes.
17507        let all = super::RateLimitUnit::ALL;
17508        for (i, a) in all.iter().enumerate() {
17509            for (j, b) in all.iter().enumerate() {
17510                if i != j {
17511                    assert_ne!(
17512                        a.as_suffix(),
17513                        b.as_suffix(),
17514                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
17515                         must be distinct — a collision silently collapses two \
17516                         arms onto one under from_suffix's linear scan"
17517                    );
17518                    assert_ne!(
17519                        a.window(),
17520                        b.window(),
17521                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
17522                         must be distinct — a collision silently collapses two \
17523                         arms onto one under from_window's linear scan"
17524                    );
17525                }
17526            }
17527        }
17528    }
17529
17530    #[test]
17531    fn rate_limit_unit_display_routes_through_as_suffix() {
17532        // Route pin: [`std::fmt::Display`] must byte-equal
17533        // [`RateLimitUnit::as_suffix`] on every arm — the single
17534        // source of truth for the canonical suffix. A future
17535        // reimplementation that hand-rolls the arms instead of
17536        // delegating to [`RateLimitUnit::as_suffix`] would silently
17537        // desynchronize `format!("{u}")` from the codec's parse arm
17538        // (which uses `as_suffix` to compare suffixes). Peer of the
17539        // sibling `caixa_kind_display_routes_through_as_str_helper` /
17540        // `placement_strategy_display_routes_through_as_str_helper`
17541        // pins on the peer closed-set typed-enum Display axes.
17542        for unit in super::RateLimitUnit::ALL {
17543            assert_eq!(
17544                unit.to_string(),
17545                unit.as_suffix(),
17546                "RateLimitUnit::{unit:?} Display must route through \
17547                 as_suffix (single source of truth: the canonical suffix \
17548                 the codec parses and renders)"
17549            );
17550        }
17551    }
17552
17553    #[test]
17554    fn rate_limit_unit_from_window_rejects_non_canonical() {
17555        // Rejection pin on the parser's accept-set: any Duration
17556        // outside the three-arm [`RateLimitUnit::window`] output set
17557        // (sub-second residue, or a second-magnitude outside `{1, 60,
17558        // 3600}`) must return `None`. A future accidental widening of
17559        // the accept-set (rounding down sub-second residue to the
17560        // nearest arm, admitting `Duration::from_secs(30)` as a
17561        // half-minute unit) would silently drift the parser's accept-
17562        // set from the emitter's — a validated slot with a
17563        // non-canonical window would then round-trip through the
17564        // codec to a canonical form the author never wrote.
17565        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
17566        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
17567        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
17568        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
17569        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
17570        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
17571        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
17572    }
17573
17574    #[test]
17575    fn rate_limit_unit_from_suffix_rejects_unknown() {
17576        // Rejection pin on the suffix parser's accept-set: any string
17577        // outside the three-arm [`RateLimitUnit::as_suffix`] output
17578        // set must return `None`. Peer of the sibling
17579        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
17580        // the [`crate::CaixaKind`] `from_wire` accept-set.
17581        for bad in [
17582            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
17583            " s",
17584        ] {
17585            assert!(
17586                super::RateLimitUnit::from_suffix(bad).is_none(),
17587                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
17588                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
17589                 outputs"
17590            );
17591        }
17592    }
17593
17594    #[test]
17595    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
17596        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
17597        // every canonical `:window` magnitude the validate gate
17598        // accepts must map to the paired [`RateLimitUnit`] arm through
17599        // this accessor. A future validate-gate rebrand that widened
17600        // the accepted-window set without extending [`RateLimitUnit`]
17601        // would silently split the accessor's `Some`-return set from
17602        // the validate gate's accept-set — a slot that satisfies
17603        // validate would land at the accessor with `None`, so a
17604        // consumer past validate that pattern-matches on the returned
17605        // `Some` would silently miss the newly-accepted magnitude.
17606        for (window_secs, expected) in [
17607            (1u64, super::RateLimitUnit::Second),
17608            (60, super::RateLimitUnit::Minute),
17609            (3600, super::RateLimitUnit::Hour),
17610        ] {
17611            let rl = RateLimit {
17612                rate: 100,
17613                window: Duration::from_secs(window_secs),
17614            };
17615            assert_eq!(
17616                rl.canonical_unit(),
17617                Some(expected),
17618                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
17619                 must return Some({expected:?})"
17620            );
17621        }
17622        // Non-canonical windows the validate gate rejects also return
17623        // None here — the accessor is the typed-enum projection of
17624        // the sibling `is_canonical_rate_limit_window` predicate.
17625        let bad = RateLimit {
17626            rate: 100,
17627            window: Duration::from_secs(30),
17628        };
17629        assert!(
17630            bad.canonical_unit().is_none(),
17631            "RateLimit with a non-canonical window must return None from \
17632             canonical_unit — the validate gate rejects the same set"
17633        );
17634    }
17635
17636    #[test]
17637    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
17638        // Fail-before-pass-after byte-parity pin: for every canonical
17639        // window the [`rate_limit_codec::render`] arm's emitted string
17640        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
17641        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
17642        // the vestigial free helper [`rate_limit_window_unit`] (a
17643        // `find_map`-walked `Duration → &'static str` delegate) onto the
17644        // substrate primitive [`RateLimit::canonical_unit`] typed method
17645        // (a closed-set `match self.window` arm on
17646        // [`RateLimitUnit::from_window`], projected through
17647        // [`RateLimitUnit::as_suffix`] via the enum's
17648        // [`std::fmt::Display`] impl). A future re-routing of the render
17649        // arm through a differently-computed unit projection would break
17650        // this pin at build time rather than as a silent per-consumer
17651        // codec round-trip drift far from the substrate primitive edit.
17652        //
17653        // Sibling to the peer
17654        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17655        // on the free-helper axis: that pin locks the two projections
17656        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
17657        // on the closed-set arm table; this pin locks the codec's render
17658        // arm reads through the typed accessor rather than the free
17659        // helper. Two production consumers of the canonical-unit axis
17660        // now key off one typed dispatch on the substrate primitive.
17661        for (window_secs, unit) in [
17662            (1u64, super::RateLimitUnit::Second),
17663            (60, super::RateLimitUnit::Minute),
17664            (3600, super::RateLimitUnit::Hour),
17665        ] {
17666            let rl = RateLimit {
17667                rate: 42,
17668                window: Duration::from_secs(window_secs),
17669            };
17670            let policy = MeshPolicy {
17671                rate_limit: Some(rl),
17672                ..Default::default()
17673            };
17674            let json = serde_json::to_string(&policy).unwrap();
17675            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
17676            assert!(
17677                json.contains(&expected),
17678                "rate_limit_codec::render must emit {expected} (via \
17679                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
17680                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
17681            );
17682            // And the accessor route resolves to the same typed unit
17683            // the render arm's Display formatting is asked to produce —
17684            // so a future edit that split the two paths (one through
17685            // the accessor, one through a re-introduced free helper)
17686            // trips this pin.
17687            assert_eq!(
17688                rl.canonical_unit(),
17689                Some(unit),
17690                "RateLimit::canonical_unit must return Some({unit:?}) for a \
17691                 {window_secs}s window; the codec render arm reads the same \
17692                 typed unit through this accessor"
17693            );
17694        }
17695    }
17696
17697    #[test]
17698    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
17699        // Fail-before-pass-after byte-parity pin on the validate gate's
17700        // canonical-window shape probe: every non-canonical `:window`
17701        // the free-helper predicate [`is_canonical_rate_limit_window`]
17702        // rejects is also rejected by the substrate primitive
17703        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
17704        // gate now reads through, and vice versa on the accepted set
17705        // (the three canonical windows). Locks the migration from the
17706        // free helper onto the substrate primitive: a future re-routing
17707        // of one of the two paths through a differently-computed unit
17708        // projection would silently split the codec's accepted set from
17709        // the validate gate's accepted set — a two-consumer drift the
17710        // codec-round-trip pin
17711        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
17712        // above closes on the render arm and this pin closes on the
17713        // validate arm.
17714        for canonical_window_secs in [1u64, 60, 3600] {
17715            let mut s = three_member_spec();
17716            let rl = RateLimit {
17717                rate: 100,
17718                window: Duration::from_secs(canonical_window_secs),
17719            };
17720            s.politicas.rate_limit = Some(rl);
17721            assert!(
17722                s.validate().is_ok(),
17723                "canonical {canonical_window_secs}s window must pass \
17724                 validate_politicas — the validate gate now reads \
17725                 RateLimit::canonical_unit().is_none() and the accessor \
17726                 returns Some on every canonical arm"
17727            );
17728            assert!(
17729                rl.canonical_unit().is_some(),
17730                "canonical {canonical_window_secs}s window must resolve to \
17731                 Some on RateLimit::canonical_unit — the validate gate reads \
17732                 this accessor directly"
17733            );
17734        }
17735        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
17736            let mut s = three_member_spec();
17737            let rl = RateLimit {
17738                rate: 100,
17739                window: Duration::from_secs(non_canonical_window_secs),
17740            };
17741            s.politicas.rate_limit = Some(rl);
17742            assert_eq!(
17743                s.validate().unwrap_err(),
17744                AplicacaoError::PolicyRateLimitWindowNotCanonical {
17745                    window: rl.window(),
17746                },
17747                "non-canonical {non_canonical_window_secs}s window must be \
17748                 rejected by validate_politicas — the validate gate now \
17749                 keys off RateLimit::canonical_unit().is_none()"
17750            );
17751            assert!(
17752                rl.canonical_unit().is_none(),
17753                "non-canonical {non_canonical_window_secs}s window must \
17754                 resolve to None on RateLimit::canonical_unit — the two \
17755                 paths (the free helper the validate gate previously read \
17756                 and the substrate primitive the validate gate now reads) \
17757                 must agree on the same rejected set"
17758            );
17759        }
17760        // And the substrate-primitive [`RateLimit::canonical_unit`]
17761        // accessor's accepted-window set matches the codec's parse arm's
17762        // accepted-suffix set on every canonical / non-canonical shape,
17763        // so a future silent drift between the codec's accepted set and
17764        // the validate gate's accepted set is a build error at test time
17765        // (both consumers key off the same closed-set enum's `match self`
17766        // arms). The predecessor free helper `is_canonical_rate_limit_window`
17767        // — a delegate that composed [`RateLimitUnit::from_window`] with
17768        // `.is_some()` — was deleted after this migration; the
17769        // canonical-window set now lives on exactly one typed dispatch
17770        // on the substrate primitive.
17771        for (secs, expected) in [
17772            (1u64, true),
17773            (60, true),
17774            (3600, true),
17775            (2, false),
17776            (30, false),
17777            (86_400, false),
17778        ] {
17779            let window = Duration::from_secs(secs);
17780            let rl = RateLimit { rate: 1, window };
17781            assert_eq!(
17782                rl.canonical_unit().is_some(),
17783                expected,
17784                "RateLimit::canonical_unit().is_some() must agree with the \
17785                 codec-accepted canonical-window set on {secs}s"
17786            );
17787            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
17788                1 => "s",
17789                60 => "m",
17790                3600 => "h",
17791                _ => return,
17792            })
17793            .is_some_and(|d| d == window);
17794            if expected {
17795                assert!(
17796                    suffix_from_axis,
17797                    "the codec's `&str → Duration` axis \
17798                     ({secs}s) must round-trip to the same Duration the \
17799                     substrate primitive's accessor returns Some on"
17800                );
17801            }
17802        }
17803    }
17804
17805    #[test]
17806    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
17807        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
17808        // derive: for each of the three variants, exactly one of the
17809        // generated `is_second` / `is_minute` / `is_hour` predicates
17810        // returns `true` and the other two return `false`. Peer of
17811        // the sibling
17812        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
17813        // sibling `IsVariant`-derived closed-set typed-enum pins.
17814        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
17815            (super::RateLimitUnit::Second, [true, false, false]),
17816            (super::RateLimitUnit::Minute, [false, true, false]),
17817            (super::RateLimitUnit::Hour, [false, false, true]),
17818        ];
17819        for (variant, expected) in rows {
17820            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
17821            assert_eq!(
17822                observed, expected,
17823                "RateLimitUnit::{variant:?} is_* predicates must partition \
17824                 the arm set (second, minute, hour); got {observed:?}"
17825            );
17826        }
17827    }
17828
17829    #[test]
17830    fn rejects_policy_timeout_sub_millisecond() {
17831        // A purely sub-millisecond `Duration` (`from_micros(500)` =
17832        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
17833        // arm passes — but `as_millis() == 0`, so the shared codec's
17834        // `render` arm returns the literal `"0s"`, which the
17835        // codec's `parse` arm then deserializes as `Duration::ZERO`
17836        // and the `PolicyTimeoutZero` zero-floor gate would reject
17837        // on re-validate. Pin the rejection at the typed slot's
17838        // canonical-floor gate so the round-trip break surfaces at
17839        // validate time, naming the offending `Duration`, rather
17840        // than at the next serialize → deserialize round-trip far
17841        // from the source `caixa.lisp`.
17842        let mut s = three_member_spec();
17843        let timeout = Duration::from_micros(500);
17844        s.politicas.timeout = Some(timeout);
17845        assert_eq!(
17846            s.validate().unwrap_err(),
17847            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
17848        );
17849    }
17850
17851    #[test]
17852    fn rejects_policy_timeout_non_integer_millisecond() {
17853        // A `Duration` with non-integer-millisecond residue
17854        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
17855        // through the shared codec's `render` arm as `"1ms"` (the
17856        // `as_millis()` floor truncates), which the codec's `parse`
17857        // arm then deserializes as `Duration::from_millis(1)` =
17858        // 1_000_000 ns — silently *different* from the original.
17859        // Pin the rejection so this round-trip break surfaces at
17860        // validate time, where the offending `Duration` is named,
17861        // rather than as a silent value-laundered round-trip on the
17862        // next codec round-trip.
17863        let mut s = three_member_spec();
17864        let timeout = Duration::from_micros(1500);
17865        s.politicas.timeout = Some(timeout);
17866        assert_eq!(
17867            s.validate().unwrap_err(),
17868            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
17869        );
17870    }
17871
17872    #[test]
17873    fn accepts_policy_timeout_integer_millisecond_forms() {
17874        // The codec's accepted set — integer multiples of 1ms — is
17875        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
17876        // `1h` all pass the canonical gate. Pin the canonical-forms
17877        // sweep so a future tightening of the codec's grammar (e.g.
17878        // dropping `:ms`) surfaces here as a test failure rather
17879        // than a silent contract narrowing on the typed slot.
17880        for timeout in [
17881            Duration::from_millis(1),
17882            Duration::from_millis(500),
17883            Duration::from_millis(1500),
17884            Duration::from_secs(30),
17885            Duration::from_secs(120),
17886            Duration::from_secs(3600),
17887        ] {
17888            let mut s = three_member_spec();
17889            s.politicas.timeout = Some(timeout);
17890            s.validate()
17891                .expect("integer-millisecond :timeout must validate");
17892        }
17893    }
17894
17895    #[test]
17896    fn policy_timeout_zero_takes_precedence_over_canonical() {
17897        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
17898        // pass the canonical-millisecond gate; the more self-locating
17899        // `PolicyTimeoutZero` arm (which names the omit-axis
17900        // remediation directly) must fire first. Pin the ordering so
17901        // a future refactor that reorders the arms surfaces here as a
17902        // test failure rather than a silent diagnostic regression.
17903        let mut s = three_member_spec();
17904        s.politicas.timeout = Some(Duration::ZERO);
17905        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
17906    }
17907
17908    #[test]
17909    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
17910        // The diagnostic envelope carries the offending `Duration`
17911        // verbatim so the author can grep their `caixa.lisp` for
17912        // `:timeout "<value>"` and fix it in one edit. Same
17913        // diagnostic shape every other typed-slot canonical-form
17914        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
17915        // peer `:rate-limit :window` axis.
17916        let mut s = three_member_spec();
17917        let timeout = Duration::from_nanos(1_000_001);
17918        s.politicas.timeout = Some(timeout);
17919        match s.validate().unwrap_err() {
17920            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
17921                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
17922            }
17923            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
17924        }
17925    }
17926
17927    #[test]
17928    fn rejects_policy_timeout_above_cap() {
17929        // The fail-before-pass-after pin: 3601s = 1h + 1s is
17930        // structurally one canonical-tick past the
17931        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
17932        // integer-millisecond magnitude the canonical-form arm above
17933        // accepts cleanly, that the codec round-trips losslessly as
17934        // `"3601s"`, and that silently passed validate on every
17935        // pre-gate codebase because the typed slot's only checks were
17936        // the zero-floor and canonical-form arms. The mesh-level
17937        // deadline degenerates only at the runtime substrate (Envoy
17938        // / Cilium L7 timeout overlay) far from the source
17939        // `caixa.lisp` with no field naming the offending policy.
17940        let mut s = three_member_spec();
17941        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
17942        s.politicas.timeout = Some(timeout);
17943        assert_eq!(
17944            s.validate().unwrap_err(),
17945            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17946        );
17947    }
17948
17949    #[test]
17950    fn rejects_policy_timeout_one_millisecond_above_cap() {
17951        // Boundary case: exactly 1ms past the cap (the granularity
17952        // the canonical-form gate enforces). Catches a future
17953        // "strictly less than" half-measure and pins the diagnostic
17954        // to name the offending `Duration` verbatim. Peer of
17955        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
17956        // boundary pin on the sibling `:limits :memory` top edge.
17957        let mut s = three_member_spec();
17958        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
17959        s.politicas.timeout = Some(timeout);
17960        assert_eq!(
17961            s.validate().unwrap_err(),
17962            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17963        );
17964    }
17965
17966    #[test]
17967    fn rejects_policy_timeout_far_above_cap() {
17968        // The "obvious authoring footgun" case: a `(:timeout "24h")`
17969        // or `(:timeout "86400s")` — values the canonical-form arm
17970        // accepts as integer-millisecond magnitudes, the codec
17971        // round-trips losslessly through serde, but the mesh-level
17972        // policy cannot honor (a 24-hour synchronous-`:contratos`
17973        // deadline is operationally indistinguishable from
17974        // omit-the-axis). Until this gate landed validate accepted
17975        // it. Pin both common above-cap values (24h, 7d) so a future
17976        // relaxation that drops the upper bound surfaces here.
17977        for timeout in [
17978            Duration::from_secs(86_400),    // 24h
17979            Duration::from_secs(604_800),   // 7d
17980            Duration::from_secs(1_000_000), // ~11.5 days
17981        ] {
17982            let mut s = three_member_spec();
17983            s.politicas.timeout = Some(timeout);
17984            assert_eq!(
17985                s.validate().unwrap_err(),
17986                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
17987            );
17988        }
17989    }
17990
17991    #[test]
17992    fn accepts_policy_timeout_at_cap() {
17993        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
17994        // must validate. The cap is inclusive on the top edge,
17995        // matching the [`POLICY_RETRIES_MAX`] /
17996        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
17997        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
17998        // sibling capped axes. Pin the boundary explicitly so a
17999        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
18000        // instead of `>`) surfaces here as a test failure rather
18001        // than a silent contract narrowing.
18002        let mut s = three_member_spec();
18003        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
18004        s.validate()
18005            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
18006    }
18007
18008    #[test]
18009    fn accepts_policy_timeout_typical_values() {
18010        // The documented production-playbook band positive-control
18011        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
18012        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
18013        // plus a sweep through the long-running-workflow band
18014        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
18015        // validated set explicitly so a future tightening of the
18016        // ceiling surfaces here as a deliberate test edit, not a
18017        // silent contract narrowing.
18018        for timeout in [
18019            Duration::from_millis(1),
18020            Duration::from_millis(500),
18021            Duration::from_secs(1),
18022            Duration::from_secs(10),
18023            Duration::from_secs(15), // Envoy default
18024            Duration::from_secs(30),
18025            Duration::from_secs(60), // AWS App Mesh typical
18026            Duration::from_secs(300),
18027            Duration::from_secs(900),
18028            Duration::from_secs(1800),
18029            Duration::from_secs(3600), // exactly 1h, the cap
18030        ] {
18031            let mut s = three_member_spec();
18032            s.politicas.timeout = Some(timeout);
18033            s.validate()
18034                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
18035        }
18036    }
18037
18038    #[test]
18039    fn policy_timeout_zero_takes_precedence_over_cap() {
18040        // The cross-arm ordering pin: `Duration::ZERO` is
18041        // structurally outside both `>= 1ms` (zero-floor) and
18042        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
18043        // diagnostic is the more self-locating one (it directly
18044        // names the omit-axis remediation), so the validate gate
18045        // must fire on zero first. Same shape every other
18046        // zero-then-shape ordering on this surface uses
18047        // ([`AplicacaoError::PolicyRetriesZero`] then
18048        // [`AplicacaoError::PolicyRetriesExceedsCap`];
18049        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18050        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18051        let mut s = three_member_spec();
18052        s.politicas.timeout = Some(Duration::ZERO);
18053        assert_eq!(
18054            s.validate().unwrap_err(),
18055            AplicacaoError::PolicyTimeoutZero,
18056            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18057        );
18058    }
18059
18060    #[test]
18061    fn policy_timeout_canonical_takes_precedence_over_cap() {
18062        // The cross-arm ordering pin: a `Duration` that is *both*
18063        // sub-millisecond (non-canonical-form) and structurally
18064        // above the cap surfaces the canonical-form diagnostic
18065        // first, because the round-trip-shape break is the more
18066        // fundamental issue (the value can't even round-trip
18067        // through the codec, so the cap diagnostic naming
18068        // `1ms..=1h` would be misleading — there's no integer-ms
18069        // form of the offending value). Pin the order so a future
18070        // refactor that reorders the arms surfaces here as a test
18071        // failure rather than a silent diagnostic regression.
18072        let mut s = three_member_spec();
18073        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
18074        // *and* total magnitude above the 1h cap.
18075        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
18076        s.politicas.timeout = Some(timeout);
18077        assert_eq!(
18078            s.validate().unwrap_err(),
18079            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
18080            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18081        );
18082    }
18083
18084    #[test]
18085    fn policy_timeout_cap_diagnostic_carries_offending_value() {
18086        // The diagnostic-shape pin: the offending `Duration` is
18087        // carried verbatim into the
18088        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
18089        // surfaced error message names the value the author wrote
18090        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
18091        // exceeds the mesh-policy ceiling …"`), not just the cap.
18092        // Same self-locating diagnostic shape every other typed-cap
18093        // arm on this surface carries
18094        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
18095        // offending retry count verbatim).
18096        let mut s = three_member_spec();
18097        let timeout = Duration::from_secs(7200); // 2h
18098        s.politicas.timeout = Some(timeout);
18099        let err = s.validate().unwrap_err();
18100        assert!(
18101            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
18102            "got {err:?}"
18103        );
18104        let msg = err.to_string();
18105        assert!(
18106            msg.contains("7200"),
18107            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
18108        );
18109    }
18110
18111    #[test]
18112    fn policy_timeout_cap_pins_canonical_value() {
18113        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
18114        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
18115        // the shared duration codec emits as a clean canonical
18116        // string (`"<n>h"`). Pinning the literal value here surfaces
18117        // a future drift (a relaxation to 24h, a tightening to 5m)
18118        // as a deliberate test edit, not a silent contract
18119        // narrowing. Same shape every other typed-cap value pin on
18120        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
18121        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
18122        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
18123    }
18124
18125    #[test]
18126    fn policy_timeout_cap_value_round_trips_through_codec() {
18127        // The codec round-trip property the cap arm preserves: the
18128        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
18129        // the shared duration codec — every value at the cap renders
18130        // to a clean canonical string (`"1h"`) and parses back to
18131        // the same `Duration`. Pin this so a future drift between
18132        // the cap constant and the codec's largest emitted unit
18133        // surfaces here. Same shape every other typed boundary pin
18134        // on this surface uses
18135        // (`wasm32_memory_cap_matches_parsed_4_gib`).
18136        let policy = MeshPolicy {
18137            timeout: Some(POLICY_TIMEOUT_MAX),
18138            ..Default::default()
18139        };
18140        let json = serde_json::to_string(&policy).unwrap();
18141        // The codec emits `"1h"` for the canonical 1-hour magnitude.
18142        assert!(
18143            json.contains("\"1h\""),
18144            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
18145        );
18146        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18147        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
18148    }
18149
18150    #[test]
18151    fn rejects_circuit_breaker_window_sub_millisecond() {
18152        // Peer of the `:timeout` sub-millisecond arm on the second
18153        // typed-`Duration` `:politicas` axis: a purely sub-ms
18154        // `Duration` (`from_micros(500)`) renders through the shared
18155        // codec as `"0s"`, which the codec parses back to
18156        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
18157        // zero-floor gate then rejects on re-validate.
18158        let mut s = three_member_spec();
18159        let window = Duration::from_micros(500);
18160        s.politicas.circuit_breaker = Some(CircuitBreaker {
18161            max_failures: 5,
18162            window,
18163        });
18164        assert_eq!(
18165            s.validate().unwrap_err(),
18166            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18167        );
18168    }
18169
18170    #[test]
18171    fn rejects_circuit_breaker_window_non_integer_millisecond() {
18172        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
18173        // with non-integer-millisecond residue renders through the
18174        // shared codec as the truncated `"<n>ms"` form, parsing back
18175        // to a *different* `Duration` on the next round-trip.
18176        let mut s = three_member_spec();
18177        let window = Duration::from_micros(1500);
18178        s.politicas.circuit_breaker = Some(CircuitBreaker {
18179            max_failures: 5,
18180            window,
18181        });
18182        assert_eq!(
18183            s.validate().unwrap_err(),
18184            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18185        );
18186    }
18187
18188    #[test]
18189    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
18190        // The canonical-forms sweep on the breaker axis: every
18191        // integer-ms multiple the codec round-trips losslessly
18192        // passes the canonical gate.
18193        for window in [
18194            Duration::from_millis(1),
18195            Duration::from_millis(500),
18196            Duration::from_millis(1500),
18197            Duration::from_secs(30),
18198            Duration::from_secs(60),
18199            Duration::from_secs(3600),
18200        ] {
18201            let mut s = three_member_spec();
18202            s.politicas.circuit_breaker = Some(CircuitBreaker {
18203                max_failures: 5,
18204                window,
18205            });
18206            s.validate()
18207                .expect("integer-millisecond :circuit-breaker :window must validate");
18208        }
18209    }
18210
18211    #[test]
18212    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
18213        // `Duration::ZERO` would pass the canonical-ms gate (the
18214        // sub-ns residue is zero) but must surface the narrower
18215        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
18216        // remediation.
18217        let mut s = three_member_spec();
18218        s.politicas.circuit_breaker = Some(CircuitBreaker {
18219            max_failures: 5,
18220            window: Duration::ZERO,
18221        });
18222        assert_eq!(
18223            s.validate().unwrap_err(),
18224            AplicacaoError::PolicyBreakerZeroWindow
18225        );
18226    }
18227
18228    #[test]
18229    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
18230        // Both axes invalid: max_failures == 0 *and* window is
18231        // sub-ms. The validate gate must fire on max_failures first
18232        // (matching the existing ordering pin
18233        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
18234        // the existing diagnostic continues to lead with the simpler
18235        // "zero threshold" framing.
18236        let mut s = three_member_spec();
18237        s.politicas.circuit_breaker = Some(CircuitBreaker {
18238            max_failures: 0,
18239            window: Duration::from_micros(500),
18240        });
18241        assert_eq!(
18242            s.validate().unwrap_err(),
18243            AplicacaoError::PolicyBreakerZeroFailures
18244        );
18245    }
18246
18247    #[test]
18248    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
18249        let mut s = three_member_spec();
18250        let window = Duration::from_nanos(60_000_000_001);
18251        s.politicas.circuit_breaker = Some(CircuitBreaker {
18252            max_failures: 5,
18253            window,
18254        });
18255        match s.validate().unwrap_err() {
18256            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
18257                assert_eq!(w, window, "diagnostic must carry the offending Duration");
18258            }
18259            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
18260        }
18261    }
18262
18263    #[test]
18264    fn rejects_circuit_breaker_window_above_cap() {
18265        // The fail-before-pass-after pin: 3601s = 1h + 1s is
18266        // structurally one canonical-tick past the
18267        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
18268        // integer-millisecond magnitude the canonical-form arm above
18269        // accepts cleanly, that the codec round-trips losslessly as
18270        // `"3601s"`, and that silently passed validate on every
18271        // pre-gate codebase because the typed slot's only checks were
18272        // the zero-floor and canonical-form arms. The
18273        // rolling-window-to-lifetime-counter degeneration surfaces
18274        // only at the runtime substrate (Envoy's outlier_detection
18275        // interval, the future CiliumClusterwideEnvoyConfig overlay)
18276        // far from the source `caixa.lisp` with no field naming the
18277        // offending policy.
18278        let mut s = three_member_spec();
18279        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18280        s.politicas.circuit_breaker = Some(CircuitBreaker {
18281            max_failures: 5,
18282            window,
18283        });
18284        assert_eq!(
18285            s.validate().unwrap_err(),
18286            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18287        );
18288    }
18289
18290    #[test]
18291    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
18292        // Boundary case: exactly 1ms past the cap (the granularity the
18293        // canonical-form gate enforces). Catches a future "strictly
18294        // less than" half-measure and pins the diagnostic to name the
18295        // offending `Duration` verbatim. Peer of
18296        // `rejects_policy_timeout_one_millisecond_above_cap` on the
18297        // sibling duration-typed `:politicas :timeout` top edge.
18298        let mut s = three_member_spec();
18299        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
18300        s.politicas.circuit_breaker = Some(CircuitBreaker {
18301            max_failures: 5,
18302            window,
18303        });
18304        assert_eq!(
18305            s.validate().unwrap_err(),
18306            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18307        );
18308    }
18309
18310    #[test]
18311    fn rejects_circuit_breaker_window_far_above_cap() {
18312        // The "obvious authoring footgun" case: a `(:window "24h")` or
18313        // `(:window "86400s")` — values the canonical-form arm
18314        // accepts as integer-millisecond magnitudes, the codec
18315        // round-trips losslessly through serde, but the
18316        // rolling-window breaker contract cannot honor (a 24-hour
18317        // rolling failure window is operationally a lifetime counter).
18318        // Until this gate landed validate accepted it. Pin both common
18319        // above-cap values (24h, 7d) so a future relaxation that
18320        // drops the upper bound surfaces here.
18321        for window in [
18322            Duration::from_secs(86_400),    // 24h
18323            Duration::from_secs(604_800),   // 7d
18324            Duration::from_secs(1_000_000), // ~11.5 days
18325        ] {
18326            let mut s = three_member_spec();
18327            s.politicas.circuit_breaker = Some(CircuitBreaker {
18328                max_failures: 5,
18329                window,
18330            });
18331            assert_eq!(
18332                s.validate().unwrap_err(),
18333                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18334            );
18335        }
18336    }
18337
18338    #[test]
18339    fn accepts_circuit_breaker_window_at_cap() {
18340        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
18341        // (1h) — must validate. The cap is inclusive on the top edge,
18342        // matching the [`POLICY_TIMEOUT_MAX`] /
18343        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
18344        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18345        // sibling capped axes. Pin the boundary explicitly so a
18346        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
18347        // instead of `>`) surfaces here as a test failure rather than
18348        // a silent contract narrowing.
18349        let mut s = three_member_spec();
18350        s.politicas.circuit_breaker = Some(CircuitBreaker {
18351            max_failures: 5,
18352            window: POLICY_BREAKER_WINDOW_MAX,
18353        });
18354        s.validate()
18355            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
18356    }
18357
18358    #[test]
18359    fn accepts_circuit_breaker_window_typical_values() {
18360        // The documented production-playbook band positive-control
18361        // sweep — every value Hystrix / resilience4j / Istio / Envoy
18362        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
18363        // through the long-tail failure-detection band (15m, 30m, 1h)
18364        // the cap accepts. Pin the inclusive validated set explicitly
18365        // so a future tightening of the ceiling surfaces here as a
18366        // deliberate test edit, not a silent contract narrowing.
18367        for window in [
18368            Duration::from_millis(1),
18369            Duration::from_millis(500),
18370            Duration::from_secs(1),
18371            Duration::from_secs(10), // Hystrix / Istio / Envoy default
18372            Duration::from_secs(30),
18373            Duration::from_secs(60),  // resilience4j typical
18374            Duration::from_secs(300), // AWS App Mesh typical
18375            Duration::from_secs(900),
18376            Duration::from_secs(1800),
18377            Duration::from_secs(3600), // exactly 1h, the cap
18378        ] {
18379            let mut s = three_member_spec();
18380            s.politicas.circuit_breaker = Some(CircuitBreaker {
18381                max_failures: 5,
18382                window,
18383            });
18384            s.validate()
18385                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
18386        }
18387    }
18388
18389    #[test]
18390    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
18391        // The cross-arm ordering pin: `Duration::ZERO` is structurally
18392        // outside both `>= 1ms` (zero-floor) and
18393        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
18394        // diagnostic is the more self-locating one (it directly names
18395        // the omit-axis remediation), so the validate gate must fire
18396        // on zero first. Same shape every other zero-then-cap
18397        // ordering on this surface uses
18398        // ([`AplicacaoError::PolicyTimeoutZero`] then
18399        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
18400        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18401        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18402        let mut s = three_member_spec();
18403        s.politicas.circuit_breaker = Some(CircuitBreaker {
18404            max_failures: 5,
18405            window: Duration::ZERO,
18406        });
18407        assert_eq!(
18408            s.validate().unwrap_err(),
18409            AplicacaoError::PolicyBreakerZeroWindow,
18410            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18411        );
18412    }
18413
18414    #[test]
18415    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
18416        // The cross-arm ordering pin: a `Duration` that is *both*
18417        // sub-millisecond (non-canonical-form) and structurally above
18418        // the cap surfaces the canonical-form diagnostic first,
18419        // because the round-trip-shape break is the more fundamental
18420        // issue (the value can't even round-trip through the codec, so
18421        // the cap diagnostic naming `1ms..=1h` would be misleading —
18422        // there's no integer-ms form of the offending value). Pin the
18423        // order so a future refactor that reorders the arms surfaces
18424        // here as a test failure rather than a silent diagnostic
18425        // regression. Peer of
18426        // `policy_timeout_canonical_takes_precedence_over_cap` on the
18427        // sibling duration-typed `:politicas :timeout` axis.
18428        let mut s = three_member_spec();
18429        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
18430        s.politicas.circuit_breaker = Some(CircuitBreaker {
18431            max_failures: 5,
18432            window,
18433        });
18434        assert_eq!(
18435            s.validate().unwrap_err(),
18436            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
18437            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18438        );
18439    }
18440
18441    #[test]
18442    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
18443        // The cross-arm ordering pin between the two breaker axes: a
18444        // `CircuitBreaker` whose *both* `max_failures` is above its
18445        // cap *and* `window` is above its cap surfaces the
18446        // max-failures cap diagnostic first, because the validate
18447        // gate visits the failures arm before the window arm. Pin the
18448        // order so a future refactor that reorders the breaker arms
18449        // surfaces here.
18450        let mut s = three_member_spec();
18451        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18452        s.politicas.circuit_breaker = Some(CircuitBreaker {
18453            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18454            window,
18455        });
18456        assert_eq!(
18457            s.validate().unwrap_err(),
18458            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18459                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
18460            },
18461            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
18462        );
18463    }
18464
18465    #[test]
18466    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
18467        // The diagnostic-shape pin: the offending `Duration` is
18468        // carried verbatim into the
18469        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
18470        // the surfaced error message names the value the author wrote
18471        // (`":politicas :circuit-breaker :window (Duration { secs:
18472        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
18473        // just the cap. Same self-locating diagnostic shape every
18474        // other typed-cap arm on this surface carries
18475        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
18476        // offending `Duration` verbatim).
18477        let mut s = three_member_spec();
18478        let window = Duration::from_secs(7200); // 2h
18479        s.politicas.circuit_breaker = Some(CircuitBreaker {
18480            max_failures: 5,
18481            window,
18482        });
18483        let err = s.validate().unwrap_err();
18484        assert!(
18485            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
18486            "got {err:?}"
18487        );
18488        let msg = err.to_string();
18489        assert!(
18490            msg.contains("7200"),
18491            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
18492        );
18493    }
18494
18495    #[test]
18496    fn circuit_breaker_window_cap_pins_canonical_value() {
18497        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
18498        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
18499        // shared duration codec emits as a clean canonical string
18500        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
18501        // the sibling duration-typed `:politicas :timeout` axis (the
18502        // two duration-typed `:politicas` axes share a uniform top
18503        // edge). Pinning the literal value here surfaces a future
18504        // drift (a relaxation to 24h, a tightening to 5m) as a
18505        // deliberate test edit, not a silent contract narrowing. Same
18506        // shape every other typed-cap value pin on this surface uses
18507        // (`policy_timeout_cap_pins_canonical_value`).
18508        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
18509        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
18510        assert_eq!(
18511            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
18512            "the two duration-typed `:politicas` caps share the same top edge"
18513        );
18514    }
18515
18516    #[test]
18517    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
18518        // The codec round-trip property the cap arm preserves: the
18519        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
18520        // through the shared duration codec — every value at the cap
18521        // renders to a clean canonical string (`"1h"`) and parses back
18522        // to the same `Duration`. Pin this so a future drift between
18523        // the cap constant and the codec's largest emitted unit
18524        // surfaces here. Same shape every other typed boundary pin on
18525        // this surface uses
18526        // (`policy_timeout_cap_value_round_trips_through_codec`).
18527        let policy = MeshPolicy {
18528            circuit_breaker: Some(CircuitBreaker {
18529                max_failures: 5,
18530                window: POLICY_BREAKER_WINDOW_MAX,
18531            }),
18532            ..Default::default()
18533        };
18534        let json = serde_json::to_string(&policy).unwrap();
18535        // The codec emits `"1h"` for the canonical 1-hour magnitude.
18536        assert!(
18537            json.contains("\"1h\""),
18538            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
18539        );
18540        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18541        assert_eq!(
18542            back.circuit_breaker.unwrap().window,
18543            POLICY_BREAKER_WINDOW_MAX
18544        );
18545    }
18546
18547    #[test]
18548    fn is_integer_millisecond_duration_predicate_tracks_codec() {
18549        // Pin the predicate's accepted set against the codec's
18550        // accepted set explicitly. The codec parses
18551        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
18552        // accepted value is an integer-millisecond multiple — so the
18553        // predicate must accept exactly that set. Same shape every
18554        // other predicate-on-the-typed-slot helper carries
18555        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
18556        // Read directly from the codec-owned predicate — the crate's
18557        // single source of truth every typed-`Duration` axis now routes
18558        // through via
18559        // [`crate::render::require_positive_canonical_bounded_duration`].
18560        use super::supervisor::duration_codec::is_integer_millisecond_duration;
18561        assert!(is_integer_millisecond_duration(Duration::ZERO));
18562        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
18563        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
18564        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
18565        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
18566        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
18567        // Non-integer-millisecond residue: rejected.
18568        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
18569        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
18570        assert!(!is_integer_millisecond_duration(Duration::from_micros(
18571            1500
18572        )));
18573        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
18574        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
18575            999_999
18576        )));
18577        // The 1-ns-past-1ms boundary: rejected (no longer a clean
18578        // integer-millisecond multiple).
18579        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
18580            1_000_001
18581        )));
18582    }
18583
18584    #[test]
18585    fn policy_timeout_validated_value_round_trips_through_codec() {
18586        // The structural property the canonical-ms gate enforces:
18587        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
18588        // round-trips losslessly through the shared `duration_codec`
18589        // (serialize → string → deserialize → equal value). Pin this
18590        // end-to-end so a future change to either side (the validate
18591        // gate's accepted granularity, the codec's parse/render unit
18592        // set) that breaks the alignment surfaces here. The
18593        // previous-state shape (typed slot accepts arbitrary
18594        // `Duration`, codec only round-trips integer-ms) would fail
18595        // this test for any `Duration::from_micros(1500)` timeout —
18596        // the validate gate now forecloses that.
18597        for timeout in [
18598            Duration::from_millis(1),
18599            Duration::from_millis(1500),
18600            Duration::from_secs(30),
18601            Duration::from_secs(3600),
18602        ] {
18603            let mut s = three_member_spec();
18604            s.politicas.timeout = Some(timeout);
18605            s.validate().unwrap();
18606            let json = serde_json::to_string(&s.politicas).unwrap();
18607            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18608            assert_eq!(
18609                back.timeout, s.politicas.timeout,
18610                "every validated :timeout must round-trip losslessly through the codec"
18611            );
18612        }
18613    }
18614
18615    #[test]
18616    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
18617        // Peer of the `:timeout` round-trip property on the breaker
18618        // axis.
18619        for window in [
18620            Duration::from_millis(1),
18621            Duration::from_millis(1500),
18622            Duration::from_secs(30),
18623            Duration::from_secs(3600),
18624        ] {
18625            let mut s = three_member_spec();
18626            s.politicas.circuit_breaker = Some(CircuitBreaker {
18627                max_failures: 5,
18628                window,
18629            });
18630            s.validate().unwrap();
18631            let json = serde_json::to_string(&s.politicas).unwrap();
18632            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18633            assert_eq!(
18634                back.circuit_breaker.unwrap().window,
18635                window,
18636                "every validated :circuit-breaker :window must round-trip losslessly"
18637            );
18638        }
18639    }
18640
18641    #[test]
18642    fn empty_politicas_validates() {
18643        // Omitting every policy axis is fine — defaults express "no
18644        // policy on this axis", not "policy = 0". The fixture's typical
18645        // values continue to validate; this test pins that
18646        // MeshPolicy::default() is a clean pass through validate().
18647        let mut s = three_member_spec();
18648        s.politicas = MeshPolicy::default();
18649        s.validate().unwrap();
18650    }
18651
18652    #[test]
18653    fn typical_politicas_validates_with_every_axis_set() {
18654        // The full §III.1 example block (timeout + retries + breaker +
18655        // mtls + rate-limit) — every axis nonzero — must remain a
18656        // clean pass.
18657        let mut s = three_member_spec();
18658        s.politicas = MeshPolicy {
18659            timeout: Some(Duration::from_secs(30)),
18660            retries: Some(3),
18661            circuit_breaker: Some(CircuitBreaker {
18662                max_failures: 5,
18663                window: Duration::from_secs(60),
18664            }),
18665            mtls_required: Some(true),
18666            rate_limit: Some(RateLimit {
18667                rate: 100,
18668                window: Duration::from_secs(1),
18669            }),
18670        };
18671        s.validate().unwrap();
18672    }
18673
18674    #[test]
18675    fn rejects_empty_cluster_name() {
18676        let mut s = three_member_spec();
18677        s.placement.clusters = vec!["rio".into(), "".into()];
18678        assert_eq!(
18679            s.validate().unwrap_err(),
18680            AplicacaoError::PlacementClusterEmpty
18681        );
18682    }
18683
18684    #[test]
18685    fn rejects_duplicate_cluster_names() {
18686        let mut s = three_member_spec();
18687        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
18688        let err = s.validate().unwrap_err();
18689        assert!(
18690            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
18691            "got {err:?}"
18692        );
18693    }
18694
18695    #[test]
18696    fn rejects_placement_cluster_with_uppercase() {
18697        // The canonical "I copied the cluster's display name verbatim"
18698        // typo — K8s context names are lowercase per DNS-1123 label
18699        // rule, but org docs often round-trip a TitleCase identifier
18700        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
18701        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
18702        // on the peer name axis.
18703        let mut s = three_member_spec();
18704        s.placement.clusters = vec!["Rio".into(), "mar".into()];
18705        let err = s.validate().unwrap_err();
18706        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18707            panic!("expected PlacementClusterInvalid, got other variant");
18708        };
18709        assert_eq!(cluster, "Rio");
18710        assert!(
18711            reason.contains("uppercase"),
18712            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
18713        );
18714        assert!(
18715            reason.contains("\"rio\""),
18716            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
18717        );
18718    }
18719
18720    #[test]
18721    fn rejects_placement_cluster_with_underscore() {
18722        // The canonical "I'm thinking of an env var / hostname slug"
18723        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
18724        // schema. K8s context filtering on `my_cluster` silently misses
18725        // the cluster the author intended; the gate moves it to caixa-
18726        // build time. Same shape as `rejects_membro_caixa_with_underscore`
18727        // (3f9d7a0).
18728        let mut s = three_member_spec();
18729        s.placement.clusters = vec!["my_cluster".into()];
18730        let err = s.validate().unwrap_err();
18731        assert!(
18732            matches!(
18733                err,
18734                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18735                    if cluster == "my_cluster" && reason.contains('_')
18736            ),
18737            "got {err:?}"
18738        );
18739    }
18740
18741    #[test]
18742    fn rejects_placement_cluster_with_dot() {
18743        // A `:placement :clusters` entry is a single DNS-1123 *label*,
18744        // not a subdomain — even though K8s context names sometimes
18745        // carry a dotted form via kubeconfig conventions, the strictest
18746        // floor among the use sites (DNS-1035 cluster.x-k8s.io
18747        // `metadata.name`, Cilium identity label values) wins. The "I
18748        // want to namespace my cluster names with `.`" intent is
18749        // expressed via `-` (`mar-east`).
18750        let mut s = three_member_spec();
18751        s.placement.clusters = vec!["team.rio".into()];
18752        let err = s.validate().unwrap_err();
18753        assert!(
18754            matches!(
18755                err,
18756                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18757                    if cluster == "team.rio" && reason.contains('.')
18758            ),
18759            "got {err:?}"
18760        );
18761    }
18762
18763    #[test]
18764    fn rejects_placement_cluster_with_leading_hyphen() {
18765        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
18766        // with an alphanumeric. The K8s apiserver rejects `-rio`
18767        // outright; the rendered fan-out would emit a `metadata.name:
18768        // "-rio"` that fails admission far from the source caixa.lisp.
18769        let mut s = three_member_spec();
18770        s.placement.clusters = vec!["-rio".into()];
18771        let err = s.validate().unwrap_err();
18772        assert!(
18773            matches!(
18774                err,
18775                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18776                    if cluster == "-rio" && reason.contains("start and end")
18777            ),
18778            "got {err:?}"
18779        );
18780    }
18781
18782    #[test]
18783    fn rejects_placement_cluster_with_trailing_hyphen() {
18784        // The symmetric arm of the boundary rule. Pin separately so
18785        // both ends are covered against a future relaxation that only
18786        // checks one boundary (parallel to
18787        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
18788        let mut s = three_member_spec();
18789        s.placement.clusters = vec!["rio-".into()];
18790        let err = s.validate().unwrap_err();
18791        assert!(
18792            matches!(
18793                err,
18794                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18795                    if cluster == "rio-"
18796            ),
18797            "got {err:?}"
18798        );
18799    }
18800
18801    #[test]
18802    fn rejects_placement_cluster_with_unicode() {
18803        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
18804        // before it reaches K8s. The byte-by-byte ASCII validity check
18805        // rejects multi-byte UTF-8 sequences by the first byte that
18806        // fails `[a-z0-9-]`.
18807        let mut s = three_member_spec();
18808        s.placement.clusters = vec!["rió".into()];
18809        let err = s.validate().unwrap_err();
18810        assert!(
18811            matches!(
18812                err,
18813                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18814                    if cluster == "rió"
18815            ),
18816            "got {err:?}"
18817        );
18818    }
18819
18820    #[test]
18821    fn rejects_placement_cluster_with_whitespace() {
18822        // Whitespace is the canonical "I pasted from a sketch / doc"
18823        // footgun. The apiserver rejects every cluster `metadata.name`
18824        // value carrying whitespace.
18825        let mut s = three_member_spec();
18826        s.placement.clusters = vec!["rio cluster".into()];
18827        let err = s.validate().unwrap_err();
18828        assert!(
18829            matches!(
18830                err,
18831                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18832                    if cluster == "rio cluster"
18833            ),
18834            "got {err:?}"
18835        );
18836    }
18837
18838    #[test]
18839    fn rejects_placement_cluster_too_long() {
18840        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
18841        // pin. The diagnostic names both the cap (63) and the actual
18842        // length so the author can shorten in one edit. Mirrors
18843        // `rejects_membro_caixa_too_long` (3f9d7a0).
18844        let mut s = three_member_spec();
18845        let too_long = "a".repeat(64);
18846        s.placement.clusters = vec![too_long.clone()];
18847        let err = s.validate().unwrap_err();
18848        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18849            panic!("expected PlacementClusterInvalid");
18850        };
18851        assert_eq!(cluster, too_long);
18852        assert!(
18853            reason.contains("63") && reason.contains("64"),
18854            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
18855        );
18856    }
18857
18858    #[test]
18859    fn placement_cluster_max_length_validates() {
18860        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
18861        // future tightening (e.g. dropping to 62) surfaces here as a
18862        // regression, mirroring `membro_caixa_max_length_validates`
18863        // (3f9d7a0).
18864        let mut s = three_member_spec();
18865        s.placement.clusters = vec!["a".repeat(63)];
18866        s.validate().unwrap();
18867    }
18868
18869    #[test]
18870    fn accepts_canonical_placement_cluster_forms() {
18871        // The DNS-1123 label shapes a caixa author is realistically
18872        // going to write for cluster names: single-word lowercase
18873        // (`rio`), regional hyphen-joined (`mar-east`), single
18874        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
18875        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
18876        // Pin every leg so a future tightening that bans (e.g.) digit-
18877        // start identifiers surfaces here.
18878        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
18879            let mut s = three_member_spec();
18880            s.placement.clusters = vec![form.into()];
18881            s.validate().unwrap_or_else(|e| {
18882                panic!("canonical cluster form {form:?} must validate, got {e:?}")
18883            });
18884        }
18885    }
18886
18887    #[test]
18888    fn placement_cluster_empty_takes_precedence_over_invalid() {
18889        // Order pin: the existing `PlacementClusterEmpty` diagnostic
18890        // (which doesn't try to parse) fires before the new
18891        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
18892        // `:clusters` entry keeps its narrower error message — the new
18893        // gate would also reject `""`, but the empty-string arm is the
18894        // more self-locating diagnostic. Mirrors the
18895        // `membro_caixa_empty_takes_precedence_over_invalid` pin
18896        // (3f9d7a0).
18897        let mut s = three_member_spec();
18898        s.placement.clusters = vec!["rio".into(), "".into()];
18899        let err = s.validate().unwrap_err();
18900        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
18901    }
18902
18903    #[test]
18904    fn placement_cluster_invalid_fires_before_duplicate_check() {
18905        // Order pin: a malformed-shape `:clusters` entry surfaces *its
18906        // own* diagnostic, even when a later entry would otherwise
18907        // collapse onto a duplicate name. The per-entry shape gate runs
18908        // inline before the duplicate-key insert, parallel to
18909        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
18910        let mut s = three_member_spec();
18911        s.placement.clusters = vec!["Rio".into(), "rio".into()];
18912        let err = s.validate().unwrap_err();
18913        assert!(
18914            matches!(
18915                err,
18916                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
18917            ),
18918            "got {err:?}"
18919        );
18920    }
18921
18922    #[test]
18923    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
18924        // The diagnostic-shape pin: the error names the offending
18925        // `:clusters` value verbatim so the author can grep their
18926        // caixa.lisp without re-running the build, and carries a
18927        // non-empty `reason` naming the specific violation. Same shape
18928        // every typed-shape gate enshrines
18929        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
18930        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
18931        let mut s = three_member_spec();
18932        s.placement.clusters = vec!["BAD_CLUSTER".into()];
18933        let err = s.validate().unwrap_err();
18934        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18935            panic!("expected PlacementClusterInvalid");
18936        };
18937        assert_eq!(cluster, "BAD_CLUSTER");
18938        assert!(
18939            !reason.is_empty(),
18940            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
18941        );
18942    }
18943
18944    #[test]
18945    fn rejects_sharded_with_empty_clusters() {
18946        // §III.1: Sharded uses :clusters as the shard pool. An empty
18947        // pool means "shard across no clusters" — meaningless, same as
18948        // Replicated with no hosts.
18949        let mut s = three_member_spec();
18950        s.placement.estrategia = PlacementStrategy::Sharded;
18951        s.placement.shard_key = Some("$tenantId".into());
18952        s.placement.clusters = vec![];
18953        assert!(matches!(
18954            s.validate().unwrap_err(),
18955            AplicacaoError::PlacementWithoutClusters {
18956                estrategia: PlacementStrategy::Sharded
18957            }
18958        ));
18959    }
18960
18961    #[test]
18962    fn rejects_sharded_with_empty_shard_key() {
18963        let mut s = three_member_spec();
18964        s.placement.estrategia = PlacementStrategy::Sharded;
18965        s.placement.shard_key = Some("".into());
18966        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
18967    }
18968
18969    #[test]
18970    fn rejects_shard_key_under_replicated_strategy() {
18971        // The fail-before-pass-after pin: a `:placement (:estrategia
18972        // Replicated :shard-key "tenantId")` manifest carries the
18973        // hash-keyed-distribution slot on a strategy that never consumes
18974        // it. Before the gate the typed slot's value silently vanished
18975        // at the renderer layer (caixa-mesh emits `placement.shardKey`
18976        // verbatim regardless of strategy; the Akka-style cluster-
18977        // sharding reconciler keys off `estrategia == Sharded` and
18978        // ignores the slot otherwise), with no diagnostic. Lifting the
18979        // rejection to a build-time gate makes the
18980        // `shard_key.is_some() == matches!(estrategia, Sharded)`
18981        // partition a structural property of every validated
18982        // [`Placement`].
18983        let mut s = three_member_spec();
18984        // The fixture already uses Replicated; just add a shard-key.
18985        s.placement.shard_key = Some("$tenantId".into());
18986        let err = s.validate().unwrap_err();
18987        let AplicacaoError::ShardKeyOnNonSharded {
18988            estrategia,
18989            shard_key,
18990        } = err
18991        else {
18992            panic!("expected ShardKeyOnNonSharded, got {err:?}");
18993        };
18994        assert_eq!(estrategia, PlacementStrategy::Replicated);
18995        assert_eq!(shard_key, "$tenantId");
18996    }
18997
18998    #[test]
18999    fn rejects_shard_key_under_singlenode_strategy() {
19000        // Peer of the Replicated case above on the SingleNode arm: OTP
19001        // distributed-app takeover (one cluster runs at a time) has no
19002        // hash-keyed routing axis to consume `:shard-key` either, so
19003        // the rejection fires on both non-Sharded arms uniformly.
19004        let mut s = three_member_spec();
19005        s.placement.estrategia = PlacementStrategy::SingleNode;
19006        s.placement.shard_key = Some("$tenantId".into());
19007        let err = s.validate().unwrap_err();
19008        let AplicacaoError::ShardKeyOnNonSharded {
19009            estrategia,
19010            shard_key,
19011        } = err
19012        else {
19013            panic!("expected ShardKeyOnNonSharded, got {err:?}");
19014        };
19015        assert_eq!(estrategia, PlacementStrategy::SingleNode);
19016        assert_eq!(shard_key, "$tenantId");
19017    }
19018
19019    #[test]
19020    fn rejects_empty_shard_key_under_replicated_strategy() {
19021        // The `Some("")` case under non-Sharded is rejected by
19022        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
19023        // fires before the empty-value gate), not
19024        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
19025        // the `Sharded` arm). Pin the partition so a future reorder of
19026        // the validate_placement match arms doesn't silently swap which
19027        // diagnostic the author sees — both are author errors, but
19028        // ShardKeyOnNonSharded names which strategy is the actual fix
19029        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
19030        // only says "pick a non-empty key".
19031        let mut s = three_member_spec();
19032        s.placement.shard_key = Some(String::new());
19033        let err = s.validate().unwrap_err();
19034        assert!(
19035            matches!(
19036                err,
19037                AplicacaoError::ShardKeyOnNonSharded {
19038                    estrategia: PlacementStrategy::Replicated,
19039                    ref shard_key,
19040                } if shard_key.is_empty()
19041            ),
19042            "got {err:?}"
19043        );
19044    }
19045
19046    #[test]
19047    fn replicated_without_shard_key_validates() {
19048        // The complement of the rejection: `:placement :estrategia
19049        // Replicated` with `:shard-key None` is the canonical happy
19050        // path on every existing fixture. Pin the no-shard-key case so
19051        // the new gate doesn't accidentally fire on `None`.
19052        let mut s = three_member_spec();
19053        assert!(matches!(
19054            s.placement.estrategia,
19055            PlacementStrategy::Replicated
19056        ));
19057        s.placement.shard_key = None;
19058        s.validate().unwrap();
19059    }
19060
19061    #[test]
19062    fn singlenode_without_shard_key_validates() {
19063        // Peer of the Replicated no-shard-key case on the SingleNode
19064        // arm — both non-Sharded strategies must validate cleanly when
19065        // the slot is omitted.
19066        let mut s = three_member_spec();
19067        s.placement.estrategia = PlacementStrategy::SingleNode;
19068        s.placement.shard_key = None;
19069        s.validate().unwrap();
19070    }
19071
19072    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
19073        // Fixture builder for the `:placement :shard-key` shape gate
19074        // tests: a three-member Aplicacao on the `Sharded` strategy
19075        // with the supplied `:shard-key` slot. Co-locates the
19076        // arm-construction so every test below carries one line of
19077        // setup (the offending `:shard-key` value) and the assertion.
19078        let mut s = three_member_spec();
19079        s.placement.estrategia = PlacementStrategy::Sharded;
19080        s.placement.shard_key = Some(key.into());
19081        s
19082    }
19083
19084    #[test]
19085    fn rejects_shard_key_with_embedded_space() {
19086        // The canonical paste-from-aligned-doc footgun:
19087        // `:shard-key "$tenant Id"` — the Akka-style entity-id
19088        // extractor reads the slot as a single-token reference, and an
19089        // embedded space breaks the token boundary at the runtime
19090        // hash-extractor pass with no diagnostic naming the offending
19091        // entry.
19092        let s = sharded_spec_with_key("$tenant Id");
19093        let err = s.validate().unwrap_err();
19094        assert!(
19095            matches!(
19096                err,
19097                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19098                    if shard_key == "$tenant Id" && reason.contains("space")
19099            ),
19100            "got {err:?}"
19101        );
19102    }
19103
19104    #[test]
19105    fn rejects_shard_key_with_leading_space() {
19106        // Leading-space arm of the embedded-whitespace footgun — the
19107        // paste-from-aligned-doc / paste-from-CSV-cell variant where
19108        // the leading column-padding leaked into the slot.
19109        let s = sharded_spec_with_key(" $tenantId");
19110        let err = s.validate().unwrap_err();
19111        assert!(
19112            matches!(
19113                err,
19114                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
19115                    if shard_key == " $tenantId"
19116            ),
19117            "got {err:?}"
19118        );
19119    }
19120
19121    #[test]
19122    fn rejects_shard_key_with_trailing_newline() {
19123        // The canonical paste-from-shell-heredoc footgun — every
19124        // `<<EOF` heredoc terminator paste leaves a trailing newline
19125        // the YAML emitter then folds away inconsistently across
19126        // emitter implementations.
19127        let s = sharded_spec_with_key("$tenantId\n");
19128        let err = s.validate().unwrap_err();
19129        assert!(
19130            matches!(
19131                err,
19132                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19133                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
19134            ),
19135            "got {err:?}"
19136        );
19137    }
19138
19139    #[test]
19140    fn rejects_shard_key_with_embedded_tab() {
19141        // The paste-from-aligned-doc tab-stop variant — tabs land
19142        // alongside spaces in copy-paste from formatted columns.
19143        let s = sharded_spec_with_key("$tenant\tId");
19144        let err = s.validate().unwrap_err();
19145        assert!(
19146            matches!(
19147                err,
19148                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19149                    if shard_key == "$tenant\tId" && reason.contains("tab")
19150            ),
19151            "got {err:?}"
19152        );
19153    }
19154
19155    #[test]
19156    fn rejects_shard_key_with_control_character() {
19157        // The paste-from-binary / paste-from-screen-cleared-terminal
19158        // footgun — an embedded `\x01` (SOH) byte that some YAML
19159        // emitters silently strip and others escape as ``,
19160        // breaking round-trip across emitter implementations.
19161        let s = sharded_spec_with_key("$tenant\u{0001}Id");
19162        let err = s.validate().unwrap_err();
19163        assert!(
19164            matches!(
19165                err,
19166                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19167                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
19168            ),
19169            "got {err:?}"
19170        );
19171    }
19172
19173    #[test]
19174    fn rejects_shard_key_with_non_ascii() {
19175        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
19176        // footgun — non-ASCII bytes normalize differently between the
19177        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
19178        // YAML parser, the same entity ID can silently map to two
19179        // distinct shards on a re-render.
19180        let s = sharded_spec_with_key("$tenàntId");
19181        let err = s.validate().unwrap_err();
19182        assert!(
19183            matches!(
19184                err,
19185                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19186                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
19187            ),
19188            "got {err:?}"
19189        );
19190    }
19191
19192    #[test]
19193    fn rejects_shard_key_too_long() {
19194        // Length cap pin: 64 bytes — one byte over the
19195        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
19196        // here is a paste-from-doc multi-line blob landing in
19197        // `:shard-key` instead of a single-token extractor expression.
19198        let too_long = "a".repeat(64);
19199        let s = sharded_spec_with_key(&too_long);
19200        let err = s.validate().unwrap_err();
19201        let AplicacaoError::ShardKeyInvalid {
19202            ref shard_key,
19203            ref reason,
19204        } = err
19205        else {
19206            panic!("expected ShardKeyInvalid, got {err:?}");
19207        };
19208        assert_eq!(shard_key, &too_long);
19209        assert!(
19210            reason.contains("63") && reason.contains("64"),
19211            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19212        );
19213    }
19214
19215    #[test]
19216    fn shard_key_max_length_validates() {
19217        // Boundary pin: 63 bytes exactly — the
19218        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
19219        // dropping to 62) surfaces here as a regression, mirroring
19220        // `placement_cluster_max_length_validates` /
19221        // `placement_affinity_max_length_validates` on the peer
19222        // identifier-shaped slots.
19223        let s = sharded_spec_with_key(&"a".repeat(63));
19224        s.validate().unwrap();
19225    }
19226
19227    #[test]
19228    fn accepts_canonical_shard_key_forms() {
19229        // The Akka-style entity-id extractor shapes a caixa author is
19230        // realistically going to write — pin every leg so a future
19231        // tightening that bans (e.g.) the `${...}` interpolation
19232        // variant or the `metadata.<field>` JSONPath form surfaces
19233        // here as a regression. The canonical forms span:
19234        //
19235        //   - bare property name (`tenantId`, `customerId`)
19236        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
19237        //   - JSONPath-style nested reference (`metadata.tenantId`,
19238        //     `$.user.id`)
19239        //   - interpolation-style template (`${tenant}`)
19240        //   - snake_case property name (`customer_id`)
19241        //   - kebab-case property name (`customer-id` — accepted
19242        //     because the slot is a printable-ASCII single-token
19243        //     reference, not a DNS-1123 label like
19244        //     `:placement :affinity` / `:clusters`)
19245        //   - single character (`a`, `$` — boundary)
19246        for form in [
19247            "tenantId",
19248            "customerId",
19249            "$tenantId",
19250            "metadata.tenantId",
19251            "$.user.id",
19252            "${tenant}",
19253            "customer_id",
19254            "customer-id",
19255            "a",
19256            "$",
19257        ] {
19258            let s = sharded_spec_with_key(form);
19259            s.validate().unwrap_or_else(|e| {
19260                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
19261            });
19262        }
19263    }
19264
19265    #[test]
19266    fn shard_key_empty_takes_precedence_over_invalid() {
19267        // Order pin: the existing `ShardedKeyEmpty` diagnostic
19268        // (reserved for the `Sharded` `Some("")` arm) fires before the
19269        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
19270        // `:shard-key` keeps its narrower error message — the new gate
19271        // would also reject `""` defensively, but the empty-string arm
19272        // is the more self-locating diagnostic. Mirrors the
19273        // `placement_cluster_empty_takes_precedence_over_invalid` pin
19274        // on the peer identifier-shaped slot.
19275        let s = sharded_spec_with_key("");
19276        let err = s.validate().unwrap_err();
19277        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
19278    }
19279
19280    #[test]
19281    fn shard_key_invalid_diagnostic_carries_offending_value() {
19282        // The diagnostic-shape pin: the error names the offending
19283        // `:shard-key` value verbatim so the author can grep their
19284        // caixa.lisp without re-running the build, and carries a
19285        // parser-shaped `reason:` naming the specific violation —
19286        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19287        // on the peer identifier-shaped slot.
19288        let s = sharded_spec_with_key("$tenant Id");
19289        let err = s.validate().unwrap_err();
19290        let AplicacaoError::ShardKeyInvalid {
19291            ref shard_key,
19292            ref reason,
19293        } = err
19294        else {
19295            panic!("expected ShardKeyInvalid, got {err:?}");
19296        };
19297        assert_eq!(shard_key, "$tenant Id");
19298        assert!(
19299            !reason.is_empty(),
19300            "reason must name the specific violation, got empty string"
19301        );
19302    }
19303
19304    #[test]
19305    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
19306        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
19307        // `:shard-key` carried on non-Sharded strategies) fires before
19308        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
19309        // a `Replicated` strategy surfaces the more self-locating
19310        // strategy-mismatch diagnostic (naming the actual fix — drop
19311        // the slot, or switch to Sharded) rather than the shape
19312        // diagnostic. The strategy-mismatch arm is the more actionable
19313        // diagnostic: a malformed shard-key on Replicated is "you
19314        // shouldn't have a :shard-key here at all", not "your
19315        // :shard-key value is malformed".
19316        let mut s = three_member_spec();
19317        // Replicated is the default fixture strategy.
19318        s.placement.shard_key = Some("$tenant Id".into());
19319        let err = s.validate().unwrap_err();
19320        assert!(
19321            matches!(
19322                err,
19323                AplicacaoError::ShardKeyOnNonSharded {
19324                    estrategia: PlacementStrategy::Replicated,
19325                    ..
19326                }
19327            ),
19328            "got {err:?}"
19329        );
19330    }
19331
19332    #[test]
19333    fn rejects_empty_affinity_hint() {
19334        let mut s = three_member_spec();
19335        s.placement.affinity = Some("".into());
19336        assert_eq!(
19337            s.validate().unwrap_err(),
19338            AplicacaoError::PlacementAffinityEmpty
19339        );
19340    }
19341
19342    #[test]
19343    fn placement_without_affinity_validates() {
19344        // Omitting :affinity is fine — the placement engine falls back
19345        // to the default heuristic. Pin the no-hint case so the
19346        // affinity-empty rejection doesn't accidentally fire on `None`.
19347        let mut s = three_member_spec();
19348        s.placement.affinity = None;
19349        s.validate().unwrap();
19350    }
19351
19352    #[test]
19353    fn rejects_placement_affinity_with_uppercase() {
19354        // The canonical "I copied the ADR's display name verbatim" typo
19355        // — placement hints land verbatim in K8s label-selector
19356        // territory, where the apiserver enforces the DNS-1123 label
19357        // rule (lowercase-only) on every identity-keyed admission axis.
19358        // Mirrors `rejects_placement_cluster_with_uppercase` on the
19359        // sibling slot.
19360        let mut s = three_member_spec();
19361        s.placement.affinity = Some("DataLocality".into());
19362        let err = s.validate().unwrap_err();
19363        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19364            panic!("expected PlacementAffinityInvalid, got other variant");
19365        };
19366        assert_eq!(affinity, "DataLocality");
19367        assert!(
19368            reason.contains("uppercase"),
19369            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19370        );
19371        assert!(
19372            reason.contains("\"datalocality\""),
19373            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19374        );
19375    }
19376
19377    #[test]
19378    fn rejects_placement_affinity_with_underscore() {
19379        // The canonical "I'm thinking of an env var / Python identifier"
19380        // leak — `_` is forbidden by every DNS-1123 label schema. Same
19381        // shape as `rejects_placement_cluster_with_underscore` on the
19382        // sibling slot.
19383        let mut s = three_member_spec();
19384        s.placement.affinity = Some("data_locality".into());
19385        let err = s.validate().unwrap_err();
19386        assert!(
19387            matches!(
19388                err,
19389                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19390                    if affinity == "data_locality" && reason.contains('_')
19391            ),
19392            "got {err:?}"
19393        );
19394    }
19395
19396    #[test]
19397    fn rejects_placement_affinity_with_dot() {
19398        // A `:placement :affinity` value is a single DNS-1123 *label*
19399        // (it lands as a K8s label value selector key), not a subdomain.
19400        // The "I want to namespace my hint with `.`" intent is expressed
19401        // via `-` (`data-locality-east`).
19402        let mut s = three_member_spec();
19403        s.placement.affinity = Some("data.locality".into());
19404        let err = s.validate().unwrap_err();
19405        assert!(
19406            matches!(
19407                err,
19408                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19409                    if affinity == "data.locality" && reason.contains('.')
19410            ),
19411            "got {err:?}"
19412        );
19413    }
19414
19415    #[test]
19416    fn rejects_placement_affinity_with_unicode() {
19417        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19418        // before it reaches K8s. The byte-by-byte ASCII validity check
19419        // rejects multi-byte UTF-8 sequences by the first byte that
19420        // fails `[a-z0-9-]`.
19421        let mut s = three_member_spec();
19422        s.placement.affinity = Some("data-localité".into());
19423        let err = s.validate().unwrap_err();
19424        assert!(
19425            matches!(
19426                err,
19427                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19428                    if affinity == "data-localité"
19429            ),
19430            "got {err:?}"
19431        );
19432    }
19433
19434    #[test]
19435    fn rejects_placement_affinity_with_leading_hyphen() {
19436        // DNS-1123 boundary rule: labels must start with an
19437        // alphanumeric. Pin separately from the trailing-hyphen arm so
19438        // a future relaxation that only checks one boundary surfaces
19439        // here as a regression (parallel to
19440        // `rejects_placement_cluster_with_leading_hyphen`).
19441        let mut s = three_member_spec();
19442        s.placement.affinity = Some("-data-locality".into());
19443        let err = s.validate().unwrap_err();
19444        assert!(
19445            matches!(
19446                err,
19447                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19448                    if affinity == "-data-locality" && reason.contains("start and end")
19449            ),
19450            "got {err:?}"
19451        );
19452    }
19453
19454    #[test]
19455    fn rejects_placement_affinity_with_trailing_hyphen() {
19456        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
19457        // ends are covered against a future relaxation.
19458        let mut s = three_member_spec();
19459        s.placement.affinity = Some("data-locality-".into());
19460        let err = s.validate().unwrap_err();
19461        assert!(
19462            matches!(
19463                err,
19464                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19465                    if affinity == "data-locality-"
19466            ),
19467            "got {err:?}"
19468        );
19469    }
19470
19471    #[test]
19472    fn rejects_placement_affinity_with_whitespace() {
19473        // Whitespace is the canonical "I pasted from a sketch / doc"
19474        // footgun. The apiserver rejects every label-selector value
19475        // carrying whitespace.
19476        let mut s = three_member_spec();
19477        s.placement.affinity = Some("data locality".into());
19478        let err = s.validate().unwrap_err();
19479        assert!(
19480            matches!(
19481                err,
19482                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19483                    if affinity == "data locality"
19484            ),
19485            "got {err:?}"
19486        );
19487    }
19488
19489    #[test]
19490    fn rejects_placement_affinity_too_long() {
19491        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
19492        // pin. The diagnostic names both the cap (63) and the actual
19493        // length so the author can shorten in one edit. Mirrors
19494        // `rejects_placement_cluster_too_long`.
19495        let mut s = three_member_spec();
19496        let too_long = "a".repeat(64);
19497        s.placement.affinity = Some(too_long.clone());
19498        let err = s.validate().unwrap_err();
19499        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19500            panic!("expected PlacementAffinityInvalid");
19501        };
19502        assert_eq!(affinity, too_long);
19503        assert!(
19504            reason.contains("63") && reason.contains("64"),
19505            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19506        );
19507    }
19508
19509    #[test]
19510    fn placement_affinity_max_length_validates() {
19511        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
19512        // future tightening (e.g. dropping to 62) surfaces here as a
19513        // regression, mirroring `placement_cluster_max_length_validates`.
19514        let mut s = three_member_spec();
19515        s.placement.affinity = Some("a".repeat(63));
19516        s.validate().unwrap();
19517    }
19518
19519    #[test]
19520    fn accepts_canonical_placement_affinity_forms() {
19521        // The DNS-1123 label shapes a caixa author is realistically
19522        // going to write for placement hints: the M3 canonical examples
19523        // (`data-locality`, `low-latency`, `anti-affinity`), the
19524        // single-token form (`affinity`), the single-character boundary
19525        // (`a`), the digit-start (DNS-1123 allows this, unlike
19526        // DNS-1035), and a regional-suffixed form. Pin every leg so a
19527        // future tightening that bans (e.g.) digit-start identifiers
19528        // surfaces here.
19529        for form in [
19530            "data-locality",
19531            "low-latency",
19532            "anti-affinity",
19533            "affinity",
19534            "a",
19535            "3-tier",
19536            "locality-east",
19537        ] {
19538            let mut s = three_member_spec();
19539            s.placement.affinity = Some(form.into());
19540            s.validate().unwrap_or_else(|e| {
19541                panic!("canonical affinity form {form:?} must validate, got {e:?}")
19542            });
19543        }
19544    }
19545
19546    #[test]
19547    fn placement_affinity_empty_takes_precedence_over_invalid() {
19548        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
19549        // (which doesn't try to parse) fires before the new
19550        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
19551        // `:affinity` keeps its narrower error message — the new gate
19552        // would also reject `""`, but the empty-string arm is the more
19553        // self-locating diagnostic. Mirrors the
19554        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
19555        let mut s = three_member_spec();
19556        s.placement.affinity = Some(String::new());
19557        let err = s.validate().unwrap_err();
19558        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
19559    }
19560
19561    #[test]
19562    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
19563        // The diagnostic shape pin: every rejection carries the offending
19564        // `affinity:` verbatim plus a parser-shaped `reason:` so the
19565        // author can grep their caixa.lisp for `:affinity "<hint>"` and
19566        // fix it in one edit. Mirrors the
19567        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19568        // pin on the sibling slot.
19569        let mut s = three_member_spec();
19570        s.placement.affinity = Some("Data_Locality".into());
19571        let err = s.validate().unwrap_err();
19572        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19573            panic!("expected PlacementAffinityInvalid");
19574        };
19575        assert_eq!(affinity, "Data_Locality");
19576        assert!(
19577            !reason.is_empty(),
19578            "diagnostic reason must not be empty (got: {reason:?})"
19579        );
19580    }
19581
19582    #[test]
19583    fn singlenode_with_takeover_candidates_validates() {
19584        // OTP distributed-application convention (MESH-COMPOSITION
19585        // §II.1): SingleNode runs on one cluster at a time but the
19586        // :clusters list enumerates the takeover candidates. Multiple
19587        // entries are not a contradiction — they are the failover pool.
19588        let mut s = three_member_spec();
19589        s.placement.estrategia = PlacementStrategy::SingleNode;
19590        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
19591        s.validate().unwrap();
19592    }
19593
19594    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
19595
19596    #[test]
19597    fn mesh_policy_default_is_empty() {
19598        // The Default impl carries None on every axis — the typed
19599        // analog of an unset `:politicas (())` slot. Renderers that
19600        // overlay the policy onto a cluster artifact key off this
19601        // predicate to skip the slot entirely; pinning so a future
19602        // axis added to MeshPolicy can't silently break the contract
19603        // (a new field whose Default is non-None would flip is_empty
19604        // to false on every existing caixa, surfacing here).
19605        assert!(MeshPolicy::default().is_empty());
19606    }
19607
19608    #[test]
19609    fn mesh_policy_with_only_timeout_is_not_empty() {
19610        let p = MeshPolicy {
19611            timeout: Some(Duration::from_secs(30)),
19612            ..Default::default()
19613        };
19614        assert!(!p.is_empty());
19615    }
19616
19617    #[test]
19618    fn mesh_policy_with_only_retries_is_not_empty() {
19619        let p = MeshPolicy {
19620            retries: Some(3),
19621            ..Default::default()
19622        };
19623        assert!(!p.is_empty());
19624    }
19625
19626    #[test]
19627    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
19628        let p = MeshPolicy {
19629            circuit_breaker: Some(CircuitBreaker {
19630                max_failures: 5,
19631                window: Duration::from_secs(60),
19632            }),
19633            ..Default::default()
19634        };
19635        assert!(!p.is_empty());
19636    }
19637
19638    #[test]
19639    fn mesh_policy_with_only_mtls_required_is_not_empty() {
19640        // Even `mtls_required: Some(false)` (an explicit opt-out) is
19641        // not empty — the author *named* the axis, the renderer needs
19642        // to honor that vs. fall back to the cluster default.
19643        let p = MeshPolicy {
19644            mtls_required: Some(false),
19645            ..Default::default()
19646        };
19647        assert!(!p.is_empty());
19648    }
19649
19650    #[test]
19651    fn mesh_policy_with_only_rate_limit_is_not_empty() {
19652        let p = MeshPolicy {
19653            rate_limit: Some(RateLimit {
19654                rate: 100,
19655                window: Duration::from_secs(1),
19656            }),
19657            ..Default::default()
19658        };
19659        assert!(!p.is_empty());
19660    }
19661
19662    #[test]
19663    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
19664        // The three-member happy-path fixture sets timeout + retries +
19665        // mtls_required — every populated axis must read non-empty.
19666        // Pin the round-trip so the M3.x per-:politicas emitter (the
19667        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
19668        // on is_empty() to decide whether to emit at all without
19669        // re-deriving the contract from inline field probes.
19670        assert!(!three_member_spec().politicas.is_empty());
19671    }
19672
19673    // ── shared duration codec: cross-slot integer-magnitude gate ──
19674    //
19675    // The integer-magnitude discipline applied to
19676    // `supervisor::duration_codec::parse` lifts onto every typed slot
19677    // that routes through the shared codec — `MeshPolicy::timeout`
19678    // (`:politicas :timeout`) and `CircuitBreaker::window`
19679    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
19680    // These cross-slot tests pin that the gate fires at the serde
19681    // layer for both typed slots, not just for the supervisor side.
19682
19683    #[test]
19684    fn policy_timeout_serde_rejects_fractional_seconds() {
19685        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
19686        // so the shared codec's integer-magnitude gate applies on
19687        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
19688        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
19689        // deserialize with the canonical-form diagnostic naming the
19690        // offending `"1.5"` and the remediation `"1500ms"`.
19691        let payload = r#"{"timeout":"1.5s"}"#;
19692        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19693        let msg = err.to_string();
19694        assert!(
19695            msg.contains("not a non-negative integer"),
19696            "expected integer-magnitude diagnostic in {msg:?}"
19697        );
19698        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
19699        assert!(
19700            msg.contains("\"1500ms\""),
19701            "missing canonical-form remediation in {msg:?}"
19702        );
19703    }
19704
19705    #[test]
19706    fn policy_timeout_serde_rejects_leading_plus_sign() {
19707        // Pin the leading-`+` arm cross-slot — the prior f64 parser
19708        // accepted `"+30s"` silently and round-tripped to `"30s"`.
19709        let payload = r#"{"timeout":"+30s"}"#;
19710        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19711        let msg = err.to_string();
19712        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
19713    }
19714
19715    #[test]
19716    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
19717        // `CircuitBreaker::window` uses `with =
19718        // "supervisor::duration_codec_required"` (the required-Duration
19719        // variant that delegates to the same shared parser). `"0.5m"`
19720        // parsed to 30s and round-tripped to `"30s"` on next emit —
19721        // DRIFT closed.
19722        let payload = format!(
19723            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
19724            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
19725            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
19726        );
19727        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
19728        let msg = err.to_string();
19729        assert!(
19730            msg.contains("not a non-negative integer"),
19731            "expected integer-magnitude diagnostic in {msg:?}"
19732        );
19733        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
19734        assert!(
19735            msg.contains("\"30s\""),
19736            "missing canonical-form remediation in {msg:?}"
19737        );
19738    }
19739
19740    #[test]
19741    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
19742        // Pin the happy-path on the cross-slot side: every canonical
19743        // author shape `render` ever emits parses cleanly through the
19744        // shared codec on the `CircuitBreaker` slot. The
19745        // codec's accepted set (post-gate) is exactly its emitted set
19746        // for the integer-magnitude class.
19747        for window_lit in ["30s", "500ms", "2m", "1h"] {
19748            let payload = format!(
19749                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
19750                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
19751                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
19752            );
19753            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
19754                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
19755            });
19756            assert_eq!(cb.max_failures, 5);
19757        }
19758    }
19759
19760    // ── rate_limit_codec: integer-magnitude gate ──
19761    //
19762    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
19763    // / 737a676 / d53c922 trajectory landed on every typed-duration /
19764    // typed-byte-size codec in caixa-core lifts onto the fifth typed
19765    // codec — `rate_limit_codec` — through the digit-only magnitude
19766    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
19767    // These tests pin the gate at the serde layer for `:politicas
19768    // :rate-limit` (the only typed slot the codec backs), and at the
19769    // codec-internal `parse` layer for the canonical positive cases.
19770
19771    #[test]
19772    fn rate_limit_serde_rejects_fractional_rate() {
19773        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
19774        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
19775        // wording, which didn't name the canonical-form remediation or
19776        // the round-trip drift the next emit would produce. Now refused
19777        // at deserialize with the canonical-form diagnostic naming the
19778        // offending `"1.5"` magnitude and the round-trip drift wording.
19779        let payload = r#"{"rateLimit":"1.5/s"}"#;
19780        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19781        let msg = err.to_string();
19782        assert!(
19783            msg.contains("not a non-negative integer"),
19784            "expected integer-magnitude diagnostic in {msg:?}"
19785        );
19786        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
19787        assert!(
19788            msg.contains("THEORY.md"),
19789            "missing render-determinism contract citation in {msg:?}"
19790        );
19791    }
19792
19793    #[test]
19794    fn rate_limit_serde_rejects_leading_plus_sign() {
19795        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
19796        // permissive-`+` parse), so `"+100/s"` silently parsed to
19797        // `RateLimit { 100, 1s }` and round-tripped through `render` to
19798        // `"100/s"` — a *different* canonical string on the next emit,
19799        // breaking the THEORY.md Part V render-determinism contract
19800        // exactly the way the peer duration codecs' `"+30s"` case did.
19801        // This is the load-bearing class the digit-only gate closes
19802        // beyond what `u32::from_str`'s strictness covers on its own.
19803        let payload = r#"{"rateLimit":"+100/s"}"#;
19804        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19805        let msg = err.to_string();
19806        assert!(
19807            msg.contains("not a non-negative integer"),
19808            "expected integer-magnitude diagnostic in {msg:?}"
19809        );
19810        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
19811    }
19812
19813    #[test]
19814    fn rate_limit_serde_rejects_leading_minus_sign() {
19815        // The signed-negative arm: `"-1/s"` lands on the
19816        // non-canonical-but-numeric branch via the `i64` fallback (the
19817        // `f64` parse also succeeds), surfacing the canonical-form
19818        // diagnostic. Replaces the prior value-laundered "not a u32"
19819        // wording with the unified diagnostic across signs.
19820        let payload = r#"{"rateLimit":"-1/s"}"#;
19821        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19822        let msg = err.to_string();
19823        assert!(
19824            msg.contains("not a non-negative integer"),
19825            "expected integer-magnitude diagnostic in {msg:?}"
19826        );
19827        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
19828    }
19829
19830    #[test]
19831    fn rate_limit_serde_rejects_decimal_shaped_integer() {
19832        // `"100.0/s"` is integer-valued numerically but not in the
19833        // codec's accepted set — `render` emits `"100/s"`, so the
19834        // round-trip would drift. Lifted to the canonical-form
19835        // diagnostic peer with the duration codec's `"1.0s"` case
19836        // (1c55a2a).
19837        let payload = r#"{"rateLimit":"100.0/s"}"#;
19838        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19839        let msg = err.to_string();
19840        assert!(
19841            msg.contains("not a non-negative integer"),
19842            "expected integer-magnitude diagnostic in {msg:?}"
19843        );
19844        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
19845    }
19846
19847    #[test]
19848    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
19849        // Non-numeric, non-digit-only input lands on the existing
19850        // narrower `"not a u32"` arm (preserved for diagnostic-shape
19851        // stability on the parser-shape footgun case). Pin this so a
19852        // future relaxation of the numeric-fallback predicate doesn't
19853        // silently collapse garbage onto the canonical-form arm — same
19854        // partition the peer duration codecs draw between
19855        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
19856        let payload = r#"{"rateLimit":"abc/s"}"#;
19857        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19858        let msg = err.to_string();
19859        assert!(
19860            msg.contains("not a u32"),
19861            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
19862        );
19863        assert!(
19864            !msg.contains("not a non-negative integer"),
19865            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
19866        );
19867    }
19868
19869    #[test]
19870    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
19871        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
19872        // u32's range. The digit-only gate passes; `u32::from_str`
19873        // fails on overflow. Surface that with the overflow-shaped
19874        // diagnostic naming the offending magnitude verbatim, peer
19875        // with `supervisor::duration_codec`'s overflow arm. Pinning
19876        // the wording so a future refactor doesn't silently collapse
19877        // overflow onto the canonical-form arm.
19878        let payload = r#"{"rateLimit":"4294967296/s"}"#;
19879        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19880        let msg = err.to_string();
19881        assert!(
19882            msg.contains("overflows u32"),
19883            "expected overflow diagnostic in {msg:?}"
19884        );
19885        assert!(
19886            msg.contains("\"4294967296\""),
19887            "missing offending magnitude in {msg:?}"
19888        );
19889    }
19890
19891    #[test]
19892    fn rate_limit_serde_rejects_leading_zero_magnitude() {
19893        // `"0100/s"` is digit-only, so the existing
19894        // non-digit-only / sign / fractional arm doesn't catch it —
19895        // `u32::from_str("0100")` returns `Ok(100)`, so before this
19896        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
19897        // round-tripped through `render` to `"100/s"` — a *different*
19898        // canonical string on the next emit, breaking the THEORY.md
19899        // Part V render-determinism contract exactly the way the
19900        // peer `"+100/s"` case did before the leading-`+` arm landed.
19901        // This is the load-bearing class the leading-zero gate closes
19902        // beyond what the existing digit-only / sign / fractional
19903        // gates cover, and the peer arm to the leading-`+` test
19904        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
19905        // canonical-form-drift axis.
19906        let payload = r#"{"rateLimit":"0100/s"}"#;
19907        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19908        let msg = err.to_string();
19909        assert!(
19910            msg.contains("non-canonical leading zero"),
19911            "expected leading-zero diagnostic in {msg:?}"
19912        );
19913        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
19914        assert!(
19915            msg.contains("THEORY.md"),
19916            "missing render-determinism contract citation in {msg:?}"
19917        );
19918    }
19919
19920    #[test]
19921    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
19922        // `"00/s"` is the degenerate leading-zero case — every byte
19923        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
19924        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
19925        // a *different* canonical string, same render-determinism
19926        // violation. The single-byte `"0/s"` itself is in the
19927        // accepted set (round-trips losslessly through `render`,
19928        // refused downstream by `PolicyRateLimitZero`); the
19929        // multi-byte `"00/s"` is not. Pins the boundary between the
19930        // accepted single-`0` and the rejected leading-zero class.
19931        let payload = r#"{"rateLimit":"00/s"}"#;
19932        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19933        let msg = err.to_string();
19934        assert!(
19935            msg.contains("non-canonical leading zero"),
19936            "expected leading-zero diagnostic in {msg:?}"
19937        );
19938        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
19939    }
19940
19941    #[test]
19942    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
19943        // Cross-window pin — the gate is window-agnostic; the
19944        // leading-zero class is a property of the magnitude, not the
19945        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
19946        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
19947        // single-window coverage extended across the three canonical
19948        // windows the codec accepts.
19949        let payload = r#"{"rateLimit":"007/h"}"#;
19950        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19951        let msg = err.to_string();
19952        assert!(
19953            msg.contains("non-canonical leading zero"),
19954            "expected leading-zero diagnostic in {msg:?}"
19955        );
19956        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
19957    }
19958
19959    #[test]
19960    fn rate_limit_serde_rejects_leading_whitespace() {
19961        // `" 100/s"` — the canonical paste-from-aligned-doc /
19962        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
19963        // the top-level `s.trim()` silently ate the leading space and
19964        // parsed the value to `RateLimit { 100, 1s }`, which then
19965        // round-tripped through `render` to `"100/s"` (a *different*
19966        // canonical string on the next emit) — the exact
19967        // canonical-form-drift class the leading-`+` / leading-zero
19968        // arms already close, extended to the whitespace byte class.
19969        let payload = r#"{"rateLimit":" 100/s"}"#;
19970        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19971        let msg = err.to_string();
19972        assert!(
19973            msg.contains("contains whitespace byte"),
19974            "expected whitespace diagnostic in {msg:?}"
19975        );
19976        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19977        assert!(
19978            msg.contains("THEORY.md"),
19979            "missing render-determinism contract citation in {msg:?}"
19980        );
19981    }
19982
19983    #[test]
19984    fn rate_limit_serde_rejects_trailing_whitespace() {
19985        // `"100/s "` — the canonical shell-history / trailing-space
19986        // paste footgun. Before this gate the top-level `s.trim()`
19987        // silently ate the trailing space and parsed to
19988        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
19989        // next emit — same canonical-form drift as the leading-space
19990        // sibling, closed on the same whitespace-byte arm.
19991        let payload = r#"{"rateLimit":"100/s "}"#;
19992        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19993        let msg = err.to_string();
19994        assert!(
19995            msg.contains("contains whitespace byte"),
19996            "expected whitespace diagnostic in {msg:?}"
19997        );
19998        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
19999    }
20000
20001    #[test]
20002    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
20003        // `"100 / s"` — the canonical typographically-spaced author
20004        // shape (the same idiom every prose reference to a rate limit
20005        // renders as, mistakenly retained when the value is pasted
20006        // into a codec-shaped slot). Before this gate the per-part
20007        // `rate_str.trim()` / `unit.trim()` calls silently ate both
20008        // spaces on either side of `/` and parsed to
20009        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
20010        // codec's *internal* whitespace-tolerance vector, orthogonal
20011        // to the leading / trailing surface but the same canonical-
20012        // form-drift class. Pins the arm as strictly stronger than the
20013        // pre-existing top-level `s.trim()` behavior: it fires on
20014        // whitespace anywhere in the value, not just at the string
20015        // boundary.
20016        let payload = r#"{"rateLimit":"100 / s"}"#;
20017        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20018        let msg = err.to_string();
20019        assert!(
20020            msg.contains("contains whitespace byte"),
20021            "expected whitespace diagnostic in {msg:?}"
20022        );
20023        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20024    }
20025
20026    #[test]
20027    fn rate_limit_serde_rejects_tab_byte() {
20028        // `"\t100/s"` — the canonical paste-from-indented-doc /
20029        // paste-from-YAML-block-scalar footgun where a tab byte leads
20030        // the magnitude. Pins that the gate covers tab (`0x09`) as
20031        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
20032        // members and both would be silently swallowed by `s.trim()`
20033        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
20034        // space alone to the full ASCII-whitespace set (space `0x20`,
20035        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
20036        // the tab arm as a representative of the non-space members.
20037        let payload = r#"{"rateLimit":"\t100/s"}"#;
20038        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20039        let msg = err.to_string();
20040        assert!(
20041            msg.contains("contains whitespace byte"),
20042            "expected whitespace diagnostic in {msg:?}"
20043        );
20044        assert!(
20045            msg.contains("0x09"),
20046            "missing offending tab byte in {msg:?}"
20047        );
20048    }
20049
20050    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
20051    //
20052    // Successor to the ASCII-whitespace arm (1ad7755) on
20053    // `rate_limit_codec` — closes the strictly-complementary class the
20054    // byte-scan cannot see, through the lifted
20055    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
20056
20057    #[test]
20058    fn rate_limit_serde_rejects_leading_nbsp() {
20059        // NBSP prefix — paste-from-typography footgun. Byte-scan
20060        // misses, `str::trim` silently strips it, value drifts to
20061        // `"100/s"` on next serialize.
20062        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
20063        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20064        let msg = err.to_string();
20065        assert!(
20066            msg.contains("non-ASCII Unicode whitespace character"),
20067            "expected non-ASCII whitespace diagnostic in {msg:?}"
20068        );
20069        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
20070    }
20071
20072    #[test]
20073    fn rate_limit_serde_rejects_internal_em_space() {
20074        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
20075        // paste-from-typography footgun on the `<integer>/<unit>`
20076        // shape.
20077        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
20078        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20079        let msg = err.to_string();
20080        assert!(
20081            msg.contains("non-ASCII Unicode whitespace character"),
20082            "expected non-ASCII whitespace diagnostic in {msg:?}"
20083        );
20084        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
20085    }
20086
20087    #[test]
20088    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
20089        // Positive-control pin: every ASCII-only canonical form the
20090        // renderer emits stays accepted through the new arm.
20091        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
20092            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
20093            let p: MeshPolicy = serde_json::from_str(&payload)
20094                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
20095            assert!(p.rate_limit.is_some());
20096        }
20097    }
20098
20099    #[test]
20100    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
20101        // The boundary case — `"0/s"` is the canonical form
20102        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
20103        // it at the parse layer; the downstream
20104        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
20105        // `rate == 0` at the typed-validate layer above. Pins the
20106        // partition: the leading-zero gate at the codec layer does
20107        // not poach the rate-zero semantic-validation arm at the
20108        // typed-validate layer above (a future stricter codec must
20109        // not reject `"0/s"` here, or it'd collapse the diagnostic
20110        // partitioning that lets `PolicyRateLimitZero` name the
20111        // offending typed slot).
20112        let payload = r#"{"rateLimit":"0/s"}"#;
20113        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
20114            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
20115        });
20116        let rl = policy.rate_limit.expect("rate_limit must be Some");
20117        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
20118        assert_eq!(
20119            rl.window,
20120            Duration::from_secs(1),
20121            "single-`0` magnitude with `s` unit must parse to window=1s"
20122        );
20123    }
20124
20125    #[test]
20126    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
20127        // The complementary boundary pin — every magnitude
20128        // `render` emits starts with `[1-9]` (or is the single byte
20129        // `"0"`), so the canonical-form predicate is `(len == 1) ||
20130        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
20131        // '1'` case explicitly so a future tightening of the gate
20132        // (e.g. an over-eager "no leading digit < 5" rule, or a
20133        // mistakenly anchored start-of-magnitude byte check) lands
20134        // here before the canonical-forms-iterating test would catch
20135        // it.
20136        let payload = r#"{"rateLimit":"100/s"}"#;
20137        let policy: MeshPolicy = serde_json::from_str(payload)
20138            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
20139        let rl = policy.rate_limit.expect("rate_limit must be Some");
20140        assert_eq!(
20141            rl.rate, 100,
20142            "canonical-100 magnitude must parse to rate=100"
20143        );
20144    }
20145
20146    #[test]
20147    fn rate_limit_serde_accepts_integer_canonical_forms() {
20148        // Pin the happy-path: every canonical author shape `render`
20149        // ever emits parses cleanly through the codec post-gate. The
20150        // codec's accepted set (post-gate) is exactly its emitted set
20151        // for the integer-magnitude class — same property
20152        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
20153        // gates guarantee on the peer codecs. Iterating across rate
20154        // magnitudes (including `"0"`, which the codec accepts even
20155        // though `validate_politicas` rejects `rate == 0` at the typed
20156        // layer above) closes the codec contract at the parse layer
20157        // independently of the validate layer.
20158        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
20159            for unit_lit in ["s", "m", "h"] {
20160                let lit = format!("{rate_lit}/{unit_lit}");
20161                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
20162                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
20163                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
20164                });
20165                let rl = policy.rate_limit.expect("rate_limit must be Some");
20166                assert_eq!(
20167                    rl.rate,
20168                    rate_lit.parse::<u32>().unwrap(),
20169                    "rate mismatch for {lit:?}"
20170                );
20171            }
20172        }
20173    }
20174
20175    #[test]
20176    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
20177        // The structural property the gate enforces: serialize ∘
20178        // deserialize is the identity on every canonical author shape.
20179        // Peer of `parse_byte_size`'s and `parse_duration`'s
20180        // `_round_trips_through_render_for_every_canonical_form` tests
20181        // on the rate-limit axis. Before the gate, `"+100/s"` violated
20182        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
20183        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
20184        for rate in [1u32, 100, 5000, 1_000_000] {
20185            for (window, unit) in [
20186                (Duration::from_secs(1), "s"),
20187                (Duration::from_secs(60), "m"),
20188                (Duration::from_secs(3600), "h"),
20189            ] {
20190                let policy = MeshPolicy {
20191                    rate_limit: Some(RateLimit { rate, window }),
20192                    ..Default::default()
20193                };
20194                let json = serde_json::to_string(&policy).unwrap();
20195                let expected = format!("\"{rate}/{unit}\"");
20196                assert!(
20197                    json.contains(&expected),
20198                    "expected {expected:?} in {json:?}"
20199                );
20200                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20201                assert_eq!(
20202                    back.rate_limit, policy.rate_limit,
20203                    "round-trip for {json:?}"
20204                );
20205            }
20206        }
20207    }
20208
20209    // ── self-membership cross-slot gate ──────────────────────────────
20210
20211    #[test]
20212    fn validate_no_self_membership_rejects_self_named_membro() {
20213        // An Aplicacao whose `:membros` lists its own `:nome` is a
20214        // one-node lacre-closure recursion — rejected, naming the parent.
20215        let membros = vec![
20216            membro("catalog", "^0.1"),
20217            membro("checkout", "^0.1"),
20218            membro("cart", "^0.1"),
20219        ];
20220        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
20221        assert!(
20222            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
20223            "got {err:?}"
20224        );
20225    }
20226
20227    #[test]
20228    fn validate_no_self_membership_accepts_distinct_membros() {
20229        // Positive control: distinct member names (including a member
20230        // that is itself an Aplicacao — recursive composition is valid,
20231        // MESH-COMPOSITION §V) pass the gate.
20232        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
20233        validate_no_self_membership(&membros, "checkout").unwrap();
20234    }
20235
20236    #[test]
20237    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
20238        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
20239        // `NoMembros` arm (the more-fundamental "graph must have nodes"
20240        // gate), not by this cross-slot self-edge gate. Keeping the
20241        // self-membership predicate vacuously-ok on the empty input
20242        // matches its supervisor-axis peer
20243        // (`validate_no_self_supervision_empty_children_is_ok`) and
20244        // makes the gate composable from any future call site (an M4
20245        // CR materializer's per-membros validator) without re-checking
20246        // emptiness.
20247        validate_no_self_membership(&[], "checkout").unwrap();
20248    }
20249
20250    #[test]
20251    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
20252        // Pinning the Display: the self-membership diagnostic must name
20253        // the offending caixa verbatim + the "lists itself" framing the
20254        // author can grep for, so the cluster-far failure surfaces at
20255        // build time with one-line remediation. Same diagnostic shape
20256        // as the supervisor-axis `ChildSupervisesSelf` peer.
20257        let membros = vec![membro("orquestra", "^0.1")];
20258        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
20259        let msg = err.to_string();
20260        assert!(
20261            msg.contains("orquestra"),
20262            "diagnostic must name the offending caixa nome (got: {msg:?})"
20263        );
20264        assert!(
20265            msg.contains("lists itself"),
20266            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
20267        );
20268    }
20269
20270    #[test]
20271    fn default_servico_port_constant_pins_canonical_8080_literal() {
20272        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
20273        // at the verbatim `8080` literal both consumers (the
20274        // `Entrada::port` serde default via [`default_port`] and the
20275        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
20276        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
20277        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
20278        // discipline (a085b26) on the per-renderer canonical-K8s-axis
20279        // string-constant axis: a future refactor that drifts the
20280        // constant out from under either consumer surfaces here ahead
20281        // of every per-renderer's first emission. The literal value
20282        // matches the well-known HTTP-alt port the `pleme-computeunit`
20283        // library chart already emits as its `trigger.service.port`
20284        // default — by construction the same value the substrate
20285        // assumes about every Servico's in-cluster L4 listener.
20286        assert_eq!(
20287            DEFAULT_SERVICO_PORT, 8080,
20288            "canonical Servico port literal must remain `8080` verbatim — \
20289             this is the value both the `Entrada::port` serde default and the \
20290             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
20291        );
20292    }
20293
20294    #[test]
20295    fn default_port_helper_returns_canonical_servico_port_constant() {
20296        // The bridge-arm — pins that the [`default_port`] helper
20297        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
20298        // attribute hooks routes through the lifted
20299        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
20300        // literal. A future refactor that re-introduces the `8080`
20301        // literal at the helper's return site (silently re-opening
20302        // the drift footgun this lift closed) surfaces here ahead of
20303        // every author-side `(:entrada (:host … :para …))` slot
20304        // without an explicit `:port`. Peer with the
20305        // `default_namespace_re_export_points_at_caixa_core_canonical`
20306        // pin on the caixa-mesh-side re-export axis.
20307        assert_eq!(
20308            default_port(),
20309            DEFAULT_SERVICO_PORT,
20310            "the serde-default helper must route through the lifted constant"
20311        );
20312    }
20313
20314    #[test]
20315    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
20316        // The end-to-end pin — an author-surface `(:entrada (:host …
20317        // :para …))` without an explicit `:port` slot deserializes to
20318        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
20319        // verbatim. Routes the canonical lifted constant through both
20320        // the serde-default machinery (the `#[serde(default =
20321        // "default_port")]` attribute) and the typed-value-shape
20322        // contract (the resulting [`Entrada::port`] value). A future
20323        // refactor that drifts either axis — replacing the serde
20324        // hook's helper, changing the typed slot's wire shape — would
20325        // surface here before any per-renderer's CNP / Gateway /
20326        // HTTPRoute emission consumed the drifted default.
20327        let entrada: Entrada =
20328            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
20329        assert_eq!(
20330            entrada.port, DEFAULT_SERVICO_PORT,
20331            "the serde default must materialize as the lifted canonical Servico port"
20332        );
20333    }
20334
20335    #[test]
20336    fn servico_port_min_pins_canonical_accept_set_floor() {
20337        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
20338        // verbatim `1` literal every typed `:entrada :port` acceptance
20339        // gate keys off. Peer with the
20340        // [`default_servico_port_constant_pins_canonical_8080_literal`]
20341        // discipline on the canonical-Servico-port-constant axis: a
20342        // future refactor that drifts the accept-set floor out from
20343        // under the sole consumer at [`AplicacaoSpec::validate`]'s
20344        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
20345        // every per-`:entrada` `EntradaPortZero` diagnostic. The
20346        // literal value matches the IANA-registered TCP/UDP port
20347        // space floor (`1..=65535` — port `0` is the "any ephemeral"
20348        // sentinel, not a well-defined destination the substrate's
20349        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
20350        // axis can honor).
20351        assert_eq!(
20352            SERVICO_PORT_MIN, 1,
20353            "canonical Servico port accept-set floor must remain `1` verbatim — \
20354             this is the value the `AplicacaoSpec::validate` gate at \
20355             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
20356        );
20357    }
20358
20359    #[test]
20360    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
20361        // The cross-const invariant pin — the substrate's canonical
20362        // default port must satisfy its own accept-set floor by
20363        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
20364        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
20365        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
20366        // override the operator pins through a future
20367        // `:placement :default-port` slot that lands out-of-range, a
20368        // per-edition Servico-port migration that lifted the floor
20369        // above the previous default without coordinating the pair —
20370        // would silently invalidate the serde-default emission at
20371        // every author-side `(:entrada (:host … :para …))` slot
20372        // without an explicit `:port`: the default port would fall
20373        // below the accept-set floor, the `AplicacaoSpec::validate`
20374        // gate would reject every default-carrying Aplicacao as
20375        // `EntradaPortZero`, and the substrate's typed
20376        // `(defcaixa … :kind Aplicacao)` surface would fail validate
20377        // on every Aplicacao whose author omitted `:entrada :port`
20378        // for the substrate's chosen default — a class of authoring-
20379        // surface footguns the compile-time pin structurally closes.
20380        // Peer with the
20381        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
20382        // (27f9b34) cross-const invariant pin discipline on the peer
20383        // canonical-Helm-per-values-block child-chart-enablement-toggle
20384        // axis pair.
20385        assert!(
20386            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
20387            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
20388             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
20389             every default-carrying `(:entrada (:host … :para …))` slot without an \
20390             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
20391             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
20392        );
20393    }
20394
20395    #[test]
20396    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
20397        // The gate-site pin — asserts the `AplicacaoSpec::validate`
20398        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
20399        // `EntradaPortZero` diagnostic on the below-floor input
20400        // `port: 0` (the only below-floor value the `u16` field can
20401        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
20402        // is the singleton `{0}`). A future refactor that drifts the
20403        // gate off the lifted const (silently re-introducing an
20404        // inline `if e.port == 0` byte-check) surfaces here — the
20405        // pin cannot distinguish `< 1` from `== 0` on the current
20406        // floor, but it *does* pin that the diagnostic fires on `0`
20407        // through whichever gate is wired, so any future accept-set
20408        // floor migration (a hypothetical unprivileged-only
20409        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
20410        // update this test alongside the const declaration —
20411        // structurally guaranteeing the gate + accept-set + pin
20412        // trio move together. Peer with the
20413        // [`rejects_zero_entrada_port`] behavioral pin on the same
20414        // per-`:entrada :port` axis — that pin asserts the pre-lift
20415        // behavioral contract (`port: 0` → `EntradaPortZero`); this
20416        // pin adds the structural link to the lifted floor const.
20417        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
20418        let mut s = three_member_spec();
20419        s.entrada.as_mut().unwrap().port = 0;
20420        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
20421    }
20422
20423    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
20424
20425    #[test]
20426    fn membro_serde_keys_match_lifted_membro_key_consts() {
20427        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
20428        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
20429        // name the exact camelCase JSON keys the
20430        // `#[serde(rename_all = "camelCase")]` attribute on
20431        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
20432        // that each canonical byte-sequence appears verbatim in the
20433        // JSON — a future accidental `rename_all = "snake_case"` /
20434        // `"kebab-case"` / verbatim-field-name flip at the derive
20435        // attribute (any of which would silently break every downstream
20436        // JSON consumer that reaches for one of the two consts via
20437        // `Value::get(...)`) surfaces here as a build-time test failure
20438        // at `aplicacao.rs`, not as an apply-time
20439        // `.get(<stale-canonical-const>)` returning `None` far from the
20440        // derive-attr drift's commit. Peer with the sibling
20441        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
20442        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
20443        // same discipline the SupervisorSpec top-level lift established,
20444        // extended here to the M3 [`Membro`] per-`:membros` axis.
20445        let m = Membro {
20446            caixa: "catalog".into(),
20447            versao: "^0.1".into(),
20448        };
20449        let json = serde_json::to_string(&m).unwrap();
20450        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
20451            let quoted = format!("\"{key}\"");
20452            assert!(
20453                json.contains(&quoted),
20454                "serialized Membro must carry the lifted MEMBRO_KEY_* \
20455                 byte-sequence {quoted} verbatim in the JSON emission \
20456                 (got: {json})",
20457            );
20458        }
20459    }
20460
20461    #[test]
20462    fn membro_key_consts_are_pairwise_distinct() {
20463        // Cross-axis drift-detection pin: a future collapse of the two
20464        // canonical [`Membro`] per-entry byte-strings onto the same
20465        // value (e.g. an accidental copy-paste flip of
20466        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
20467        // silently reroute every downstream probe on one axis onto the
20468        // sibling axis's overlay entry and pass every propagation-probe
20469        // test that expected only the stale axis's value. Peer of the
20470        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
20471        // (40cc4e5).
20472        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
20473        for (i, a) in all.iter().enumerate() {
20474            for b in all.iter().skip(i + 1) {
20475                assert_ne!(
20476                    a, b,
20477                    "MEMBRO_KEY_* consts must be pairwise-distinct \
20478                     canonical byte-sequences — got `{a}` == `{b}`",
20479                );
20480            }
20481        }
20482    }
20483
20484    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
20485    //    URL-path fallback resolver every HTTPRoute-aware renderer
20486    //    reaching for a per-rule path-list resolution routes through.
20487    //    The four pin tests below fix the four-way accept-set the
20488    //    resolver must always honor: (:paths-non-empty-verbatim,
20489    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
20490    //    :paths-preserves-order-across-multiple-entries) — drift on any
20491    //    arm surfaces at caixa-core build time rather than at cluster-
20492    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
20493    //    sibling `:politicas` typed-primitive dispatch axis.
20494
20495    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
20496        Entrada {
20497            host: "example.com".into(),
20498            para: "cart".into(),
20499            paths: paths.into_iter().map(String::from).collect(),
20500            port: DEFAULT_SERVICO_PORT,
20501        }
20502    }
20503
20504    #[test]
20505    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
20506        // The typed `:entrada :paths` slot carries an author-declared
20507        // list — the resolver returns each entry verbatim, no
20508        // catch-all substitution. The canonical "author declared
20509        // paths, honor them verbatim" arm of the path-list dispatch.
20510        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
20511        assert_eq!(
20512            e.resolved_paths(),
20513            vec!["/api/cart", "/api/products"],
20514            "resolved_paths must return each `:entrada :paths` entry \
20515             verbatim when the typed slot is non-empty (got {:?})",
20516            e.resolved_paths(),
20517        );
20518    }
20519
20520    #[test]
20521    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
20522        // Empty `:entrada :paths` slot — the resolver substitutes the
20523        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
20524        // catch-all fallback verbatim. Pins the empty-arm of the
20525        // resolver's four-way accept-set against a future silent
20526        // detour that returned an empty Vec (which would emit an
20527        // HTTPRoute with zero rules — silently dropping every
20528        // external `:entrada` flow at admission time), routed to a
20529        // different fallback shape, or dropped the catch-all
20530        // altogether.
20531        let e = entrada_with_paths(vec![]);
20532        assert_eq!(
20533            e.resolved_paths(),
20534            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
20535            "resolved_paths on empty `:entrada :paths` must fall back \
20536             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
20537             all — got {:?}",
20538            e.resolved_paths(),
20539        );
20540    }
20541
20542    #[test]
20543    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
20544        // Single-entry `:entrada :paths` — the resolver returns the
20545        // single declared path verbatim, NOT the catch-all fallback
20546        // (author declared a path, honor it — the empty-arm and the
20547        // len-1 arm are semantically distinct axes of the resolver's
20548        // accept-set). Pins that the resolver treats "author declared
20549        // one path" as authored input, not as the empty case.
20550        let e = entrada_with_paths(vec!["/api/only"]);
20551        assert_eq!(
20552            e.resolved_paths(),
20553            vec!["/api/only"],
20554            "resolved_paths on single-entry `:entrada :paths` must \
20555             return the declared path verbatim, NOT the catch-all \
20556             fallback (got {:?})",
20557            e.resolved_paths(),
20558        );
20559    }
20560
20561    #[test]
20562    fn resolved_paths_preserves_author_declared_order() {
20563        // The `:entrada :paths` list is author-ordered — the resolver
20564        // preserves the author's declaration order verbatim, since
20565        // per-rule dispatch order at the K8s Gateway API HTTPRoute
20566        // consumer is significant (first-match-wins under the
20567        // path-prefix matcher). Pins against a future silent
20568        // re-sort / dedup / normalize detour that reordered author
20569        // input.
20570        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
20571        assert_eq!(
20572            e.resolved_paths(),
20573            vec!["/z/last", "/a/first", "/m/mid"],
20574            "resolved_paths must preserve author-declared `:entrada \
20575             :paths` order verbatim — got {:?}",
20576            e.resolved_paths(),
20577        );
20578    }
20579
20580    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
20581    //    slot `&[String]` slice accessor every per-`:entrada` consumer
20582    //    that must see the author's declaration verbatim (not the
20583    //    fallback-applied projection the sibling `resolved_paths`
20584    //    returns) routes through. The three pin tests below fix the
20585    //    accept-set the accessor must honor: (:non-empty-byte-equal,
20586    //    :empty-projects-empty-slice, :preserves-author-declared-order)
20587    //    — drift on any arm surfaces at caixa-core build time rather
20588    //    than at cluster-apply time. Peer discipline with the sibling
20589    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
20590    //    peer M3 mesh-slot `Vec<String>`-carry axis.
20591
20592    #[test]
20593    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
20594        // Byte-equal pin: [`Entrada::paths`] must project the raw
20595        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
20596        // slice borrowed from the typed slot's own [`Vec<String>`]
20597        // storage — no re-ordering, no dedup, no per-entry normalization,
20598        // no fallback substitution (the fallback-applying projection is
20599        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
20600        // a future silent detour that re-normalized the list, dropped
20601        // duplicates the [`AplicacaoSpec::validate`]
20602        // `EntradaPathDuplicate` refusal already rejects at build time,
20603        // or (most severe) accidentally routed through the fallback-
20604        // applying sibling and returned the substrate catch-all when
20605        // the author declared an empty list — collapsing the raw-slot
20606        // and fallback-applied axes into one and breaking the
20607        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
20608        //
20609        // Peer of the sibling
20610        // [`Placement::clusters`]-shape byte-equal pin
20611        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20612        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
20613        let fixtures: Vec<Vec<String>> = vec![
20614            Vec::new(),
20615            vec!["/api/cart".into()],
20616            vec!["/api/cart".into(), "/api/products".into()],
20617            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
20618        ];
20619        for paths in fixtures {
20620            let e = Entrada {
20621                host: "example.com".into(),
20622                para: "cart".into(),
20623                paths: paths.clone(),
20624                port: DEFAULT_SERVICO_PORT,
20625            };
20626            assert_eq!(
20627                e.paths(),
20628                paths.as_slice(),
20629                "Entrada::paths must return :entrada :paths verbatim \
20630                 (got {:?}, expected {:?})",
20631                e.paths(),
20632                paths.as_slice(),
20633            );
20634            assert_eq!(
20635                e.paths(),
20636                e.paths.as_slice(),
20637                "Entrada::paths accessor and .paths.as_slice() field \
20638                 access must byte-equal — the accessor is the substrate-\
20639                 primitive typed dispatch every downstream per-`:entrada` \
20640                 raw-slot path-list consumer must route through",
20641            );
20642            assert_eq!(
20643                e.paths().len(),
20644                e.paths.len(),
20645                "Entrada::paths().len() must byte-equal self.paths.len() \
20646                 — a length drift would silently split the paired \
20647                 pre-flight cascade-head `.is_empty()` probe input in \
20648                 the sibling [`Entrada::resolved_paths`] resolver from \
20649                 the per-entry validate loop's traversal input in \
20650                 [`AplicacaoSpec::validate`]",
20651            );
20652        }
20653    }
20654
20655    #[test]
20656    fn resolved_paths_reads_through_lifted_paths_accessor() {
20657        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
20658        // pre-flight `.paths().is_empty()` cascade-head probe (which
20659        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
20660        // catch-all fallback arm when the accessor projects the empty
20661        // slice) and the per-entry `.paths().iter().map(String::as_str)`
20662        // projection (which must reach every entry in the same order
20663        // the accessor projects, so the sibling
20664        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
20665        // per-entry projection stay in lockstep by construction) must
20666        // both key off the lifted accessor. Pins the two-site coherence
20667        // by exercising each production consumer end-to-end: (1) the
20668        // catch-all-fallback arm under the empty slice, (2) the
20669        // author-declared-verbatim arm under a two-entry cohort whose
20670        // per-entry projection must byte-equal the input's per-entry
20671        // author-declared paths in the author's declared order.
20672        //
20673        // Peer of the sibling M3
20674        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
20675        // `validate_placement_reads_through_lifted_clusters_accessor`
20676        // on the sibling `Placement::clusters` reader-site convergence.
20677        let empty = entrada_with_paths(vec![]);
20678        assert_eq!(
20679            empty.resolved_paths(),
20680            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
20681            "resolved_paths on empty :entrada :paths must trip the \
20682             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
20683             catch-all fallback — routing through the lifted paths() \
20684             accessor must not silently drop the fallback arm",
20685        );
20686
20687        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
20688        assert_eq!(
20689            declared.resolved_paths(),
20690            vec!["/api/cart", "/api/products"],
20691            "resolved_paths on non-empty :entrada :paths must return each \
20692             entry verbatim in the author's declared order — routing \
20693             through the lifted paths() accessor must not silently \
20694             reorder or drop entries",
20695        );
20696        // Byte-equal pin against the raw-slot accessor to keep the
20697        // fallback-applying resolver's per-entry projection input in
20698        // lockstep with the raw-slot accessor's projection.
20699        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
20700        assert_eq!(
20701            declared.resolved_paths(),
20702            raw_projected,
20703            "resolved_paths non-empty projection must byte-equal the \
20704             lifted paths() accessor's per-entry String::as_str projection \
20705             — the two projections share the same input slice by \
20706             construction, so any drift here would surface a silent \
20707             re-ordering / dedup / normalization detour in the resolver",
20708        );
20709    }
20710
20711    #[test]
20712    fn validate_reads_through_lifted_entrada_paths_accessor() {
20713        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
20714        // per-entry value-shape gate's `for p in e.paths()` traversal
20715        // (which must reach every entry in the same order the accessor
20716        // projects, so both the per-entry `EntradaPathEmpty` /
20717        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
20718        // the duplicate-detection HashSet insert that trips
20719        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
20720        // projection) must route through the lifted accessor. Pins the
20721        // coherence by exercising each production consumer end-to-end:
20722        // (1) the `EntradaPathEmpty` refusal fires on the second entry
20723        // of a two-entry cohort whose head is valid but tail is empty
20724        // (which requires the loop to reach the second entry through
20725        // the accessor), and (2) the `EntradaPathDuplicate` refusal
20726        // fires on the second entry of a two-entry cohort that shares
20727        // a path (which requires the loop to reach both entries — a
20728        // first-entry-only projection would silently pass since the
20729        // dedup HashSet has room for the first insert).
20730        //
20731        // Peer of the sibling
20732        // `validate_placement_reads_through_lifted_clusters_accessor`
20733        // on the sibling `Placement::clusters` reader-site convergence.
20734        let base = crate::AplicacaoSpec {
20735            membros: vec![crate::Membro {
20736                caixa: "cart".into(),
20737                versao: "^0.1".into(),
20738            }],
20739            contratos: Vec::new(),
20740            politicas: crate::MeshPolicy::default(),
20741            placement: crate::Placement {
20742                estrategia: crate::PlacementStrategy::SingleNode,
20743                clusters: vec!["rio".into()],
20744                shard_key: None,
20745                affinity: None,
20746            },
20747            entrada: Some(Entrada {
20748                host: "example.com".into(),
20749                para: "cart".into(),
20750                paths: vec!["/api/cart".into(), String::new()],
20751                port: DEFAULT_SERVICO_PORT,
20752            }),
20753        };
20754        assert_eq!(
20755            base.validate(),
20756            Err(crate::AplicacaoError::EntradaPathEmpty),
20757            "validate must trip EntradaPathEmpty on the second entry of \
20758             a two-entry cohort — routing through the lifted paths() \
20759             accessor must not silently short-circuit the loop at the \
20760             valid head entry",
20761        );
20762
20763        let mut dup = base;
20764        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
20765        assert_eq!(
20766            dup.validate(),
20767            Err(crate::AplicacaoError::EntradaPathDuplicate {
20768                path: "/api/cart".into(),
20769            }),
20770            "validate must trip EntradaPathDuplicate on the second entry \
20771             of a two-entry cohort that shares a path — routing through \
20772             the lifted paths() accessor must not silently short-circuit \
20773             the dedup HashSet insert at the first entry",
20774        );
20775    }
20776
20777    // ── Entrada::hostname / Entrada::hostnames — the substrate-
20778    //    canonical per-`:entrada` DNS-hostname resolver pair every
20779    //    Gateway-API-aware renderer reaching for a per-listener
20780    //    singular `hostname:` filter (Gateway) or a per-route plural
20781    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
20782    //    The three pin tests below fix the two-way accept-set the pair
20783    //    must always honor: (:singular-byte-equal-to-host,
20784    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
20785    //    on any arm surfaces at caixa-core build time rather than at
20786    //    cluster-apply time when the API server refuses the HTTPRoute
20787    //    for non-intersecting hostname filters. Peer discipline with
20788    //    the sibling `resolved_paths` accept-set pin block above on the
20789    //    per-`:entrada` path-list resolver axis.
20790
20791    fn entrada_with_host(host: &str) -> Entrada {
20792        Entrada {
20793            host: host.into(),
20794            para: "cart".into(),
20795            paths: Vec::new(),
20796            port: DEFAULT_SERVICO_PORT,
20797        }
20798    }
20799
20800    #[test]
20801    fn hostname_returns_entrada_host_byte_equal() {
20802        // The canonical singular-axis pin: [`Entrada::hostname`] must
20803        // return the `:entrada :host` field byte-for-byte, borrowed
20804        // from the typed slot's own [`String`] storage. Pins against a
20805        // future silent detour that re-normalized the host (an
20806        // accidental `.to_lowercase()` — validate_entrada_host already
20807        // enforces lowercase, so any re-normalization is redundant + a
20808        // drift surface between the validator and the accessor), a
20809        // trailing-`.` fully-qualified DNS shape substitution, or a
20810        // Punycode round-trip that lowered a Unicode host through IDNA.
20811        let e = entrada_with_host("checkout.quero.cloud");
20812        assert_eq!(
20813            e.hostname(),
20814            "checkout.quero.cloud",
20815            "Entrada::hostname must return :entrada :host verbatim \
20816             (got {:?})",
20817            e.hostname(),
20818        );
20819        assert_eq!(
20820            e.hostname(),
20821            e.host.as_str(),
20822            "Entrada::hostname must byte-equal the .host field access",
20823        );
20824    }
20825
20826    #[test]
20827    fn hostnames_returns_singleton_of_hostname_accessor() {
20828        // The pair-invariant pin: [`Entrada::hostnames`] must always
20829        // return exactly `vec![hostname()]` — the singleton list whose
20830        // sole entry is the substrate's canonical per-`:entrada`
20831        // singular hostname. Pins the two-consumer coherence axis: the
20832        // Gateway listener's singular `hostname:` filter and the
20833        // HTTPRoute's plural `spec.hostnames[]` filter list must
20834        // agree, else the Gateway API v1.x conformance layer rejects
20835        // the HTTPRoute at attach time with
20836        // `Accepted:False/NoMatchingParent` (the parent Gateway's
20837        // listener hostname doesn't intersect the route's hostname
20838        // filter list) — a divergence whose apply-time symptom is far
20839        // from any single-site commit and never surfaces in the
20840        // emitted YAML. Pinning the pair-invariant here makes any
20841        // future accidental split (an accidental `.to_string() + "."`
20842        // trailing-`.` on the plural side that didn't land on the
20843        // singular side, an accidental prefix stripping on one axis,
20844        // an accidental wildcard prepend the SNI fan-out overlay
20845        // authors on the plural side without a paired singular
20846        // migration) trip at caixa-core build time.
20847        let e = entrada_with_host("checkout.quero.cloud");
20848        assert_eq!(
20849            e.hostnames(),
20850            vec![e.hostname()],
20851            "Entrada::hostnames must return `vec![hostname()]` under \
20852             the pair-invariant — got {:?} vs. singleton {:?}",
20853            e.hostnames(),
20854            vec![e.hostname()],
20855        );
20856    }
20857
20858    #[test]
20859    fn hostnames_is_singleton_under_single_host_author_surface() {
20860        // The singleton-shape pin: under today's single-hostname-per-
20861        // `:entrada` author surface (the `:host` slot is a single
20862        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
20863        // must always return a list of length exactly one. Pins
20864        // against a future silent detour that returned an empty list
20865        // (which would emit an HTTPRoute with `spec.hostnames: []` —
20866        // matching every incoming Host header regardless of the
20867        // Aplicacao's declared ingress apex, silently over-matching
20868        // every foreign VirtualHost the parent Gateway also fronts) or
20869        // a duplicated entry (which the Gateway API v1.x parser
20870        // accepts as a `[]-length-2 list of equal hostnames]` but
20871        // whose semantics differ from the intended singleton). The
20872        // author-surface extension point ("a future `:entrada
20873        // :alt-hosts` list overlay" the docstring names) is the sole
20874        // future axis that flips this pin — that migration will re-
20875        // author this test to pin the new plural cardinality.
20876        let e = entrada_with_host("checkout.quero.cloud");
20877        assert_eq!(
20878            e.hostnames().len(),
20879            1,
20880            "Entrada::hostnames must be a singleton under today's \
20881             single-hostname-per-`:entrada` author surface — got \
20882             length {}: {:?}",
20883            e.hostnames().len(),
20884            e.hostnames(),
20885        );
20886    }
20887
20888    // ── Entrada::destination — the substrate-canonical per-`:entrada`
20889    //    destination-Servico scalar accessor every Gateway-API
20890    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
20891    //    discriminator arg (HTTPRoute name composer) or a per-rule
20892    //    `backendRefs[0].name` axis routes through. The two pin tests
20893    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
20894    //    either arm surfaces at caixa-core build time rather than at
20895    //    cluster-apply time when an HTTPRoute's `metadata.name` and
20896    //    `backendRefs[]` silently disagree on which destination Servico
20897    //    the ingress fronts. Peer discipline with the sibling
20898    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
20899    //    blocks above on the per-`:entrada` path-list / DNS-hostname
20900    //    resolver axes.
20901
20902    #[test]
20903    fn destination_returns_entrada_para_byte_equal() {
20904        // The canonical destination-scalar pin: [`Entrada::destination`]
20905        // must return the `:entrada :para` field byte-for-byte, borrowed
20906        // from the typed slot's own [`String`] storage. Pins against a
20907        // future silent detour that re-normalized the destination (an
20908        // accidental `.to_lowercase()` — the destination Servico is
20909        // already validated as a DNS-1123 label upstream, so any
20910        // re-normalization is redundant + a drift surface between the
20911        // validator and the accessor), a namespace-prefix rewrite (an
20912        // accidental `format!("{namespace}/{para}")` per-CR fully-
20913        // qualified rewrite that didn't land on the peer axis), or a
20914        // per-cluster suffix stamp the operator authors on one
20915        // consumer without the other.
20916        for para in ["cart", "checkout", "catalog", "orders-v2"] {
20917            let e = Entrada {
20918                host: "checkout.quero.cloud".into(),
20919                para: para.into(),
20920                paths: Vec::new(),
20921                port: DEFAULT_SERVICO_PORT,
20922            };
20923            assert_eq!(
20924                e.destination(),
20925                para,
20926                "Entrada::destination must return :entrada :para verbatim \
20927                 (got {:?}, expected {para:?})",
20928                e.destination(),
20929            );
20930            assert_eq!(
20931                e.destination(),
20932                e.para.as_str(),
20933                "Entrada::destination must byte-equal the .para field access",
20934            );
20935        }
20936    }
20937
20938    #[test]
20939    fn destination_borrows_from_entrada_para_storage() {
20940        // The borrow-not-copy pin: [`Entrada::destination`] must
20941        // return a `&str` slice that borrows from the typed slot's
20942        // own [`String`] storage — same-address invariant with
20943        // `entrada.para.as_str()`. Pins against a future silent detour
20944        // that allocated a fresh `String` (`self.para.clone()` in the
20945        // body would type-check but silently drop the borrow, and
20946        // every downstream consumer that assumed the returned slice
20947        // outlives `&self` would break on a stale-reference use-after-
20948        // free). Peer with the sibling `hostname_returns_entrada_
20949        // host_byte_equal` on the singular-DNS-hostname axis.
20950        let e = entrada_with_host("checkout.quero.cloud");
20951        let dest = e.destination();
20952        let para_slice = e.para.as_str();
20953        assert_eq!(
20954            dest.as_ptr(),
20955            para_slice.as_ptr(),
20956            "Entrada::destination must borrow from the .para String's \
20957             backing storage — a fresh allocation here means the \
20958             accessor no longer names the substrate-primitive typed \
20959             dispatch and every downstream consumer would silently \
20960             carry a detached copy",
20961        );
20962        assert_eq!(
20963            dest.len(),
20964            para_slice.len(),
20965            "Entrada::destination and .para.as_str() must byte-equal in \
20966             length as well as in address",
20967        );
20968    }
20969
20970    #[test]
20971    fn port_returns_entrada_port_verbatim_across_permutations() {
20972        // The canonical L4-port-scalar pin: [`Entrada::port`] must
20973        // return the `:entrada :port` field verbatim as a `u16` across
20974        // every author-declared value in the validated accept-set
20975        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
20976        // silent detour that clamped the port (an accidental
20977        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
20978        // land on the peer [`AplicacaoSpec::port_for_destination`]
20979        // resolver), rewrote it through a per-cluster port-remap table
20980        // the operator authors on one consumer without the other, or
20981        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
20982        // serde-default value (which would silently collapse the
20983        // distinction between "author explicitly declared `:port 8080`"
20984        // and "author omitted the slot and inherited the default" the
20985        // future per-cluster override slot depends on). Peer with the
20986        // sibling `destination_returns_entrada_para_byte_equal` +
20987        // `hostname_returns_entrada_host_byte_equal` pins on the
20988        // per-`:entrada` `&str` scalar axes.
20989        for port in [
20990            SERVICO_PORT_MIN,
20991            DEFAULT_SERVICO_PORT,
20992            8443u16,
20993            9090u16,
20994            u16::MAX,
20995        ] {
20996            let e = Entrada {
20997                host: "checkout.quero.cloud".into(),
20998                para: "cart".into(),
20999                paths: Vec::new(),
21000                port,
21001            };
21002            assert_eq!(
21003                e.port(),
21004                port,
21005                "Entrada::port must return :entrada :port verbatim \
21006                 (got {}, expected {port})",
21007                e.port(),
21008            );
21009            assert_eq!(
21010                e.port(),
21011                e.port,
21012                "Entrada::port accessor and .port field access must \
21013                 byte-equal — the accessor is the substrate-primitive \
21014                 typed dispatch every downstream L4-port consumer must \
21015                 route through",
21016            );
21017        }
21018    }
21019
21020    #[test]
21021    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
21022        // Two-consumer coherence pin: the
21023        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
21024        // (which reads through [`Entrada::port`] to compare against
21025        // [`SERVICO_PORT_MIN`]) and the
21026        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
21027        // through [`Entrada::port`] to emit the per-destination
21028        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
21029        // lifted accessor, so any future rebrand on the typed slot's
21030        // reader shape lands at exactly one place. Pins the two-site
21031        // coherence by exercising a below-floor port through validate
21032        // (which must reject) and a validated in-accept-set port through
21033        // port_for_destination (which must emit the same value the
21034        // accessor returns).
21035        let mut spec = three_member_spec();
21036        if let Some(e) = spec.entrada.as_mut() {
21037            e.port = 0;
21038        }
21039        assert_eq!(
21040            spec.validate().unwrap_err(),
21041            AplicacaoError::EntradaPortZero,
21042            "validate must reject `:entrada :port 0` through the lifted \
21043             Entrada::port accessor — port zero lies below \
21044             SERVICO_PORT_MIN and the validator routes through port() \
21045             to name the floor",
21046        );
21047
21048        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
21049            let mut spec = three_member_spec();
21050            if let Some(e) = spec.entrada.as_mut() {
21051                e.port = port;
21052            }
21053            spec.validate().expect(
21054                "entrada with in-accept-set :port must validate — the \
21055                 structural-floor gate reads through Entrada::port",
21056            );
21057            let entrada_ref = spec.entrada().expect(":entrada present");
21058            assert_eq!(
21059                spec.port_for_destination(entrada_ref.destination()),
21060                entrada_ref.port(),
21061                "port_for_destination(entrada.destination()) must equal \
21062                 entrada.port() — the two consumers of the per-:entrada \
21063                 L4-port axis (validator, per-destination resolver) both \
21064                 route through Entrada::port",
21065            );
21066        }
21067    }
21068
21069    #[test]
21070    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
21071        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
21072        // must return the `:contratos :de` field byte-for-byte, borrowed
21073        // from the typed slot's own [`String`] storage. Peer of the
21074        // sibling `destination_returns_entrada_para_byte_equal` pin on
21075        // the per-`:entrada` axis — same "the substrate-primitive
21076        // accessor must byte-equal the raw field access verbatim across
21077        // every author-declared value" discipline extended to the
21078        // per-`:contratos` caller arm. Pins against a future silent
21079        // detour that re-normalized the caller (an accidental
21080        // `.to_lowercase()` — every `:contratos :de` is validated as a
21081        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
21082        // re-normalization is redundant + a drift surface between the
21083        // validator and the accessor), a namespace-prefix rewrite (an
21084        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
21085        // rewrite that didn't land on the peer axis), or a per-cluster
21086        // suffix stamp the operator authors on one consumer without the
21087        // other.
21088        for de in ["cart", "checkout", "catalog", "orders-v2"] {
21089            let c = WitContract {
21090                de: de.into(),
21091                para: "downstream".into(),
21092                wit: "wasi:http/proxy".into(),
21093                endpoint: Some("/lookup".into()),
21094                subject: None,
21095                slot: None,
21096            };
21097            assert_eq!(
21098                c.source(),
21099                de,
21100                "WitContract::source must return :contratos :de verbatim \
21101                 (got {:?}, expected {de:?})",
21102                c.source(),
21103            );
21104            assert_eq!(
21105                c.source(),
21106                c.de.as_str(),
21107                "WitContract::source must byte-equal the .de field access",
21108            );
21109        }
21110    }
21111
21112    #[test]
21113    fn wit_contract_source_borrows_from_de_storage() {
21114        // The borrow-not-copy pin: [`WitContract::source`] must return a
21115        // `&str` slice that borrows from the typed slot's own [`String`]
21116        // storage — same-address invariant with `c.de.as_str()`. Pins
21117        // against a future silent detour that allocated a fresh `String`
21118        // (`self.de.clone()` in the body would type-check but silently
21119        // drop the borrow, and every downstream consumer that assumed
21120        // the returned slice outlives `&self` would break on a stale-
21121        // reference use-after-free). Peer of the sibling
21122        // `destination_borrows_from_entrada_para_storage` on the
21123        // per-`:entrada` axis.
21124        let c = WitContract {
21125            de: "cart".into(),
21126            para: "catalog".into(),
21127            wit: "wasi:http/proxy".into(),
21128            endpoint: Some("/lookup".into()),
21129            subject: None,
21130            slot: None,
21131        };
21132        let src = c.source();
21133        let de_slice = c.de.as_str();
21134        assert_eq!(
21135            src.as_ptr(),
21136            de_slice.as_ptr(),
21137            "WitContract::source must borrow from the .de String's \
21138             backing storage — a fresh allocation here means the \
21139             accessor no longer names the substrate-primitive typed \
21140             dispatch and every downstream consumer would silently \
21141             carry a detached copy",
21142        );
21143        assert_eq!(
21144            src.len(),
21145            de_slice.len(),
21146            "WitContract::source and .de.as_str() must byte-equal in \
21147             length as well as in address",
21148        );
21149    }
21150
21151    #[test]
21152    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
21153        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
21154        // must return the `:contratos :para` field byte-for-byte,
21155        // borrowed from the typed slot's own [`String`] storage. Peer of
21156        // the sibling `destination_returns_entrada_para_byte_equal` on
21157        // the per-`:entrada` axis — both accessors name "the destination-
21158        // Servico byte-string" concept on their respective mesh-slot
21159        // atoms (per-ingress apex vs. per-typed-edge callee) and both
21160        // must project the underlying `.para` field verbatim so every
21161        // downstream renderer that composes them with peer accessors
21162        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
21163        // per-edge L4 port emit site) reads the same byte-string the
21164        // author declared.
21165        for para in ["catalog", "payment", "orders", "inventory-v3"] {
21166            let c = WitContract {
21167                de: "cart".into(),
21168                para: para.into(),
21169                wit: "wasi:http/proxy".into(),
21170                endpoint: Some("/lookup".into()),
21171                subject: None,
21172                slot: None,
21173            };
21174            assert_eq!(
21175                c.destination(),
21176                para,
21177                "WitContract::destination must return :contratos :para \
21178                 verbatim (got {:?}, expected {para:?})",
21179                c.destination(),
21180            );
21181            assert_eq!(
21182                c.destination(),
21183                c.para.as_str(),
21184                "WitContract::destination must byte-equal the .para \
21185                 field access",
21186            );
21187        }
21188    }
21189
21190    #[test]
21191    fn wit_contract_destination_borrows_from_para_storage() {
21192        // The borrow-not-copy pin: [`WitContract::destination`] must
21193        // return a `&str` slice that borrows from the typed slot's own
21194        // [`String`] storage — same-address invariant with
21195        // `c.para.as_str()`. Peer of the sibling
21196        // `destination_borrows_from_entrada_para_storage` on the
21197        // per-`:entrada` axis.
21198        let c = WitContract {
21199            de: "cart".into(),
21200            para: "catalog".into(),
21201            wit: "wasi:http/proxy".into(),
21202            endpoint: Some("/lookup".into()),
21203            subject: None,
21204            slot: None,
21205        };
21206        let dest = c.destination();
21207        let para_slice = c.para.as_str();
21208        assert_eq!(
21209            dest.as_ptr(),
21210            para_slice.as_ptr(),
21211            "WitContract::destination must borrow from the .para \
21212             String's backing storage — a fresh allocation here means \
21213             the accessor no longer names the substrate-primitive typed \
21214             dispatch and every downstream consumer would silently \
21215             carry a detached copy",
21216        );
21217        assert_eq!(
21218            dest.len(),
21219            para_slice.len(),
21220            "WitContract::destination and .para.as_str() must byte-equal \
21221             in length as well as in address",
21222        );
21223    }
21224
21225    #[test]
21226    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
21227        // The canonical per-`:contratos` WIT-world-reference scalar pin:
21228        // [`WitContract::world_ref`] must return the `:contratos :wit`
21229        // field byte-for-byte, borrowed from the typed slot's own
21230        // [`String`] storage. Sibling of the peer per-`:contratos`
21231        // [`WitContract::source`] / [`WitContract::destination`]
21232        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
21233        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
21234        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
21235        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
21236        // "the substrate-primitive accessor must byte-equal the raw
21237        // field access verbatim across every author-declared value"
21238        // discipline extended to the per-`:contratos` WIT-world arm.
21239        // Pins against a future silent detour that re-canonicalized the
21240        // WIT world reference (an accidental `.to_lowercase()` pass that
21241        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
21242        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
21243        // gate is already lowercase-prefixed so any re-normalization is
21244        // redundant + a drift surface between the validator and the
21245        // accessor), an M4-promotion-shape rewrite that formatted a
21246        // typed WIT-world enum through [`Display`] and silently drifted
21247        // the printer output from the source `caixa.lisp`, or a per-
21248        // cluster WIT-alias rewrite that didn't land on the peer field-
21249        // access sites. Five values sweep the shape-dispatch accept-set
21250        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
21251        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
21252        // `wasi:keyvalue/`).
21253        for (wit, endpoint, subject, slot) in [
21254            ("wasi:http/proxy", Some("/lookup"), None, None),
21255            ("http:proxy", Some("/health"), None, None),
21256            ("nats:pub-sub", None, Some("orders.paid"), None),
21257            ("kafka:events", None, Some("checkout-events"), None),
21258            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
21259        ] {
21260            let c = WitContract {
21261                de: "cart".into(),
21262                para: "downstream".into(),
21263                wit: wit.into(),
21264                endpoint: endpoint.map(str::to_string),
21265                subject: subject.map(str::to_string),
21266                slot: slot.map(str::to_string),
21267            };
21268            assert_eq!(
21269                c.world_ref(),
21270                wit,
21271                "WitContract::world_ref must return :contratos :wit \
21272                 verbatim (got {:?}, expected {wit:?})",
21273                c.world_ref(),
21274            );
21275            assert_eq!(
21276                c.world_ref(),
21277                c.wit.as_str(),
21278                "WitContract::world_ref must byte-equal the .wit field \
21279                 access",
21280            );
21281        }
21282    }
21283
21284    #[test]
21285    fn wit_contract_world_ref_borrows_from_wit_storage() {
21286        // The borrow-not-copy pin: [`WitContract::world_ref`] must
21287        // return a `&str` slice that borrows from the typed slot's own
21288        // [`String`] storage — same-address invariant with
21289        // `c.wit.as_str()`. Pins against a future silent detour that
21290        // allocated a fresh `String` (`self.wit.clone()` in the body
21291        // would type-check but silently drop the borrow, and every
21292        // downstream consumer that assumed the returned slice outlives
21293        // `&self` would break on a stale-reference use-after-free — the
21294        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
21295        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
21296        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
21297        // / [`is_pubsub`][WitContract::is_pubsub] /
21298        // [`is_store`][WitContract::is_store] methods route through —
21299        // each borrow from the WitContract's own storage and each would
21300        // silently misbehave if this accessor produced a detached copy).
21301        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
21302        // [`WitContract::destination`] and per-`:entrada`
21303        // [`Entrada::destination`] / [`Entrada::hostname`] and
21304        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
21305        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
21306        let c = WitContract {
21307            de: "cart".into(),
21308            para: "catalog".into(),
21309            wit: "wasi:http/proxy".into(),
21310            endpoint: Some("/lookup".into()),
21311            subject: None,
21312            slot: None,
21313        };
21314        let world = c.world_ref();
21315        let wit_slice = c.wit.as_str();
21316        assert_eq!(
21317            world.as_ptr(),
21318            wit_slice.as_ptr(),
21319            "WitContract::world_ref must borrow from the .wit String's \
21320             backing storage — a fresh allocation here means the \
21321             accessor no longer names the substrate-primitive typed \
21322             dispatch and every downstream consumer would silently carry \
21323             a detached copy",
21324        );
21325        assert_eq!(
21326            world.len(),
21327            wit_slice.len(),
21328            "WitContract::world_ref and .wit.as_str() must byte-equal in \
21329             length as well as in address",
21330        );
21331    }
21332
21333    #[test]
21334    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
21335        // Sibling-triple invariant pin composing all three per-`:contratos`
21336        // substrate-primitive typed dispatches — [`WitContract::source`]
21337        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
21338        // [`WitContract::world_ref`] — at the joint
21339        // `(source(), destination(), world_ref())` call shape every
21340        // renderer that fans on per-edge caller-callee-shape identity
21341        // keys off. The invariant, evaluated per-contract:
21342        //
21343        //   (c.source(), c.destination(), c.world_ref())
21344        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
21345        //
21346        // Closes the last unlifted per-`:contratos` scalar axis — every
21347        // downstream consumer that reads the triple now routes through
21348        // exactly three typed dispatches on the substrate primitive,
21349        // not two typed + one open-coded field access. A future refactor
21350        // that silently split any one accessor's projection (an
21351        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
21352        // canonicalization that didn't reach the peer `source`/
21353        // `destination` arms, an accidental `source()` per-cluster
21354        // caller-alias rewrite that didn't land on the `world_ref` peer)
21355        // surfaces at caixa-core build time. Peer of the sibling per-
21356        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
21357        // per-`:entrada` `(hostname(), destination())` (6db982c /
21358        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
21359        // axes, extended to the per-`:contratos` triple.
21360        for (de, para, wit, endpoint, subject, slot) in [
21361            (
21362                "cart",
21363                "catalog",
21364                "wasi:http/proxy",
21365                Some("/lookup"),
21366                None,
21367                None,
21368            ),
21369            (
21370                "checkout",
21371                "orders",
21372                "nats:pub-sub",
21373                None,
21374                Some("orders.paid"),
21375                None,
21376            ),
21377            (
21378                "cart",
21379                "kv",
21380                "wasi:keyvalue/store",
21381                None,
21382                None,
21383                Some("carts/{cart_id}"),
21384            ),
21385            (
21386                "orders-v2",
21387                "inventory-v3",
21388                "http:proxy",
21389                Some("/reserve"),
21390                None,
21391                None,
21392            ),
21393        ] {
21394            let c = WitContract {
21395                de: de.into(),
21396                para: para.into(),
21397                wit: wit.into(),
21398                endpoint: endpoint.map(str::to_string),
21399                subject: subject.map(str::to_string),
21400                slot: slot.map(str::to_string),
21401            };
21402            assert_eq!(
21403                (c.source(), c.destination(), c.world_ref()),
21404                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
21405                "(WitContract::source, ::destination, ::world_ref) must \
21406                 project (.de, .para, .wit) verbatim across every author-\
21407                 declared triple (got ({:?}, {:?}, {:?}), expected \
21408                 ({de:?}, {para:?}, {wit:?}))",
21409                c.source(),
21410                c.destination(),
21411                c.world_ref(),
21412            );
21413        }
21414    }
21415
21416    #[test]
21417    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
21418        // The canonical per-`:contratos` owned-form caller-callee-pair
21419        // pin: [`WitContract::edge_pair`] must return the
21420        // `(source(), destination())` tuple in owned form byte-for-byte,
21421        // projected through the lifted [`WitContract::source`] /
21422        // [`WitContract::destination`] scalar accessors. Pins the
21423        // composite-projection invariant on the per-`:contratos`
21424        // mesh-slot atom — every author-declared `(de, para)` pair must
21425        // round-trip verbatim through the substrate primitive's typed
21426        // dispatch, so the nine [`AplicacaoError`] diagnostic-
21427        // construction sites the accessor now feeds
21428        // ([`AplicacaoError::EmptyWit`],
21429        // [`AplicacaoError::ContratoEndpointEmpty`],
21430        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
21431        // [`AplicacaoError::ContratoEndpointInvalid`],
21432        // [`AplicacaoError::ContratoSubjectEmpty`],
21433        // [`AplicacaoError::ContratoSubjectInvalid`],
21434        // [`AplicacaoError::ContratoSlotEmpty`],
21435        // [`AplicacaoError::ContratoSlotInvalid`],
21436        // [`AplicacaoError::ContratoDuplicate`]) all read the same
21437        // `(de, para)` label pair every author sees at the source
21438        // `caixa.lisp`. Pins against a future silent detour that swapped
21439        // the `.0` / `.1` arms (an accidental `(destination(),
21440        // source())` re-order in the body would silently invert every
21441        // downstream diagnostic's `de:` / `para:` label pair, silently
21442        // reversing the direction of every operator-facing typed error
21443        // arrow), a fresh-allocation shape drift (an accidental
21444        // `.to_string()` on one arm but not the other would leave the
21445        // owned/borrowed pair mismatched vs. the sibling `source()` /
21446        // `destination()` returns), or an M4 per-cluster caller/callee-
21447        // alias rewrite that landed on `source()` without reaching
21448        // `destination()` (or vice versa). Peer of the sibling per-
21449        // `:contratos` `(source, destination, world_ref)` triple
21450        // pin above on the mesh-slot-atom scalar-value axes, extended
21451        // to the owned-form pair-projection axis.
21452        for (de, para, wit, endpoint, subject, slot) in [
21453            (
21454                "cart",
21455                "catalog",
21456                "wasi:http/proxy",
21457                Some("/lookup"),
21458                None,
21459                None,
21460            ),
21461            (
21462                "checkout",
21463                "orders",
21464                "nats:pub-sub",
21465                None,
21466                Some("orders.paid"),
21467                None,
21468            ),
21469            (
21470                "cart",
21471                "kv",
21472                "wasi:keyvalue/store",
21473                None,
21474                None,
21475                Some("carts/{cart_id}"),
21476            ),
21477            (
21478                "orders-v2",
21479                "inventory-v3",
21480                "http:proxy",
21481                Some("/reserve"),
21482                None,
21483                None,
21484            ),
21485        ] {
21486            let c = WitContract {
21487                de: de.into(),
21488                para: para.into(),
21489                wit: wit.into(),
21490                endpoint: endpoint.map(str::to_string),
21491                subject: subject.map(str::to_string),
21492                slot: slot.map(str::to_string),
21493            };
21494            assert_eq!(
21495                c.edge_pair(),
21496                (de.to_string(), para.to_string()),
21497                "WitContract::edge_pair must return (:contratos :de, \
21498                 :contratos :para) as an owned tuple verbatim (got {:?}, \
21499                 expected ({de:?}, {para:?}))",
21500                c.edge_pair(),
21501            );
21502        }
21503    }
21504
21505    #[test]
21506    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
21507        // The composition pin: [`WitContract::edge_pair`] must return
21508        // exactly `(source().to_string(), destination().to_string())` —
21509        // the owned form of the sibling accessor pair — so any future
21510        // refactor that silently re-authored the caller-arm / callee-arm
21511        // projection to bypass the lifted scalar accessors (an accidental
21512        // `(self.de.clone(), self.para.clone())` regression back to the
21513        // raw field-access shape, an M4-typed-caller-enum `Display`
21514        // re-canonicalization on `source()` that didn't reach
21515        // `edge_pair()`, a per-cluster alias rewrite the operator lands
21516        // on `destination()` without reaching this composite projection)
21517        // trips at caixa-core build time. Pins the "typed dispatch
21518        // composes with typed dispatch, not with raw field access"
21519        // discipline every downstream diagnostic-construction site now
21520        // routes through — a `de:` / `para:` label pair whose
21521        // projection silently drifted off the substrate primitive's
21522        // scalar accessors would silently split the diagnostic's self-
21523        // locating signal from the source `caixa.lisp` author's view.
21524        // Peer of the sibling per-`:politicas` `is_empty` /
21525        // `validate_politicas` accessor-routing-pin family on the M3
21526        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
21527        let c = WitContract {
21528            de: "cart".into(),
21529            para: "catalog".into(),
21530            wit: "wasi:http/proxy".into(),
21531            endpoint: Some("/lookup".into()),
21532            subject: None,
21533            slot: None,
21534        };
21535        assert_eq!(
21536            c.edge_pair(),
21537            (c.source().to_string(), c.destination().to_string()),
21538            "WitContract::edge_pair must compose exactly \
21539             (source().to_string(), destination().to_string()) — a \
21540             bypass of either sibling accessor here would silently \
21541             decouple the composite-projection axis from the \
21542             substrate-primitive scalar accessors every downstream \
21543             consumer routes through",
21544        );
21545    }
21546
21547    #[test]
21548    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
21549     {
21550        // The canonical per-`:contratos` owned-form
21551        // caller-callee-world-ref-triple pin:
21552        // [`WitContract::edge_triple`] must return the
21553        // `(source(), destination(), world_ref())` tuple in owned form
21554        // byte-for-byte, projected through the lifted
21555        // [`WitContract::source`] / [`WitContract::destination`] /
21556        // [`WitContract::world_ref`] scalar accessors. Pins the
21557        // composite-projection invariant on the per-`:contratos`
21558        // mesh-slot atom — every author-declared `(de, para, wit)`
21559        // triple must round-trip verbatim through the substrate
21560        // primitive's typed dispatch, so the nine
21561        // [`AplicacaoError`] diagnostic-construction sites the
21562        // accessor now feeds (the [`WitTarget`]-dispatch's eight
21563        // wrong-target / missing-target / invalid-wit / capability-
21564        // with-payload arms in [`WitContract::target`], plus the
21565        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
21566        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
21567        // read the same `(de, para, wit)` triple every author sees at
21568        // the source `caixa.lisp`. Pins against a future silent
21569        // detour that swapped any two arms (an accidental `(destination(),
21570        // source(), world_ref())` re-order in the body would silently
21571        // invert every downstream diagnostic's `de:` / `para:` label
21572        // pair, silently reversing the direction of every operator-
21573        // facing typed error arrow), a fresh-allocation shape drift
21574        // (an accidental `.to_string()` skipped on one arm would leave
21575        // the owned/borrowed triple mismatched vs. the sibling
21576        // `source()` / `destination()` / `world_ref()` returns), or an
21577        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
21578        // canonicalization pass that landed on one accessor without
21579        // reaching the peers. Peer of the sibling per-`:contratos`
21580        // caller-callee-pair
21581        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
21582        // pin on the mesh-slot-atom composite-projection axis,
21583        // extended to the triple-projection axis.
21584        for (de, para, wit, endpoint, subject, slot) in [
21585            (
21586                "cart",
21587                "catalog",
21588                "wasi:http/proxy",
21589                Some("/lookup"),
21590                None,
21591                None,
21592            ),
21593            (
21594                "checkout",
21595                "orders",
21596                "nats:pub-sub",
21597                None,
21598                Some("orders.paid"),
21599                None,
21600            ),
21601            (
21602                "cart",
21603                "kv",
21604                "wasi:keyvalue/store",
21605                None,
21606                None,
21607                Some("carts/{cart_id}"),
21608            ),
21609            (
21610                "orders-v2",
21611                "inventory-v3",
21612                "http:proxy",
21613                Some("/reserve"),
21614                None,
21615                None,
21616            ),
21617        ] {
21618            let c = WitContract {
21619                de: de.into(),
21620                para: para.into(),
21621                wit: wit.into(),
21622                endpoint: endpoint.map(str::to_string),
21623                subject: subject.map(str::to_string),
21624                slot: slot.map(str::to_string),
21625            };
21626            assert_eq!(
21627                c.edge_triple(),
21628                (de.to_string(), para.to_string(), wit.to_string()),
21629                "WitContract::edge_triple must return (:contratos :de, \
21630                 :contratos :para, :contratos :wit) as an owned triple \
21631                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
21632                c.edge_triple(),
21633            );
21634        }
21635    }
21636
21637    #[test]
21638    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
21639        // The composition pin: [`WitContract::edge_triple`] must return
21640        // exactly `(source().to_string(), destination().to_string(),
21641        // world_ref().to_string())` — the owned form of the sibling
21642        // scalar-accessor triple — so any future refactor that silently
21643        // re-authored one arm's projection to bypass the lifted scalar
21644        // accessors (an accidental `(self.de.clone(), self.para.clone(),
21645        // self.wit.clone())` regression back to the raw field-access
21646        // shape the internal `edge` closure and the ContratoDuplicate
21647        // diagnostic both carried before this lift landed, an
21648        // M4-typed-caller-enum `Display` re-canonicalization on
21649        // `source()` that didn't reach `edge_triple()`, a per-cluster
21650        // alias rewrite the operator lands on `destination()` /
21651        // `world_ref()` without reaching this composite projection)
21652        // trips at caixa-core build time. Pins the "typed dispatch
21653        // composes with typed dispatch, not with raw field access"
21654        // discipline every downstream diagnostic-construction site now
21655        // routes through — a `de:` / `para:` / `wit:` triple whose
21656        // projection silently drifted off the substrate primitive's
21657        // scalar accessors would silently split the diagnostic's self-
21658        // locating signal from the source `caixa.lisp` author's view.
21659        // Peer of the sibling per-`:contratos` edge_pair composition-
21660        // pin above on the mesh-slot-atom composite-projection axis.
21661        let c = WitContract {
21662            de: "cart".into(),
21663            para: "catalog".into(),
21664            wit: "wasi:http/proxy".into(),
21665            endpoint: Some("/lookup".into()),
21666            subject: None,
21667            slot: None,
21668        };
21669        assert_eq!(
21670            c.edge_triple(),
21671            (
21672                c.source().to_string(),
21673                c.destination().to_string(),
21674                c.world_ref().to_string(),
21675            ),
21676            "WitContract::edge_triple must compose exactly \
21677             (source().to_string(), destination().to_string(), \
21678             world_ref().to_string()) — a bypass of any sibling accessor \
21679             here would silently decouple the composite-projection axis \
21680             from the substrate-primitive scalar accessors every \
21681             downstream consumer routes through",
21682        );
21683    }
21684
21685    #[test]
21686    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
21687        // The canonical semantics-pin: [`WitContract::edge_triple`] must
21688        // project the full `(de, para, wit)` identity of a `:contratos`
21689        // edge — the sub-triple every triple-carrying
21690        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
21691        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
21692        // missing-target, capability-with-payload, invalid-wit, and the
21693        // duplicate-gate). Rejects a drift in shape (an accidental
21694        // silent detour that returned a `(de, para)` pair or added an
21695        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
21696        // would trip here because the return type would no longer
21697        // pattern-match the eight `let (de, para, wit) = edge();`
21698        // destructures the [`WitContract::target`] dispatch feeds off
21699        // + the paired duplicate-gate `let (de, para, wit) =
21700        // c.edge_triple();` destructure in
21701        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
21702        // `:contratos` caller-callee-pair pin above extended to the
21703        // triple projection surface: closes the "one composite
21704        // accessor per typed diagnostic-construction sub-tuple"
21705        // discipline on the per-`:contratos` mesh-slot-atom axis.
21706        let c = WitContract {
21707            de: "checkout".into(),
21708            para: "orders".into(),
21709            wit: "nats:pub-sub".into(),
21710            endpoint: None,
21711            subject: Some("orders.paid".into()),
21712            slot: None,
21713        };
21714        let (de, para, wit) = c.edge_triple();
21715        assert_eq!(de, "checkout");
21716        assert_eq!(para, "orders");
21717        assert_eq!(wit, "nats:pub-sub");
21718    }
21719
21720    #[test]
21721    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
21722     {
21723        // The composition pin: [`WitContract::identity`] must return
21724        // exactly `(source(), destination(), world_ref(), endpoint(),
21725        // subject(), slot())` — the borrowed form of the six-scalar-
21726        // accessor identity axis. Any future refactor that silently
21727        // re-authored one arm's projection to bypass a scalar accessor
21728        // (a `self.de.as_str()` regression back to raw field access on
21729        // any of the three required arms, a `self.endpoint.as_deref()`
21730        // regression on any of the three optional arms, an M4 per-
21731        // cluster caller/callee-alias rewrite the operator lands on
21732        // `source()` / `destination()` without reaching this composite
21733        // projection) trips at caixa-core build time. Sweeps four
21734        // permutations of the WIT-shape × payload lattice — HTTP with
21735        // endpoint, pub-sub with subject, store with slot, payload-less
21736        // capability — so every payload arm is exercised. Peer of the
21737        // sibling per-`:contratos`
21738        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
21739        // composition pin on the mesh-slot-atom composite-projection
21740        // axis; extends the discipline from the (de, para, wit) prefix
21741        // onto the full-identity axis carrying the three payload arms.
21742        for (de, para, wit, endpoint, subject, slot) in [
21743            (
21744                "cart",
21745                "catalog",
21746                "wasi:http/proxy",
21747                Some("/lookup"),
21748                None,
21749                None,
21750            ),
21751            (
21752                "checkout",
21753                "orders",
21754                "nats:pub-sub",
21755                None,
21756                Some("orders.paid"),
21757                None,
21758            ),
21759            (
21760                "cart",
21761                "kv",
21762                "wasi:keyvalue/store",
21763                None,
21764                None,
21765                Some("carts/{cart_id}"),
21766            ),
21767            ("audit", "sink", "wasi:logging", None, None, None),
21768        ] {
21769            let c = WitContract {
21770                de: de.into(),
21771                para: para.into(),
21772                wit: wit.into(),
21773                endpoint: endpoint.map(str::to_owned),
21774                subject: subject.map(str::to_owned),
21775                slot: slot.map(str::to_owned),
21776            };
21777            assert_eq!(
21778                c.identity(),
21779                (
21780                    c.source(),
21781                    c.destination(),
21782                    c.world_ref(),
21783                    c.endpoint(),
21784                    c.subject(),
21785                    c.slot(),
21786                ),
21787                "WitContract::identity must compose exactly \
21788                 (source(), destination(), world_ref(), endpoint(), \
21789                 subject(), slot()) — a bypass of any sibling accessor \
21790                 here would silently decouple the identity-projection \
21791                 axis from the substrate-primitive scalar accessors \
21792                 every dedup-key consumer routes through",
21793            );
21794        }
21795    }
21796
21797    #[test]
21798    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
21799        // The canonical semantics-pin: [`WitContract::identity`] must
21800        // project the six-axis (de, para, wit, endpoint, subject, slot)
21801        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
21802        // gate keys off — two `WitContract`s that agree on all six axes
21803        // are the same typed edge declared twice, the graph-edge
21804        // analogue of duplicate `:membros` / `:placement :clusters` /
21805        // `:entrada :paths` entries. Rejects a shape drift (an
21806        // accidental silent detour that returned a prefix tuple or
21807        // added an extra field) by pattern-matching the six-arm shape.
21808        // Peer of the sibling per-`:contratos`
21809        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
21810        // pin extended from the (de, para, wit) prefix onto the full
21811        // six-axis identity that the dedup key rides.
21812        let c = WitContract {
21813            de: "cart".into(),
21814            para: "catalog".into(),
21815            wit: "wasi:http/proxy".into(),
21816            endpoint: Some("/products/:id".into()),
21817            subject: None,
21818            slot: None,
21819        };
21820        let (de, para, wit, endpoint, subject, slot) = c.identity();
21821        assert_eq!(de, "cart");
21822        assert_eq!(para, "catalog");
21823        assert_eq!(wit, "wasi:http/proxy");
21824        assert_eq!(endpoint, Some("/products/:id"));
21825        assert_eq!(subject, None);
21826        assert_eq!(slot, None);
21827
21828        // Two byte-identical contracts must produce equal identities —
21829        // the dedup key's foundational invariant.
21830        let c2 = c.clone();
21831        assert_eq!(c.identity(), c2.identity());
21832
21833        // Any change on any of the six axes must break the identity —
21834        // sweeps by mutating one axis at a time.
21835        let mut mutated = c.clone();
21836        mutated.de = "search".into();
21837        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
21838        let mut mutated = c.clone();
21839        mutated.para = "warehouse".into();
21840        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
21841        let mut mutated = c.clone();
21842        mutated.wit = "http:legacy".into();
21843        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
21844        let mut mutated = c.clone();
21845        mutated.endpoint = Some("/search".into());
21846        assert_ne!(
21847            c.identity(),
21848            mutated.identity(),
21849            "endpoint axis must partition"
21850        );
21851        let mut mutated = c.clone();
21852        mutated.subject = Some("orders.paid".into());
21853        assert_ne!(
21854            c.identity(),
21855            mutated.identity(),
21856            "subject axis must partition"
21857        );
21858        let mut mutated = c;
21859        mutated.slot = Some("carts/{id}".into());
21860        assert_ne!(mutated.identity().5, None, "slot axis must partition");
21861    }
21862
21863    #[test]
21864    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
21865        // The canonical per-`:contratos` structural-self-edge pin:
21866        // [`WitContract::is_self_loop`] must return `true` when the
21867        // `:de` and `:para` fields agree byte-for-byte, across every
21868        // WIT-shape variant the per-edge shape family carries. Pins
21869        // the shape-agnostic identity-space partition the
21870        // [`AplicacaoSpec::validate`] self-edge gate at
21871        // caixa-core/src/aplicacao.rs:5559 fires against — all four
21872        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
21873        // under the same one predicate. Four permutations sweep the
21874        // accept-set: HTTP with endpoint, pub-sub with subject, KV
21875        // store with slot, and payload-less capability.
21876        for (nome, wit, endpoint, subject, slot) in [
21877            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
21878            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
21879            (
21880                "kv",
21881                "wasi:keyvalue/store",
21882                None,
21883                None,
21884                Some("carts/{cart_id}"),
21885            ),
21886            ("audit", "wasi:logging", None, None, None),
21887        ] {
21888            let c = WitContract {
21889                de: nome.into(),
21890                para: nome.into(),
21891                wit: wit.into(),
21892                endpoint: endpoint.map(str::to_string),
21893                subject: subject.map(str::to_string),
21894                slot: slot.map(str::to_string),
21895            };
21896            assert!(
21897                c.is_self_loop(),
21898                "WitContract::is_self_loop must return true when \
21899                 :contratos :de == :contratos :para (got false on \
21900                 {nome:?} under {wit:?})",
21901            );
21902        }
21903    }
21904
21905    #[test]
21906    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
21907        // The complement pin: [`WitContract::is_self_loop`] must return
21908        // `false` on every well-shaped inter-Servico contract (the
21909        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
21910        // names — "Servico A calls Servico B" between two distinct
21911        // graph nodes). Pins against a future silent detour that
21912        // inverted the predicate (an accidental `!= ` swap for `==`
21913        // would silently reject every legitimate inter-Servico edge
21914        // and admit every self-edge — the exact inversion of the
21915        // author-intended shape). Four permutations sweep the same
21916        // WIT-shape accept-set the sibling positive-arm test carries.
21917        for (de, para, wit, endpoint, subject, slot) in [
21918            (
21919                "cart",
21920                "catalog",
21921                "wasi:http/proxy",
21922                Some("/lookup"),
21923                None,
21924                None,
21925            ),
21926            (
21927                "checkout",
21928                "orders",
21929                "nats:pub-sub",
21930                None,
21931                Some("orders.paid"),
21932                None,
21933            ),
21934            (
21935                "cart",
21936                "kv",
21937                "wasi:keyvalue/store",
21938                None,
21939                None,
21940                Some("carts/{cart_id}"),
21941            ),
21942            ("audit", "sink", "wasi:logging", None, None, None),
21943        ] {
21944            let c = WitContract {
21945                de: de.into(),
21946                para: para.into(),
21947                wit: wit.into(),
21948                endpoint: endpoint.map(str::to_string),
21949                subject: subject.map(str::to_string),
21950                slot: slot.map(str::to_string),
21951            };
21952            assert!(
21953                !c.is_self_loop(),
21954                "WitContract::is_self_loop must return false when \
21955                 :contratos :de differs from :contratos :para (got true \
21956                 on {de:?} → {para:?} under {wit:?})",
21957            );
21958        }
21959    }
21960
21961    #[test]
21962    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
21963        // The composition pin: [`WitContract::is_self_loop`] must
21964        // resolve to exactly `self.source() == self.destination()` —
21965        // the equality probe of the sibling scalar-accessor pair — so
21966        // any future refactor that silently re-authored the predicate
21967        // to bypass the lifted scalar accessors (an accidental
21968        // `self.de == self.para` regression back to the raw field-
21969        // access shape, an M4-typed-caller-enum identity-comparison
21970        // rule that landed on `source()` without reaching
21971        // `destination()`, a per-cluster alias rewrite the operator
21972        // pins on `destination()` without reaching this predicate)
21973        // trips at caixa-core build time. Pins the "typed dispatch
21974        // composes with typed dispatch, not with raw field access"
21975        // discipline the sibling [`WitContract::edge_pair`] /
21976        // [`WitContract::edge_triple`] composite-projection accessors
21977        // already carry, extended onto the per-edge endpoint-equality
21978        // predicate axis. Positive and complement arms both fire.
21979        let self_edge = WitContract {
21980            de: "cart".into(),
21981            para: "cart".into(),
21982            wit: "wasi:http/proxy".into(),
21983            endpoint: Some("/lookup".into()),
21984            subject: None,
21985            slot: None,
21986        };
21987        assert_eq!(
21988            self_edge.is_self_loop(),
21989            self_edge.source() == self_edge.destination(),
21990            "WitContract::is_self_loop must compose exactly \
21991             `source() == destination()` — a bypass of either sibling \
21992             accessor here would silently decouple the endpoint-\
21993             equality predicate from the substrate-primitive scalar \
21994             accessors every downstream consumer routes through",
21995        );
21996        let inter_edge = WitContract {
21997            de: "cart".into(),
21998            para: "catalog".into(),
21999            wit: "wasi:http/proxy".into(),
22000            endpoint: Some("/lookup".into()),
22001            subject: None,
22002            slot: None,
22003        };
22004        assert_eq!(
22005            inter_edge.is_self_loop(),
22006            inter_edge.source() == inter_edge.destination(),
22007            "WitContract::is_self_loop must compose exactly \
22008             `source() == destination()` on the complement arm too",
22009        );
22010    }
22011
22012    #[test]
22013    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
22014        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
22015        // pin: [`WitContract::endpoint`] must return the `:contratos
22016        // :endpoint` field byte-for-byte, borrowed from the typed slot's
22017        // own `Option<String>` storage. Peer of the sibling
22018        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
22019        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
22020        // mesh-slot `Option<String>` optional-scalar axes — same "the
22021        // substrate-primitive accessor must byte-equal the raw field
22022        // access verbatim across every author-declared value" discipline
22023        // extended to the per-`:contratos` HTTP-payload-carrier arm.
22024        // Pins against a future silent detour that re-canonicalized the
22025        // endpoint (an accidental percent-encoding pass that didn't
22026        // reach the peer field-access site at the dedup key, a per-CR
22027        // fully-qualified prefix rewrite the operator authors on one
22028        // consumer without the other, or an M4 typed-path-template
22029        // `Display` re-canonicalization that silently drifted the
22030        // printer output from the source `caixa.lisp`). Four values
22031        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
22032        // gate upstream admits (short root-path, dashed, param-shaped,
22033        // deep-hierarchy).
22034        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
22035            let c = WitContract {
22036                de: "cart".into(),
22037                para: "catalog".into(),
22038                wit: "wasi:http/proxy".into(),
22039                endpoint: Some(endpoint.into()),
22040                subject: None,
22041                slot: None,
22042            };
22043            assert_eq!(
22044                c.endpoint(),
22045                Some(endpoint),
22046                "WitContract::endpoint must return :contratos :endpoint \
22047                 verbatim (got {:?}, expected Some({endpoint:?}))",
22048                c.endpoint(),
22049            );
22050            assert_eq!(
22051                c.endpoint(),
22052                c.endpoint.as_deref(),
22053                "WitContract::endpoint must byte-equal the .endpoint \
22054                 field's `.as_deref()` projection",
22055            );
22056        }
22057    }
22058
22059    #[test]
22060    fn wit_contract_endpoint_none_when_field_is_none() {
22061        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
22062        // payload-carrier accessor pin: when the typed slot is absent —
22063        // the canonical shape under a non-HTTP `:wit` world per the
22064        // [`WitContract::target`]-enforced shape ↔ target partition
22065        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
22066        // carries `:slot`, [`WitTarget::Capability`] carries none) —
22067        // [`WitContract::endpoint`] must return `None`. Pins against a
22068        // future silent detour that projected the absent slot to a
22069        // `Some("")` empty-string default (the canonical `Option<String>`
22070        // → `String` collapse footgun the sibling M2
22071        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22072        // emptiness predicates already guard on the peer M2 typed-slot
22073        // surfaces), a `Some("None")` stringified-None round-trip, or a
22074        // `Some` arm whose contents were derived from a sibling slot (an
22075        // accidental fallback to the `:subject` / `:slot` payload that
22076        // read the pub-sub / store payload into the endpoint axis).
22077        // Three contracts sweep the accept-set every non-HTTP `:wit`
22078        // world lands on — pub-sub NATS, key/value, and payload-less
22079        // capability.
22080        for (wit, subject, slot) in [
22081            ("nats:pub-sub", Some("orders.paid"), None),
22082            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22083            ("wasi:cli/environment", None, None),
22084        ] {
22085            let c = WitContract {
22086                de: "cart".into(),
22087                para: "downstream".into(),
22088                wit: wit.into(),
22089                endpoint: None,
22090                subject: subject.map(str::to_string),
22091                slot: slot.map(str::to_string),
22092            };
22093            assert!(
22094                c.endpoint().is_none(),
22095                "WitContract::endpoint must return None when the typed \
22096                 slot is absent under :wit {wit:?} (got {:?})",
22097                c.endpoint(),
22098            );
22099            assert_eq!(
22100                c.endpoint(),
22101                c.endpoint.as_deref(),
22102                "WitContract::endpoint must byte-equal the .endpoint \
22103                 field's `.as_deref()` projection in the absent arm",
22104            );
22105        }
22106    }
22107
22108    #[test]
22109    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
22110        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
22111        // an `Option<&str>` whose `Some` arm borrows from the typed
22112        // slot's own [`String`] storage — same-address invariant with
22113        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
22114        // detour that allocated a fresh `String`
22115        // (`self.endpoint.clone().map(...)` in the body would type-check
22116        // but silently drop the borrow, and every downstream consumer
22117        // that assumed the returned slice outlives `&self` would break
22118        // on a stale-reference use-after-free — the [`WitContract::target`]
22119        // Http-arm payload extraction rebinds the returned `Option<&str>`
22120        // through `.ok_or_else(...)` and threads the `&str` payload into
22121        // [`WitTarget::Http { endpoint: &'a str }`], the
22122        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
22123        // [`ContratoIdentity`] dedup key threads the returned
22124        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
22125        // from the WitContract's own storage and each would silently
22126        // misbehave if this accessor produced a detached copy). Peer of
22127        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
22128        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22129        // shaped optional-scalar axes — first extension of the
22130        // `Option<&str>` borrow-not-copy discipline onto the
22131        // per-`:contratos` HTTP-shaped payload-carrier axis.
22132        let c = WitContract {
22133            de: "cart".into(),
22134            para: "catalog".into(),
22135            wit: "wasi:http/proxy".into(),
22136            endpoint: Some("/lookup".into()),
22137            subject: None,
22138            slot: None,
22139        };
22140        let ep = c.endpoint().expect("Some arm");
22141        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
22142        assert_eq!(
22143            ep.as_ptr(),
22144            storage_slice.as_ptr(),
22145            "WitContract::endpoint must borrow from the .endpoint \
22146             String's backing storage — a fresh allocation here means \
22147             the accessor no longer names the substrate-primitive typed \
22148             dispatch and every downstream consumer would silently \
22149             carry a detached copy",
22150        );
22151        assert_eq!(
22152            ep.len(),
22153            storage_slice.len(),
22154            "WitContract::endpoint and .endpoint.as_deref() must byte-\
22155             equal in length as well as in address",
22156        );
22157    }
22158
22159    #[test]
22160    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
22161        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
22162        // pin: [`WitContract::subject`] must return the `:contratos
22163        // :subject` field byte-for-byte, borrowed from the typed slot's
22164        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
22165        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
22166        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22167        // optional-scalar axis — same "the substrate-primitive accessor
22168        // must byte-equal the raw field access verbatim across every
22169        // author-declared value" discipline extended to the pub-sub arm.
22170        // Pins against a future silent detour that re-canonicalized the
22171        // subject (an accidental `.to_lowercase()` normalization that
22172        // didn't reach the peer field-access site at the dedup key, a
22173        // per-CR fully-qualified prefix rewrite the operator authors on
22174        // one consumer without the other, or an M4 typed-subject-template
22175        // `Display` re-canonicalization that silently drifted the printer
22176        // output from the source `caixa.lisp`). Four values sweep the
22177        // NATS accept-set every pub-sub author-declared subject lands on
22178        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
22179        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
22180            let c = WitContract {
22181                de: "cart".into(),
22182                para: "notifier".into(),
22183                wit: "nats:pub-sub".into(),
22184                endpoint: None,
22185                subject: Some(subject.into()),
22186                slot: None,
22187            };
22188            assert_eq!(
22189                c.subject(),
22190                Some(subject),
22191                "WitContract::subject must return :contratos :subject \
22192                 verbatim (got {:?}, expected Some({subject:?}))",
22193                c.subject(),
22194            );
22195            assert_eq!(
22196                c.subject(),
22197                c.subject.as_deref(),
22198                "WitContract::subject must byte-equal the .subject \
22199                 field's `.as_deref()` projection",
22200            );
22201        }
22202    }
22203
22204    #[test]
22205    fn wit_contract_subject_none_when_field_is_none() {
22206        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
22207        // shaped payload-carrier accessor pin: when the typed slot is
22208        // absent — the canonical shape under a non-pub-sub `:wit` world
22209        // per the [`WitContract::target`]-enforced shape ↔ target
22210        // partition ([`WitTarget::Http`] carries `:endpoint`,
22211        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
22212        // carries none) — [`WitContract::subject`] must return `None`.
22213        // Pins against a future silent detour that projected the absent
22214        // slot to a `Some("")` empty-string default (the canonical
22215        // `Option<String>` → `String` collapse footgun the sibling M2
22216        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22217        // emptiness predicates already guard on the peer M2 typed-slot
22218        // surfaces), a `Some("None")` stringified-None round-trip, or a
22219        // `Some` arm whose contents were derived from a sibling slot (an
22220        // accidental fallback to the `:endpoint` / `:slot` payload that
22221        // read the HTTP / store payload into the subject axis). Three
22222        // contracts sweep the accept-set every non-pub-sub `:wit` world
22223        // lands on — HTTP proxy, key/value store, and payload-less
22224        // capability.
22225        for (wit, endpoint, slot) in [
22226            ("wasi:http/proxy", Some("/lookup"), None),
22227            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22228            ("wasi:cli/environment", None, None),
22229        ] {
22230            let c = WitContract {
22231                de: "cart".into(),
22232                para: "downstream".into(),
22233                wit: wit.into(),
22234                endpoint: endpoint.map(str::to_string),
22235                subject: None,
22236                slot: slot.map(str::to_string),
22237            };
22238            assert!(
22239                c.subject().is_none(),
22240                "WitContract::subject must return None when the typed \
22241                 slot is absent under :wit {wit:?} (got {:?})",
22242                c.subject(),
22243            );
22244            assert_eq!(
22245                c.subject(),
22246                c.subject.as_deref(),
22247                "WitContract::subject must byte-equal the .subject \
22248                 field's `.as_deref()` projection in the absent arm",
22249            );
22250        }
22251    }
22252
22253    #[test]
22254    fn wit_contract_subject_borrows_from_subject_storage() {
22255        // The borrow-not-copy pin: [`WitContract::subject`] must return
22256        // an `Option<&str>` whose `Some` arm borrows from the typed
22257        // slot's own [`String`] storage — same-address invariant with
22258        // `c.subject.as_deref().unwrap()`. Pins against a future silent
22259        // detour that allocated a fresh `String`
22260        // (`self.subject.clone().map(...)` in the body would type-check
22261        // but silently drop the borrow, and every downstream consumer
22262        // that assumed the returned slice outlives `&self` would break
22263        // on a stale-reference use-after-free — the [`WitContract::target`]
22264        // PubSub-arm payload extraction rebinds the returned
22265        // `Option<&str>` through `.ok_or_else(...)` and threads the
22266        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
22267        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22268        // [`ContratoIdentity`] dedup key threads the returned
22269        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
22270        // from the WitContract's own storage and each would silently
22271        // misbehave if this accessor produced a detached copy). Peer of
22272        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
22273        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22274        // shaped optional-scalar axis — second extension of the
22275        // `Option<&str>` borrow-not-copy discipline onto the
22276        // per-`:contratos` payload-carrier family, this time on the
22277        // pub-sub arm.
22278        let c = WitContract {
22279            de: "cart".into(),
22280            para: "notifier".into(),
22281            wit: "nats:pub-sub".into(),
22282            endpoint: None,
22283            subject: Some("orders.paid".into()),
22284            slot: None,
22285        };
22286        let sub = c.subject().expect("Some arm");
22287        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
22288        assert_eq!(
22289            sub.as_ptr(),
22290            storage_slice.as_ptr(),
22291            "WitContract::subject must borrow from the .subject \
22292             String's backing storage — a fresh allocation here means \
22293             the accessor no longer names the substrate-primitive typed \
22294             dispatch and every downstream consumer would silently \
22295             carry a detached copy",
22296        );
22297        assert_eq!(
22298            sub.len(),
22299            storage_slice.len(),
22300            "WitContract::subject and .subject.as_deref() must byte-\
22301             equal in length as well as in address",
22302        );
22303    }
22304
22305    #[test]
22306    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
22307        // The canonical per-`:contratos` key/value-store-shaped
22308        // `:slot`-scalar pin: [`WitContract::slot`] must return the
22309        // `:contratos :slot` field byte-for-byte, borrowed from the
22310        // typed slot's own `Option<String>` storage. Peer of the
22311        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
22312        // [`WitContract::subject`] (90de675) accessor pins on the M3
22313        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22314        // optional-scalar axis — same "the substrate-primitive
22315        // accessor must byte-equal the raw field access verbatim
22316        // across every author-declared value" discipline extended to
22317        // the store arm. Pins against a future silent detour that
22318        // re-canonicalized the slot template (an accidental
22319        // `.to_lowercase()` bucket-prefix normalization that didn't
22320        // reach the peer field-access site at the dedup key, a per-CR
22321        // fully-qualified prefix rewrite the operator authors on one
22322        // consumer without the other, or an M4 typed-key-template
22323        // `Display` re-canonicalization that silently drifted the
22324        // printer output from the source `caixa.lisp`). Four values
22325        // sweep the wasi:keyvalue accept-set every store-shaped
22326        // author-declared slot lands on (flat bucket, single-param
22327        // template, multi-param template, nested-hierarchy template).
22328        for slot in [
22329            "sessions",
22330            "carts/{cart_id}",
22331            "orders/{tenant}/{order_id}",
22332            "cache/tenant-a/orders/{id}",
22333        ] {
22334            let c = WitContract {
22335                de: "cart".into(),
22336                para: "kv".into(),
22337                wit: "wasi:keyvalue/store".into(),
22338                endpoint: None,
22339                subject: None,
22340                slot: Some(slot.into()),
22341            };
22342            assert_eq!(
22343                c.slot(),
22344                Some(slot),
22345                "WitContract::slot must return :contratos :slot \
22346                 verbatim (got {:?}, expected Some({slot:?}))",
22347                c.slot(),
22348            );
22349            assert_eq!(
22350                c.slot(),
22351                c.slot.as_deref(),
22352                "WitContract::slot must byte-equal the .slot field's \
22353                 `.as_deref()` projection",
22354            );
22355        }
22356    }
22357
22358    #[test]
22359    fn wit_contract_slot_none_when_field_is_none() {
22360        // The absent-`:slot` arm of the per-`:contratos` store-shaped
22361        // payload-carrier accessor pin: when the typed slot is absent —
22362        // the canonical shape under a non-store `:wit` world per the
22363        // [`WitContract::target`]-enforced shape ↔ target partition
22364        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
22365        // carries `:subject`, [`WitTarget::Capability`] carries none) —
22366        // [`WitContract::slot`] must return `None`. Pins against a
22367        // future silent detour that projected the absent slot to a
22368        // `Some("")` empty-string default (the canonical
22369        // `Option<String>` → `String` collapse footgun the sibling M2
22370        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22371        // emptiness predicates already guard on the peer M2 typed-slot
22372        // surfaces), a `Some("None")` stringified-None round-trip, or
22373        // a `Some` arm whose contents were derived from a sibling
22374        // slot (an accidental fallback to the `:endpoint` / `:subject`
22375        // payload that read the HTTP / pub-sub payload into the store
22376        // axis). Three contracts sweep the accept-set every non-store
22377        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
22378        // payload-less capability.
22379        for (wit, endpoint, subject) in [
22380            ("wasi:http/proxy", Some("/lookup"), None),
22381            ("nats:pub-sub", None, Some("orders.paid")),
22382            ("wasi:cli/environment", None, None),
22383        ] {
22384            let c = WitContract {
22385                de: "cart".into(),
22386                para: "downstream".into(),
22387                wit: wit.into(),
22388                endpoint: endpoint.map(str::to_string),
22389                subject: subject.map(str::to_string),
22390                slot: None,
22391            };
22392            assert!(
22393                c.slot().is_none(),
22394                "WitContract::slot must return None when the typed \
22395                 slot is absent under :wit {wit:?} (got {:?})",
22396                c.slot(),
22397            );
22398            assert_eq!(
22399                c.slot(),
22400                c.slot.as_deref(),
22401                "WitContract::slot must byte-equal the .slot field's \
22402                 `.as_deref()` projection in the absent arm",
22403            );
22404        }
22405    }
22406
22407    #[test]
22408    fn wit_contract_slot_borrows_from_slot_storage() {
22409        // The borrow-not-copy pin: [`WitContract::slot`] must return
22410        // an `Option<&str>` whose `Some` arm borrows from the typed
22411        // slot's own [`String`] storage — same-address invariant with
22412        // `c.slot.as_deref().unwrap()`. Pins against a future silent
22413        // detour that allocated a fresh `String`
22414        // (`self.slot.clone().map(...)` in the body would type-check
22415        // but silently drop the borrow, and every downstream consumer
22416        // that assumed the returned slice outlives `&self` would
22417        // break on a stale-reference use-after-free — the
22418        // [`WitContract::target`] Store-arm payload extraction rebinds
22419        // the returned `Option<&str>` through `.ok_or_else(...)` and
22420        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
22421        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22422        // [`ContratoIdentity`] dedup key threads the returned
22423        // `Option<&str>` into the six-tuple's store arm — each borrow
22424        // from the WitContract's own storage and each would silently
22425        // misbehave if this accessor produced a detached copy). Peer
22426        // of the sibling per-`:contratos` [`WitContract::endpoint`]
22427        // (7020470) / [`WitContract::subject`] (90de675)
22428        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
22429        // shaped optional-scalar axis — third and final extension of
22430        // the `Option<&str>` borrow-not-copy discipline onto the
22431        // per-`:contratos` payload-carrier family, this time on the
22432        // store arm.
22433        let c = WitContract {
22434            de: "cart".into(),
22435            para: "kv".into(),
22436            wit: "wasi:keyvalue/store".into(),
22437            endpoint: None,
22438            subject: None,
22439            slot: Some("carts/{cart_id}".into()),
22440        };
22441        let slot = c.slot().expect("Some arm");
22442        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
22443        assert_eq!(
22444            slot.as_ptr(),
22445            storage_slice.as_ptr(),
22446            "WitContract::slot must borrow from the .slot String's \
22447             backing storage — a fresh allocation here means the \
22448             accessor no longer names the substrate-primitive typed \
22449             dispatch and every downstream consumer would silently \
22450             carry a detached copy",
22451        );
22452        assert_eq!(
22453            slot.len(),
22454            storage_slice.len(),
22455            "WitContract::slot and .slot.as_deref() must byte-equal \
22456             in length as well as in address",
22457        );
22458    }
22459
22460    #[test]
22461    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
22462        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
22463        // [`Membro::nome`] must return the `:membros :caixa` field
22464        // byte-for-byte, borrowed from the typed slot's own [`String`]
22465        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
22466        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22467        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
22468        // slot-atom scalar-value axes — same "the substrate-primitive
22469        // accessor must byte-equal the raw field access verbatim across
22470        // every author-declared value" discipline extended to the
22471        // per-`:membros` member-identity arm. Pins against a future
22472        // silent detour that re-normalized the member identity (an
22473        // accidental `.to_lowercase()` — every `:membros :caixa` is
22474        // validated as a DNS-1123 label upstream via
22475        // [`validate_membro_caixa`], so any re-normalization is
22476        // redundant + a drift surface between the validator and the
22477        // accessor), a namespace-prefix rewrite (an accidental
22478        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
22479        // rewrite that didn't land on the peer axes), or a per-cluster
22480        // alias stamp the operator authors on one consumer without the
22481        // other. Four values sweep the accept-set the DNS-1123 gate
22482        // upstream admits (short single-word / dashed / v-suffixed
22483        // member names).
22484        for name in ["cart", "checkout", "catalog", "orders-v2"] {
22485            let m = Membro {
22486                caixa: name.into(),
22487                versao: "^0.1".into(),
22488            };
22489            assert_eq!(
22490                m.nome(),
22491                name,
22492                "Membro::nome must return :membros :caixa verbatim \
22493                 (got {:?}, expected {name:?})",
22494                m.nome(),
22495            );
22496            assert_eq!(
22497                m.nome(),
22498                m.caixa.as_str(),
22499                "Membro::nome must byte-equal the .caixa field access",
22500            );
22501        }
22502    }
22503
22504    #[test]
22505    fn membro_nome_borrows_from_caixa_storage() {
22506        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
22507        // slice that borrows from the typed slot's own [`String`]
22508        // storage — same-address invariant with `m.caixa.as_str()`. Pins
22509        // against a future silent detour that allocated a fresh `String`
22510        // (`self.caixa.clone()` in the body would type-check but
22511        // silently drop the borrow, and every downstream consumer that
22512        // assumed the returned slice outlives `&self` would break on a
22513        // stale-reference use-after-free — the `HashSet<&str>` collector
22514        // at [`AplicacaoSpec::validate`]'s `names` seed, the
22515        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
22516        // [`AplicacaoSpec::detect_sync_cycles`], the
22517        // [`crate::render::insert_first_seen`] dedup key at
22518        // [`AplicacaoSpec::validate_membros`] — each borrow from the
22519        // Membro's own storage and each would silently misbehave if
22520        // this accessor produced a detached copy). Peer of the sibling
22521        // per-`:contratos` [`WitContract::source`] /
22522        // [`WitContract::destination`] and per-`:entrada`
22523        // [`Entrada::destination`] borrow-invariant pins on the mesh-
22524        // slot-atom scalar-value axes.
22525        let m = Membro {
22526            caixa: "checkout".into(),
22527            versao: "^0.1".into(),
22528        };
22529        let name = m.nome();
22530        let caixa_slice = m.caixa.as_str();
22531        assert_eq!(
22532            name.as_ptr(),
22533            caixa_slice.as_ptr(),
22534            "Membro::nome must borrow from the .caixa String's backing \
22535             storage — a fresh allocation here means the accessor no \
22536             longer names the substrate-primitive typed dispatch and \
22537             every downstream consumer would silently carry a detached \
22538             copy",
22539        );
22540        assert_eq!(
22541            name.len(),
22542            caixa_slice.len(),
22543            "Membro::nome and .caixa.as_str() must byte-equal in length \
22544             as well as in address",
22545        );
22546    }
22547
22548    #[test]
22549    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
22550        // The canonical per-`:membros` member-`:versao`-scalar pin:
22551        // [`Membro::versao_requirement`] must return the
22552        // `:membros :versao` field byte-for-byte, borrowed from the typed
22553        // slot's own [`String`] storage. Sibling of the peer
22554        // `membro_nome_returns_caixa_byte_equal_across_permutations`
22555        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
22556        // — same "the substrate-primitive accessor must byte-equal the
22557        // raw field access verbatim across every author-declared value"
22558        // discipline extended to the per-`:membros` member-`:versao`
22559        // requirement-string arm. Pins against a future silent detour
22560        // that re-canonicalized the requirement (an accidental
22561        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
22562        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
22563        // drifted the printer output away from the source `caixa.lisp`,
22564        // an accidental whitespace trim on `"^ 0.1"` that no consumer
22565        // ever produced from the field-access side, an accidental
22566        // per-cluster lacre-projected concrete-version rewrite that
22567        // didn't land on the peer field-access sites). Five values sweep
22568        // the accept-set the shared
22569        // [`crate::render::require_valid_versao_requirement`] gate
22570        // admits (caret / tilde / exact / wildcard / bare-major).
22571        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
22572            let m = Membro {
22573                caixa: "cart".into(),
22574                versao: req.into(),
22575            };
22576            assert_eq!(
22577                m.versao_requirement(),
22578                req,
22579                "Membro::versao_requirement must return :membros :versao \
22580                 verbatim (got {:?}, expected {req:?})",
22581                m.versao_requirement(),
22582            );
22583            assert_eq!(
22584                m.versao_requirement(),
22585                m.versao.as_str(),
22586                "Membro::versao_requirement must byte-equal the .versao \
22587                 field access",
22588            );
22589        }
22590    }
22591
22592    #[test]
22593    fn membro_versao_requirement_borrows_from_versao_storage() {
22594        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
22595        // return a `&str` slice that borrows from the typed slot's own
22596        // [`String`] storage — same-address invariant with
22597        // `m.versao.as_str()`. Pins against a future silent detour that
22598        // allocated a fresh `String` (`self.versao.clone()` in the body
22599        // would type-check but silently drop the borrow, and every
22600        // downstream consumer that assumed the returned slice outlives
22601        // `&self` would break on a stale-reference use-after-free). Peer
22602        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
22603        // per-`:contratos` [`WitContract::source`] /
22604        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22605        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
22606        // the mesh-slot-atom scalar-value axes.
22607        let m = Membro {
22608            caixa: "checkout".into(),
22609            versao: "^0.1".into(),
22610        };
22611        let req = m.versao_requirement();
22612        let versao_slice = m.versao.as_str();
22613        assert_eq!(
22614            req.as_ptr(),
22615            versao_slice.as_ptr(),
22616            "Membro::versao_requirement must borrow from the .versao \
22617             String's backing storage — a fresh allocation here means \
22618             the accessor no longer names the substrate-primitive typed \
22619             dispatch and every downstream consumer would silently carry \
22620             a detached copy",
22621        );
22622        assert_eq!(
22623            req.len(),
22624            versao_slice.len(),
22625            "Membro::versao_requirement and .versao.as_str() must byte-\
22626             equal in length as well as in address",
22627        );
22628    }
22629
22630    #[test]
22631    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
22632        // Sibling-pair invariant pin composing both per-`:membros`
22633        // substrate-primitive typed dispatches — [`Membro::nome`]
22634        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
22635        // `(nome(), versao_requirement())` call shape every renderer
22636        // that fans on per-member identity + version pin keys off. The
22637        // invariant, evaluated per-member:
22638        //
22639        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
22640        //
22641        // Closes the last unlifted per-`:membros` scalar axis — every
22642        // downstream consumer that reads the pair now routes through
22643        // exactly two typed dispatches on the substrate primitive, not
22644        // one typed + one open-coded field access. A future refactor
22645        // that silently split either accessor's projection (an
22646        // accidental `nome()` namespace-prefix rewrite that didn't
22647        // reach the peer, an accidental `versao_requirement()` lacre-
22648        // projected concrete-version rewrite that didn't land on the
22649        // `nome()` peer) surfaces at caixa-core build time. Peer of the
22650        // sibling per-`:entrada` `(hostname(), destination())` and
22651        // per-`:contratos` `(source(), destination())` pair invariants
22652        // on the mesh-slot-atom scalar-value axes.
22653        for (caixa, versao) in [
22654            ("cart", "^0.1"),
22655            ("checkout", "~0.1.2"),
22656            ("catalog", "0.1.0"),
22657            ("orders-v2", "*"),
22658        ] {
22659            let m = Membro {
22660                caixa: caixa.into(),
22661                versao: versao.into(),
22662            };
22663            assert_eq!(
22664                (m.nome(), m.versao_requirement()),
22665                (m.caixa.as_str(), m.versao.as_str()),
22666                "(Membro::nome, Membro::versao_requirement) must project \
22667                 (.caixa, .versao) verbatim across every author-declared \
22668                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
22669                m.nome(),
22670                m.versao_requirement(),
22671            );
22672        }
22673    }
22674
22675    #[test]
22676    fn validate_membros_empty_gate_routes_through_nome_accessor() {
22677        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
22678        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
22679        // not the raw `.caixa` field access. Structurally: setting
22680        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
22681        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
22682        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
22683        // (i.e. the empty string) — so the emptiness predicate the
22684        // refusal arm reaches under is the accessor-projected value,
22685        // not a peer field that would silently drift under a future
22686        // accessor-side rewrite.
22687        //
22688        // Pins against a future silent detour that (a) re-derived the
22689        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
22690        // instead of `self.nome().is_empty()`, silently disagreeing with
22691        // every peer consumer (the `validate_membro_caixa(m.nome())`
22692        // call one line below, the dedup-key `insert_first_seen(&mut
22693        // seen, m.nome(), …)` two lines below, the emit-side per-
22694        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
22695        // (b) accessor-side introduced a per-tenant alias arm the
22696        // caller was unaware of, silently rewriting an author-declared
22697        // `:caixa "checkout"` to `""` — the raw-field-access gate
22698        // would fail-open while the accessor-routed peer consumers
22699        // would fail-closed, splitting the diagnostic from the actual
22700        // failure surface.
22701        //
22702        // Peer of the sibling
22703        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
22704        // (c0110f1) composition pin — same "the shape-gate predicate
22705        // must route through the substrate-primitive typed dispatch"
22706        // discipline extended onto the per-`:membros` empty-`:caixa`
22707        // refusal-arm axis. Closes the last unlifted `.caixa` production-
22708        // code read site on `Membro` — after this converge every
22709        // caixa-core `.caixa` field access outside the accessor's own
22710        // body is either a test-side field-setter (in-module tests
22711        // constructing invalid-shape inputs) or a doc-comment reference.
22712        let mut s = three_member_spec();
22713        s.membros[1].caixa = String::new();
22714        assert!(
22715            s.membros[1].nome().is_empty(),
22716            "Membro::nome must byte-equal the .caixa field access — an \
22717             accessor-side detour that no longer projects the raw field \
22718             would silently split this drift-detection test from the \
22719             validate() refusal arm",
22720        );
22721        assert_eq!(
22722            s.membros[1].nome(),
22723            s.membros[1].caixa.as_str(),
22724            "Membro::nome and .caixa.as_str() must byte-equal on an \
22725             empty-`:caixa` entry — the emptiness gate keys off the \
22726             accessor by construction",
22727        );
22728        assert_eq!(
22729            s.validate().unwrap_err(),
22730            AplicacaoError::MembroCaixaEmpty,
22731            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
22732             on an entry whose accessor-projected `nome()` is empty",
22733        );
22734    }
22735
22736    #[test]
22737    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
22738        // The canonical per-`:placement` Akka-cluster-sharding
22739        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
22740        // the `:placement :shard-key` field byte-for-byte, borrowed
22741        // from the typed slot's own `Option<String>` storage. Peer of
22742        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
22743        // per-`:contratos` [`WitContract::source`] /
22744        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22745        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
22746        // slot-atom scalar-value axes — same "the substrate-primitive
22747        // accessor must byte-equal the raw field access verbatim across
22748        // every author-declared value" discipline extended to the
22749        // per-`:placement` Akka-cluster-sharding key extractor arm.
22750        // Pins against a future silent detour that re-normalized the
22751        // key (an accidental `.to_lowercase()` — every non-empty
22752        // `:shard-key` is validated as a printable-ASCII single-token
22753        // reference upstream via [`validate_placement_shard_key`], so
22754        // any re-normalization is redundant + a drift surface between
22755        // the validator and the accessor), a per-cluster alias rewrite
22756        // the operator authors on one consumer without the other, or an
22757        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
22758        // that didn't land on the peer field-access sites. Four values
22759        // sweep the accept-set the shape gate admits — bare identifier,
22760        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
22761        // the four canonical Akka-style entity-id extractor shapes the
22762        // future M4 cluster-sharding reconciler hashes.
22763        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
22764            let p = Placement {
22765                estrategia: PlacementStrategy::Sharded,
22766                clusters: vec!["rio".into()],
22767                affinity: None,
22768                shard_key: Some(key.into()),
22769            };
22770            assert_eq!(
22771                p.shard_key(),
22772                Some(key),
22773                "Placement::shard_key must return :placement :shard-key \
22774                 verbatim (got {:?}, expected Some({key:?}))",
22775                p.shard_key(),
22776            );
22777            assert_eq!(
22778                p.shard_key(),
22779                p.shard_key.as_deref(),
22780                "Placement::shard_key must byte-equal the .shard_key \
22781                 field's `.as_deref()` projection",
22782            );
22783        }
22784    }
22785
22786    #[test]
22787    fn placement_shard_key_none_when_field_is_none() {
22788        // The absent-`:shard-key` arm of the per-`:placement`
22789        // Akka-cluster-sharding accessor pin: when the typed slot is
22790        // absent — the canonical shape under `:estrategia Replicated` /
22791        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
22792        // enforced `shard_key.is_some() == matches!(estrategia,
22793        // Sharded)` partition — [`Placement::shard_key`] must return
22794        // `None`. Pins against a future silent detour that projected
22795        // the absent slot to a `Some("")` empty-string default (the
22796        // canonical `Option<String>` → `String` collapse footgun the
22797        // sibling M2 [`crate::LimitsSpec::is_empty`] /
22798        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
22799        // already guard on the peer M2 typed-slot surfaces), a
22800        // `Some("None")` stringified-None round-trip, or a `Some` arm
22801        // whose contents were derived from a sibling slot (an
22802        // accidental fallback to `estrategia.as_str()` that read the
22803        // strategy discriminator into the key axis). Two placements
22804        // sweep the accept-set every `validate`-passing non-`Sharded`
22805        // shape lands on — `Replicated` (Erlang/OTP distributed-app
22806        // takeover) and `SingleNode` (single-node hosting).
22807        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
22808            let p = Placement {
22809                estrategia,
22810                clusters: vec!["rio".into()],
22811                affinity: None,
22812                shard_key: None,
22813            };
22814            assert!(
22815                p.shard_key().is_none(),
22816                "Placement::shard_key must return None when the typed \
22817                 slot is absent under :estrategia {estrategia:?} (got {:?})",
22818                p.shard_key(),
22819            );
22820            assert_eq!(
22821                p.shard_key(),
22822                p.shard_key.as_deref(),
22823                "Placement::shard_key must byte-equal the .shard_key \
22824                 field's `.as_deref()` projection in the absent arm",
22825            );
22826        }
22827    }
22828
22829    #[test]
22830    fn placement_shard_key_borrows_from_shard_key_storage() {
22831        // The borrow-not-copy pin: [`Placement::shard_key`] must return
22832        // an `Option<&str>` whose `Some` arm borrows from the typed
22833        // slot's own [`String`] storage — same-address invariant with
22834        // `p.shard_key.as_deref().unwrap()`. Pins against a future
22835        // silent detour that allocated a fresh `String`
22836        // (`self.shard_key.clone().map(...)` in the body would type-
22837        // check but silently drop the borrow, and every downstream
22838        // consumer that assumed the returned slice outlives `&self`
22839        // would break on a stale-reference use-after-free — the
22840        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
22841        // gate's `Some(k)`-bound match arm reads `k: &str` under the
22842        // accessor's return type and would silently misbehave if this
22843        // accessor produced a detached copy). Peer of the sibling
22844        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
22845        // [`WitContract::source`] / [`WitContract::destination`]
22846        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
22847        // (6db982c) borrow-invariant pins on the mesh-slot-atom
22848        // scalar-value axes — first extension of the discipline onto
22849        // an `Option<String>`-shaped optional-scalar axis.
22850        let p = Placement {
22851            estrategia: PlacementStrategy::Sharded,
22852            clusters: vec!["rio".into()],
22853            affinity: None,
22854            shard_key: Some("tenantId".into()),
22855        };
22856        let key = p.shard_key().expect("Some arm");
22857        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
22858        assert_eq!(
22859            key.as_ptr(),
22860            storage_slice.as_ptr(),
22861            "Placement::shard_key must borrow from the .shard_key \
22862             String's backing storage — a fresh allocation here means \
22863             the accessor no longer names the substrate-primitive typed \
22864             dispatch and every downstream consumer would silently \
22865             carry a detached copy",
22866        );
22867        assert_eq!(
22868            key.len(),
22869            storage_slice.len(),
22870            "Placement::shard_key and .shard_key.as_deref() must byte-\
22871             equal in length as well as in address",
22872        );
22873    }
22874
22875    #[test]
22876    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
22877        // The canonical per-`:placement` M3-Adaptive-compression-hint
22878        // scalar pin: [`Placement::affinity`] must return the
22879        // `:placement :affinity` field byte-for-byte, borrowed from the
22880        // typed slot's own `Option<String>` storage. Peer of the sibling
22881        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
22882        // pin on the sibling `Option<&str>` optional-scalar axis — same
22883        // "the substrate-primitive accessor must byte-equal the raw
22884        // field access verbatim across every author-declared value"
22885        // discipline extended to the peer per-`:placement` M3-Adaptive-
22886        // compression-hint arm. Pins against a future silent detour
22887        // that re-normalized the hint (an accidental `.to_lowercase()`
22888        // — every `:affinity` is already validated as a DNS-1123 label
22889        // upstream via [`validate_placement_affinity`], so any re-
22890        // normalization is redundant + a drift surface between the
22891        // validator and the accessor), a per-cluster alias rewrite the
22892        // operator authors on one consumer without the other, or an
22893        // accidental hint-family collapse (`low-latency` → `latency`
22894        // that dropped the qualifier prefix). Four values sweep the
22895        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
22896        // canonical adaptive-compression-weight biases the future M4
22897        // placement engine reads.
22898        for hint in [
22899            "data-locality",
22900            "low-latency",
22901            "high-throughput",
22902            "cost-optimized",
22903        ] {
22904            let p = Placement {
22905                estrategia: PlacementStrategy::Replicated,
22906                clusters: vec!["rio".into()],
22907                affinity: Some(hint.into()),
22908                shard_key: None,
22909            };
22910            assert_eq!(
22911                p.affinity(),
22912                Some(hint),
22913                "Placement::affinity must return :placement :affinity \
22914                 verbatim (got {:?}, expected Some({hint:?}))",
22915                p.affinity(),
22916            );
22917            assert_eq!(
22918                p.affinity(),
22919                p.affinity.as_deref(),
22920                "Placement::affinity must byte-equal the .affinity \
22921                 field's `.as_deref()` projection",
22922            );
22923        }
22924    }
22925
22926    #[test]
22927    fn placement_affinity_none_when_field_is_none() {
22928        // The absent-`:affinity` arm of the per-`:placement`
22929        // M3-Adaptive-compression-hint accessor pin: when the typed
22930        // slot is absent — the canonical shape of an Aplicacao that
22931        // leaves the compression weighting up to the placement engine's
22932        // cluster-default arm — [`Placement::affinity`] must return
22933        // `None`. Pins against a future silent detour that projected
22934        // the absent slot to a `Some("")` empty-string default (the
22935        // canonical `Option<String>` → `String` collapse footgun the
22936        // sibling M2 [`crate::LimitsSpec::is_empty`] /
22937        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
22938        // already guard on the peer M2 typed-slot surfaces), a
22939        // `Some("None")` stringified-None round-trip, a `Some` arm
22940        // whose contents were derived from a sibling slot (an
22941        // accidental fallback to `estrategia.as_str()` that read the
22942        // strategy discriminator into the hint axis), or a
22943        // `Some("default")` implicit-default that would silently biases
22944        // the routing without the author having written one. Three
22945        // placements sweep the accept-set every `validate`-passing
22946        // `:affinity None` shape lands on — one per PlacementStrategy
22947        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
22948        // with a shard-key), since `:affinity` is orthogonal to
22949        // `:estrategia` in the typed grammar.
22950        for (estrategia, shard_key) in [
22951            (PlacementStrategy::SingleNode, None),
22952            (PlacementStrategy::Replicated, None),
22953            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
22954        ] {
22955            let p = Placement {
22956                estrategia,
22957                clusters: vec!["rio".into()],
22958                affinity: None,
22959                shard_key,
22960            };
22961            assert!(
22962                p.affinity().is_none(),
22963                "Placement::affinity must return None when the typed \
22964                 slot is absent under :estrategia {estrategia:?} (got {:?})",
22965                p.affinity(),
22966            );
22967            assert_eq!(
22968                p.affinity(),
22969                p.affinity.as_deref(),
22970                "Placement::affinity must byte-equal the .affinity \
22971                 field's `.as_deref()` projection in the absent arm",
22972            );
22973        }
22974    }
22975
22976    #[test]
22977    fn placement_affinity_borrows_from_affinity_storage() {
22978        // The borrow-not-copy pin: [`Placement::affinity`] must return
22979        // an `Option<&str>` whose `Some` arm borrows from the typed
22980        // slot's own [`String`] storage — same-address invariant with
22981        // `p.affinity.as_deref().unwrap()`. Pins against a future
22982        // silent detour that allocated a fresh `String`
22983        // (`self.affinity.clone().map(...)` in the body would type-
22984        // check but silently drop the borrow, and every downstream
22985        // consumer that assumed the returned slice outlives `&self`
22986        // would break on a stale-reference use-after-free — the
22987        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
22988        // gate reads the accessor's `&str` return through the
22989        // [`validate_placement_affinity`] `&str` parameter and would
22990        // silently misbehave if this accessor produced a detached
22991        // copy). Peer of the sibling per-`:placement`
22992        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
22993        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
22994        // extends the discipline onto the sibling per-`:placement`
22995        // M3-Adaptive-compression-hint arm.
22996        let p = Placement {
22997            estrategia: PlacementStrategy::Replicated,
22998            clusters: vec!["rio".into()],
22999            affinity: Some("data-locality".into()),
23000            shard_key: None,
23001        };
23002        let hint = p.affinity().expect("Some arm");
23003        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
23004        assert_eq!(
23005            hint.as_ptr(),
23006            storage_slice.as_ptr(),
23007            "Placement::affinity must borrow from the .affinity \
23008             String's backing storage — a fresh allocation here means \
23009             the accessor no longer names the substrate-primitive typed \
23010             dispatch and every downstream consumer would silently \
23011             carry a detached copy",
23012        );
23013        assert_eq!(
23014            hint.len(),
23015            storage_slice.len(),
23016            "Placement::affinity and .affinity.as_deref() must byte-\
23017             equal in length as well as in address",
23018        );
23019    }
23020
23021    #[test]
23022    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
23023        // The canonical per-`:placement` distribution-strategy-scalar
23024        // pin: [`Placement::estrategia`] must return the `:placement
23025        // :estrategia` field verbatim as a [`PlacementStrategy`],
23026        // `Copy`-projected from the typed slot's own `PlacementStrategy`
23027        // storage across every variant in the closed accept-set
23028        // (`SingleNode` — Erlang/OTP distributed-app takeover;
23029        // `Replicated` — active-active across every named cluster;
23030        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
23031        // against a future silent detour that re-derived the strategy
23032        // from a peer axis (an accidental fallback to
23033        // `if shard_key.is_some() { Sharded } else { Replicated }`
23034        // collapse that read the shard-key axis into the strategy
23035        // discriminator), a variant remap the operator authors on one
23036        // consumer without the other, or a stale-derive detour that
23037        // substituted [`PlacementStrategy::default`] when the field
23038        // held any explicit variant (which would silently collapse the
23039        // distinction between "author explicitly declared `:estrategia
23040        // Replicated`" and "author omitted the slot and inherited the
23041        // default" the future per-cluster override slot depends on).
23042        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
23043        // pin on the `Copy`-return `u16` scalar axis — same "the
23044        // substrate-primitive accessor must byte-equal the raw field
23045        // access verbatim across every author-declared value" discipline
23046        // extended onto the per-`:placement` distribution-strategy
23047        // `Copy`-composite-enum scalar axis.
23048        for estrategia in [
23049            PlacementStrategy::SingleNode,
23050            PlacementStrategy::Replicated,
23051            PlacementStrategy::Sharded,
23052        ] {
23053            // Route the paired `:shard-key` fixture-builder through the
23054            // typed cross-slot invariant predicate
23055            // [`PlacementStrategy::requires_shard_key`] rather than the
23056            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
23057            // arm-identity predicate — same discipline the sibling
23058            // `placement_strategy_variants_round_trip` fixture builder now
23059            // reads through.
23060            let shard_key = estrategia
23061                .requires_shard_key()
23062                .then(|| "tenantId".to_string());
23063            let p = Placement {
23064                estrategia,
23065                clusters: vec!["rio".into()],
23066                affinity: None,
23067                shard_key,
23068            };
23069            assert_eq!(
23070                p.estrategia(),
23071                estrategia,
23072                "Placement::estrategia must return :placement :estrategia \
23073                 verbatim (got {:?}, expected {estrategia:?})",
23074                p.estrategia(),
23075            );
23076            assert_eq!(
23077                p.estrategia(),
23078                p.estrategia,
23079                "Placement::estrategia accessor and .estrategia field \
23080                 access must byte-equal — the accessor is the substrate-\
23081                 primitive typed dispatch every downstream distribution-\
23082                 strategy consumer must route through",
23083            );
23084        }
23085    }
23086
23087    #[test]
23088    fn validate_placement_reads_through_lifted_estrategia_accessor() {
23089        // Three-consumer coherence pin: the
23090        // [`AplicacaoSpec::validate_placement`]
23091        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
23092        // `estrategia:` field (which reads through
23093        // [`Placement::estrategia`] to name the strategy the empty
23094        // `:clusters` list was declared against), the same method's
23095        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
23096        // reads through [`Placement::estrategia`] to fan across the
23097        // shape-gate cascades), and the non-`Sharded`-arm
23098        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
23099        // `estrategia:` field (which reads through
23100        // [`Placement::estrategia`] to name the strategy the declared-
23101        // but-inert `:shard-key` was authored under) must all key off
23102        // the lifted accessor, so any future rebrand on the typed
23103        // slot's reader shape lands at exactly one place. Pins the
23104        // three-site coherence by exercising each error surface end-
23105        // to-end and asserting the surfaced `estrategia:` field byte-
23106        // equals the accessor's return. Peer of the sibling per-
23107        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
23108        // pin on the M3 mesh-slot `Copy`-return scalar axis.
23109
23110        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
23111        // whose `estrategia:` field must byte-equal the accessor's return
23112        // for every variant in the closed accept-set.
23113        for estrategia in [
23114            PlacementStrategy::SingleNode,
23115            PlacementStrategy::Replicated,
23116            PlacementStrategy::Sharded,
23117        ] {
23118            let mut spec = three_member_spec();
23119            spec.placement.estrategia = estrategia;
23120            spec.placement.clusters = Vec::new();
23121            // Route the paired `:shard-key` spec-mutator through the typed
23122            // cross-slot invariant predicate
23123            // [`PlacementStrategy::requires_shard_key`] rather than the
23124            // [`gen_platform::IsVariant`]-derived
23125            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
23126            // same discipline the sibling
23127            // `placement_strategy_variants_round_trip` and
23128            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
23129            // fixture builders now read through.
23130            spec.placement.shard_key = estrategia
23131                .requires_shard_key()
23132                .then(|| "tenantId".to_string());
23133            let err = spec.validate().unwrap_err();
23134            match err {
23135                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
23136                    assert_eq!(
23137                        e,
23138                        spec.placement.estrategia(),
23139                        "PlacementWithoutClusters.estrategia must byte-equal \
23140                         Placement::estrategia() — the error carrier reads \
23141                         through the lifted accessor",
23142                    );
23143                }
23144                other => panic!(
23145                    "expected PlacementWithoutClusters, got {other:?} for \
23146                     estrategia={estrategia:?}"
23147                ),
23148            }
23149        }
23150
23151        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
23152        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
23153        // must byte-equal the accessor's return for both non-`Sharded`
23154        // strategies.
23155        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
23156            let mut spec = three_member_spec();
23157            spec.placement.estrategia = estrategia;
23158            spec.placement.shard_key = Some("tenantId".into());
23159            let err = spec.validate().unwrap_err();
23160            match err {
23161                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
23162                    assert_eq!(
23163                        e,
23164                        spec.placement.estrategia(),
23165                        "ShardKeyOnNonSharded.estrategia must byte-equal \
23166                         Placement::estrategia() — the non-Sharded-arm \
23167                         refusal reads through the lifted accessor",
23168                    );
23169                }
23170                other => panic!(
23171                    "expected ShardKeyOnNonSharded, got {other:?} for \
23172                     estrategia={estrategia:?}"
23173                ),
23174            }
23175        }
23176    }
23177
23178    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
23179    //
23180    // The [`Placement::clusters`] accessor lift is the second slice-return
23181    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
23182    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
23183    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
23184    // below cover (1) the accessor's byte-equal projection against the raw
23185    // field access across the empty / singleton / cohort fixtures the
23186    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
23187    // and the per-cluster validate loop fan between, and (2) the two-
23188    // consumer coherence of the paired pre-flight refusal probe and the
23189    // per-cluster validate loop routing through the accessor on both arms.
23190
23191    #[test]
23192    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
23193        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
23194        // [`Placement::clusters`] must return the `:placement :clusters`
23195        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
23196        // the same backing buffer the raw `self.clusters.as_slice()`
23197        // field access borrows from, byte-equal across every
23198        // representative fixture in the accept-set — the empty slice
23199        // (the pre-validation sentinel every
23200        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
23201        // the singleton slice (the minimal `SingleNode`-shape cohort),
23202        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
23203        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
23204        //
23205        // Pins against a future silent detour that returned
23206        // `&Vec<String>` (which would type-check but leak the storage-
23207        // side `Vec`'s grow/push/reserve surface no consumer of the
23208        // typed view reaches for), a fresh-allocated `Vec<String>` copy
23209        // (which would type-check via a coercion but silently break
23210        // every downstream caller that relied on the slice sharing the
23211        // backing buffer's identity), or an out-of-order or length-
23212        // drifted projection (which would silently split the paired
23213        // pre-flight `.is_empty()` refusal probe's input from the per-
23214        // cluster validate loop's traversal input).
23215        //
23216        // Peer of the sibling M2
23217        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23218        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23219        // `:supervisor` static-child-list axis, extended onto the M3
23220        // per-`:placement` distribution-target-list `Vec`-carry axis.
23221        let fixtures: Vec<Vec<String>> = vec![
23222            Vec::new(),
23223            vec!["rio".into()],
23224            vec!["rio".into(), "mar".into()],
23225            vec!["rio".into(), "mar".into(), "plo".into()],
23226        ];
23227        for clusters in fixtures {
23228            let p = Placement {
23229                clusters: clusters.clone(),
23230                ..Placement::default()
23231            };
23232            assert_eq!(
23233                p.clusters(),
23234                clusters.as_slice(),
23235                "Placement::clusters must return :placement :clusters \
23236                 verbatim (got {:?}, expected {:?})",
23237                p.clusters(),
23238                clusters.as_slice(),
23239            );
23240            assert_eq!(
23241                p.clusters(),
23242                p.clusters.as_slice(),
23243                "Placement::clusters accessor and .clusters.as_slice() \
23244                 field access must byte-equal — the accessor is the \
23245                 substrate-primitive typed dispatch every downstream \
23246                 cluster-pool consumer must route through",
23247            );
23248            assert_eq!(
23249                p.clusters().len(),
23250                p.clusters.len(),
23251                "Placement::clusters().len() must byte-equal \
23252                 self.clusters.len() — a length-drift would silently \
23253                 split the paired pre-flight `.is_empty()` refusal \
23254                 probe input from the per-cluster validate loop's \
23255                 traversal input",
23256            );
23257        }
23258    }
23259
23260    #[test]
23261    fn validate_placement_reads_through_lifted_clusters_accessor() {
23262        // Two-consumer coherence pin: the
23263        // [`AplicacaoSpec::validate_placement`] pre-flight
23264        // `self.placement.clusters().is_empty()` refusal probe (which
23265        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
23266        // the accessor projects the empty slice) and the per-cluster
23267        // validate loop's `for c in self.placement.clusters()`
23268        // traversal (which must reach every entry in the same order
23269        // the accessor projects, so both the per-entry value-shape
23270        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
23271        // and the duplicate-detection HashSet insert that trips
23272        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
23273        // accessor's projection) must both key off the lifted
23274        // accessor, so any future rebrand on the typed slot's reader
23275        // shape lands at exactly one place. Pins the two-site
23276        // coherence by exercising each production consumer end-to-end:
23277        // (1) the `PlacementWithoutClusters` refusal under the empty
23278        // slice, (2) the `PlacementClusterInvalid` refusal fires on
23279        // the second entry of a two-cluster cohort whose head is
23280        // valid but tail is not (which requires the loop to reach the
23281        // second entry through the accessor), and (3) the
23282        // `PlacementClusterDuplicate` refusal fires on the second
23283        // entry of a two-cluster cohort that shares a name (which
23284        // requires the loop to reach both entries — a first-entry-only
23285        // projection would silently pass since the dedup HashSet has
23286        // room for the first insert).
23287        //
23288        // Peer of the sibling M2
23289        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23290        // (bc92bce) coherence pin on the per-`:supervisor` static-
23291        // child-list axis, extended onto the M3 per-`:placement`
23292        // distribution-target-list `Vec`-carry axis.
23293
23294        // (1) Pre-flight `.is_empty()` probe: the empty slice must
23295        // trip `PlacementWithoutClusters`.
23296        let mut spec = three_member_spec();
23297        spec.placement.clusters = Vec::new();
23298        match spec.validate().unwrap_err() {
23299            AplicacaoError::PlacementWithoutClusters { .. } => {}
23300            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
23301        }
23302        assert!(
23303            spec.placement.clusters().is_empty(),
23304            "the pre-flight refusal input must be the empty slice per \
23305             the accessor's projection",
23306        );
23307
23308        // (2) Per-cluster validate loop: a two-cluster cohort with an
23309        // invalid tail entry must trip `PlacementClusterInvalid` on
23310        // the tail — the loop must reach the second entry through
23311        // the accessor.
23312        let mut spec = three_member_spec();
23313        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
23314        match spec.validate().unwrap_err() {
23315            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
23316                assert_eq!(
23317                    cluster, "BAD_CLUSTER",
23318                    "PlacementClusterInvalid.cluster must carry the \
23319                     tail entry the loop reached through the accessor",
23320                );
23321            }
23322            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
23323        }
23324        assert_eq!(
23325            spec.placement.clusters().len(),
23326            2,
23327            "the per-cluster validate loop's traversal input must be \
23328             a two-element slice per the accessor's projection",
23329        );
23330
23331        // (3) Per-cluster validate loop: a two-cluster cohort that
23332        // shares a name must trip `PlacementClusterDuplicate` on the
23333        // second entry — the loop must reach both entries through the
23334        // accessor for the dedup HashSet's second insert to collide.
23335        let mut spec = three_member_spec();
23336        spec.placement.clusters = vec!["rio".into(), "rio".into()];
23337        match spec.validate().unwrap_err() {
23338            AplicacaoError::PlacementClusterDuplicate { cluster } => {
23339                assert_eq!(
23340                    cluster, "rio",
23341                    "PlacementClusterDuplicate.cluster must carry the \
23342                     shared cluster name verbatim",
23343                );
23344            }
23345            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
23346        }
23347        assert_eq!(
23348            spec.placement.clusters().len(),
23349            2,
23350            "the per-cluster validate loop's traversal input must be \
23351             a two-element slice per the accessor's projection",
23352        );
23353    }
23354
23355    #[test]
23356    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
23357        // The canonical per-`:membros` member-list-slice-shape pin:
23358        // [`AplicacaoSpec::membros`] must return the `:membros` typed
23359        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
23360        // same backing buffer the raw `self.membros.as_slice()` field
23361        // access borrows from, byte-equal across every representative
23362        // fixture in the accept-set — the empty slice (the pre-
23363        // validation sentinel every [`AplicacaoError::NoMembros`]
23364        // refusal keys off), the singleton slice (the minimal one-
23365        // Servico Aplicacao shape), and multi-entry cohorts (the peer
23366        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
23367        // load-bearing identity of the application graph).
23368        //
23369        // Pins against a future silent detour that returned
23370        // `&Vec<Membro>` (which would type-check but leak the storage-
23371        // side `Vec`'s grow/push/reserve surface no consumer of the
23372        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
23373        // (which would type-check via a coercion but silently break
23374        // every downstream caller that relied on the slice sharing the
23375        // backing buffer's identity), or an out-of-order or length-
23376        // drifted projection (which would silently split the paired
23377        // `HashSet<&str>` name-set seed's collect input from the
23378        // pre-flight `.is_empty()` refusal probe's input from the per-
23379        // member validate loop's traversal input from the
23380        // programs.yaml emitter's per-entry fan-out loop's input from
23381        // the `feira app graph` per-member print traversal's input).
23382        //
23383        // Peer of the sibling M2
23384        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23385        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23386        // `:supervisor` static-child-list axis and the sibling M3
23387        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
23388        // (a6e18d7) `&[String]` byte-equal pin on the per-
23389        // `:placement` distribution-target-list axis — extends the
23390        // slice-return-accessor byte-equal-projection discipline onto
23391        // the outermost M3 mesh-slot type's per-Aplicacao member-list
23392        // `Vec`-carry axis.
23393        let fixtures: Vec<Vec<Membro>> = vec![
23394            Vec::new(),
23395            vec![membro("catalog", "^0.1")],
23396            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23397            vec![
23398                membro("catalog", "^0.1"),
23399                membro("cart", "^0.1"),
23400                membro("payment", "^0.2"),
23401            ],
23402        ];
23403        for membros in fixtures {
23404            let s = AplicacaoSpec {
23405                membros: membros.clone(),
23406                contratos: Vec::new(),
23407                politicas: MeshPolicy::default(),
23408                placement: Placement::default(),
23409                entrada: None,
23410            };
23411            assert_eq!(
23412                s.membros(),
23413                membros.as_slice(),
23414                "AplicacaoSpec::membros must return :membros verbatim \
23415                 (got {:?}, expected {:?})",
23416                s.membros(),
23417                membros.as_slice(),
23418            );
23419            assert_eq!(
23420                s.membros(),
23421                s.membros.as_slice(),
23422                "AplicacaoSpec::membros accessor and .membros.as_slice() \
23423                 field access must byte-equal — the accessor is the \
23424                 substrate-primitive typed dispatch every downstream \
23425                 member-list consumer must route through",
23426            );
23427            assert_eq!(
23428                s.membros().len(),
23429                s.membros.len(),
23430                "AplicacaoSpec::membros().len() must byte-equal \
23431                 self.membros.len() — a length-drift would silently \
23432                 split the paired `HashSet<&str>` name-set seed's \
23433                 collect input from the pre-flight `.is_empty()` \
23434                 refusal probe input from the per-member validate \
23435                 loop's traversal input",
23436            );
23437        }
23438    }
23439
23440    #[test]
23441    fn validate_reads_through_lifted_membros_accessor() {
23442        // Three-consumer coherence pin: the
23443        // [`AplicacaoSpec::validate_membros`] pre-flight
23444        // `self.membros().is_empty()` refusal probe (which must trip
23445        // [`AplicacaoError::NoMembros`] when the accessor projects the
23446        // empty slice), the same method's per-member validate loop's
23447        // `for m in self.membros()` traversal (which must reach every
23448        // entry in the same order the accessor projects, so both the
23449        // per-entry empty-`:caixa` gate that trips
23450        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
23451        // detection `insert_first_seen` that trips
23452        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
23453        // projection), and the peer [`AplicacaoSpec::validate`]'s
23454        // `HashSet<&str>` name-set seed's
23455        // `self.membros().iter().map(Membro::nome).collect()` collect
23456        // input (which every `:contratos` `:de` / `:para` membership
23457        // lookup rejects an unknown name against) must all three key
23458        // off the lifted accessor, so any future rebrand on the typed
23459        // slot's reader shape lands at exactly one place. Pins the
23460        // three-site coherence by exercising each production consumer
23461        // end-to-end: (1) the `NoMembros` refusal under the empty
23462        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
23463        // second entry of a two-member cohort whose head is valid but
23464        // tail has an empty `:caixa` (which requires the loop to
23465        // reach the second entry through the accessor), and (3) the
23466        // `MembroDuplicate` refusal fires on the second entry of a
23467        // two-member cohort that shares a `:caixa` name (which
23468        // requires the loop to reach both entries through the
23469        // accessor for the dedup HashSet's second insert to collide).
23470        //
23471        // Peer of the sibling M2
23472        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23473        // (bc92bce) coherence pin on the per-`:supervisor` static-
23474        // child-list axis and the sibling M3
23475        // `validate_placement_reads_through_lifted_clusters_accessor`
23476        // (a6e18d7) coherence pin on the per-`:placement` distribution-
23477        // target-list axis — extends the slice-return-accessor
23478        // multi-consumer coherence discipline onto the outermost M3
23479        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
23480
23481        // (1) Pre-flight `.is_empty()` probe: the empty slice must
23482        // trip `NoMembros`.
23483        let mut spec = three_member_spec();
23484        spec.membros = Vec::new();
23485        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
23486        assert!(
23487            spec.membros().is_empty(),
23488            "the pre-flight refusal input must be the empty slice per \
23489             the accessor's projection",
23490        );
23491
23492        // (2) Per-member validate loop: a two-member cohort with an
23493        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
23494        // the tail — the loop must reach the second entry through
23495        // the accessor.
23496        let mut spec = three_member_spec();
23497        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
23498        assert_eq!(
23499            spec.validate().unwrap_err(),
23500            AplicacaoError::MembroCaixaEmpty,
23501        );
23502        assert_eq!(
23503            spec.membros().len(),
23504            2,
23505            "the per-member validate loop's traversal input must be \
23506             a two-element slice per the accessor's projection",
23507        );
23508
23509        // (3) Per-member validate loop: a two-member cohort that
23510        // shares a `:caixa` name must trip `MembroDuplicate` on the
23511        // second entry — the loop must reach both entries through the
23512        // accessor for the dedup HashSet's second insert to collide.
23513        let mut spec = three_member_spec();
23514        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
23515        match spec.validate().unwrap_err() {
23516            AplicacaoError::MembroDuplicate { caixa } => {
23517                assert_eq!(
23518                    caixa, "catalog",
23519                    "MembroDuplicate.caixa must carry the shared \
23520                     member name verbatim",
23521                );
23522            }
23523            other => panic!("expected MembroDuplicate, got {other:?}"),
23524        }
23525        assert_eq!(
23526            spec.membros().len(),
23527            2,
23528            "the per-member validate loop's traversal input must be \
23529             a two-element slice per the accessor's projection",
23530        );
23531    }
23532
23533    #[test]
23534    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
23535        // The canonical per-`:contratos` contract-list-slice-shape pin:
23536        // [`AplicacaoSpec::contratos`] must return the `:contratos`
23537        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
23538        // slice-view over the same backing buffer the raw
23539        // `self.contratos.as_slice()` field access borrows from, byte-
23540        // equal across every representative fixture in the accept-set —
23541        // the empty slice (the pre-validation "internal-only mesh" shape
23542        // an Aplicacao whose members exchange no typed edges renders
23543        // through), the singleton slice (the minimal one-edge Aplicacao
23544        // shape), and multi-entry cohorts (the peer multi-edge shapes
23545        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
23546        // of the application graph).
23547        //
23548        // Pins against a future silent detour that returned
23549        // `&Vec<WitContract>` (which would type-check but leak the
23550        // storage-side `Vec`'s grow/push/reserve surface no consumer of
23551        // the typed view reaches for), a fresh-allocated
23552        // `Vec<WitContract>` copy (which would type-check via a coercion
23553        // but silently break every downstream caller that relied on the
23554        // slice sharing the backing buffer's identity), or an out-of-
23555        // order or length-drifted projection (which would silently split
23556        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
23557        // seed's traversal input from the `detect_sync_cycles` per-edge
23558        // adjacency-list seed's traversal input from the
23559        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
23560        // BTreeMap grouping loop's traversal input from the
23561        // `feira app graph` per-contract print traversal's input).
23562        //
23563        // Peer of the immediately-adjacent sibling M3
23564        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
23565        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
23566        // node-list axis, the sibling M3
23567        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
23568        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
23569        // distribution-target-list axis, and the sibling M2
23570        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23571        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23572        // `:supervisor` static-child-list axis — extends the slice-
23573        // return-accessor byte-equal-projection discipline onto the
23574        // outermost M3 mesh-slot type's per-Aplicacao contract-list
23575        // `Vec`-carry axis, closing the last unlifted per-
23576        // `AplicacaoSpec` `Vec`-carry axis.
23577        let fixtures: Vec<Vec<WitContract>> = vec![
23578            Vec::new(),
23579            vec![contract_http("cart", "catalog", "/products/:id")],
23580            vec![
23581                contract_http("cart", "catalog", "/products/:id"),
23582                contract_http("cart", "payment", "/charge"),
23583            ],
23584            vec![
23585                contract_http("cart", "catalog", "/products/:id"),
23586                contract_http("cart", "payment", "/charge"),
23587                contract_http("payment", "catalog", "/audit"),
23588            ],
23589        ];
23590        for contratos in fixtures {
23591            let s = AplicacaoSpec {
23592                membros: vec![
23593                    membro("catalog", "^0.1"),
23594                    membro("cart", "^0.1"),
23595                    membro("payment", "^0.2"),
23596                ],
23597                contratos: contratos.clone(),
23598                politicas: MeshPolicy::default(),
23599                placement: Placement::default(),
23600                entrada: None,
23601            };
23602            assert_eq!(
23603                s.contratos(),
23604                contratos.as_slice(),
23605                "AplicacaoSpec::contratos must return :contratos verbatim \
23606                 (got {:?}, expected {:?})",
23607                s.contratos(),
23608                contratos.as_slice(),
23609            );
23610            assert_eq!(
23611                s.contratos(),
23612                s.contratos.as_slice(),
23613                "AplicacaoSpec::contratos accessor and \
23614                 .contratos.as_slice() field access must byte-equal — \
23615                 the accessor is the substrate-primitive typed dispatch \
23616                 every downstream contract-list consumer must route \
23617                 through",
23618            );
23619            assert_eq!(
23620                s.contratos().len(),
23621                s.contratos.len(),
23622                "AplicacaoSpec::contratos().len() must byte-equal \
23623                 self.contratos.len() — a length-drift would silently \
23624                 split the paired per-edge validate-loop's traversal \
23625                 input from the sync-cycle adjacency-list seed's \
23626                 traversal input from the cilium_network_policies \
23627                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
23628                 input from the `feira app graph` per-contract print \
23629                 traversal's input",
23630            );
23631        }
23632    }
23633
23634    #[test]
23635    fn validate_reads_through_lifted_contratos_accessor() {
23636        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
23637        // per-`:contratos` validate-loop's `for c in self.contratos()`
23638        // traversal (which must reach every entry in the same order the
23639        // accessor projects, so both the per-entry
23640        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
23641        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
23642        // dedup `HashSet` insert key off the accessor's projection),
23643        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
23644        // `for c in self.contratos()` adjacency-list seed (which drives
23645        // the sync-subgraph deadlock-detection gate via
23646        // [`AplicacaoError::SyncCycle`]), and the peer
23647        // [`caixa_mesh::cilium_network_policies`]'s
23648        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
23649        // grouping loop (which drives the per-CNP fan-out) must all
23650        // three key off the lifted accessor, so any future rebrand on
23651        // the typed slot's reader shape lands at exactly one place. Pins
23652        // the three-site coherence by exercising the two caixa-core
23653        // production consumers end-to-end: (1) the empty-`:contratos`
23654        // slice must validate without a per-edge diagnostic (the
23655        // per-edge loop is a no-op under the empty projection), (2) the
23656        // `ContratoMemberMissing` refusal fires on the second entry of a
23657        // two-edge cohort whose head references a valid member but tail
23658        // references a phantom name (which requires the loop to reach
23659        // the second entry through the accessor), and (3) the
23660        // `SyncCycle` refusal fires on a self-referential two-edge
23661        // cohort through the sync-cycle detector's peer projection
23662        // (which requires the detector to iterate the accessor's
23663        // projection to add the back-edge to its adjacency list).
23664        //
23665        // Peer of the sibling M3
23666        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23667        // three-consumer coherence pin on the per-`:membros` node-list
23668        // axis and the sibling M3
23669        // `validate_placement_reads_through_lifted_clusters_accessor`
23670        // (a6e18d7) coherence pin on the per-`:placement` distribution-
23671        // target-list axis — extends the slice-return-accessor multi-
23672        // consumer coherence discipline onto the outermost M3 mesh-slot
23673        // type's per-Aplicacao contract-list `Vec`-carry axis.
23674
23675        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
23676        // and no per-edge diagnostic surfaces. Validate succeeds on
23677        // the well-formed `:membros` head.
23678        let mut spec = three_member_spec();
23679        spec.contratos = Vec::new();
23680        assert!(
23681            spec.validate().is_ok(),
23682            "empty :contratos must validate — the per-edge loop is a \
23683             no-op under the accessor's empty projection",
23684        );
23685        assert!(
23686            spec.contratos().is_empty(),
23687            "the per-edge validate loop's traversal input must be the \
23688             empty slice per the accessor's projection",
23689        );
23690
23691        // (2) Per-edge validate loop: a two-edge cohort whose tail
23692        // references a phantom `:para` member must trip
23693        // `ContratoMemberMissing` on the tail — the loop must reach
23694        // the second entry through the accessor for the membership
23695        // lookup to fail on the phantom name.
23696        let mut spec = three_member_spec();
23697        spec.contratos = vec![
23698            contract_http("cart", "catalog", "/products/:id"),
23699            contract_http("cart", "phantom", "/x"),
23700        ];
23701        let err = spec.validate().unwrap_err();
23702        assert!(
23703            matches!(
23704                err,
23705                AplicacaoError::ContratoMemberMissing { ref caixa }
23706                    if caixa == "phantom"
23707            ),
23708            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
23709        );
23710        assert_eq!(
23711            spec.contratos().len(),
23712            2,
23713            "the per-edge validate loop's traversal input must be \
23714             a two-element slice per the accessor's projection",
23715        );
23716
23717        // (3) Sync-cycle detector: a two-edge synchronous cohort
23718        // whose second edge closes the sync-subgraph back onto the
23719        // first must trip [`AplicacaoError::ContratoCycle`] — the
23720        // detector must iterate the accessor's projection to add
23721        // both edges to its adjacency list, so a length-drift on
23722        // the accessor's projection would silently disagree with
23723        // the sync-cycle detector on which edge closes the loop.
23724        // Peer projection to the `validate` per-edge loop above:
23725        // the sync-cycle detector routes through the same lifted
23726        // accessor, so a rebrand of the reader shape lands at one
23727        // place. Uses a two-edge cohort (cart → catalog → cart)
23728        // because the per-edge `ContratoSelfLoop` gate fires before
23729        // the sync-cycle detector on a single self-referential edge
23730        // (`cart → cart`) — the cycle-detector's input must be a
23731        // multi-edge cohort for its per-edge traversal input to be
23732        // observably wider than the per-edge validate loop's input.
23733        let mut spec = three_member_spec();
23734        spec.contratos = vec![
23735            contract_http("cart", "catalog", "/products/:id"),
23736            contract_http("catalog", "cart", "/callback"),
23737        ];
23738        let err = spec.validate().unwrap_err();
23739        assert!(
23740            matches!(err, AplicacaoError::ContratoCycle { .. }),
23741            "expected ContratoCycle from the sync-cycle detector on a \
23742             two-edge back-edge cohort, got {err:?}",
23743        );
23744        assert_eq!(
23745            spec.contratos().len(),
23746            2,
23747            "the sync-cycle detector's traversal input must be a \
23748             two-element slice per the accessor's projection",
23749        );
23750    }
23751
23752    #[test]
23753    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
23754        // The canonical per-`:politicas` outer-composite-reference-shape
23755        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
23756        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
23757        // the same backing storage the raw `&self.politicas` field
23758        // access borrows from, byte-equal across every representative
23759        // fixture in the accept-set — the default `MeshPolicy` (the
23760        // author-empty "no policy on any axis" shape whose
23761        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
23762        // shapes carrying one axis at a time
23763        // (`{mtls_required, timeout, retries, circuit_breaker,
23764        // rate_limit}` — the minimal five-axis fan-out over the
23765        // per-axis lifted accessor family every downstream mesh-artifact
23766        // emitter dispatches on), and the multi-axis composite (the
23767        // canonical `three_member_spec` fixture's `{timeout, retries,
23768        // mtls_required}` triple — the load-bearing shape every
23769        // Aplicacao-scoped fixture in this suite constructs).
23770        //
23771        // Pins against a future silent detour that returned a fresh-
23772        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
23773        // impl but silently break every downstream caller that relied
23774        // on the reference sharing the composite's backing identity), a
23775        // reference to an operator-resolved overlay (the future
23776        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
23777        // acknowledges — its resolution must land at exactly this
23778        // accessor body, not silently divert the raw slot away from a
23779        // second consumer), or an axis-shuffled projection (a future
23780        // detour that swapped `timeout` and `retries` through the
23781        // accessor would silently split the paired `validate_politicas`
23782        // per-axis bracket-dispatch's traversal input from the peer
23783        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
23784        // emitter's fan-out input from the peer
23785        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
23786        // overlay emitter's fan-out input).
23787        //
23788        // Peer of the sibling M3
23789        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
23790        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
23791        // node-list `Vec`-carry axis and the sibling M3
23792        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
23793        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
23794        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
23795        // accessor byte-equal-projection discipline onto the outermost
23796        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
23797        // reference axis, the first `&Composite`-return accessor on the
23798        // outer [`AplicacaoSpec`] type.
23799        let fixtures: Vec<MeshPolicy> = vec![
23800            MeshPolicy::default(),
23801            MeshPolicy {
23802                mtls_required: Some(true),
23803                ..MeshPolicy::default()
23804            },
23805            MeshPolicy {
23806                mtls_required: Some(false),
23807                ..MeshPolicy::default()
23808            },
23809            MeshPolicy {
23810                timeout: Some(Duration::from_secs(30)),
23811                ..MeshPolicy::default()
23812            },
23813            MeshPolicy {
23814                retries: Some(3),
23815                ..MeshPolicy::default()
23816            },
23817            MeshPolicy {
23818                circuit_breaker: Some(CircuitBreaker {
23819                    max_failures: 5,
23820                    window: Duration::from_secs(30),
23821                }),
23822                ..MeshPolicy::default()
23823            },
23824            MeshPolicy {
23825                rate_limit: Some(RateLimit {
23826                    rate: 100,
23827                    window: Duration::from_secs(1),
23828                }),
23829                ..MeshPolicy::default()
23830            },
23831            MeshPolicy {
23832                timeout: Some(Duration::from_secs(30)),
23833                retries: Some(3),
23834                mtls_required: Some(true),
23835                ..MeshPolicy::default()
23836            },
23837        ];
23838        for politicas in fixtures {
23839            let s = AplicacaoSpec {
23840                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23841                contratos: Vec::new(),
23842                politicas: politicas.clone(),
23843                placement: Placement::default(),
23844                entrada: None,
23845            };
23846            assert_eq!(
23847                *s.politicas(),
23848                politicas,
23849                "AplicacaoSpec::politicas must return :politicas verbatim \
23850                 (got {:?}, expected {:?})",
23851                s.politicas(),
23852                politicas,
23853            );
23854            assert!(
23855                std::ptr::eq(s.politicas(), &s.politicas),
23856                "AplicacaoSpec::politicas accessor and &self.politicas \
23857                 field access must borrow the same backing storage — \
23858                 the accessor is the substrate-primitive typed dispatch \
23859                 every downstream mesh-policy composite consumer must \
23860                 route through, and a reference-identity split would \
23861                 silently break every consumer that relied on the \
23862                 borrow sharing the composite's storage",
23863            );
23864            assert_eq!(
23865                s.politicas().is_empty(),
23866                s.politicas.is_empty(),
23867                "AplicacaoSpec::politicas().is_empty() must byte-equal \
23868                 self.politicas.is_empty() — an emptiness-drift would \
23869                 silently split the paired `validate_politicas` \
23870                 per-axis bracket-dispatch's seed from the peer \
23871                 caixa-mesh CNP mTLS-overlay emitter's key from the \
23872                 peer caixa-mesh HTTPRoute timeout+retry overlay \
23873                 emitter's key",
23874            );
23875        }
23876    }
23877
23878    #[test]
23879    fn validate_politicas_reads_through_lifted_politicas_accessor() {
23880        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
23881        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
23882        // followed by the per-axis fan-out `p.timeout()` /
23883        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
23884        // the lifted axis-level accessor family) must key off the
23885        // lifted outer accessor, so any future rebrand on the typed
23886        // slot's outer-composite reader shape lands at exactly one
23887        // place. Pins the multi-axis coherence by exercising each
23888        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
23889        // a `Some(Duration::ZERO)` timeout under the outer accessor's
23890        // reference projection, (2) `PolicyRetriesZero` fires on a
23891        // `Some(0)` retries under the same projection, and (3) an
23892        // empty [`MeshPolicy::default`] passes `validate_politicas` —
23893        // the outer accessor's reference-projection reaches every
23894        // per-axis branch without silently short-circuiting any.
23895        //
23896        // Peer of the sibling M3
23897        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23898        // three-consumer coherence pin on the per-`:membros` node-list
23899        // axis and the sibling M3
23900        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
23901        // three-consumer coherence pin on the per-`:contratos`
23902        // edge-list axis — extends the multi-consumer coherence
23903        // discipline onto the outermost M3 mesh-slot type's per-
23904        // Aplicacao mesh-policy composite-reference axis, the first
23905        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
23906        // type.
23907
23908        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
23909        // reference projection: a `Some(Duration::ZERO)` timeout must
23910        // trip the zero-floor gate. The bracket-dispatch's first arm
23911        // reads `p.timeout()` on the reference returned by the outer
23912        // accessor.
23913        let mut spec = three_member_spec();
23914        spec.politicas.timeout = Some(Duration::ZERO);
23915        spec.politicas.retries = None;
23916        spec.politicas.circuit_breaker = None;
23917        spec.politicas.rate_limit = None;
23918        assert_eq!(
23919            spec.validate().unwrap_err(),
23920            AplicacaoError::PolicyTimeoutZero,
23921        );
23922        assert!(
23923            std::ptr::eq(spec.politicas(), &spec.politicas),
23924            "the `validate_politicas` per-axis bracket-dispatch's \
23925             traversal input must be the same backing composite the \
23926             accessor's reference projection borrows from",
23927        );
23928
23929        // (2) `PolicyRetriesZero` refusal under the outer accessor's
23930        // reference projection: a `Some(0)` retries must trip the
23931        // zero-floor gate. The bracket-dispatch's second arm reads
23932        // `p.retries()` on the reference returned by the outer accessor.
23933        let mut spec = three_member_spec();
23934        spec.politicas.timeout = None;
23935        spec.politicas.retries = Some(0);
23936        spec.politicas.circuit_breaker = None;
23937        spec.politicas.rate_limit = None;
23938        assert_eq!(
23939            spec.validate().unwrap_err(),
23940            AplicacaoError::PolicyRetriesZero,
23941        );
23942
23943        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
23944        // — every per-axis arm short-circuits on `None`, so the outer
23945        // accessor's reference projection reaches the fall-through
23946        // `Ok(())` without any per-axis refusal firing.
23947        let mut spec = three_member_spec();
23948        spec.politicas = MeshPolicy::default();
23949        assert!(
23950            spec.validate().is_ok(),
23951            "an empty `MeshPolicy` must pass `validate_politicas` — \
23952             every per-axis arm short-circuits on `None` under the \
23953             outer accessor's reference projection",
23954        );
23955        assert!(
23956            spec.politicas().is_empty(),
23957            "the outer accessor's reference projection must be the \
23958             empty composite per the `MeshPolicy::default()` fixture",
23959        );
23960    }
23961
23962    #[test]
23963    #[allow(clippy::too_many_lines)]
23964    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
23965        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
23966        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
23967        // must both key off the lifted axis-level accessors
23968        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
23969        // the peer `:circuit-breaker` / `:rate-limit` arms already
23970        // routing through [`MeshPolicy::circuit_breaker`] /
23971        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
23972        // per axis on the substrate primitive" shape at the fan-out
23973        // (four axes, four accessors, no raw-field-access site
23974        // anywhere on the bracket-dispatch). Pins the per-axis
23975        // coherence at the accept-set boundaries the bracket carves:
23976        //   1. accessor byte-equal to raw field on every representative
23977        //      accept-set value (`None`, sub-cap, at-cap, past-cap
23978        //      sentinel) — a future accessor drift that no longer
23979        //      shipped the raw slot verbatim would surface here,
23980        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
23981        //      routed through the accessor's projection, proving the
23982        //      first arm reads through the accessor rather than a
23983        //      silent-detour peer-axis field access,
23984        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
23985        //      through the accessor's projection, proving the second
23986        //      arm reads through the accessor,
23987        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
23988        //      passes validate under the accessor projection (paired
23989        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
23990        //      sibling axis), pinning the upper-boundary accept-arm
23991        //      also routes through the accessor.
23992        //
23993        // Peer of the sibling M3
23994        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
23995        // outer-composite-reference coherence pin (which asserts the
23996        // `let p = self.politicas()` seed); extends the discipline onto
23997        // the per-axis fan-out layer that consumes the seed's
23998        // reference. Same shape as
23999        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24000        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24001        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
24002        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
24003
24004        // (1) Accessor byte-equal to raw field on the `:timeout` axis
24005        // across the accept-set boundaries the bracket dispatch's
24006        // three-arm gate carves out
24007        // ([`crate::render::require_positive_canonical_bounded_duration`]
24008        // — zero-floor + canonical-form + upper-cap).
24009        for timeout in [
24010            None,
24011            Some(Duration::ZERO),
24012            Some(Duration::from_millis(1)),
24013            Some(POLICY_TIMEOUT_MAX),
24014        ] {
24015            let p = MeshPolicy {
24016                timeout,
24017                ..MeshPolicy::default()
24018            };
24019            assert_eq!(
24020                p.timeout(),
24021                p.timeout,
24022                "MeshPolicy::timeout accessor must byte-equal the raw \
24023                 .timeout field across every accept-set boundary the \
24024                 validate_politicas :timeout arm carves out — a drift \
24025                 here would silently split the validate bracket's arm \
24026                 from the peer caixa-mesh HTTPRoute timeout-overlay \
24027                 emitter's read",
24028            );
24029        }
24030
24031        // (2) Accessor byte-equal to raw field on the `:retries` axis
24032        // across the accept-set boundaries the bracket dispatch's
24033        // two-arm gate carves out
24034        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
24035        // + upper-cap).
24036        for retries in [
24037            None,
24038            Some(0u32),
24039            Some(1u32),
24040            Some(POLICY_RETRIES_MAX),
24041            Some(POLICY_RETRIES_MAX + 1),
24042            Some(u32::MAX),
24043        ] {
24044            let p = MeshPolicy {
24045                retries,
24046                ..MeshPolicy::default()
24047            };
24048            assert_eq!(
24049                p.retries(),
24050                p.retries,
24051                "MeshPolicy::retries accessor must byte-equal the raw \
24052                 .retries field across every accept-set boundary the \
24053                 validate_politicas :retries arm carves out — a drift \
24054                 here would silently split the validate bracket's arm \
24055                 from the peer caixa-mesh HTTPRoute retry-overlay \
24056                 emitter's read",
24057            );
24058        }
24059
24060        // (3) `PolicyTimeoutZero` fires on the accessor-projected
24061        // zero-floor boundary. A silent detour that no longer read
24062        // through `p.timeout()` (a peer-axis field read, an accidental
24063        // Option::and-then chain that collapsed the None arm to Some,
24064        // an accessor rebrand that clamped the return through the
24065        // upper cap) would fail to refuse here.
24066        let mut spec = three_member_spec();
24067        spec.politicas.timeout = Some(Duration::ZERO);
24068        spec.politicas.retries = None;
24069        spec.politicas.circuit_breaker = None;
24070        spec.politicas.rate_limit = None;
24071        assert_eq!(
24072            spec.politicas().timeout(),
24073            Some(Duration::ZERO),
24074            "the accessor projection must reflect the fixture's \
24075             `Some(Duration::ZERO)` :timeout verbatim",
24076        );
24077        assert_eq!(
24078            spec.validate().unwrap_err(),
24079            AplicacaoError::PolicyTimeoutZero,
24080            "the validate_politicas :timeout zero-floor arm must fire \
24081             through the lifted accessor's projection — a silent \
24082             detour to a peer-axis field would fail to refuse",
24083        );
24084
24085        // (4) `PolicyRetriesZero` fires on the accessor-projected
24086        // zero-floor boundary on the sibling `:retries` axis.
24087        let mut spec = three_member_spec();
24088        spec.politicas.timeout = None;
24089        spec.politicas.retries = Some(0);
24090        spec.politicas.circuit_breaker = None;
24091        spec.politicas.rate_limit = None;
24092        assert_eq!(
24093            spec.politicas().retries(),
24094            Some(0),
24095            "the accessor projection must reflect the fixture's \
24096             `Some(0)` :retries verbatim",
24097        );
24098        assert_eq!(
24099            spec.validate().unwrap_err(),
24100            AplicacaoError::PolicyRetriesZero,
24101            "the validate_politicas :retries zero-floor arm must fire \
24102             through the lifted accessor's projection — a silent \
24103             detour to a peer-axis field would fail to refuse",
24104        );
24105
24106        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
24107        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
24108        // must pass validate under the accessor projection — pins the
24109        // upper-boundary accept-arm also routes through the lifted
24110        // accessor (a drift that clamped or short-circuited at the
24111        // upper boundary would fail the whole-spec validate here).
24112        let mut spec = three_member_spec();
24113        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
24114        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
24115        spec.politicas.circuit_breaker = None;
24116        spec.politicas.rate_limit = None;
24117        assert_eq!(
24118            spec.politicas().timeout(),
24119            Some(POLICY_TIMEOUT_MAX),
24120            "the accessor projection must reflect the fixture's \
24121             at-cap :timeout verbatim",
24122        );
24123        assert_eq!(
24124            spec.politicas().retries(),
24125            Some(POLICY_RETRIES_MAX),
24126            "the accessor projection must reflect the fixture's \
24127             at-cap :retries verbatim",
24128        );
24129        assert!(
24130            spec.validate().is_ok(),
24131            "at-cap :timeout + :retries must pass validate under the \
24132             accessor projection — the upper-boundary accept-arm on \
24133             both axes routes through the lifted accessor",
24134        );
24135    }
24136
24137    #[test]
24138    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
24139        // The canonical per-`:placement` outer-composite-reference-shape
24140        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
24141        // typed `Placement` verbatim as a `&Placement` reference over the
24142        // same backing storage the raw `&self.placement` field access
24143        // borrows from, byte-equal across every representative fixture in
24144        // the accept-set — the default `Placement` (the substrate seed
24145        // shape whose [`PlacementStrategy::default`] evaluates to
24146        // `SingleNode` with an empty `:clusters` pool and both
24147        // optional-scalar axes `None`), and every canonical strategy /
24148        // cluster-pool / optional-scalar combination the
24149        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
24150        // three [`PlacementStrategy`] variants — `SingleNode`,
24151        // `Replicated`, `Sharded` — cross-projected with a non-empty
24152        // `:clusters` pool and, on the `Sharded` arm, a non-empty
24153        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
24154        // canonical `three_member_spec` `Replicated` fixture's
24155        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
24156        //
24157        // Pins against a future silent detour that returned a fresh-
24158        // cloned `Placement` copy (which would type-check via a `Clone`
24159        // impl but silently break every downstream caller that relied on
24160        // the reference sharing the composite's backing identity), a
24161        // reference to an operator-resolved overlay (the future per-
24162        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
24163        // acknowledges — its resolution must land at exactly this
24164        // accessor body, not silently divert the raw slot away from a
24165        // second consumer), or an axis-shuffled projection (a future
24166        // detour that swapped `clusters` and `affinity` through the
24167        // accessor would silently split the paired `validate_placement`
24168        // per-axis bracket-dispatch's traversal input from the peer
24169        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
24170        // programs.yaml distribution-annotation emitter's fan-out input
24171        // from the peer `feira app graph` per-Aplicacao print line's
24172        // input).
24173        //
24174        // Peer of the sibling M3
24175        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24176        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
24177        // outer mesh-policy composite-reference axis, and of the sibling
24178        // slice-return `aplicacao_spec_membros_returns_membros_slice_
24179        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
24180        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
24181        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
24182        // the outer-accessor byte-equal-projection discipline onto the
24183        // outermost M3 mesh-slot type's per-Aplicacao distribution
24184        // composite-reference axis, the second `&Composite`-return
24185        // accessor on the outer [`AplicacaoSpec`] type.
24186        let fixtures: Vec<Placement> = vec![
24187            Placement::default(),
24188            Placement {
24189                estrategia: PlacementStrategy::SingleNode,
24190                clusters: vec!["rio".into()],
24191                affinity: None,
24192                shard_key: None,
24193            },
24194            Placement {
24195                estrategia: PlacementStrategy::Replicated,
24196                clusters: vec!["rio".into(), "mar".into()],
24197                affinity: None,
24198                shard_key: None,
24199            },
24200            Placement {
24201                estrategia: PlacementStrategy::Replicated,
24202                clusters: vec!["rio".into(), "mar".into()],
24203                affinity: Some("data-locality".into()),
24204                shard_key: None,
24205            },
24206            Placement {
24207                estrategia: PlacementStrategy::Sharded,
24208                clusters: vec!["rio".into(), "mar".into()],
24209                affinity: None,
24210                shard_key: Some("tenantId".into()),
24211            },
24212            Placement {
24213                estrategia: PlacementStrategy::Sharded,
24214                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
24215                affinity: Some("low-latency".into()),
24216                shard_key: Some("metadata.tenantId".into()),
24217            },
24218        ];
24219        for placement in fixtures {
24220            let s = AplicacaoSpec {
24221                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24222                contratos: Vec::new(),
24223                politicas: MeshPolicy::default(),
24224                placement: placement.clone(),
24225                entrada: None,
24226            };
24227            assert_eq!(
24228                *s.placement(),
24229                placement,
24230                "AplicacaoSpec::placement must return :placement verbatim \
24231                 (got {:?}, expected {:?})",
24232                s.placement(),
24233                placement,
24234            );
24235            assert!(
24236                std::ptr::eq(s.placement(), &s.placement),
24237                "AplicacaoSpec::placement accessor and &self.placement \
24238                 field access must borrow the same backing storage — the \
24239                 accessor is the substrate-primitive typed dispatch every \
24240                 downstream distribution-composite consumer must route \
24241                 through, and a reference-identity split would silently \
24242                 break every consumer that relied on the borrow sharing \
24243                 the composite's storage",
24244            );
24245            assert_eq!(
24246                s.placement().estrategia(),
24247                s.placement.estrategia,
24248                "AplicacaoSpec::placement().estrategia() must byte-equal \
24249                 self.placement.estrategia — a strategy-drift would \
24250                 silently split the paired `validate_placement` \
24251                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
24252                 peer caixa-mesh programs.yaml `placement.estrategia` \
24253                 emitter's key from the peer `feira app graph` printer's \
24254                 strategy label",
24255            );
24256            assert_eq!(
24257                s.placement().clusters(),
24258                s.placement.clusters.as_slice(),
24259                "AplicacaoSpec::placement().clusters() must byte-equal \
24260                 self.placement.clusters — a cluster-pool drift would \
24261                 silently split the paired `validate_placement` \
24262                 pre-flight `.is_empty()` refusal probe's traversal from \
24263                 the peer caixa-mesh programs.yaml `placement.clusters` \
24264                 emitter's fan-out from the peer `feira app graph` \
24265                 printer's cluster list",
24266            );
24267        }
24268    }
24269
24270    #[test]
24271    fn validate_placement_reads_through_lifted_placement_accessor() {
24272        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
24273        // per-axis bracket-dispatch seed (`let p = self.placement();`,
24274        // followed by the per-axis fan-out `p.clusters()` /
24275        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
24276        // lifted axis-level accessor family) must key off the lifted
24277        // outer accessor, so any future rebrand on the typed slot's
24278        // outer-composite reader shape lands at exactly one place. Pins
24279        // the multi-axis coherence by exercising each per-axis refusal
24280        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
24281        // `:clusters` pool under the outer accessor's reference
24282        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
24283        // strategy with a `None` `:shard-key` under the same projection,
24284        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
24285        // with a `Some` `:shard-key` under the same projection, and
24286        // (4) the canonical `three_member_spec` `Replicated` fixture
24287        // passes `validate_placement` under the outer accessor's
24288        // reference projection — the accessor's reference-projection
24289        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
24290        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
24291        // without silently short-circuiting any.
24292        //
24293        // Peer of the sibling M3
24294        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24295        // (534dc21) multi-axis coherence pin on the per-`:politicas`
24296        // outer mesh-policy composite-reference axis — extends the
24297        // multi-consumer coherence discipline onto the outermost M3
24298        // mesh-slot type's per-Aplicacao distribution composite-
24299        // reference axis, the second `&Composite`-return accessor on
24300        // the outer [`AplicacaoSpec`] type.
24301
24302        // (1) `PlacementWithoutClusters` refusal under the outer
24303        // accessor's reference projection: an empty `:clusters` pool
24304        // must trip the pre-flight refusal probe. The bracket-dispatch's
24305        // first arm reads `p.clusters()` on the reference returned by
24306        // the outer accessor.
24307        let mut spec = three_member_spec();
24308        spec.placement.clusters = Vec::new();
24309        assert_eq!(
24310            spec.validate().unwrap_err(),
24311            AplicacaoError::PlacementWithoutClusters {
24312                estrategia: PlacementStrategy::Replicated,
24313            },
24314        );
24315        assert!(
24316            std::ptr::eq(spec.placement(), &spec.placement),
24317            "the `validate_placement` per-axis bracket-dispatch's \
24318             traversal input must be the same backing composite the \
24319             accessor's reference projection borrows from",
24320        );
24321
24322        // (2) `ShardedWithoutKey` refusal under the outer accessor's
24323        // reference projection: a `Sharded` strategy with a `None`
24324        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
24325        // The bracket-dispatch's third arm reads `p.estrategia()` for
24326        // the match scrutinee then `p.shard_key()` for the cascade
24327        // scrutinee, both on the reference returned by the outer
24328        // accessor.
24329        let mut spec = three_member_spec();
24330        spec.placement.estrategia = PlacementStrategy::Sharded;
24331        spec.placement.shard_key = None;
24332        assert_eq!(
24333            spec.validate().unwrap_err(),
24334            AplicacaoError::ShardedWithoutKey,
24335        );
24336
24337        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
24338        // reference projection: a non-`Sharded` strategy with a `Some`
24339        // `:shard-key` must trip the declared-but-inert refusal. The
24340        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
24341        // + `p.estrategia()` for the diagnostic on the reference
24342        // returned by the outer accessor.
24343        let mut spec = three_member_spec();
24344        spec.placement.estrategia = PlacementStrategy::Replicated;
24345        spec.placement.shard_key = Some("tenantId".into());
24346        assert_eq!(
24347            spec.validate().unwrap_err(),
24348            AplicacaoError::ShardKeyOnNonSharded {
24349                estrategia: PlacementStrategy::Replicated,
24350                shard_key: "tenantId".into(),
24351            },
24352        );
24353
24354        // (4) Canonical `three_member_spec` `Replicated` fixture passes
24355        // `validate_placement` — every per-axis arm reaches the fall-
24356        // through `Ok(())` without any per-axis refusal firing under the
24357        // outer accessor's reference projection.
24358        let spec = three_member_spec();
24359        assert!(
24360            spec.validate().is_ok(),
24361            "the canonical Replicated placement fixture must pass \
24362             `validate_placement` — every per-axis arm short-circuits on \
24363             valid input under the outer accessor's reference projection",
24364        );
24365        assert_eq!(
24366            spec.placement().estrategia(),
24367            PlacementStrategy::Replicated,
24368            "the outer accessor's reference projection must be the \
24369             canonical Replicated fixture's strategy",
24370        );
24371        assert_eq!(
24372            spec.placement().clusters(),
24373            &["rio", "mar"],
24374            "the outer accessor's reference projection must be the \
24375             canonical Replicated fixture's cluster pool",
24376        );
24377    }
24378
24379    #[test]
24380    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
24381        // The canonical per-`:entrada` outer-composite-optional-
24382        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
24383        // the `:entrada` typed `Option<Entrada>` verbatim as an
24384        // `Option<&Entrada>` reference over the same backing storage
24385        // the raw `self.entrada.as_ref()` field access borrows from,
24386        // byte-equal across every representative fixture in the
24387        // accept-set — the author-omitted `None` shape (the
24388        // "internal-only mesh" partition every downstream external-
24389        // gateway emitter treats as "emit nothing"), the minimal
24390        // singleton `:entrada` composite (host + destination + empty
24391        // paths + default port), the paths-carrying composite (the
24392        // canonical `three_member_spec` fixture's ["/api" "/health"]
24393        // path-list shape every HTTPRoute per-rule fan-out emitter
24394        // reads), and the non-default port composite (the canonical
24395        // custom-port shape the port-fallback resolver reads).
24396        //
24397        // Pins against a future silent detour that returned a fresh-
24398        // cloned `Entrada` copy (which would type-check via a `Clone`
24399        // impl but silently break every downstream caller that
24400        // relied on the reference sharing the composite's backing
24401        // identity), a reference to an operator-resolved overlay
24402        // (the future per-cluster `:entrada-overrides` slot the
24403        // MESH-COMPOSITION §V federation roadmap acknowledges — its
24404        // resolution must land at exactly this accessor body, not
24405        // silently divert the raw slot away from a second consumer),
24406        // a `None` → `Some(Entrada::default)` cluster-default
24407        // projection (which would collapse the load-bearing
24408        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
24409        // the peer `gateway_routes` early-return + `feira app graph`
24410        // internal-only-mesh partition both read), or an axis-
24411        // shuffled projection (a future detour that swapped
24412        // `host` and `para` through the accessor would silently
24413        // split the paired `validate` per-`:entrada` shape-and-
24414        // membership gate's traversal input from the peer
24415        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
24416        // fan-out input from the peer `feira app graph` external-
24417        // gateway summary line).
24418        //
24419        // Peer of the sibling M3
24420        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24421        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
24422        // `:politicas` outer mesh-policy composite-reference axis
24423        // and of the sibling M3
24424        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
24425        // (9abb8f0) `&Placement` byte-equal pin on the per-
24426        // `:placement` outer distribution-composite composite-
24427        // reference axis — extends the outer-accessor byte-equal-
24428        // projection discipline onto the last unlifted outermost M3
24429        // mesh-slot type's per-Aplicacao external-gateway composite-
24430        // reference axis, the third and final `&Composite`-return
24431        // accessor on the outer [`AplicacaoSpec`] type.
24432        let fixtures: Vec<Option<Entrada>> = vec![
24433            None,
24434            Some(Entrada {
24435                host: "checkout.quero.cloud".into(),
24436                para: "cart".into(),
24437                paths: Vec::new(),
24438                port: DEFAULT_SERVICO_PORT,
24439            }),
24440            Some(Entrada {
24441                host: "checkout.quero.cloud".into(),
24442                para: "cart".into(),
24443                paths: vec!["/api".into(), "/health".into()],
24444                port: DEFAULT_SERVICO_PORT,
24445            }),
24446            Some(Entrada {
24447                host: "checkout.quero.cloud".into(),
24448                para: "cart".into(),
24449                paths: vec!["/api".into()],
24450                port: 9443,
24451            }),
24452        ];
24453        for entrada in fixtures {
24454            let s = AplicacaoSpec {
24455                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24456                contratos: Vec::new(),
24457                politicas: MeshPolicy::default(),
24458                placement: Placement::default(),
24459                entrada: entrada.clone(),
24460            };
24461            assert_eq!(
24462                s.entrada(),
24463                entrada.as_ref(),
24464                "AplicacaoSpec::entrada must return :entrada verbatim \
24465                 (got {:?}, expected {:?})",
24466                s.entrada(),
24467                entrada.as_ref(),
24468            );
24469            match (s.entrada(), s.entrada.as_ref()) {
24470                (Some(a), Some(b)) => assert!(
24471                    std::ptr::eq(a, b),
24472                    "AplicacaoSpec::entrada accessor and \
24473                     self.entrada.as_ref() field access must borrow \
24474                     the same backing storage — the accessor is the \
24475                     substrate-primitive typed dispatch every \
24476                     downstream external-gateway composite consumer \
24477                     must route through, and a reference-identity \
24478                     split would silently break every consumer that \
24479                     relied on the borrow sharing the composite's \
24480                     storage",
24481                ),
24482                (None, None) => {}
24483                _ => panic!(
24484                    "AplicacaoSpec::entrada presence bit must byte-\
24485                     equal self.entrada.is_some() — a presence-bit \
24486                     drift would silently split the paired `validate` \
24487                     per-`:entrada` shape-and-membership gate's \
24488                     traversal head from the peer \
24489                     caixa-mesh gateway_routes early-return partition \
24490                     from the peer `feira app graph` internal-only-\
24491                     mesh partition",
24492                ),
24493            }
24494            assert_eq!(
24495                s.entrada().is_some(),
24496                s.entrada.is_some(),
24497                "AplicacaoSpec::entrada().is_some() must byte-equal \
24498                 self.entrada.is_some() — a presence-bit drift would \
24499                 silently split every downstream `Option<&Entrada>` \
24500                 consumer's partition on the internal-only-mesh arm",
24501            );
24502        }
24503    }
24504
24505    #[test]
24506    fn validate_reads_through_lifted_entrada_accessor() {
24507        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
24508        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
24509        // self.entrada() { … }`, followed by the per-axis fan-out
24510        // `validate_entrada_para(&e.para)` /
24511        // `EntradaMemberMissing` membership lookup /
24512        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
24513        // per-`e.paths` `validate_entrada_path` traversal) must key
24514        // off the lifted outer accessor, so any future rebrand on
24515        // the typed slot's outer-composite reader shape lands at
24516        // exactly one place. Pins the multi-axis coherence by
24517        // exercising each per-axis refusal end-to-end: (1) the
24518        // author-omitted `None` shape short-circuits past every
24519        // per-`:entrada` refusal (the internal-only mesh partition
24520        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
24521        // fires on a well-shaped but phantom `:para` under the outer
24522        // accessor's reference projection, and (3) the canonical
24523        // `three_member_spec` `:entrada` fixture passes `validate`
24524        // under the outer accessor's reference projection.
24525        //
24526        // Peer of the sibling M3
24527        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24528        // (534dc21) multi-axis coherence pin on the per-`:politicas`
24529        // outer mesh-policy composite-reference axis and the sibling
24530        // M3
24531        // [`validate_placement_reads_through_lifted_placement_accessor`]
24532        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
24533        // outer distribution-composite composite-reference axis —
24534        // extends the multi-consumer coherence discipline onto the
24535        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
24536        // external-gateway composite-reference axis, the third and
24537        // final `&Composite`-return accessor on the outer
24538        // [`AplicacaoSpec`] type.
24539
24540        // (1) `None` :entrada — the internal-only-mesh partition
24541        // short-circuits past every per-`:entrada` refusal. The outer
24542        // accessor's reference projection reaches the fall-through
24543        // `Ok(())` on the `None` arm without any per-axis refusal
24544        // firing.
24545        let mut spec = three_member_spec();
24546        spec.entrada = None;
24547        assert!(
24548            spec.validate().is_ok(),
24549            "an author-omitted `:entrada` must pass `validate` — the \
24550             internal-only-mesh partition short-circuits past every \
24551             per-`:entrada` refusal under the outer accessor's \
24552             reference projection",
24553        );
24554        assert!(
24555            spec.entrada().is_none(),
24556            "the outer accessor's reference projection must name the \
24557             internal-only-mesh partition per the `None` fixture",
24558        );
24559
24560        // (2) `EntradaMemberMissing` refusal under the outer accessor's
24561        // reference projection: a well-shaped but phantom `:para` must
24562        // trip the membership-lookup refusal. The gate's second arm
24563        // reads `e.para` on the reference returned by the outer
24564        // accessor.
24565        let mut spec = three_member_spec();
24566        if let Some(e) = spec.entrada.as_mut() {
24567            e.para = "phantom".into();
24568        }
24569        assert_eq!(
24570            spec.validate().unwrap_err(),
24571            AplicacaoError::EntradaMemberMissing {
24572                para: "phantom".into(),
24573            },
24574        );
24575        match (spec.entrada(), spec.entrada.as_ref()) {
24576            (Some(a), Some(b)) => assert!(
24577                std::ptr::eq(a, b),
24578                "the `validate` per-`:entrada` gate's traversal head \
24579                 must be the same backing composite the accessor's \
24580                 reference projection borrows from",
24581            ),
24582            _ => panic!("fixture must carry Some(:entrada)"),
24583        }
24584
24585        // (3) Canonical `three_member_spec` `:entrada` fixture passes
24586        // `validate` — every per-axis arm reaches the fall-through
24587        // `Ok(())` without any per-axis refusal firing under the
24588        // outer accessor's reference projection.
24589        let spec = three_member_spec();
24590        assert!(
24591            spec.validate().is_ok(),
24592            "the canonical `:entrada` fixture must pass `validate` — \
24593             every per-axis arm short-circuits on valid input under \
24594             the outer accessor's reference projection",
24595        );
24596        assert!(
24597            spec.entrada().is_some(),
24598            "the outer accessor's reference projection must be the \
24599             canonical `:entrada` fixture's composite",
24600        );
24601    }
24602
24603    #[test]
24604    fn port_for_destination_reads_through_lifted_entrada_accessor() {
24605        // Peer coherence pin: the
24606        // [`AplicacaoSpec::port_for_destination`] per-destination
24607        // L4-port fallback resolver's composite-projection seed
24608        // (`self.entrada().filter(…).map_or(…)`) must key off the
24609        // lifted outer accessor. Pins the coherence by exercising
24610        // the resolver end-to-end: (1) the `None` `:entrada` shape
24611        // falls through to `DEFAULT_SERVICO_PORT` under the outer
24612        // accessor's reference projection, (2) a non-matching
24613        // destination falls through to `DEFAULT_SERVICO_PORT` under
24614        // the outer accessor's reference projection, and (3) the
24615        // matching destination resolves to the `:entrada :port`
24616        // value under the outer accessor's reference projection.
24617        //
24618        // Peer of the sibling
24619        // [`validate_reads_through_lifted_entrada_accessor`] multi-
24620        // consumer coherence pin on the same per-`:entrada` outer-
24621        // composite axis — extends the multi-consumer coherence
24622        // discipline onto the second per-`:entrada` production
24623        // consumer, the L4-port fallback resolver.
24624
24625        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
24626        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
24627        // arm under the outer accessor's reference projection.
24628        let mut spec = three_member_spec();
24629        spec.entrada = None;
24630        assert_eq!(
24631            spec.port_for_destination("cart"),
24632            DEFAULT_SERVICO_PORT,
24633            "the port-fallback resolver must fall through to \
24634             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
24635             under the outer accessor's reference projection",
24636        );
24637
24638        // (2) Non-matching destination — the resolver's `filter(…)`
24639        // arm rejects a mismatched destination and falls through
24640        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
24641        // reference projection.
24642        let mut spec = three_member_spec();
24643        if let Some(e) = spec.entrada.as_mut() {
24644            e.para = "cart".into();
24645            e.port = 9443;
24646        }
24647        assert_eq!(
24648            spec.port_for_destination("catalog"),
24649            DEFAULT_SERVICO_PORT,
24650            "the port-fallback resolver must fall through to \
24651             DEFAULT_SERVICO_PORT on a non-matching destination \
24652             under the outer accessor's reference projection",
24653        );
24654
24655        // (3) Matching destination — the resolver's `map_or(…)` arm
24656        // returns the `:entrada :port` value under the outer
24657        // accessor's reference projection.
24658        let mut spec = three_member_spec();
24659        if let Some(e) = spec.entrada.as_mut() {
24660            e.para = "cart".into();
24661            e.port = 9443;
24662        }
24663        assert_eq!(
24664            spec.port_for_destination("cart"),
24665            9443,
24666            "the port-fallback resolver must return the \
24667             `:entrada :port` value on a matching destination \
24668             under the outer accessor's reference projection",
24669        );
24670    }
24671
24672    #[test]
24673    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
24674        // The canonical per-`:politicas` `:mtls-required` mTLS-
24675        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
24676        // must return the `:politicas :mtls-required` typed bool
24677        // verbatim as an `Option<bool>`, byte-equal to the raw field
24678        // access across every value in the three-way accept-set —
24679        // `None` (cluster default applies), `Some(true)` (mTLS
24680        // handshake enforced — the sandboxing-by-default arm the
24681        // MeshPolicy's docstring names), `Some(false)` (handshake
24682        // skipped — the explicit debug-edge opt-out).
24683        //
24684        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
24685        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
24686        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
24687        // shape — first `Option<Copy-T>`-return accessor on the M3
24688        // mesh-slot family. Pins against a future silent detour that
24689        // re-derived the toggle from a peer axis (an accidental
24690        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
24691        // whenever a breaker is set), a `None` → `Some(false)` cluster-
24692        // default projection (the canonical `Option<bool>` → `bool`
24693        // collapse footgun the surrounding `is_empty()` predicate
24694        // guards on the peer emptiness axis), or a `Some(true)` /
24695        // `Some(false)` variant swap that landed on one consumer
24696        // without the other.
24697        for required in [None, Some(true), Some(false)] {
24698            let p = MeshPolicy {
24699                mtls_required: required,
24700                ..MeshPolicy::default()
24701            };
24702            assert_eq!(
24703                p.mtls_required(),
24704                required,
24705                "MeshPolicy::mtls_required must return :politicas \
24706                 :mtls-required verbatim (got {:?}, expected {required:?})",
24707                p.mtls_required(),
24708            );
24709            assert_eq!(
24710                p.mtls_required(),
24711                p.mtls_required,
24712                "MeshPolicy::mtls_required must byte-equal the raw \
24713                 .mtls_required field access across every value in the \
24714                 three-way accept-set",
24715            );
24716        }
24717    }
24718
24719    #[test]
24720    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
24721        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
24722        // arm must key off [`MeshPolicy::mtls_required`], not the raw
24723        // `.mtls_required` field access. Structurally: toggling ONLY
24724        // the `mtls_required` slot on an otherwise-default MeshPolicy
24725        // must flip `is_empty()` from `true` (all-`None`) to `false`
24726        // (one axis carries a value); the flip must be observed for
24727        // both `Some(true)` and `Some(false)` since the emptiness
24728        // semantic reads "any axis carries a value" — not "any axis
24729        // carries a truthy value" — the same non-collapsing shape the
24730        // sibling M2 [`crate::LimitsSpec::is_empty`] /
24731        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
24732        // peer `Option<T>`-typed slot surfaces.
24733        //
24734        // Pins against a future silent detour that re-derived the
24735        // emptiness predicate off a peer axis (an accidental
24736        // `.rate_limit.is_none()`-only chain that dropped the
24737        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
24738        // collapse to a truthy-only check (which would silently
24739        // classify `Some(false)` as empty), or an accessor-side
24740        // detour that no longer names the substrate-primitive typed
24741        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
24742        // == false` fallback in the accessor that would silently
24743        // classify both `None` and `Some(false)` as the same value).
24744        //
24745        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
24746        // (7cd2a28) accessor-composition pin on the sibling optional-
24747        // scalar axis — same "the emptiness / shape-gate predicate
24748        // must route through the substrate-primitive typed dispatch"
24749        // discipline extended onto the peer per-`:politicas` emptiness
24750        // predicate.
24751        let empty = MeshPolicy::default();
24752        assert!(
24753            empty.is_empty(),
24754            "MeshPolicy::default() must be is_empty() — every axis \
24755             defaults to None",
24756        );
24757        for required in [Some(true), Some(false)] {
24758            let p = MeshPolicy {
24759                mtls_required: required,
24760                ..MeshPolicy::default()
24761            };
24762            assert!(
24763                !p.is_empty(),
24764                "MeshPolicy::is_empty must return false when \
24765                 :mtls-required is {required:?} — the emptiness \
24766                 predicate reads \"any axis carries a value\", not \
24767                 \"any axis carries a truthy value\"",
24768            );
24769            assert_eq!(
24770                p.mtls_required().is_none(),
24771                p.is_empty(),
24772                "when :mtls-required is the only set axis, \
24773                 is_empty() must equal mtls_required().is_none() — \
24774                 the accessor and the emptiness predicate must \
24775                 route through the same substrate-primitive typed \
24776                 dispatch on the :mtls-required arm",
24777            );
24778        }
24779    }
24780
24781    #[test]
24782    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
24783        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
24784        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
24785        // accessor must return by value, not by reference. Peer of the
24786        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
24787        // borrow-invariant pin on the sibling `Option<String>` slot,
24788        // but extended onto the peer `Option<bool>` copy-invariant
24789        // shape — the accessor's returned `Option<bool>` must outlive
24790        // `&self` (multiple calls must return equal values from a
24791        // dropped-`&self` copy, since the returned Option carries no
24792        // borrow), and calling the accessor twice on the same
24793        // MeshPolicy must yield the same `Option<bool>` verbatim
24794        // (idempotent, no side effects on `&self`).
24795        //
24796        // Pins against a future silent detour that returned
24797        // `Option<&bool>` (which would type-check but silently break
24798        // every downstream caller — [`single_field_overlay`]'s first
24799        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
24800        // detached copy at the call site), an accidental
24801        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
24802        // would also type-check but return `Option<&bool>`), or a
24803        // one-arm-only accessor that reads `Some(*b)` in the Some arm
24804        // but reads a fresh Default::default() in the None arm.
24805        for required in [None, Some(true), Some(false)] {
24806            let p = MeshPolicy {
24807                mtls_required: required,
24808                ..MeshPolicy::default()
24809            };
24810            let first = p.mtls_required();
24811            let second = p.mtls_required();
24812            assert_eq!(
24813                first, second,
24814                "MeshPolicy::mtls_required must be idempotent — two \
24815                 successive calls on the same &self must return the \
24816                 same Option<bool>",
24817            );
24818            assert_eq!(
24819                first, required,
24820                "MeshPolicy::mtls_required must return :politicas \
24821                 :mtls-required verbatim by copy — got {first:?}, \
24822                 expected {required:?}",
24823            );
24824        }
24825    }
24826
24827    #[test]
24828    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
24829        // The canonical per-`:politicas` `:retries` transient-failure-
24830        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
24831        // the `:politicas :retries` typed `u32` verbatim as an
24832        // `Option<u32>`, byte-equal to the raw field access across every
24833        // representative value in the accept-set — `None` (cluster
24834        // default applies — typically "no retries beyond a single
24835        // dispatch attempt" the caixa-mesh `retry_overlay` builder
24836        // documents), `Some(1)` (the lower boundary of the
24837        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
24838        // `AplicacaoSpec::validate_politicas` gate carves out on the
24839        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
24840        // (the upper boundary the same gate carves out on the sibling
24841        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
24842        // past-the-guard sentinel that pins the accessor doesn't perform
24843        // a silent bounds-collapse at the return path).
24844        //
24845        // Sibling of the peer per-`:politicas`
24846        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
24847        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
24848        // peer per-`:politicas` `Option<u32>` shape — second
24849        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
24850        // Pins against a future silent detour that re-derived the retry
24851        // cap from a peer axis (an accidental `.circuit_breaker
24852        // .as_ref().map(|b| b.max_failures)` collapse that read the
24853        // breaker's max-failure count as a retry budget), a
24854        // `None → Some(0)` cluster-default projection (which would
24855        // silently re-introduce the `PolicyRetriesZero` refusal case at
24856        // the emit boundary), or a bounds-collapsing accessor that
24857        // clamped the return through `POLICY_RETRIES_MAX` (the
24858        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
24859        // must ship the raw slot verbatim so a validate-time gate
24860        // regression surfaces at the emit boundary rather than being
24861        // silently absorbed).
24862        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
24863            let p = MeshPolicy {
24864                retries,
24865                ..MeshPolicy::default()
24866            };
24867            assert_eq!(
24868                p.retries(),
24869                retries,
24870                "MeshPolicy::retries must return :politicas :retries \
24871                 verbatim (got {:?}, expected {retries:?})",
24872                p.retries(),
24873            );
24874            assert_eq!(
24875                p.retries(),
24876                p.retries,
24877                "MeshPolicy::retries must byte-equal the raw .retries \
24878                 field access across every value in the accept-set",
24879            );
24880        }
24881    }
24882
24883    #[test]
24884    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
24885        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
24886        // must key off [`MeshPolicy::retries`], not the raw `.retries`
24887        // field access. Structurally: toggling ONLY the `retries` slot
24888        // on an otherwise-default MeshPolicy must flip `is_empty()`
24889        // from `true` (all-`None`) to `false` (one axis carries a
24890        // value); the flip must be observed for every value in the
24891        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
24892        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
24893        // the emptiness semantic reads "any axis carries a value" —
24894        // not "any axis carries a value the validate gate accepts" —
24895        // the same non-collapsing shape the peer M2
24896        // [`crate::LimitsSpec::is_empty`] /
24897        // [`crate::BehaviorSpec::is_empty`] predicates carry.
24898        //
24899        // Pins against a future silent detour that re-derived the
24900        // emptiness predicate off a peer axis (an accidental
24901        // `.rate_limit.is_none()`-only chain that dropped the
24902        // `retries` arm entirely), a `retries == Some(_)` collapse
24903        // that key-off a validate-gate-clamped bounds check (which
24904        // would silently classify a past-the-guard `Some(u32::MAX)`
24905        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
24906        // check), or an accessor-side detour that no longer names the
24907        // substrate-primitive typed dispatch.
24908        //
24909        // Sibling of the peer per-`:politicas`
24910        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
24911        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
24912        // same "the emptiness predicate must route through the
24913        // substrate-primitive typed dispatch" discipline extended onto
24914        // the peer per-`:politicas` `Option<u32>` axis.
24915        let empty = MeshPolicy::default();
24916        assert!(
24917            empty.is_empty(),
24918            "MeshPolicy::default() must be is_empty() — every axis \
24919             defaults to None",
24920        );
24921        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
24922            let p = MeshPolicy {
24923                retries,
24924                ..MeshPolicy::default()
24925            };
24926            assert!(
24927                !p.is_empty(),
24928                "MeshPolicy::is_empty must return false when \
24929                 :retries is {retries:?} — the emptiness \
24930                 predicate reads \"any axis carries a value\", not \
24931                 \"any axis carries a value the validate gate \
24932                 accepts\"",
24933            );
24934            assert_eq!(
24935                p.retries().is_none(),
24936                p.is_empty(),
24937                "when :retries is the only set axis, is_empty() \
24938                 must equal retries().is_none() — the accessor and \
24939                 the emptiness predicate must route through the same \
24940                 substrate-primitive typed dispatch on the :retries \
24941                 arm",
24942            );
24943        }
24944    }
24945
24946    #[test]
24947    fn mesh_policy_retries_projects_option_u32_by_copy() {
24948        // The by-copy pin: [`MeshPolicy::retries`] returns
24949        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
24950        // accessor must return by value, not by reference. Sibling of
24951        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
24952        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
24953        // extended onto the sibling `Option<u32>` copy-invariant
24954        // shape — the accessor's returned `Option<u32>` must outlive
24955        // `&self` (multiple calls must return equal values from a
24956        // dropped-`&self` copy, since the returned Option carries no
24957        // borrow), and calling the accessor twice on the same
24958        // MeshPolicy must yield the same `Option<u32>` verbatim
24959        // (idempotent, no side effects on `&self`).
24960        //
24961        // Pins against a future silent detour that returned
24962        // `Option<&u32>` (which would type-check but silently break
24963        // every downstream caller — [`crate::render::single_field_overlay`]'s
24964        // first parameter is `Option<T: Clone>`, and `&u32` would
24965        // fold to a detached copy at the call site), an accidental
24966        // `Option::as_ref()` projection (`self.retries.as_ref()` would
24967        // also type-check but return `Option<&u32>`), or a one-arm-
24968        // only accessor that reads `Some(*n)` in the Some arm but
24969        // reads a fresh `Default::default()` (`0_u32`) in the None
24970        // arm.
24971        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
24972            let p = MeshPolicy {
24973                retries,
24974                ..MeshPolicy::default()
24975            };
24976            let first = p.retries();
24977            let second = p.retries();
24978            assert_eq!(
24979                first, second,
24980                "MeshPolicy::retries must be idempotent — two \
24981                 successive calls on the same &self must return the \
24982                 same Option<u32>",
24983            );
24984            assert_eq!(
24985                first, retries,
24986                "MeshPolicy::retries must return :politicas :retries \
24987                 verbatim by copy — got {first:?}, expected {retries:?}",
24988            );
24989        }
24990    }
24991
24992    #[test]
24993    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
24994        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
24995        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
24996        // return the `:politicas :timeout` typed [`Duration`] verbatim
24997        // as an `Option<Duration>`, byte-equal to the raw field access
24998        // across every representative value in the accept-set — `None`
24999        // (cluster default applies — typically the gateway class's
25000        // implementation-side per-request wall-clock cap the caixa-mesh
25001        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
25002        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
25003        // set the surrounding `AplicacaoSpec::validate_politicas` gate
25004        // carves out on the sibling `PolicyTimeoutZero` /
25005        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
25006        // (the upper boundary the same gate carves out on the sibling
25007        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
25008        // (a past-the-guard sentinel that pins the accessor doesn't
25009        // perform a silent bounds-collapse into `None` on the zero-
25010        // Duration arm — validate rejects zero but the accessor must
25011        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
25012        // past-the-guard sentinel that pins the accessor doesn't
25013        // perform a silent bounds-collapse at the return path).
25014        //
25015        // Sibling of the peer per-`:politicas`
25016        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
25017        // `Option<u32>` optional-scalar axis and the peer per-
25018        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
25019        // pin on the sibling `Option<bool>` optional-scalar axis,
25020        // extended onto the peer per-`:politicas` `Option<Duration>`
25021        // shape — third `Option<Copy-T>`-return accessor on the M3
25022        // mesh-slot family. Pins against a future silent detour that
25023        // re-derived the per-call cap from a peer axis (an accidental
25024        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
25025        // read the breaker's rolling-window duration as a per-call
25026        // deadline), a `None → Some(Duration::MAX)` cluster-default
25027        // projection (which would silently re-introduce the
25028        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
25029        // blocking" arm at the emit boundary), or a bounds-collapsing
25030        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
25031        // (the `AplicacaoSpec::validate` gate owns the bounds; the
25032        // accessor must ship the raw slot verbatim so a validate-time
25033        // gate regression surfaces at the emit boundary rather than
25034        // being silently absorbed).
25035        for timeout in [
25036            None,
25037            Some(Duration::from_millis(1)),
25038            Some(POLICY_TIMEOUT_MAX),
25039            Some(Duration::ZERO),
25040            Some(Duration::MAX),
25041        ] {
25042            let p = MeshPolicy {
25043                timeout,
25044                ..MeshPolicy::default()
25045            };
25046            assert_eq!(
25047                p.timeout(),
25048                timeout,
25049                "MeshPolicy::timeout must return :politicas :timeout \
25050                 verbatim (got {:?}, expected {timeout:?})",
25051                p.timeout(),
25052            );
25053            assert_eq!(
25054                p.timeout(),
25055                p.timeout,
25056                "MeshPolicy::timeout must byte-equal the raw .timeout \
25057                 field access across every value in the accept-set",
25058            );
25059        }
25060    }
25061
25062    #[test]
25063    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
25064        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
25065        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
25066        // field access. Structurally: toggling ONLY the `timeout` slot
25067        // on an otherwise-default MeshPolicy must flip `is_empty()`
25068        // from `true` (all-`None`) to `false` (one axis carries a
25069        // value); the flip must be observed for every value in the
25070        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25071        // gate accepts (`Some(Duration::from_millis(1))`,
25072        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
25073        // reads "any axis carries a value" — not "any axis carries a
25074        // value the validate gate accepts" — the same non-collapsing
25075        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
25076        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25077        //
25078        // Pins against a future silent detour that re-derived the
25079        // emptiness predicate off a peer axis (an accidental
25080        // `.rate_limit.is_none()`-only chain that dropped the
25081        // `timeout` arm entirely), a `timeout == Some(_)` collapse
25082        // that key-off a validate-gate-clamped bounds check (which
25083        // would silently classify a past-the-guard `Some(Duration::MAX)`
25084        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
25085        // check), or an accessor-side detour that no longer names the
25086        // substrate-primitive typed dispatch.
25087        //
25088        // Sibling of the peer per-`:politicas`
25089        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
25090        // the sibling `Option<u32>` optional-scalar axis and the peer
25091        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25092        // accessor-composition pin on the sibling `Option<bool>`
25093        // optional-scalar axis — same "the emptiness predicate must
25094        // route through the substrate-primitive typed dispatch"
25095        // discipline extended onto the peer per-`:politicas`
25096        // `Option<Duration>` axis.
25097        let empty = MeshPolicy::default();
25098        assert!(
25099            empty.is_empty(),
25100            "MeshPolicy::default() must be is_empty() — every axis \
25101             defaults to None",
25102        );
25103        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
25104            let p = MeshPolicy {
25105                timeout,
25106                ..MeshPolicy::default()
25107            };
25108            assert!(
25109                !p.is_empty(),
25110                "MeshPolicy::is_empty must return false when \
25111                 :timeout is {timeout:?} — the emptiness \
25112                 predicate reads \"any axis carries a value\", not \
25113                 \"any axis carries a value the validate gate \
25114                 accepts\"",
25115            );
25116            assert_eq!(
25117                p.timeout().is_none(),
25118                p.is_empty(),
25119                "when :timeout is the only set axis, is_empty() \
25120                 must equal timeout().is_none() — the accessor and \
25121                 the emptiness predicate must route through the same \
25122                 substrate-primitive typed dispatch on the :timeout \
25123                 arm",
25124            );
25125        }
25126    }
25127
25128    #[test]
25129    fn mesh_policy_timeout_projects_option_duration_by_copy() {
25130        // The by-copy pin: [`MeshPolicy::timeout`] returns
25131        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
25132        // and the accessor must return by value, not by reference.
25133        // Sibling of the peer per-`:politicas`
25134        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
25135        // sibling `Option<u32>` optional-scalar axis and the peer
25136        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25137        // by-copy pin on the sibling `Option<bool>` optional-scalar
25138        // axis, extended onto the peer per-`:politicas`
25139        // `Option<Duration>` copy-invariant shape — the accessor's
25140        // returned `Option<Duration>` must outlive `&self` (multiple
25141        // calls must return equal values from a dropped-`&self`
25142        // copy, since the returned Option carries no borrow), and
25143        // calling the accessor twice on the same MeshPolicy must
25144        // yield the same `Option<Duration>` verbatim (idempotent, no
25145        // side effects on `&self`).
25146        //
25147        // Pins against a future silent detour that returned
25148        // `Option<&Duration>` (which would type-check but silently
25149        // break every downstream caller — [`crate::render::single_field_overlay`]'s
25150        // first parameter is `Option<T: Clone>`, and `&Duration`
25151        // would fold to a detached copy at the call site), an
25152        // accidental `Option::as_ref()` projection
25153        // (`self.timeout.as_ref()` would also type-check but return
25154        // `Option<&Duration>`), or a one-arm-only accessor that
25155        // reads `Some(*d)` in the Some arm but reads a fresh
25156        // `Default::default()` (`Duration::ZERO`) in the None arm
25157        // (which would silently re-classify every unset `:timeout`
25158        // as the `PolicyTimeoutZero`-refused zero-Duration value at
25159        // the accessor boundary).
25160        for timeout in [
25161            None,
25162            Some(Duration::from_millis(1)),
25163            Some(POLICY_TIMEOUT_MAX),
25164            Some(Duration::ZERO),
25165            Some(Duration::MAX),
25166        ] {
25167            let p = MeshPolicy {
25168                timeout,
25169                ..MeshPolicy::default()
25170            };
25171            let first = p.timeout();
25172            let second = p.timeout();
25173            assert_eq!(
25174                first, second,
25175                "MeshPolicy::timeout must be idempotent — two \
25176                 successive calls on the same &self must return the \
25177                 same Option<Duration>",
25178            );
25179            assert_eq!(
25180                first, timeout,
25181                "MeshPolicy::timeout must return :politicas :timeout \
25182                 verbatim by copy — got {first:?}, expected {timeout:?}",
25183            );
25184        }
25185    }
25186
25187    #[test]
25188    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
25189        // The canonical per-`:politicas` `:rate-limit` Envoy-
25190        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
25191        // [`MeshPolicy::rate_limit`] must return the `:politicas
25192        // :rate-limit` typed [`RateLimit`] verbatim as an
25193        // `Option<RateLimit>`, byte-equal to the raw field access
25194        // across every representative value in the accept-set — `None`
25195        // (cluster default applies — no per-Aplicacao rate declaration,
25196        // the gateway-class per-listener default arm the future caixa-
25197        // mesh `local_rate_limit_overlay` emitter documents),
25198        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
25199        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
25200        // accept-set the surrounding
25201        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25202        // sibling `PolicyRateLimitZero` refusal, paired with the
25203        // canonical-window "1 second" arm of the three-unit
25204        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
25205        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
25206        // (the upper boundary the same gate carves out on the sibling
25207        // `PolicyRateLimitExceedsCap` refusal, paired with the
25208        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
25209        // (a past-the-guard sentinel that pins the accessor doesn't
25210        // perform a silent bounds-collapse into `None` on the
25211        // zero-rate/zero-window arm — validate rejects zero but the
25212        // accessor must ship the raw slot verbatim so a validate-time
25213        // gate regression surfaces at the emit boundary rather than
25214        // being silently absorbed), and
25215        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
25216        // (a past-the-guard sentinel that pins the accessor doesn't
25217        // perform a silent bounds-collapse at the return path).
25218        //
25219        // First `Option<Copy-composite-T>`-return accessor pin on the
25220        // M3 mesh-slot family (peer of the sibling per-`:politicas`
25221        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
25222        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
25223        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
25224        // Copy accessor pins, extended onto the peer per-`:politicas`
25225        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
25226        // and the accessor returns by value). Pins against a future
25227        // silent detour that re-derived the rate declaration from a
25228        // peer axis (an accidental
25229        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
25230        // collapse that read the breaker's trip threshold + rolling
25231        // window as a rate declaration), a `None → Some(default())`
25232        // cluster-default projection (which would silently re-
25233        // introduce a "cluster default is 0/s" arm the emit boundary
25234        // would take as "declared but inert" — the canonical
25235        // declared-but-inert footgun the sibling
25236        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
25237        // amplification-shape axis), a bounds-collapsing accessor
25238        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
25239        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
25240        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
25241        // accessor must ship the raw slot verbatim), or a
25242        // by-reference detour (`Option<&RateLimit>`) that broke every
25243        // downstream consumer keying off `Option<RateLimit>` by-copy.
25244        for rl in [
25245            None,
25246            Some(RateLimit {
25247                rate: 1,
25248                window: Duration::from_secs(1),
25249            }),
25250            Some(RateLimit {
25251                rate: POLICY_RATE_LIMIT_MAX,
25252                window: Duration::from_secs(3600),
25253            }),
25254            Some(RateLimit {
25255                rate: 0,
25256                window: Duration::ZERO,
25257            }),
25258            Some(RateLimit {
25259                rate: u32::MAX,
25260                window: Duration::MAX,
25261            }),
25262        ] {
25263            let p = MeshPolicy {
25264                rate_limit: rl,
25265                ..MeshPolicy::default()
25266            };
25267            assert_eq!(
25268                p.rate_limit(),
25269                rl,
25270                "MeshPolicy::rate_limit must return :politicas :rate-limit \
25271                 verbatim (got {:?}, expected {rl:?})",
25272                p.rate_limit(),
25273            );
25274            assert_eq!(
25275                p.rate_limit(),
25276                p.rate_limit,
25277                "MeshPolicy::rate_limit must byte-equal the raw \
25278                 .rate_limit field access across every value in the \
25279                 accept-set",
25280            );
25281        }
25282    }
25283
25284    #[test]
25285    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
25286        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
25287        // must key off [`MeshPolicy::rate_limit`], not the raw
25288        // `.rate_limit` field access. Structurally: toggling ONLY the
25289        // `rate_limit` slot on an otherwise-default MeshPolicy must
25290        // flip `is_empty()` from `true` (all-`None`) to `false` (one
25291        // axis carries a value); the flip must be observed for every
25292        // representative value in the accept-set the surrounding
25293        // [`AplicacaoSpec::validate_politicas`] gate accepts
25294        // (`Some(RateLimit { rate: 1, window: 1s })`,
25295        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
25296        // since the emptiness semantic reads "any axis carries a
25297        // value" — not "any axis carries a value the validate gate
25298        // accepts" — the same non-collapsing shape the peer M2
25299        // [`crate::LimitsSpec::is_empty`] /
25300        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25301        //
25302        // Pins against a future silent detour that re-derived the
25303        // emptiness predicate off a peer axis (an accidental
25304        // `.timeout.is_none()`-only chain that dropped the
25305        // `rate_limit` arm entirely — the last unlifted inline field
25306        // access on `is_empty` before this lift), a `rate_limit ==
25307        // Some(_)` collapse that key-off a validate-gate-clamped
25308        // bounds check (which would silently classify a past-the-
25309        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
25310        // because it fails the value-shape gate), or an accessor-
25311        // side detour that no longer names the substrate-primitive
25312        // typed dispatch.
25313        //
25314        // Fourth "the emptiness predicate must route through the
25315        // substrate-primitive typed dispatch" composition pin on the
25316        // M3 mesh-slot family — closes the last unlifted composition
25317        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
25318        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
25319        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
25320        // 7073d0f is_empty-composition pins on the sibling primitive-
25321        // Copy axes, extended onto the peer per-`:politicas`
25322        // composite-Copy `Option<RateLimit>` axis).
25323        let empty = MeshPolicy::default();
25324        assert!(
25325            empty.is_empty(),
25326            "MeshPolicy::default() must be is_empty() — every axis \
25327             defaults to None",
25328        );
25329        for rl in [
25330            RateLimit {
25331                rate: 1,
25332                window: Duration::from_secs(1),
25333            },
25334            RateLimit {
25335                rate: POLICY_RATE_LIMIT_MAX,
25336                window: Duration::from_secs(3600),
25337            },
25338        ] {
25339            let p = MeshPolicy {
25340                rate_limit: Some(rl),
25341                ..MeshPolicy::default()
25342            };
25343            assert!(
25344                !p.is_empty(),
25345                "MeshPolicy::is_empty must return false when \
25346                 :rate-limit is {rl:?} — the emptiness predicate \
25347                 reads \"any axis carries a value\", not \"any axis \
25348                 carries a value the validate gate accepts\"",
25349            );
25350            assert_eq!(
25351                p.rate_limit().is_none(),
25352                p.is_empty(),
25353                "when :rate-limit is the only set axis, is_empty() \
25354                 must equal rate_limit().is_none() — the accessor \
25355                 and the emptiness predicate must route through the \
25356                 same substrate-primitive typed dispatch on the \
25357                 :rate-limit arm",
25358            );
25359        }
25360    }
25361
25362    #[test]
25363    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
25364        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25365        // `:rate-limit` value-shape gate must key off
25366        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
25367        // field bind. Structurally: a `MeshPolicy` whose only set
25368        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
25369        // the `PolicyRateLimitZero` refusal exactly, and the same
25370        // MeshPolicy with the rate at the canonical lower boundary
25371        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
25372        // The pair jointly pins the accessor + validate-gate
25373        // composition: any future silent detour that had the accessor
25374        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
25375        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
25376        // silently absorb the `PolicyRateLimitZero` refusal at the
25377        // accessor boundary — the composition pin catches that at
25378        // caixa-core build time.
25379        //
25380        // Sibling of the peer [`validate_politicas`]
25381        // `:mtls-required` / `:retries` / `:timeout` composition pins
25382        // on the sibling primitive-Copy optional-scalar axes — same
25383        // "the validate / shape-gate predicate must route through the
25384        // substrate-primitive typed dispatch" discipline extended
25385        // onto the peer per-`:politicas` composite-Copy
25386        // `Option<RateLimit>` axis. Second composition-with-accessor
25387        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
25388        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
25389        let mut spec = three_member_spec();
25390        spec.politicas = MeshPolicy {
25391            rate_limit: Some(RateLimit {
25392                rate: 0,
25393                window: Duration::from_secs(1),
25394            }),
25395            ..MeshPolicy::default()
25396        };
25397        assert!(
25398            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
25399            "validate_politicas must reject rate == 0 with \
25400             PolicyRateLimitZero — the accessor and the validate gate \
25401             must route through the same substrate-primitive typed \
25402             dispatch on the :rate-limit zero-floor arm",
25403        );
25404        spec.politicas = MeshPolicy {
25405            rate_limit: Some(RateLimit {
25406                rate: 1,
25407                window: Duration::from_secs(1),
25408            }),
25409            ..MeshPolicy::default()
25410        };
25411        assert!(
25412            spec.validate().is_ok(),
25413            "validate_politicas must accept rate == 1 (the canonical \
25414             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
25415             set) with a canonical 1s window",
25416        );
25417    }
25418
25419    #[test]
25420    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
25421        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
25422        // `outlier_detection`-mesh consecutive-failure-ejection scalar
25423        // pin: [`MeshPolicy::circuit_breaker`] must return the
25424        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
25425        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
25426        // raw field access across every representative value in the
25427        // accept-set — `None` (cluster default applies — no
25428        // per-Aplicacao breaker declaration, the gateway-class per-
25429        // listener default arm the future caixa-mesh
25430        // `outlier_detection_overlay` emitter documents),
25431        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
25432        // (the lower boundary of the accept-set the surrounding
25433        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25434        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
25435        // refusals),
25436        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
25437        // (the upper boundary the same gate carves out on the sibling
25438        // `PolicyBreakerMaxFailuresExceedsCap` /
25439        // `PolicyBreakerWindowExceedsCap` refusals),
25440        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
25441        // (a past-the-guard sentinel that pins the accessor doesn't
25442        // perform a silent bounds-collapse into `None` on the
25443        // zero-failures/zero-window arm — validate rejects zero but
25444        // the accessor must ship the raw slot verbatim so a validate-
25445        // time gate regression surfaces at the emit boundary rather
25446        // than being silently absorbed), and
25447        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
25448        // (a past-the-guard sentinel that pins the accessor doesn't
25449        // perform a silent bounds-collapse at the return path).
25450        //
25451        // Second `Option<Copy-composite-T>`-return accessor pin on the
25452        // M3 mesh-slot family (peer of the sibling per-`:politicas`
25453        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
25454        // composite-Copy accessor pin, and of the sibling per-
25455        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
25456        // [`MeshPolicy::retries`] bdfb399 /
25457        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
25458        // accessor pins). Pins against a future silent detour that
25459        // re-derived the breaker declaration from a peer axis (an
25460        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
25461        // collapse that read the rate-limit's bucket capacity + refill
25462        // period as a breaker declaration), a `None → Some(default())`
25463        // cluster-default projection (which would silently re-
25464        // introduce the `PolicyBreakerZeroFailures` /
25465        // `PolicyBreakerZeroWindow` refusal cases at the emit
25466        // boundary), a bounds-collapsing accessor that clamped
25467        // `cb.max_failures` through
25468        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
25469        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
25470        // [`AplicacaoSpec::validate`] gate owns the bounds; the
25471        // accessor must ship the raw slot verbatim), or a
25472        // by-reference detour (`Option<&CircuitBreaker>`) that broke
25473        // every downstream consumer keying off `Option<CircuitBreaker>`
25474        // by-copy.
25475        for cb in [
25476            None,
25477            Some(CircuitBreaker {
25478                max_failures: 1,
25479                window: Duration::from_millis(1),
25480            }),
25481            Some(CircuitBreaker {
25482                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25483                window: POLICY_BREAKER_WINDOW_MAX,
25484            }),
25485            Some(CircuitBreaker {
25486                max_failures: 0,
25487                window: Duration::ZERO,
25488            }),
25489            Some(CircuitBreaker {
25490                max_failures: u32::MAX,
25491                window: Duration::MAX,
25492            }),
25493        ] {
25494            let p = MeshPolicy {
25495                circuit_breaker: cb,
25496                ..MeshPolicy::default()
25497            };
25498            assert_eq!(
25499                p.circuit_breaker(),
25500                cb,
25501                "MeshPolicy::circuit_breaker must return :politicas \
25502                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
25503                p.circuit_breaker(),
25504            );
25505            assert_eq!(
25506                p.circuit_breaker(),
25507                p.circuit_breaker,
25508                "MeshPolicy::circuit_breaker must byte-equal the raw \
25509                 .circuit_breaker field access across every value in \
25510                 the accept-set",
25511            );
25512        }
25513    }
25514
25515    #[test]
25516    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
25517        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
25518        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
25519        // `.circuit_breaker` field access. Structurally: toggling ONLY
25520        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
25521        // must flip `is_empty()` from `true` (all-`None`) to `false`
25522        // (one axis carries a value); the flip must be observed for
25523        // every representative value in the accept-set the surrounding
25524        // [`AplicacaoSpec::validate_politicas`] gate accepts
25525        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
25526        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
25527        // since the emptiness semantic reads "any axis carries a
25528        // value" — not "any axis carries a value the validate gate
25529        // accepts" — the same non-collapsing shape the peer M2
25530        // [`crate::LimitsSpec::is_empty`] /
25531        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25532        //
25533        // Pins against a future silent detour that re-derived the
25534        // emptiness predicate off a peer axis (an accidental
25535        // `.rate_limit.is_none()`-only chain that dropped the
25536        // `circuit_breaker` arm entirely — the last unlifted inline
25537        // field access on `is_empty` before this lift), a
25538        // `circuit_breaker == Some(_)` collapse that key-off a
25539        // validate-gate-clamped bounds check (which would silently
25540        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
25541        // 0, window: 0s })` as empty because it fails the value-shape
25542        // gate), or an accessor-side detour that no longer names the
25543        // substrate-primitive typed dispatch.
25544        //
25545        // Fifth "the emptiness predicate must route through the
25546        // substrate-primitive typed dispatch" composition pin on the
25547        // M3 mesh-slot family — closes the last unlifted composition
25548        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
25549        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
25550        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
25551        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
25552        // composition pins on the sibling primitive-Copy + composite-
25553        // Copy axes, extended onto the peer per-`:politicas`
25554        // composite-Copy `Option<CircuitBreaker>` axis).
25555        let empty = MeshPolicy::default();
25556        assert!(
25557            empty.is_empty(),
25558            "MeshPolicy::default() must be is_empty() — every axis \
25559             defaults to None",
25560        );
25561        for cb in [
25562            CircuitBreaker {
25563                max_failures: 1,
25564                window: Duration::from_millis(1),
25565            },
25566            CircuitBreaker {
25567                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25568                window: POLICY_BREAKER_WINDOW_MAX,
25569            },
25570        ] {
25571            let p = MeshPolicy {
25572                circuit_breaker: Some(cb),
25573                ..MeshPolicy::default()
25574            };
25575            assert!(
25576                !p.is_empty(),
25577                "MeshPolicy::is_empty must return false when \
25578                 :circuit-breaker is {cb:?} — the emptiness predicate \
25579                 reads \"any axis carries a value\", not \"any axis \
25580                 carries a value the validate gate accepts\"",
25581            );
25582            assert_eq!(
25583                p.circuit_breaker().is_none(),
25584                p.is_empty(),
25585                "when :circuit-breaker is the only set axis, \
25586                 is_empty() must equal circuit_breaker().is_none() — \
25587                 the accessor and the emptiness predicate must route \
25588                 through the same substrate-primitive typed dispatch \
25589                 on the :circuit-breaker arm",
25590            );
25591        }
25592    }
25593
25594    #[test]
25595    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
25596        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25597        // `:circuit-breaker` value-shape gate must key off
25598        // [`MeshPolicy::circuit_breaker`], not the raw
25599        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
25600        // whose only set axis is a `Some(CircuitBreaker { max_failures:
25601        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
25602        // refusal exactly, and the same MeshPolicy with the breaker at
25603        // the canonical lower boundary
25604        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
25605        // pass validate. The pair jointly pins the accessor +
25606        // validate-gate composition: any future silent detour that had
25607        // the accessor omit the `Some(CircuitBreaker { max_failures:
25608        // 0, .. })` arm (a
25609        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
25610        // collapse) would silently absorb the
25611        // `PolicyBreakerZeroFailures` refusal at the accessor
25612        // boundary — the composition pin catches that at caixa-core
25613        // build time.
25614        //
25615        // Sibling of the peer [`validate_politicas`]
25616        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
25617        // composition pins on the sibling primitive-Copy + composite-
25618        // Copy optional-scalar axes — same "the validate / shape-gate
25619        // predicate must route through the substrate-primitive typed
25620        // dispatch" discipline extended onto the peer per-`:politicas`
25621        // composite-Copy `Option<CircuitBreaker>` axis. Second
25622        // composition-with-accessor pin on the M3 mesh-slot
25623        // `Option<CircuitBreaker>` arm alongside the
25624        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
25625        let mut spec = three_member_spec();
25626        spec.politicas = MeshPolicy {
25627            circuit_breaker: Some(CircuitBreaker {
25628                max_failures: 0,
25629                window: Duration::from_millis(1),
25630            }),
25631            ..MeshPolicy::default()
25632        };
25633        assert!(
25634            matches!(
25635                spec.validate(),
25636                Err(AplicacaoError::PolicyBreakerZeroFailures)
25637            ),
25638            "validate_politicas must reject max_failures == 0 with \
25639             PolicyBreakerZeroFailures — the accessor and the validate \
25640             gate must route through the same substrate-primitive \
25641             typed dispatch on the :circuit-breaker zero-floor arm",
25642        );
25643        spec.politicas = MeshPolicy {
25644            circuit_breaker: Some(CircuitBreaker {
25645                max_failures: 1,
25646                window: Duration::from_millis(1),
25647            }),
25648            ..MeshPolicy::default()
25649        };
25650        assert!(
25651            spec.validate().is_ok(),
25652            "validate_politicas must accept a CircuitBreaker at the \
25653             canonical lower boundary (max_failures = 1, window = \
25654             1ms) — the accessor and the validate gate must route \
25655             through the same substrate-primitive typed dispatch on \
25656             the :circuit-breaker arm",
25657        );
25658    }
25659
25660    #[test]
25661    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
25662        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
25663        // Envoy-outlier-detection trip-threshold scalar pin:
25664        // [`CircuitBreaker::max_failures`] must return the
25665        // `:politicas :circuit-breaker :max-failures` typed `u32`
25666        // verbatim, byte-equal to the raw field access across every
25667        // representative value in the accept-set — `1` (the lower
25668        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
25669        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
25670        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
25671        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
25672        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
25673        // refusal), `0` (a past-the-guard sentinel that pins the accessor
25674        // doesn't perform a silent bounds-collapse into `1` on the zero
25675        // arm — validate rejects zero but the accessor must ship the
25676        // raw slot verbatim so a validate-time gate regression surfaces
25677        // at the emit boundary rather than being silently absorbed),
25678        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
25679        // doesn't perform a silent bounds-collapse through
25680        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
25681        //
25682        // First sub-struct required-scalar accessor pin on the M3
25683        // mesh-slot family — sibling in shape to the peer per-`:membros`
25684        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
25685        // (a40b0e3) required-`String`-carry accessor pins and the peer
25686        // per-`:contratos` [`WitContract::source`] /
25687        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
25688        // accessor pins, extended onto the peer per-`CircuitBreaker`
25689        // required-`u32` scalar-value axis. Pins against a future silent
25690        // detour that re-derived the trip threshold from a peer axis (an
25691        // accidental `self.window.as_secs() as u32` collapse that read
25692        // the breaker's rolling-window duration as a failure count), a
25693        // `0 → 1` cluster-default projection (which would silently absorb
25694        // the `PolicyBreakerZeroFailures` refusal case at the accessor
25695        // boundary), or a bounds-collapsing accessor that clamped the
25696        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
25697        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25698        // must ship the raw slot verbatim).
25699        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
25700            let cb = CircuitBreaker {
25701                max_failures,
25702                window: Duration::from_secs(60),
25703            };
25704            assert_eq!(
25705                cb.max_failures(),
25706                max_failures,
25707                "CircuitBreaker::max_failures must return :politicas \
25708                 :circuit-breaker :max-failures verbatim (got {}, \
25709                 expected {max_failures})",
25710                cb.max_failures(),
25711            );
25712            assert_eq!(
25713                cb.max_failures(),
25714                cb.max_failures,
25715                "CircuitBreaker::max_failures must byte-equal the raw \
25716                 .max_failures field access across every value in the \
25717                 u32 accept-set",
25718            );
25719        }
25720    }
25721
25722    #[test]
25723    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
25724        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25725        // `:circuit-breaker :max-failures` zero-floor arm must key off
25726        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
25727        // field access. Structurally: a `CircuitBreaker { max_failures:
25728        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
25729        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
25730        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
25731        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
25732        // pass validate. The pair jointly pins the accessor +
25733        // validate-gate composition: any future silent detour that had
25734        // the accessor return a fresh `1` on the zero arm (a
25735        // `.max_failures().max(1)` collapse) would silently absorb the
25736        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
25737        // and the validate gate would accept a struct-literal
25738        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
25739        // catches that at caixa-core build time.
25740        //
25741        // Peer of the sibling per-`:politicas`
25742        // [`MeshPolicy::mtls_required`] (c0110f1) /
25743        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
25744        // (7073d0f) accessor-composition pins on the sibling optional-
25745        // scalar axes — same "the validate / shape-gate predicate must
25746        // route through the substrate-primitive typed dispatch"
25747        // discipline extended onto the peer per-`CircuitBreaker`
25748        // required-scalar composition axis.
25749        let mut spec = three_member_spec();
25750        spec.politicas = MeshPolicy {
25751            circuit_breaker: Some(CircuitBreaker {
25752                max_failures: 0,
25753                window: Duration::from_secs(60),
25754            }),
25755            ..MeshPolicy::default()
25756        };
25757        assert!(
25758            matches!(
25759                spec.validate(),
25760                Err(AplicacaoError::PolicyBreakerZeroFailures)
25761            ),
25762            "validate_politicas must reject max_failures == 0 with \
25763             PolicyBreakerZeroFailures — the accessor and the validate \
25764             gate must route through the same substrate-primitive typed \
25765             dispatch on the :max-failures zero-floor arm",
25766        );
25767        spec.politicas = MeshPolicy {
25768            circuit_breaker: Some(CircuitBreaker {
25769                max_failures: 1,
25770                window: Duration::from_secs(60),
25771            }),
25772            ..MeshPolicy::default()
25773        };
25774        assert!(
25775            spec.validate().is_ok(),
25776            "validate_politicas must accept max_failures == 1 (the \
25777             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
25778             accept-set)",
25779        );
25780    }
25781
25782    #[test]
25783    fn circuit_breaker_max_failures_projects_u32_by_copy() {
25784        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
25785        // `u32` by copy — `u32` is `Copy` and the accessor must return
25786        // by value, not by reference. Peer of the sibling
25787        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
25788        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
25789        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
25790        // optional-scalar axes, extended onto the peer
25791        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
25792        // the accessor's returned `u32` must outlive `&self` (multiple
25793        // calls must return equal values from a dropped-`&self` copy,
25794        // since the returned scalar carries no borrow), and calling
25795        // the accessor twice on the same CircuitBreaker must yield the
25796        // same `u32` verbatim (idempotent, no side effects on `&self`).
25797        //
25798        // Pins against a future silent detour that returned `&u32`
25799        // (which would type-check but silently break every downstream
25800        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
25801        // first parameter is `u32`, and `&u32` would fold to a detached
25802        // copy at the call site with a `*` deref the sibling accessors
25803        // don't need), an accidental `.max_failures.wrapping_add(0)`
25804        // detour that returned a fresh copy through an arithmetic
25805        // no-op (breaking a future `const fn` regression), or a
25806        // one-arm-only accessor that returned a saturating value on
25807        // some sentinel input (breaking the pass-through invariant the
25808        // sibling required-scalar accessors carry).
25809        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
25810            let cb = CircuitBreaker {
25811                max_failures,
25812                window: Duration::from_secs(60),
25813            };
25814            let first = cb.max_failures();
25815            let second = cb.max_failures();
25816            assert_eq!(
25817                first, second,
25818                "CircuitBreaker::max_failures must be idempotent — two \
25819                 successive calls on the same &self must return the \
25820                 same u32",
25821            );
25822            assert_eq!(
25823                first, max_failures,
25824                "CircuitBreaker::max_failures must return :politicas \
25825                 :circuit-breaker :max-failures verbatim by copy — \
25826                 got {first}, expected {max_failures}",
25827            );
25828        }
25829    }
25830
25831    #[test]
25832    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
25833        // The canonical per-`:politicas :circuit-breaker` `:window`
25834        // Envoy-outlier-detection rolling-observation-interval scalar
25835        // pin: [`CircuitBreaker::window`] must return the
25836        // `:politicas :circuit-breaker :window` typed `Duration`
25837        // verbatim, byte-equal to the raw field access across every
25838        // representative value in the accept-set — `Duration::from_millis(1)`
25839        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
25840        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
25841        // gate carves out on the sibling `PolicyBreakerZeroWindow`
25842        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
25843        // same gate carves out on the sibling
25844        // `PolicyBreakerWindowExceedsCap` refusal),
25845        // `Duration::ZERO` (a past-the-guard sentinel that pins the
25846        // accessor doesn't perform a silent bounds-collapse into
25847        // `Duration::from_millis(1)` on the zero arm — validate rejects
25848        // zero but the accessor must ship the raw slot verbatim so a
25849        // validate-time gate regression surfaces at the emit boundary
25850        // rather than being silently absorbed),
25851        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
25852        // far above the 1h cap — that pins the accessor doesn't perform
25853        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
25854        // at the return path).
25855        //
25856        // Second sub-struct required-scalar accessor pin on the M3
25857        // mesh-slot family — sibling in shape to the just-landed
25858        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
25859        // (3a74062) required-`u32` accessor pin on the peer
25860        // per-`CircuitBreaker` required-axis, extended onto the
25861        // per-sub-struct required-`Duration` axis. Pins against a
25862        // future silent detour that re-derived the observation window
25863        // from a peer axis (an accidental
25864        // `Duration::from_secs(self.max_failures as u64)` collapse that
25865        // read the breaker's trip count as an observation-interval
25866        // duration), a `Duration::ZERO → Duration::from_millis(1)`
25867        // cluster-default projection (which would silently absorb the
25868        // `PolicyBreakerZeroWindow` refusal case at the accessor
25869        // boundary), or a bounds-collapsing accessor that clamped the
25870        // return through `POLICY_BREAKER_WINDOW_MAX` (the
25871        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25872        // must ship the raw slot verbatim).
25873        for window in [
25874            Duration::from_millis(1),
25875            POLICY_BREAKER_WINDOW_MAX,
25876            Duration::ZERO,
25877            Duration::from_secs(86_400),
25878        ] {
25879            let cb = CircuitBreaker {
25880                max_failures: 5,
25881                window,
25882            };
25883            assert_eq!(
25884                cb.window(),
25885                window,
25886                "CircuitBreaker::window must return :politicas \
25887                 :circuit-breaker :window verbatim (got {:?}, \
25888                 expected {window:?})",
25889                cb.window(),
25890            );
25891            assert_eq!(
25892                cb.window(),
25893                cb.window,
25894                "CircuitBreaker::window must byte-equal the raw \
25895                 .window field access across every value in the \
25896                 Duration accept-set",
25897            );
25898        }
25899    }
25900
25901    #[test]
25902    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
25903        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25904        // `:circuit-breaker :window` zero-floor arm must key off
25905        // [`CircuitBreaker::window`], not the raw `.window` field
25906        // access. Structurally: a `CircuitBreaker { window:
25907        // Duration::ZERO, .. }` embedded in a
25908        // `:politicas :circuit-breaker` slot must surface the
25909        // `PolicyBreakerZeroWindow` refusal exactly, and a
25910        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
25911        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
25912        // accept-set) must pass validate. The pair jointly pins the
25913        // accessor + validate-gate composition: any future silent
25914        // detour that had the accessor return a fresh
25915        // `Duration::from_millis(1)` on the zero arm (a
25916        // `.window().max(Duration::from_millis(1))` collapse) would
25917        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
25918        // accessor boundary and the validate gate would accept a
25919        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
25920        // — the composition pin catches that at caixa-core build time.
25921        //
25922        // Peer of the sibling per-`CircuitBreaker`
25923        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
25924        // pin on the peer required-scalar `:max-failures` axis — same
25925        // "the validate / shape-gate predicate must route through the
25926        // substrate-primitive typed dispatch" discipline extended onto
25927        // the peer per-`CircuitBreaker` required-`Duration` composition
25928        // axis.
25929        let mut spec = three_member_spec();
25930        spec.politicas = MeshPolicy {
25931            circuit_breaker: Some(CircuitBreaker {
25932                max_failures: 5,
25933                window: Duration::ZERO,
25934            }),
25935            ..MeshPolicy::default()
25936        };
25937        assert!(
25938            matches!(
25939                spec.validate(),
25940                Err(AplicacaoError::PolicyBreakerZeroWindow)
25941            ),
25942            "validate_politicas must reject window == Duration::ZERO \
25943             with PolicyBreakerZeroWindow — the accessor and the \
25944             validate gate must route through the same substrate-\
25945             primitive typed dispatch on the :window zero-floor arm",
25946        );
25947        spec.politicas = MeshPolicy {
25948            circuit_breaker: Some(CircuitBreaker {
25949                max_failures: 5,
25950                window: Duration::from_millis(1),
25951            }),
25952            ..MeshPolicy::default()
25953        };
25954        assert!(
25955            spec.validate().is_ok(),
25956            "validate_politicas must accept window == \
25957             Duration::from_millis(1) (the lower boundary of the \
25958             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
25959        );
25960    }
25961
25962    #[test]
25963    fn circuit_breaker_window_projects_duration_by_copy() {
25964        // The by-copy pin: [`CircuitBreaker::window`] returns
25965        // `Duration` by copy — `Duration` is `Copy` and the accessor
25966        // must return by value, not by reference. Peer of the sibling
25967        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
25968        // (3a74062) by-copy pin on the peer required-scalar
25969        // `:max-failures` axis, extended onto the peer
25970        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
25971        // — the accessor's returned `Duration` must outlive `&self`
25972        // (multiple calls must return equal values from a
25973        // dropped-`&self` copy, since the returned scalar carries no
25974        // borrow), and calling the accessor twice on the same
25975        // CircuitBreaker must yield the same `Duration` verbatim
25976        // (idempotent, no side effects on `&self`).
25977        //
25978        // Pins against a future silent detour that returned
25979        // `&Duration` (which would type-check but silently break every
25980        // downstream `Duration`-by-value consumer —
25981        // [`crate::render::require_positive_canonical_bounded_duration`]'s
25982        // first parameter is `Duration`, and `&Duration` would fold to
25983        // a detached copy at the call site with a `*` deref the sibling
25984        // accessors don't need), an accidental `.window + Duration::ZERO`
25985        // detour that returned a fresh copy through an arithmetic
25986        // no-op (breaking a future `const fn` regression), or a
25987        // one-arm-only accessor that returned a saturating value on
25988        // some sentinel input (breaking the pass-through invariant the
25989        // sibling required-scalar accessors carry).
25990        for window in [
25991            Duration::from_millis(1),
25992            POLICY_BREAKER_WINDOW_MAX,
25993            Duration::ZERO,
25994            Duration::from_secs(86_400),
25995        ] {
25996            let cb = CircuitBreaker {
25997                max_failures: 5,
25998                window,
25999            };
26000            let first = cb.window();
26001            let second = cb.window();
26002            assert_eq!(
26003                first, second,
26004                "CircuitBreaker::window must be idempotent — two \
26005                 successive calls on the same &self must return the \
26006                 same Duration",
26007            );
26008            assert_eq!(
26009                first, window,
26010                "CircuitBreaker::window must return :politicas \
26011                 :circuit-breaker :window verbatim by copy — \
26012                 got {first:?}, expected {window:?}",
26013            );
26014        }
26015    }
26016
26017    #[test]
26018    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
26019        // Apex-identity pair-invariant pin composing both substrate-
26020        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
26021        // and [`WitContract::destination`] — at the emit-side call shape
26022        // every per-`(:de, :para)` CNP L4 port reader now takes. The
26023        // invariant, evaluated per-edge:
26024        //
26025        //   spec.port_for_destination(c.destination()) == expected_port
26026        //
26027        // where `expected_port` is `entrada.port` when
26028        // `c.destination() == entrada.destination()` and
26029        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
26030        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
26031        // pin on the per-`:entrada` axis — that pin encodes the apex
26032        // ingress L4 identity via `entrada.destination()`; this pin
26033        // encodes the per-edge L4 identity via `c.destination()`, and
26034        // both compose on the same substrate-primitive resolver so a
26035        // future refactor that silently split either accessor's apex
26036        // behavior surfaces at caixa-core build time.
26037        let mut spec = three_member_spec();
26038        if let Some(e) = spec.entrada.as_mut() {
26039            e.para = "cart".into();
26040            e.port = 8443;
26041        }
26042        let apex_contract = WitContract {
26043            de: "checkout".into(),
26044            para: "cart".into(),
26045            wit: "wasi:http/proxy".into(),
26046            endpoint: Some("/hello".into()),
26047            subject: None,
26048            slot: None,
26049        };
26050        assert_eq!(
26051            spec.port_for_destination(apex_contract.destination()),
26052            8443,
26053            "`spec.port_for_destination(c.destination())` must equal \
26054             `entrada.port` when the contract callee names the ingress \
26055             apex — the CNP per-edge L4 port and the HTTPRoute apex \
26056             backendRef port share this substrate-primitive resolver.",
26057        );
26058        let non_apex_contract = WitContract {
26059            de: "cart".into(),
26060            para: "payment".into(),
26061            wit: "wasi:http/proxy".into(),
26062            endpoint: Some("/charge".into()),
26063            subject: None,
26064            slot: None,
26065        };
26066        assert_eq!(
26067            spec.port_for_destination(non_apex_contract.destination()),
26068            DEFAULT_SERVICO_PORT,
26069            "`spec.port_for_destination(c.destination())` must fall back \
26070             to the substrate-canonical port floor when the contract \
26071             callee is not the ingress apex — the resolver's non-apex \
26072             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
26073        );
26074    }
26075
26076    #[test]
26077    fn membro_key_consts_are_lower_camel_case_shape() {
26078        // Shape-pin: every `MEMBRO_KEY_*` const must be a
26079        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26080        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26081        // leading capital, no whitespace / dots) — the canonical shape
26082        // the `#[serde(rename_all = "camelCase")]` derive produces on
26083        // [`Membro`]. A future flip to a non-camelCase attribute at
26084        // the derive surfaces both here (this test fails on the
26085        // stale-constant shape) and at
26086        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
26087        // fails on the mismatch between const and derive). Peer with
26088        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
26089        // on the sibling `SupervisorSpec` top-level axis.
26090        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
26091            assert!(
26092                !key.is_empty(),
26093                "MEMBRO_KEY_* must be non-empty (got {key:?})"
26094            );
26095            let first = key.chars().next().unwrap();
26096            assert!(
26097                first.is_ascii_lowercase(),
26098                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
26099                 (got {key:?}, leads with {first:?})",
26100            );
26101            assert!(
26102                key.chars().all(|c| c.is_ascii_alphanumeric()),
26103                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
26104                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26105            );
26106        }
26107    }
26108
26109    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
26110
26111    #[test]
26112    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
26113        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
26114        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
26115        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
26116        // keys the `#[serde(rename_all = "camelCase")]` attribute on
26117        // [`WitContract`] emits for the required-triad. The three
26118        // sibling payload-arm keys already pin under
26119        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
26120        // `STORE_FIELD_NAME` — pin all six alongside so a future
26121        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26122        // verbatim-field-name flip at the derive attribute (any of which
26123        // would silently break every downstream JSON consumer that
26124        // reaches for one of the six via `Value::get(...)`) surfaces
26125        // here as a build-time test failure at `aplicacao.rs`, not as an
26126        // apply-time `.get(<stale-canonical-const>)` returning `None`
26127        // far from the derive-attr drift's commit. Peer with the sibling
26128        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26129        // pin on the M3 `:membros` per-entry axis — same discipline the
26130        // `Membro` per-entry lift established, extended here to the
26131        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
26132        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
26133        // axis on the Aplicacao surface without a lifted serde-key peer.
26134        let c = WitContract {
26135            de: "cart".into(),
26136            para: "catalog".into(),
26137            wit: "wasi:http/proxy".into(),
26138            endpoint: Some("/lookup".into()),
26139            subject: None,
26140            slot: None,
26141        };
26142        let json = serde_json::to_string(&c).unwrap();
26143        for key in [
26144            crate::CONTRATO_KEY_DE,
26145            crate::CONTRATO_KEY_PARA,
26146            crate::CONTRATO_KEY_WIT,
26147            WitTarget::HTTP_FIELD_NAME,
26148        ] {
26149            let quoted = format!("\"{key}\"");
26150            assert!(
26151                json.contains(&quoted),
26152                "serialized WitContract must carry the lifted \
26153                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
26154                 {quoted} verbatim in the JSON emission (got: {json})",
26155            );
26156        }
26157
26158        // Pin the two remaining payload-arm keys by round-tripping a
26159        // `WitContract` under each payload-shape (pub-sub, store) — the
26160        // required-triad appears on every emission but the payload arms
26161        // only surface when their `Option<String>` field is `Some`.
26162        let pubsub = WitContract {
26163            de: "cart".into(),
26164            para: "events".into(),
26165            wit: "nats:pub-sub".into(),
26166            endpoint: None,
26167            subject: Some("orders.placed".into()),
26168            slot: None,
26169        };
26170        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
26171        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
26172        assert!(
26173            pubsub_json.contains(&pubsub_quoted),
26174            "serialized pub-sub WitContract must carry the lifted \
26175             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
26176             verbatim in the JSON emission (got: {pubsub_json})",
26177        );
26178        let store = WitContract {
26179            de: "cart".into(),
26180            para: "sessions".into(),
26181            wit: "wasi:keyvalue/store".into(),
26182            endpoint: None,
26183            subject: None,
26184            slot: Some("cart/$id".into()),
26185        };
26186        let store_json = serde_json::to_string(&store).unwrap();
26187        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
26188        assert!(
26189            store_json.contains(&store_quoted),
26190            "serialized store WitContract must carry the lifted \
26191             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
26192             verbatim in the JSON emission (got: {store_json})",
26193        );
26194    }
26195
26196    #[test]
26197    fn contrato_key_consts_are_pairwise_distinct() {
26198        // Cross-axis drift-detection pin: a future collapse of the six
26199        // canonical [`WitContract`] per-entry byte-strings onto the same
26200        // value (e.g. an accidental copy-paste flip of
26201        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
26202        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
26203        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
26204        // every downstream probe on one axis onto the sibling axis's
26205        // overlay entry and pass every propagation-probe test that
26206        // expected only the stale axis's value. Peer of the sibling
26207        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
26208        // widened here to the six-way axis the `WitContract`
26209        // required-triad + `WitTarget` payload-triad jointly cover.
26210        let all = [
26211            crate::CONTRATO_KEY_DE,
26212            crate::CONTRATO_KEY_PARA,
26213            crate::CONTRATO_KEY_WIT,
26214            WitTarget::HTTP_FIELD_NAME,
26215            WitTarget::PUBSUB_FIELD_NAME,
26216            WitTarget::STORE_FIELD_NAME,
26217        ];
26218        for (i, a) in all.iter().enumerate() {
26219            for b in all.iter().skip(i + 1) {
26220                assert_ne!(
26221                    a, b,
26222                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
26223                     must be pairwise-distinct canonical byte-sequences \
26224                     — got `{a}` == `{b}`",
26225                );
26226            }
26227        }
26228    }
26229
26230    #[test]
26231    fn contrato_key_consts_are_lower_camel_case_shape() {
26232        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
26233        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
26234        // byte-sequence (no `snake_case` underscores, no `kebab-case`
26235        // hyphens, no leading colon, no `PascalCase` leading capital, no
26236        // whitespace / dots) — the canonical shape the
26237        // `#[serde(rename_all = "camelCase")]` derive produces on
26238        // [`WitContract`]. A future flip to a non-camelCase attribute at
26239        // the derive surfaces both here (this test fails on the
26240        // stale-constant shape) and at
26241        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26242        // (that test fails on the mismatch between const and derive).
26243        // Peer with `membro_key_consts_are_lower_camel_case_shape`
26244        // (ce80ca0) on the sibling `Membro` per-entry axis.
26245        for key in [
26246            crate::CONTRATO_KEY_DE,
26247            crate::CONTRATO_KEY_PARA,
26248            crate::CONTRATO_KEY_WIT,
26249            WitTarget::HTTP_FIELD_NAME,
26250            WitTarget::PUBSUB_FIELD_NAME,
26251            WitTarget::STORE_FIELD_NAME,
26252        ] {
26253            assert!(
26254                !key.is_empty(),
26255                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26256                 non-empty (got {key:?})"
26257            );
26258            let first = key.chars().next().unwrap();
26259            assert!(
26260                first.is_ascii_lowercase(),
26261                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
26262                 with an ASCII-lowercase byte (got {key:?}, leads with \
26263                 {first:?})",
26264            );
26265            assert!(
26266                key.chars().all(|c| c.is_ascii_alphanumeric()),
26267                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26268                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
26269                 whitespace (got {key:?})",
26270            );
26271        }
26272    }
26273
26274    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
26275
26276    #[test]
26277    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
26278        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
26279        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
26280        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
26281        // name the exact camelCase JSON keys the
26282        // `#[serde(rename_all = "camelCase")]` attribute on
26283        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
26284        // pin that each canonical byte-sequence appears verbatim in the
26285        // JSON — a future accidental `rename_all = "snake_case"` /
26286        // `"kebab-case"` / verbatim-field-name flip at the derive
26287        // attribute (any of which would silently break every downstream
26288        // JSON consumer that reaches for one of the four consts via
26289        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
26290        // emitter's per-Aplicacao hostname/paths/port projection, the
26291        // future `app-operator` reconciler's per-Aplicacao ingress
26292        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
26293        // materializer's admission-time cross-check) surfaces here as
26294        // a build-time test failure at `aplicacao.rs`, not as an
26295        // apply-time `.get(<stale-canonical-const>)` returning `None`
26296        // far from the derive-attr drift's commit. Peer with the
26297        // sibling
26298        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26299        // (ca463a4) and
26300        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26301        // pins on the M3 collection-slot atom axes — same discipline
26302        // both collection-slot lifts established, extended here to the
26303        // singleton `:entrada` mesh-slot atom axis, the last M3
26304        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
26305        // axis on the Aplicacao surface without a lifted serde-key
26306        // peer.
26307        let e = Entrada {
26308            host: "checkout.quero.cloud".into(),
26309            para: "cart".into(),
26310            paths: vec!["/cart".into()],
26311            port: 8080,
26312        };
26313        let json = serde_json::to_string(&e).unwrap();
26314        for key in [
26315            crate::ENTRADA_KEY_HOST,
26316            crate::ENTRADA_KEY_PARA,
26317            crate::ENTRADA_KEY_PATHS,
26318            crate::ENTRADA_KEY_PORT,
26319        ] {
26320            let quoted = format!("\"{key}\"");
26321            assert!(
26322                json.contains(&quoted),
26323                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
26324                 byte-sequence {quoted} verbatim in the JSON emission \
26325                 (got: {json})",
26326            );
26327        }
26328    }
26329
26330    #[test]
26331    fn entrada_key_consts_are_pairwise_distinct() {
26332        // Cross-axis drift-detection pin: a future collapse of the four
26333        // canonical [`Entrada`] singleton byte-strings onto the same
26334        // value (e.g. an accidental copy-paste flip of
26335        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
26336        // silently reroute every downstream probe on one axis onto the
26337        // sibling axis's overlay entry and pass every propagation-probe
26338        // test that expected only the stale axis's value — the
26339        // Gateway/HTTPRoute emitter would read the hostname string
26340        // where the destination-Servico name was expected (or vice
26341        // versa), the admission-webhook cross-check would compare the
26342        // wrong pair of values, and the resulting Gateway resource
26343        // would either be admitted with garbage or rejected at the
26344        // controller far from the rebrand commit's source. Peer of the
26345        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
26346        // tetrad (40cc4e5), the two-way distinct pin on the
26347        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
26348        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
26349        // triad (ca463a4).
26350        let all = [
26351            crate::ENTRADA_KEY_HOST,
26352            crate::ENTRADA_KEY_PARA,
26353            crate::ENTRADA_KEY_PATHS,
26354            crate::ENTRADA_KEY_PORT,
26355        ];
26356        for (i, a) in all.iter().enumerate() {
26357            for b in all.iter().skip(i + 1) {
26358                assert_ne!(
26359                    a, b,
26360                    "ENTRADA_KEY_* consts must be pairwise-distinct \
26361                     canonical byte-sequences — got `{a}` == `{b}`",
26362                );
26363            }
26364        }
26365    }
26366
26367    #[test]
26368    fn entrada_key_consts_are_lower_camel_case_shape() {
26369        // Shape-pin: every `ENTRADA_KEY_*` const must be a
26370        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26371        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26372        // leading capital, no whitespace / dots) — the canonical shape
26373        // the `#[serde(rename_all = "camelCase")]` derive produces on
26374        // [`Entrada`]. A future flip to a non-camelCase attribute at
26375        // the derive surfaces both here (this test fails on the
26376        // stale-constant shape) and at
26377        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
26378        // test fails on the mismatch between const and derive). Peer
26379        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
26380        // and `contrato_key_consts_are_lower_camel_case_shape`
26381        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
26382        // entry axes.
26383        for key in [
26384            crate::ENTRADA_KEY_HOST,
26385            crate::ENTRADA_KEY_PARA,
26386            crate::ENTRADA_KEY_PATHS,
26387            crate::ENTRADA_KEY_PORT,
26388        ] {
26389            assert!(
26390                !key.is_empty(),
26391                "ENTRADA_KEY_* must be non-empty (got {key:?})"
26392            );
26393            let first = key.chars().next().unwrap();
26394            assert!(
26395                first.is_ascii_lowercase(),
26396                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
26397                 (got {key:?}, leads with {first:?})",
26398            );
26399            assert!(
26400                key.chars().all(|c| c.is_ascii_alphanumeric()),
26401                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
26402                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26403            );
26404        }
26405    }
26406
26407    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
26408
26409    #[test]
26410    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
26411        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
26412        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
26413        // [`crate::POLITICAS_KEY_RETRIES`] /
26414        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
26415        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
26416        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
26417        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
26418        // on [`MeshPolicy`] emits. Three of the five axes
26419        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
26420        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
26421        // camelCase transforms — the derive-attribute is load-bearing
26422        // on those, unlike the sibling `Entrada` / `Membro` /
26423        // `WitContract` structs whose fields are all lowercase-single-
26424        // word and where the derive is a no-op on every axis.
26425        // Serialize a fully-populated [`MeshPolicy`] (every axis
26426        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
26427        // on none of the five slots) and pin that each canonical
26428        // byte-sequence appears verbatim in the JSON — a future
26429        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26430        // verbatim-field-name flip at the derive attribute (any of
26431        // which would silently break every downstream JSON consumer
26432        // that reaches for one of the five consts via
26433        // `Value::get(...)` — the future M4 per-edge `:politicas`
26434        // overlay projection onto Cilium `L7Rules` and Gateway API
26435        // `HTTPRoute` backend timeouts, the future
26436        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26437        // admission-time mesh-policy cross-check, the future
26438        // `feira lint` per-`:politicas` bound-check gate) surfaces here
26439        // as a build-time test failure at `aplicacao.rs`, not as an
26440        // apply-time `.get(<stale-canonical-const>)` returning `None`
26441        // far from the derive-attr drift's commit. Peer with the
26442        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
26443        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26444        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
26445        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
26446        // atom axes — same discipline every M3 sibling lift
26447        // established, extended here to the singleton `:politicas`
26448        // mesh-slot atom axis, closing the last M3 typed-struct
26449        // top-level `#[serde(rename_all = "camelCase")]` axis on the
26450        // Aplicacao surface without a lifted serde-key peer.
26451        let p = MeshPolicy {
26452            timeout: Some(Duration::from_secs(30)),
26453            retries: Some(3),
26454            circuit_breaker: Some(CircuitBreaker {
26455                max_failures: 5,
26456                window: Duration::from_secs(60),
26457            }),
26458            mtls_required: Some(true),
26459            rate_limit: Some(RateLimit {
26460                rate: 100,
26461                window: Duration::from_secs(1),
26462            }),
26463        };
26464        let json = serde_json::to_string(&p).unwrap();
26465        for key in [
26466            crate::POLITICAS_KEY_TIMEOUT,
26467            crate::POLITICAS_KEY_RETRIES,
26468            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26469            crate::POLITICAS_KEY_MTLS_REQUIRED,
26470            crate::POLITICAS_KEY_RATE_LIMIT,
26471        ] {
26472            let quoted = format!("\"{key}\"");
26473            assert!(
26474                json.contains(&quoted),
26475                "serialized MeshPolicy must carry the lifted \
26476                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
26477                 JSON emission (got: {json})",
26478            );
26479        }
26480    }
26481
26482    #[test]
26483    fn politicas_key_consts_are_pairwise_distinct() {
26484        // Cross-axis drift-detection pin: a future collapse of the five
26485        // canonical [`MeshPolicy`] singleton byte-strings onto the same
26486        // value (e.g. an accidental copy-paste flip of
26487        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
26488        // would silently reroute every downstream probe on one axis
26489        // onto the sibling axis's overlay entry and pass every
26490        // propagation-probe test that expected only the stale axis's
26491        // value — the M4 per-edge `:politicas` overlay projection would
26492        // read the retry-count string where the timeout duration was
26493        // expected (or vice versa), the CR materializer's admission
26494        // cross-check would compare the wrong pair of values, and the
26495        // resulting mesh reconciler would either bind the wrong axis
26496        // or reject the resource at reconcile far from the rebrand
26497        // commit's source. Peer of the sibling four-way distinct pin
26498        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
26499        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
26500        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
26501        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
26502        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26503        let all = [
26504            crate::POLITICAS_KEY_TIMEOUT,
26505            crate::POLITICAS_KEY_RETRIES,
26506            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26507            crate::POLITICAS_KEY_MTLS_REQUIRED,
26508            crate::POLITICAS_KEY_RATE_LIMIT,
26509        ];
26510        for (i, a) in all.iter().enumerate() {
26511            for b in all.iter().skip(i + 1) {
26512                assert_ne!(
26513                    a, b,
26514                    "POLITICAS_KEY_* consts must be pairwise-distinct \
26515                     canonical byte-sequences — got `{a}` == `{b}`",
26516                );
26517            }
26518        }
26519    }
26520
26521    #[test]
26522    fn politicas_key_consts_are_lower_camel_case_shape() {
26523        // Shape-pin: every `POLITICAS_KEY_*` const must be a
26524        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26525        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26526        // leading capital, no whitespace / dots) — the canonical shape
26527        // the `#[serde(rename_all = "camelCase")]` derive produces on
26528        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
26529        // at the derive surfaces both here (this test fails on the
26530        // stale-constant shape) and at
26531        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26532        // (that test fails on the mismatch between const and derive).
26533        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
26534        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26535        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26536        // (ca463a4) on the sibling M3 typed-struct axes.
26537        for key in [
26538            crate::POLITICAS_KEY_TIMEOUT,
26539            crate::POLITICAS_KEY_RETRIES,
26540            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26541            crate::POLITICAS_KEY_MTLS_REQUIRED,
26542            crate::POLITICAS_KEY_RATE_LIMIT,
26543        ] {
26544            assert!(
26545                !key.is_empty(),
26546                "POLITICAS_KEY_* must be non-empty (got {key:?})"
26547            );
26548            let first = key.chars().next().unwrap();
26549            assert!(
26550                first.is_ascii_lowercase(),
26551                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
26552                 byte (got {key:?}, leads with {first:?})",
26553            );
26554            assert!(
26555                key.chars().all(|c| c.is_ascii_alphanumeric()),
26556                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
26557                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26558            );
26559        }
26560    }
26561
26562    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
26563
26564    #[test]
26565    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
26566        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
26567        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
26568        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
26569        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
26570        // [`CircuitBreaker`] emits inside the
26571        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
26572        // two axes (`max_failures` → `maxFailures`) is a non-trivial
26573        // camelCase transform — the derive-attribute is load-bearing on
26574        // that axis, unlike the sibling `window` field where the derive
26575        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
26576        // pin that each canonical byte-sequence appears verbatim in the
26577        // JSON — a future accidental `rename_all = "snake_case"` /
26578        // `"kebab-case"` / verbatim-field-name flip at the derive
26579        // attribute (any of which would silently break every downstream
26580        // JSON consumer that reaches for one of the two consts via
26581        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
26582        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
26583        // per-edge `:politicas` overlay projection onto the mesh's
26584        // per-backend consecutive-failure-counter tripping threshold, the
26585        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26586        // admission-time breaker cross-check, the future `feira lint`
26587        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
26588        // here as a build-time test failure at `aplicacao.rs`, not as an
26589        // apply-time `.get(<stale-canonical-const>)` returning `None`
26590        // far from the derive-attr drift's commit. Peer with the sibling
26591        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26592        // (b55cca7) parent-axis pin — that test pins the outer
26593        // sub-block key the derive on [`MeshPolicy`] emits, this test
26594        // pins the inner keys the derive on the payload type emits, so
26595        // the two together lock the whole [`MeshPolicy`] breaker-tuning
26596        // shape end-to-end at build time.
26597        let cb = CircuitBreaker {
26598            max_failures: 5,
26599            window: Duration::from_secs(60),
26600        };
26601        let json = serde_json::to_string(&cb).unwrap();
26602        for key in [
26603            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26604            crate::CIRCUIT_BREAKER_KEY_WINDOW,
26605        ] {
26606            let quoted = format!("\"{key}\"");
26607            assert!(
26608                json.contains(&quoted),
26609                "serialized CircuitBreaker must carry the lifted \
26610                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
26611                 in the JSON emission (got: {json})",
26612            );
26613        }
26614    }
26615
26616    #[test]
26617    fn circuit_breaker_key_consts_are_pairwise_distinct() {
26618        // Cross-axis drift-detection pin: a future collapse of the two
26619        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
26620        // same value (e.g. an accidental copy-paste flip of
26621        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
26622        // `"maxFailures"`) would silently reroute every downstream
26623        // probe on one axis onto the sibling axis's overlay entry and
26624        // pass every propagation-probe test that expected only the
26625        // stale axis's value — the M4 per-edge `:politicas` overlay
26626        // projection would read the failure-count where the window
26627        // duration was expected (or vice versa), the CR materializer's
26628        // admission cross-check would compare the wrong pair of values,
26629        // and the resulting mesh reconciler would either bind the wrong
26630        // axis or reject the resource at reconcile far from the rebrand
26631        // commit's source. Peer of the sibling five-way distinct pin on
26632        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
26633        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
26634        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
26635        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
26636        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26637        let all = [
26638            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26639            crate::CIRCUIT_BREAKER_KEY_WINDOW,
26640        ];
26641        for (i, a) in all.iter().enumerate() {
26642            for b in all.iter().skip(i + 1) {
26643                assert_ne!(
26644                    a, b,
26645                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
26646                     canonical byte-sequences — got `{a}` == `{b}`",
26647                );
26648            }
26649        }
26650    }
26651
26652    #[test]
26653    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
26654        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
26655        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26656        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26657        // leading capital, no whitespace / dots) — the canonical shape
26658        // the `#[serde(rename_all = "camelCase")]` derive produces on
26659        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
26660        // at the derive surfaces both here (this test fails on the
26661        // stale-constant shape) and at
26662        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
26663        // (that test fails on the mismatch between const and derive).
26664        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
26665        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
26666        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26667        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26668        // (ca463a4) on the sibling M3 typed-struct axes.
26669        for key in [
26670            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26671            crate::CIRCUIT_BREAKER_KEY_WINDOW,
26672        ] {
26673            assert!(
26674                !key.is_empty(),
26675                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
26676            );
26677            let first = key.chars().next().unwrap();
26678            assert!(
26679                first.is_ascii_lowercase(),
26680                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
26681                 byte (got {key:?}, leads with {first:?})",
26682            );
26683            assert!(
26684                key.chars().all(|c| c.is_ascii_alphanumeric()),
26685                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
26686                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26687            );
26688        }
26689    }
26690
26691    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
26692
26693    #[test]
26694    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
26695        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
26696        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
26697        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
26698        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
26699        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
26700        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
26701        // [`Placement`] emits. One of the four axes (`shard_key` →
26702        // `shardKey`) is a non-trivial camelCase transform — the
26703        // derive-attribute is load-bearing on that axis, unlike the
26704        // sibling `estrategia` / `clusters` / `affinity` axes whose
26705        // source-side field names carry no `_` and where the derive is a
26706        // no-op. Serialize a fully-populated [`Placement`] (both
26707        // `Option`-carrying axes `Some(_)` so
26708        // `skip_serializing_if = "Option::is_none"` fires on neither of
26709        // the two optional slots) and pin that each canonical
26710        // byte-sequence appears verbatim in the JSON — a future
26711        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26712        // verbatim-field-name flip at the derive attribute (any of which
26713        // would silently break every downstream consumer that reaches
26714        // for one of the four consts via
26715        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
26716        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
26717        // aggregator's per-cluster fanout filter keying off
26718        // `placement.clusters`, the M3 shard-pool dispatch materializer
26719        // keying off `placement.shardKey`, the M3 Adaptive compression
26720        // pass weighting off `placement.affinity`, every downstream
26721        // dispatcher branching on `placement.estrategia`, the future
26722        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26723        // admission-time placement cross-check, the future `feira lint`
26724        // per-`:placement` bound-check gate) surfaces here as a
26725        // build-time test failure at `aplicacao.rs`, not as an
26726        // apply-time `.get(<stale-canonical-const>)` returning `None`
26727        // far from the derive-attr drift's commit. Peer with the sibling
26728        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26729        // (b55cca7),
26730        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
26731        // (468e959),
26732        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
26733        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26734        // (ca463a4), and
26735        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26736        // pins on the M3 collection-slot / singleton-slot atom axes —
26737        // closes the last M3 typed-struct top-level
26738        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
26739        // surface without a drift-detection pin.
26740        let p = Placement {
26741            estrategia: PlacementStrategy::Sharded,
26742            clusters: vec!["rio".into(), "mar".into()],
26743            affinity: Some("data-locality".into()),
26744            shard_key: Some("$tenantId".into()),
26745        };
26746        let json = serde_json::to_string(&p).unwrap();
26747        for key in [
26748            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26749            crate::M3_PLACEMENT_KEY_CLUSTERS,
26750            crate::M3_PLACEMENT_KEY_AFFINITY,
26751            crate::M3_PLACEMENT_KEY_SHARD_KEY,
26752        ] {
26753            let quoted = format!("\"{key}\"");
26754            assert!(
26755                json.contains(&quoted),
26756                "serialized Placement must carry the lifted \
26757                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
26758                 the JSON emission (got: {json})",
26759            );
26760        }
26761    }
26762
26763    #[test]
26764    fn m3_placement_key_consts_are_pairwise_distinct() {
26765        // Cross-axis drift-detection pin: a future collapse of the four
26766        // canonical [`Placement`] sub-block byte-strings onto the same
26767        // value (e.g. an accidental copy-paste flip of
26768        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
26769        // `"affinity"`) would silently reroute every downstream probe on
26770        // one axis onto the sibling axis's overlay entry and pass every
26771        // propagation-probe test that expected only the stale axis's
26772        // value — the M3 shard-pool dispatch materializer would read the
26773        // affinity placement-hint where the shard-selection template was
26774        // expected (or vice versa), the M3 Adaptive compression pass's
26775        // cross-check would compare the wrong pair of values, and the
26776        // resulting placement engine would either bind the wrong axis or
26777        // reject the resource at reconcile far from the rebrand commit's
26778        // source. Peer of the sibling two-way distinct pin on the
26779        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
26780        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
26781        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
26782        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
26783        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
26784        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26785        let all = [
26786            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26787            crate::M3_PLACEMENT_KEY_CLUSTERS,
26788            crate::M3_PLACEMENT_KEY_AFFINITY,
26789            crate::M3_PLACEMENT_KEY_SHARD_KEY,
26790        ];
26791        for (i, a) in all.iter().enumerate() {
26792            for b in all.iter().skip(i + 1) {
26793                assert_ne!(
26794                    a, b,
26795                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
26796                     canonical byte-sequences — got `{a}` == `{b}`",
26797                );
26798            }
26799        }
26800    }
26801
26802    #[test]
26803    fn m3_placement_key_consts_are_lower_camel_case_shape() {
26804        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
26805        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26806        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26807        // leading capital, no whitespace / dots) — the canonical shape
26808        // the `#[serde(rename_all = "camelCase")]` derive produces on
26809        // [`Placement`]. A future flip to a non-camelCase attribute at
26810        // the derive surfaces both here (this test fails on the stale-
26811        // constant shape) and at
26812        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
26813        // (that test fails on the mismatch between const and derive).
26814        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
26815        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
26816        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
26817        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26818        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26819        // (ca463a4) on the sibling M3 typed-struct axes.
26820        for key in [
26821            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26822            crate::M3_PLACEMENT_KEY_CLUSTERS,
26823            crate::M3_PLACEMENT_KEY_AFFINITY,
26824            crate::M3_PLACEMENT_KEY_SHARD_KEY,
26825        ] {
26826            assert!(
26827                !key.is_empty(),
26828                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
26829            );
26830            let first = key.chars().next().unwrap();
26831            assert!(
26832                first.is_ascii_lowercase(),
26833                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
26834                 byte (got {key:?}, leads with {first:?})",
26835            );
26836            assert!(
26837                key.chars().all(|c| c.is_ascii_alphanumeric()),
26838                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
26839                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26840            );
26841        }
26842    }
26843
26844    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
26845    //    destination-facing L4 port resolver every per-Aplicacao renderer
26846    //    reaching for a per-destination Servico TCP port axis routes
26847    //    through. The four pin tests below fix the four-way accept-set
26848    //    the resolver must always honor: (:entrada-para-matches,
26849    //    :entrada-para-mismatches, :entrada-none-so-fallback,
26850    //    :entrada-port-non-default-honored) — drift on any arm surfaces
26851    //    at caixa-core build time rather than at cluster-apply time.
26852
26853    #[test]
26854    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
26855        // The typed `:entrada` block's `:para "cart"` matches the
26856        // queried destination, so the resolver returns the author-
26857        // declared `:port` scalar verbatim — the canonical "the
26858        // destination Servico IS the ingress apex, honor the typed
26859        // listener port" arm of the port-resolution dispatch.
26860        let mut spec = three_member_spec();
26861        if let Some(e) = spec.entrada.as_mut() {
26862            e.para = "cart".into();
26863            e.port = 9090;
26864        }
26865        assert_eq!(
26866            spec.port_for_destination("cart"),
26867            9090,
26868            "port_for_destination(entrada.para) must return entrada.port \
26869             verbatim, not the DEFAULT_SERVICO_PORT fallback"
26870        );
26871    }
26872
26873    #[test]
26874    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
26875        // The typed `:entrada` block names `:para "cart"`, but the
26876        // queried destination is `"payment"` — a Servico that
26877        // participates in the mesh graph but is not the ingress apex.
26878        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
26879        // canonical port floor, closing the "non-apex destination reads
26880        // the substrate default" arm. Same fixture the peer
26881        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
26882        // pin at caixa-mesh exercises through the CNP emit-side path;
26883        // this pin exercises the shared underlying resolver directly.
26884        let spec = three_member_spec();
26885        assert_eq!(
26886            spec.port_for_destination("payment"),
26887            DEFAULT_SERVICO_PORT,
26888            "port_for_destination(non-apex-destination) must route \
26889             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
26890        );
26891    }
26892
26893    #[test]
26894    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
26895        // Internal-only Aplicacao — no `:entrada` block declared. Every
26896        // per-destination port query falls back to the lifted
26897        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
26898        // the Aplicacao surface admits `:entrada None` (internal mesh
26899        // with no external gateway); every downstream renderer's per-
26900        // destination port axis must still resolve to a well-defined
26901        // scalar even without an ingress apex.
26902        let mut spec = three_member_spec();
26903        spec.entrada = None;
26904        assert_eq!(
26905            spec.port_for_destination("cart"),
26906            DEFAULT_SERVICO_PORT,
26907            "port_for_destination on an internal-only Aplicacao must \
26908             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
26909             every destination"
26910        );
26911        assert_eq!(
26912            spec.port_for_destination("payment"),
26913            DEFAULT_SERVICO_PORT,
26914            "port_for_destination on an internal-only Aplicacao must \
26915             fall back uniformly across every destination — the fallback \
26916             is not entrada-shape-conditional"
26917        );
26918    }
26919
26920    #[test]
26921    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
26922        // Structural pin against a hypothetical future refactor that
26923        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
26924        // the resolver (a "normalize to the default when the author's
26925        // port matches the substrate default" collapse) — that would
26926        // break renderer sites that carry meaning on the emitted port
26927        // value beyond bare equality (a future per-cluster listener-
26928        // audit that keys off the author-declared port, not the
26929        // resolved-with-fallback port). Pin that a non-default
26930        // entrada.port is returned verbatim so drift here surfaces at
26931        // caixa-core build time.
26932        let mut spec = three_member_spec();
26933        if let Some(e) = spec.entrada.as_mut() {
26934            e.para = "cart".into();
26935            e.port = 8443;
26936        }
26937        assert_ne!(
26938            8443, DEFAULT_SERVICO_PORT,
26939            "test fixture must probe a port distinct from \
26940             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
26941        );
26942        assert_eq!(
26943            spec.port_for_destination("cart"),
26944            8443,
26945            "port_for_destination(entrada.para) must return entrada.port \
26946             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
26947        );
26948    }
26949
26950    #[test]
26951    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
26952        // Apex-identity pair-invariant pin composing both substrate-
26953        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
26954        // and [`Entrada::destination`] — at the emit-side call shape
26955        // every per-Aplicacao renderer's ingress-apex L4 port reader
26956        // now takes. The invariant:
26957        //
26958        //   spec.port_for_destination(entrada.destination()) == entrada.port
26959        //
26960        // holds by construction under today's single-destination
26961        // `:entrada` slot (`destination()` returns `entrada.para`, and
26962        // the resolver's apex arm matches `para == destination` and
26963        // returns `entrada.port`), and every downstream consumer that
26964        // composes the two accessors at the ingress apex — the
26965        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
26966        // `backendRefs[0].port` emit-site path, the peer future M4 CR
26967        // materializer's admission-webhook that promotes the scalar to
26968        // a per-CR override overlay, every future per-Aplicacao snapshot
26969        // renderer's apex-facing L4 port reader — reaches through the
26970        // same composition. Pin the identity across four permutations
26971        // (`:para` × `:port` including a non-default port to exercise
26972        // the honor-verbatim arm and a non-cart `:para` to exercise
26973        // destination-agnostic identity) so a future refactor that
26974        // silently split either accessor's apex behavior surfaces at
26975        // caixa-core build time — a subtle `destination()` renaming
26976        // that returned `entrada.host.as_str()` instead of
26977        // `entrada.para.as_str()` would blow this pin loudly, closing
26978        // the last quiet failure mode the two lifts admit in composition.
26979        //
26980        // Peer discipline with the sibling caixa-mesh cross-crate pin
26981        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
26982        // on the two-renderer pair-invariant axis; this pin encodes the
26983        // same two-consumer coherence rule at the substrate-primitive
26984        // level so the invariant survives even if every renderer is
26985        // deleted.
26986        for (para, port) in [
26987            ("cart", DEFAULT_SERVICO_PORT),
26988            ("cart", 8443u16),
26989            ("payment", 9090u16),
26990            ("catalog", 443u16),
26991        ] {
26992            let mut spec = three_member_spec();
26993            if let Some(e) = spec.entrada.as_mut() {
26994                e.para = para.into();
26995                e.port = port;
26996            }
26997            let expected_port = spec
26998                .entrada()
26999                .expect("three_member_spec carries a typed `:entrada` block")
27000                .port();
27001            let composed_port = {
27002                let entrada = spec.entrada().expect("entrada present");
27003                spec.port_for_destination(entrada.destination())
27004            };
27005            assert_eq!(
27006                composed_port, expected_port,
27007                "`spec.port_for_destination(entrada.destination())` must \
27008                 equal `entrada.port` under today's single-destination \
27009                 `:entrada` slot — this is the apex-identity contract \
27010                 every downstream ingress-apex L4 port reader relies on. \
27011                 Input :entrada :para: {para:?}, :entrada :port: {port}"
27012            );
27013        }
27014    }
27015
27016    #[test]
27017    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
27018        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
27019        // per-`:entrada` apex-arm membership probe must key off
27020        // [`Entrada::destination`], not the raw `.para` field access.
27021        // Structurally: setting ONLY the `:entrada :para` field to a
27022        // fresh non-cart destination on an otherwise-well-formed
27023        // Aplicacao must (1) leave `e.destination()` byte-equal to
27024        // `e.para.as_str()` (the accessor is byte-projective by
27025        // definition), and (2) cause the resolver's apex arm to fire
27026        // and return `entrada.port` at exactly that new destination
27027        // while every other destination string falls through to
27028        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
27029        // membership check. Pins against a future silent detour that
27030        // (a) re-derived the apex-arm membership probe off
27031        // `e.para == destination` in `port_for_destination` instead of
27032        // `e.destination() == destination`, silently disagreeing with
27033        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
27034        // consumers (`entrada.destination()` at
27035        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
27036        // caixa-mesh/src/lib.rs:2739) that already reach through the
27037        // accessor, (b) accessor-side introduced a per-tenant alias
27038        // arm the caller was unaware of, silently rewriting an
27039        // author-declared `:para "cart"` value to a canary-aliased
27040        // form — the raw-field-access resolver would fall through to
27041        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
27042        // while the peer emit-site consumers landed on the aliased
27043        // destination, splitting the ingress-apex L4 port at
27044        // cluster-apply time.
27045        //
27046        // Peer of the sibling
27047        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
27048        // (d0de220) composition pin on the per-`:membros` refusal-arm
27049        // axis — same "the shape-gate predicate must route through the
27050        // substrate-primitive typed dispatch" discipline extended onto
27051        // the per-`:entrada` apex-arm membership-probe axis. Closes
27052        // the last unlifted `.para` production-code read site on
27053        // `Entrada` in `caixa-core` — after this converge every
27054        // `caixa-core` `.para` field access outside the accessor's own
27055        // body and outside the `WitContract` per-`:contratos` sibling
27056        // axis is either a test-side field-setter or a doc-comment
27057        // reference.
27058        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
27059            let mut spec = three_member_spec();
27060            if let Some(e) = spec.entrada.as_mut() {
27061                e.para = para.into();
27062                e.port = port;
27063            }
27064            let e = spec
27065                .entrada
27066                .as_ref()
27067                .expect("three_member_spec carries a typed `:entrada` block");
27068            assert_eq!(
27069                e.destination(),
27070                e.para.as_str(),
27071                "Entrada::destination must byte-equal the .para field \
27072                 access — an accessor-side detour that no longer \
27073                 projects the raw field would silently split this \
27074                 drift-detection test from the port_for_destination \
27075                 apex-arm membership probe",
27076            );
27077            assert_eq!(
27078                spec.port_for_destination(para),
27079                port,
27080                "port_for_destination must key off the accessor-projected \
27081                 destination and return `entrada.port` on the apex arm — \
27082                 input :entrada :para: {para:?}, :entrada :port: {port}",
27083            );
27084            assert_eq!(
27085                spec.port_for_destination("ghost-destination-never-a-member"),
27086                DEFAULT_SERVICO_PORT,
27087                "port_for_destination must fall through to \
27088                 DEFAULT_SERVICO_PORT on a non-matching destination \
27089                 under the accessor-projected membership check — input \
27090                 :entrada :para: {para:?}, :entrada :port: {port}",
27091            );
27092        }
27093    }
27094
27095    #[test]
27096    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
27097        // The canonical per-`:politicas :rate-limit` `:rate`
27098        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
27099        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
27100        // typed `u32` verbatim, byte-equal to the raw field access
27101        // across every representative value in the accept-set — `1` (the
27102        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
27103        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
27104        // carves out on the sibling `PolicyRateLimitZero` refusal),
27105        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
27106        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
27107        // `0` (a past-the-guard sentinel that pins the accessor doesn't
27108        // perform a silent bounds-collapse into `1` on the zero arm —
27109        // validate rejects zero but the accessor must ship the raw slot
27110        // verbatim so a validate-time gate regression surfaces at the
27111        // emit boundary rather than being silently absorbed), `u32::MAX`
27112        // (a past-the-guard sentinel that pins the accessor doesn't
27113        // perform a silent bounds-collapse through
27114        // `POLICY_RATE_LIMIT_MAX` at the return path).
27115        //
27116        // First sub-struct required-scalar accessor pin on the
27117        // `RateLimit` axis — sibling in shape to the peer
27118        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
27119        // required-`u32` accessor pin on the peer per-sub-struct
27120        // required-axis. Pins against a future silent detour that
27121        // re-derived the token capacity from a peer axis (an accidental
27122        // `self.window.as_secs() as u32` collapse that read the
27123        // rate-limit window duration as a token count), a `0 → 1`
27124        // cluster-default projection (which would silently absorb the
27125        // `PolicyRateLimitZero` refusal case at the accessor boundary),
27126        // or a bounds-collapsing accessor that clamped the return
27127        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
27128        // gate owns the bounds; the accessor must ship the raw slot
27129        // verbatim).
27130        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27131            let rl = RateLimit {
27132                rate,
27133                window: Duration::from_secs(1),
27134            };
27135            assert_eq!(
27136                rl.rate(),
27137                rate,
27138                "RateLimit::rate must return :politicas :rate-limit :rate \
27139                 verbatim (got {}, expected {rate})",
27140                rl.rate(),
27141            );
27142            assert_eq!(
27143                rl.rate(),
27144                rl.rate,
27145                "RateLimit::rate must byte-equal the raw .rate field \
27146                 access across every value in the u32 accept-set",
27147            );
27148        }
27149    }
27150
27151    #[test]
27152    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
27153        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27154        // `:rate-limit :rate` zero-floor arm must key off
27155        // [`RateLimit::rate`], not the raw `.rate` field access.
27156        // Structurally: a `RateLimit { rate: 0, window:
27157        // Duration::from_secs(1) }` embedded in a `:politicas
27158        // :rate-limit` slot must surface the `PolicyRateLimitZero`
27159        // refusal exactly, and a `RateLimit { rate: 1, window:
27160        // Duration::from_secs(1) }` (the lower boundary of the
27161        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
27162        // The pair jointly pins the accessor + validate-gate composition:
27163        // any future silent detour that had the accessor return a fresh
27164        // `1` on the zero arm (a `.rate().max(1)` collapse) would
27165        // silently absorb the `PolicyRateLimitZero` refusal at the
27166        // accessor boundary and the validate gate would accept a
27167        // struct-literal `RateLimit { rate: 0, .. }` — the composition
27168        // pin catches that at caixa-core build time.
27169        //
27170        // Peer of the sibling per-`CircuitBreaker`
27171        // [`CircuitBreaker::max_failures`] (3a74062) /
27172        // [`CircuitBreaker::window`] (373957f) accessor-composition
27173        // pins on the peer required-scalar axes — same "the validate /
27174        // shape-gate predicate must route through the substrate-primitive
27175        // typed dispatch" discipline extended onto the peer
27176        // per-`RateLimit` required-`u32` composition axis.
27177        let mut spec = three_member_spec();
27178        spec.politicas = MeshPolicy {
27179            rate_limit: Some(RateLimit {
27180                rate: 0,
27181                window: Duration::from_secs(1),
27182            }),
27183            ..MeshPolicy::default()
27184        };
27185        assert!(
27186            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
27187            "validate_politicas must reject rate == 0 with \
27188             PolicyRateLimitZero — the accessor and the validate gate \
27189             must route through the same substrate-primitive typed \
27190             dispatch on the :rate zero-floor arm",
27191        );
27192        spec.politicas = MeshPolicy {
27193            rate_limit: Some(RateLimit {
27194                rate: 1,
27195                window: Duration::from_secs(1),
27196            }),
27197            ..MeshPolicy::default()
27198        };
27199        assert!(
27200            spec.validate().is_ok(),
27201            "validate_politicas must accept rate == 1 (the lower \
27202             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
27203        );
27204    }
27205
27206    #[test]
27207    fn rate_limit_rate_projects_u32_by_copy() {
27208        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
27209        // `u32` is `Copy` and the accessor must return by value, not by
27210        // reference. Peer of the sibling per-`CircuitBreaker`
27211        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
27212        // peer required-scalar `:max-failures` axis, extended onto the
27213        // peer per-`RateLimit` required-`u32` copy-invariant shape —
27214        // the accessor's returned `u32` must outlive `&self` (multiple
27215        // calls must return equal values from a dropped-`&self` copy,
27216        // since the returned scalar carries no borrow), and calling the
27217        // accessor twice on the same RateLimit must yield the same
27218        // `u32` verbatim (idempotent, no side effects on `&self`).
27219        //
27220        // Pins against a future silent detour that returned `&u32`
27221        // (which would type-check but silently break every downstream
27222        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
27223        // first parameter is `u32`, and `&u32` would fold to a detached
27224        // copy at the call site with a `*` deref the sibling accessors
27225        // don't need), an accidental `.rate.wrapping_add(0)` detour that
27226        // returned a fresh copy through an arithmetic no-op (breaking a
27227        // future `const fn` regression), or a one-arm-only accessor
27228        // that returned a saturating value on some sentinel input
27229        // (breaking the pass-through invariant the sibling required-
27230        // scalar accessors carry).
27231        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27232            let rl = RateLimit {
27233                rate,
27234                window: Duration::from_secs(1),
27235            };
27236            let first = rl.rate();
27237            let second = rl.rate();
27238            assert_eq!(
27239                first, second,
27240                "RateLimit::rate must be idempotent — two successive \
27241                 calls on the same &self must return the same u32",
27242            );
27243            assert_eq!(
27244                first, rate,
27245                "RateLimit::rate must return :politicas :rate-limit :rate \
27246                 verbatim by copy — got {first}, expected {rate}",
27247            );
27248        }
27249    }
27250
27251    #[test]
27252    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
27253        // The canonical per-`:politicas :rate-limit` `:window`
27254        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
27255        // pin: [`RateLimit::window`] must return the
27256        // `:politicas :rate-limit :window` typed `Duration` verbatim,
27257        // byte-equal to the raw field access across every
27258        // representative value in the accept-set — `Duration::from_secs(1)`
27259        // (the `"s"` canonical window, the lower row of
27260        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
27261        // [`AplicacaoSpec::validate_politicas`] gate accepts via
27262        // [`is_canonical_rate_limit_window`]),
27263        // `Duration::from_secs(60)` (the `"m"` canonical window, the
27264        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
27265        // window, the upper row), `Duration::ZERO` (a past-the-guard
27266        // sentinel that pins the accessor doesn't perform a silent
27267        // bounds-collapse into `Duration::from_secs(1)` on the zero
27268        // arm — validate rejects an off-set window through
27269        // `PolicyRateLimitWindowNotCanonical` but the accessor must
27270        // ship the raw slot verbatim so a validate-time gate
27271        // regression surfaces at the emit boundary rather than being
27272        // silently absorbed), `Duration::from_millis(500)` (a
27273        // sub-canonical past-the-guard sentinel that pins the accessor
27274        // doesn't silently normalize a non-canonical fractional
27275        // magnitude onto the nearest canonical row).
27276        //
27277        // Second sub-struct required-scalar accessor pin on the
27278        // `RateLimit` axis — sibling in shape to the just-landed
27279        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
27280        // accessor pin on the peer per-sub-struct required-axis,
27281        // extended onto the per-`RateLimit` required-`Duration` axis.
27282        // Pins against a future silent detour that re-derived the
27283        // refill period from a peer axis (an accidental
27284        // `Duration::from_secs(self.rate as u64)` collapse that read
27285        // the rate-limit token capacity as a refill-interval
27286        // duration), a `Duration::ZERO → Duration::from_secs(1)`
27287        // canonical-default projection (which would silently absorb
27288        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
27289        // accessor boundary), or a canonical-set-collapsing accessor
27290        // that clamped the return through [`rate_limit_window_unit`]
27291        // (the `AplicacaoSpec::validate` gate owns the canonical-set
27292        // membership; the accessor must ship the raw slot verbatim).
27293        for window in [
27294            Duration::from_secs(1),
27295            Duration::from_secs(60),
27296            Duration::from_secs(3600),
27297            Duration::ZERO,
27298            Duration::from_millis(500),
27299        ] {
27300            let rl = RateLimit { rate: 100, window };
27301            assert_eq!(
27302                rl.window(),
27303                window,
27304                "RateLimit::window must return :politicas :rate-limit :window \
27305                 verbatim (got {:?}, expected {window:?})",
27306                rl.window(),
27307            );
27308            assert_eq!(
27309                rl.window(),
27310                rl.window,
27311                "RateLimit::window must byte-equal the raw .window field \
27312                 access across every value in the Duration accept-set",
27313            );
27314        }
27315    }
27316
27317    #[test]
27318    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
27319        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27320        // `:rate-limit :window` canonical-set arm must key off
27321        // [`RateLimit::window`], not the raw `.window` field access.
27322        // Structurally: a `RateLimit { window: Duration::from_millis(500),
27323        // .. }` embedded in a `:politicas :rate-limit` slot must
27324        // surface the `PolicyRateLimitWindowNotCanonical` refusal
27325        // exactly (with the sub-canonical `Duration::from_millis(500)`
27326        // magnitude carried through verbatim), and a `RateLimit
27327        // { window: Duration::from_secs(1), .. }` (the lower row of
27328        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
27329        // The pair jointly pins the accessor + validate-gate
27330        // composition: any future silent detour that had the accessor
27331        // normalize the off-set window to the nearest canonical row
27332        // (a `.window().max(Duration::from_secs(1))` collapse, or a
27333        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
27334        // collapse) would silently absorb the
27335        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
27336        // boundary — including a drift in the error's `window` payload
27337        // (the emit-side diagnostic reader keys off the offending
27338        // magnitude verbatim, so a normalization at the accessor
27339        // boundary would silently pin the wrong magnitude in the
27340        // refusal). The composition pin catches that at caixa-core
27341        // build time.
27342        //
27343        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
27344        // (7f81a60) accessor-composition pin on the peer required-
27345        // scalar `:rate` axis — same "the validate / shape-gate
27346        // predicate must route through the substrate-primitive typed
27347        // dispatch, and the error payload must project through the
27348        // same accessor" discipline extended onto the peer
27349        // per-`RateLimit` required-`Duration` composition axis.
27350        let mut spec = three_member_spec();
27351        spec.politicas = MeshPolicy {
27352            rate_limit: Some(RateLimit {
27353                rate: 100,
27354                window: Duration::from_millis(500),
27355            }),
27356            ..MeshPolicy::default()
27357        };
27358        match spec.validate() {
27359            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
27360                assert_eq!(
27361                    window,
27362                    Duration::from_millis(500),
27363                    "PolicyRateLimitWindowNotCanonical must carry the \
27364                     offending :window magnitude verbatim through the \
27365                     accessor — got {window:?}, expected 500ms",
27366                );
27367            }
27368            other => panic!(
27369                "validate_politicas must reject non-canonical :window \
27370                 with PolicyRateLimitWindowNotCanonical — the accessor \
27371                 and the validate gate must route through the same \
27372                 substrate-primitive typed dispatch on the :window \
27373                 canonical-set arm; got {other:?}",
27374            ),
27375        }
27376        spec.politicas = MeshPolicy {
27377            rate_limit: Some(RateLimit {
27378                rate: 100,
27379                window: Duration::from_secs(1),
27380            }),
27381            ..MeshPolicy::default()
27382        };
27383        assert!(
27384            spec.validate().is_ok(),
27385            "validate_politicas must accept window == Duration::from_secs(1) \
27386             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
27387        );
27388    }
27389
27390    #[test]
27391    fn rate_limit_window_projects_duration_by_copy() {
27392        // The by-copy pin: [`RateLimit::window`] returns `Duration`
27393        // by copy — `Duration` is `Copy` and the accessor must return
27394        // by value, not by reference. Peer of the sibling per-`RateLimit`
27395        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
27396        // required-scalar `:rate` axis, extended onto the peer
27397        // per-`RateLimit` required-`Duration` copy-invariant shape —
27398        // the accessor's returned `Duration` must outlive `&self`
27399        // (multiple calls must return equal values from a
27400        // dropped-`&self` copy, since the returned scalar carries no
27401        // borrow), and calling the accessor twice on the same
27402        // RateLimit must yield the same `Duration` verbatim
27403        // (idempotent, no side effects on `&self`).
27404        //
27405        // Pins against a future silent detour that returned
27406        // `&Duration` (which would type-check but silently break every
27407        // downstream `Duration`-by-value consumer —
27408        // [`is_canonical_rate_limit_window`]'s first parameter is
27409        // `Duration`, and `&Duration` would fold to a detached copy at
27410        // the call site with a `*` deref the sibling accessors don't
27411        // need), an accidental `.window + Duration::ZERO` detour that
27412        // returned a fresh copy through an arithmetic no-op (breaking
27413        // a future `const fn` regression), or a one-arm-only accessor
27414        // that returned a canonical fallback on some sentinel input
27415        // (breaking the pass-through invariant the sibling required-
27416        // scalar accessors carry).
27417        for window in [
27418            Duration::from_secs(1),
27419            Duration::from_secs(60),
27420            Duration::from_secs(3600),
27421            Duration::ZERO,
27422            Duration::from_millis(500),
27423        ] {
27424            let rl = RateLimit { rate: 100, window };
27425            let first = rl.window();
27426            let second = rl.window();
27427            assert_eq!(
27428                first, second,
27429                "RateLimit::window must be idempotent — two successive \
27430                 calls on the same &self must return the same Duration",
27431            );
27432            assert_eq!(
27433                first, window,
27434                "RateLimit::window must return :politicas :rate-limit :window \
27435                 verbatim by copy — got {first:?}, expected {window:?}",
27436            );
27437        }
27438    }
27439
27440    #[test]
27441    fn placement_estrategia_default_pins_m3_canonical_value() {
27442        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
27443        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
27444        // active-active-across-every-named-cluster arm, the closest
27445        // canonical M3 production reference the substrate carries and
27446        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
27447        // for every un-`:placement`-declared Aplicacao. Pinning the arm
27448        // here surfaces a future rebrand of the M3-canonical
27449        // distribution default (a widening to `Sharded` once the
27450        // substrate discovers hash-keyed distribution as the more
27451        // common production shape, a tightening to `SingleNode` for
27452        // stateful Erlang/OTP distributed-app-takeover semantics
27453        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
27454        // operator pins through a future `:placement-overrides` slot)
27455        // as a deliberate test edit, not a silent contract migration.
27456        // Peer of the sibling M2 per-supervisor value pins
27457        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
27458        // /
27459        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
27460        // extended onto the M3 mesh-primitive-defining `:placement
27461        // :estrategia` axis.
27462        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
27463    }
27464
27465    #[test]
27466    fn placement_strategy_default_routes_through_lifted_default() {
27467        // Composition pin: the [`Default for PlacementStrategy`] impl's
27468        // return arm must route through the substrate-canonical
27469        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
27470        // a raw `Self::Replicated` arm. Prior to the lift the impl
27471        // carried an inline `Self::Replicated` arm with no compile-time
27472        // link back to the shared M3-canonical `Replicated` arm the
27473        // paired [`Default for Placement`] impl's struct-literal
27474        // `estrategia` field, the serde-side `#[serde(default)]` on
27475        // [`Placement::estrategia`] that resolves an author-omitted
27476        // wire-form `:placement :estrategia` scalar through the impl,
27477        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
27478        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
27479        // routes through [`Placement::default`] which routes through the
27480        // strategy default) all key off — so a future rebrand of the
27481        // M3-canonical distribution default would have had to be threaded
27482        // through the `Default` impl and the three peer routes in
27483        // lockstep or the four consumers would silently split. Byte-
27484        // parity against the lifted constant closes the split. Peer of
27485        // the sibling
27486        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
27487        // /
27488        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
27489        // composition pins on the M2 per-supervisor axes.
27490        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
27491    }
27492
27493    #[test]
27494    fn placement_default_estrategia_routes_through_lifted_default() {
27495        // Composition pin: the [`Default for Placement`] impl's
27496        // struct-literal `estrategia` field must route through the
27497        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
27498        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
27499        // impl that the sibling
27500        // `placement_strategy_default_routes_through_lifted_default` pin
27501        // already routes onto the constant). Structurally: every
27502        // `Placement::default()` call must yield an `estrategia` field
27503        // byte-equal to the lifted constant so the two paired defaults —
27504        // the [`Default for PlacementStrategy`] impl arm and the
27505        // struct-literal default arm here — cannot silently split on any
27506        // future M3-canonical distribution-default rebrand. Peer of the
27507        // sibling M2
27508        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
27509        // byte-parity pin on the [`Default for SupervisorSpec`]
27510        // struct-literal `estrategia` field extended onto the M3
27511        // mesh-primitive-defining slot family.
27512        assert_eq!(
27513            Placement::default().estrategia,
27514            PLACEMENT_ESTRATEGIA_DEFAULT,
27515        );
27516    }
27517
27518    #[test]
27519    fn placement_serde_default_estrategia_routes_through_lifted_default() {
27520        // Composition pin: the serde-side `#[serde(default)]` on
27521        // [`Placement::estrategia`] — the wire-format author-omitted
27522        // `:placement :estrategia` arm — must resolve onto the substrate-
27523        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
27524        // (via the [`Default for PlacementStrategy`] impl the sibling
27525        // `placement_strategy_default_routes_through_lifted_default` pin
27526        // already routes onto the constant). Structurally: a `Placement`
27527        // deserialized from a payload that omits the `estrategia` key
27528        // must yield an `estrategia` field byte-equal to the lifted
27529        // constant, so the wire-format author-omitted arm and the
27530        // [`PlacementStrategy::default`] impl arm cannot silently split
27531        // on any future M3-canonical distribution-default rebrand. Peer
27532        // of the sibling M2
27533        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
27534        // byte-parity pin on the wire-format author-omitted `:children
27535        // :restart` scalar extended onto the M3 mesh-primitive-defining
27536        // slot family.
27537        let omitted: Placement = serde_json::from_str("{}")
27538            .expect("Placement must deserialize with the estrategia key omitted");
27539        assert_eq!(
27540            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
27541            "an author-omitted :placement :estrategia slot must degrade onto \
27542             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
27543             {:?}, expected {:?})",
27544            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
27545        );
27546    }
27547}