Skip to main content

caixa_core/
aplicacao.rs

1//! Typed Aplicacao — the fourth caixa kind that turns a graph of
2//! Servicos into a single declarative application (mesh).
3//!
4//! See `theory/MESH-COMPOSITION.md` for the design frame: an
5//! Aplicacao composes [`crate::CaixaKind::Servico`] caixas via WIT-typed
6//! `:contratos` (inter-Servico edges), declares mesh-level
7//! `:politicas` (timeouts, retries, breakers, mTLS), pins
8//! `:placement` strategy (single-node / replicated / sharded), and
9//! exposes `:entrada` (gateway).
10//!
11//! ```lisp
12//! (defcaixa
13//!   :nome      "checkout"
14//!   :versao    "0.1.0"
15//!   :kind      Aplicacao
16//!   :membros   ((:caixa "catalog"     :versao "^0.1")
17//!               (:caixa "cart"        :versao "^0.1")
18//!               (:caixa "payment"     :versao "^0.2"))
19//!   :contratos ((:de "cart" :para "catalog"
20//!                :wit "wasi:http/proxy" :endpoint "/products/:id")
21//!               (:de "cart" :para "payment"
22//!                :wit "wasi:http/proxy" :endpoint "/charge"))
23//!   :politicas ((:timeout "30s")
24//!               (:retries 3)
25//!               (:circuit-breaker (:max-failures 5 :window "60s"))
26//!               (:mtls-required t))
27//!   :placement (:estrategia replicated
28//!               :clusters   ("rio" "mar" "plo"))
29//!   :entrada   (:host  "checkout.quero.cloud"
30//!               :para  "cart"
31//!               :paths ("/api/cart" "/api/products")))
32//! ```
33//!
34//! All the typed slots compose with the M2 primitives the Servicos
35//! they reference already declare (`:limits`, `:behavior`,
36//! `:upgrade-from`). The Aplicacao adds the *graph-level*
37//! standardization on top.
38
39use std::time::Duration;
40
41use serde::{Deserialize, Serialize};
42use thiserror::Error;
43
44use crate::supervisor; // we reuse the duration-string codec at module scope
45
46// ── inter-Servico contracts ──────────────────────────────────────────
47
48/// One typed edge in the Aplicacao graph. The build refuses any
49/// contract whose `:de` or `:para` doesn't appear in `:membros`, and
50/// (M3+) cross-checks the `:wit` shape against both Servicos'
51/// declared imports/exports.
52#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
53#[serde(rename_all = "camelCase")]
54pub struct WitContract {
55    /// Caller Servico — must reference an entry in the Aplicacao's
56    /// `:membros`. The Servico's caixa.lisp must declare a matching
57    /// `:capabilities` import for the `:wit` world.
58    pub de: String,
59
60    /// Callee Servico — must reference an entry in `:membros`. The
61    /// Servico must declare a matching `:capabilities` export.
62    pub para: String,
63
64    /// WIT world reference — e.g. `"wasi:http/proxy"`,
65    /// `"wasi:keyvalue/store"`, `"nats:pub-sub"`. Strings for V0;
66    /// M4 promotes these to a typed enum once the WIT registry
67    /// stabilizes in tatara-lisp.
68    pub wit: String,
69
70    /// HTTP endpoint path, present when `:wit` is HTTP-shaped.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub endpoint: Option<String>,
73
74    /// NATS / event-stream subject, present when `:wit` is pub-sub-shaped.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub subject: Option<String>,
77
78    /// Key/value or queue slot, present when `:wit` is store-shaped.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub slot: Option<String>,
81}
82
83/// Canonical lowercase byte-prefix set the substrate's WIT-shape
84/// dispatch routes `wasi:http/*` / `http:*` values through as the
85/// HTTP-shaped arm. The single source of truth every consumer that
86/// classifies a `:wit` value as HTTP-shaped consults —
87/// [`WitContract::is_http`] on the typed contract, the
88/// `AplicacaoSpec::validate` positive-sweep test's payload-dispatch
89/// helper, and every future renderer that routes an L7 emission off a
90/// bare `&str` (the M4 per-edge WIT registry resolver, the future
91/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer). Spelled
92/// exactly as the [`is_wit_world_ref`][iwr] predicate documents the
93/// canonical lowercase prefixes ("`wasi:http/`, `nats:`,
94/// `wasi:keyvalue/`, `kafka:`, `kv:`, `http:`") so drift between the
95/// substrate's accept-set and this crate's dispatch-set is a
96/// build-time compile error (unused-import), not a per-renderer
97/// silent L7-→-L4 demotion at apply time.
98///
99/// [iwr]: crate::render::is_wit_world_ref
100pub const WIT_HTTP_SHAPE_PREFIXES: &[&str] = &["wasi:http/", "http:"];
101
102/// Canonical lowercase byte-prefix set the substrate's WIT-shape
103/// dispatch routes `nats:*` / `kafka:*` values through as the
104/// pub-sub-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
105/// [`WIT_STORE_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
106/// HTTP constant's docstring for the full lift rationale.
107pub const WIT_PUBSUB_SHAPE_PREFIXES: &[&str] = &["nats:", "kafka:"];
108
109/// Canonical lowercase byte-prefix set the substrate's WIT-shape
110/// dispatch routes `wasi:keyvalue/*` / `kv:*` values through as the
111/// key/value-store-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
112/// [`WIT_PUBSUB_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
113/// HTTP constant's docstring for the full lift rationale.
114pub const WIT_STORE_SHAPE_PREFIXES: &[&str] = &["wasi:keyvalue/", "kv:"];
115
116/// True when `wit` — a raw `:contratos :wit` value — starts with any
117/// entry in the `prefixes` accept-set. The single canonical
118/// prefix-driven WIT-shape classification combinator every peer
119/// per-shape predicate ([`wit_shape_is_http`], [`wit_shape_is_pubsub`],
120/// [`wit_shape_is_store`]) routes through, closing the 3-site
121/// duplication of the `PREFIXES.iter().any(|p| wit.starts_with(p))`
122/// combinator the prior open-coded implementations each carried.
123///
124/// A future 4th WIT-shape dispatch arm (a hypothetical `wasi:sockets/*`
125/// / `tcp:*` transport-layer shape, an `oci:*` capability-import
126/// carrier) becomes exactly one new [`WIT_*_SHAPE_PREFIXES`] const +
127/// one new `wit_shape_is_<name>` one-liner routing through this
128/// combinator, not a fourth copy of the `iter().any(starts_with)`
129/// combinator paired to its own prefix-set. Same "one canonical
130/// combinator, thin per-arm projections" discipline the peer
131/// [`WitTarget::payload_pair`] (6788ed6) already established for the
132/// downstream per-arm `(field, payload)` dispatch, extended to the
133/// upstream per-arm `PREFIXES → bool` dispatch.
134///
135/// Declared `pub const fn` — the four peer classifiers
136/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
137/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) route through
138/// this combinator in `const`-eval context, so the raw `&str → bool`
139/// WIT-shape dispatch reaches every substrate-side `const`-context
140/// consumer (the module-scope `const _: () = assert!(…)` canonical-
141/// accept-set + partition-witness pins immediately below the four
142/// peer classifiers, any future M4
143/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
144/// webhook `const fn` per-`:contratos :wit` shape-arm resolver over a
145/// raw &str, any future `const fn` per-`:contratos`-edge WIT-registry
146/// prefix-set overlay resolver over the substrate primitive that fans
147/// on the shape arm at compile time) through the same typed dispatch
148/// on the substrate primitive at const-eval time as at runtime. The
149/// prior `prefixes.iter().any(|p| wit.starts_with(p))` body carried
150/// non-`const` bounds on stable Rust 1.94 (`.iter()` / `.any()` /
151/// `str::starts_with(&str)` via the non-`const` `Pattern` trait); the
152/// new body routes the per-prefix probe through a manual byte-level
153/// `starts_with` loop over the paired `str::as_bytes` (`pub const fn`)
154/// slice projections, dispatching through primitive-`u8` `!=` and
155/// `usize` comparison + `pub const fn` `<[u8]>::len` and const-stable
156/// slice indexing (since Rust 1.79) — every operation `const`-eval-
157/// callable on stable, no iterator methods, no `Pattern` trait.
158#[must_use]
159pub const fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
160    let bytes = wit.as_bytes();
161    let mut i = 0;
162    while i < prefixes.len() {
163        let prefix = prefixes[i].as_bytes();
164        if prefix.len() <= bytes.len() {
165            let mut j = 0;
166            let mut matches = true;
167            while j < prefix.len() {
168                if bytes[j] != prefix[j] {
169                    matches = false;
170                    break;
171                }
172                j += 1;
173            }
174            if matches {
175                return true;
176            }
177        }
178        i += 1;
179    }
180    false
181}
182
183/// True when `wit` — a raw `:contratos :wit` value — targets an
184/// HTTP-shaped WIT world (starts with any prefix in
185/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
186/// consumer routes L7-HTTP emission through, whether they carry a
187/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
188/// here) or only the raw `wit` string (the positive-sweep test's
189/// payload-dispatch helper, future renderers that classify off a
190/// bare `&str`). Lifting to a free function makes the shape-dispatch
191/// arm reachable without materializing a scratch [`WitContract`] at
192/// every classification point, and pins the six-prefix accept-set at
193/// one place so future additions (e.g. an `"https:"` peer of
194/// `"http:"`) reach every consumer by construction. Routes through
195/// the lifted [`wit_shape_matches`] combinator so the
196/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
197/// canonical primitive, not one open-coded copy per peer arm.
198///
199/// Declared `pub const fn` — routes through the peer `pub const fn`
200/// [`wit_shape_matches`] combinator so every substrate-side
201/// `const`-context WIT-shape-arm-classifier consumer (the module-scope
202/// `const _: () = assert!(…)` canonical-accept-set + partition-witness
203/// pins immediately below, any future M4 admission-webhook
204/// `const fn` per-`:contratos :wit` HTTP-arm resolver over a raw &str)
205/// reaches through the same typed dispatch on the substrate primitive
206/// at const-eval time as at runtime.
207#[must_use]
208pub const fn wit_shape_is_http(wit: &str) -> bool {
209    wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES)
210}
211
212/// True when `wit` — a raw `:contratos :wit` value — targets a
213/// pub-sub-shaped WIT world (starts with any prefix in
214/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
215/// [`wit_shape_is_store`] on the shape-dispatch axis; see
216/// [`wit_shape_is_http`] for the lift rationale. Routes through the
217/// lifted [`wit_shape_matches`] combinator.
218///
219/// Declared `pub const fn` — sibling in `const`-eval posture to the
220/// peer [`wit_shape_is_http`] classifier; see that function's `const`
221/// posture-block for the full rationale.
222#[must_use]
223pub const fn wit_shape_is_pubsub(wit: &str) -> bool {
224    wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES)
225}
226
227/// True when `wit` — a raw `:contratos :wit` value — targets a
228/// key/value-store-shaped WIT world (starts with any prefix in
229/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
230/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
231/// [`wit_shape_is_http`] for the lift rationale. Routes through the
232/// lifted [`wit_shape_matches`] combinator.
233///
234/// Declared `pub const fn` — sibling in `const`-eval posture to the
235/// peer [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] classifiers;
236/// see [`wit_shape_is_http`]'s `const` posture-block for the full
237/// rationale.
238#[must_use]
239pub const fn wit_shape_is_store(wit: &str) -> bool {
240    wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES)
241}
242
243/// True when `wit` — a raw `:contratos :wit` value — targets *none* of
244/// the three known payload-shape WIT worlds; the payload-less
245/// capability arm of the 4-way WIT-shape partition on the raw
246/// `:contratos :wit` axis. Peer of [`wit_shape_is_http`] /
247/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] on the shape-
248/// dispatch axis — closes the free-function classifier family the
249/// three payload-arm predicates opened onto the exact-inverse
250/// disjunction of the trio, so any downstream consumer that must
251/// classify a raw `:wit` `&str` onto the payload-less capability arm
252/// (a future substrate-side capability-shape-only emitter — the M4
253/// per-Aplicacao WIT-registry capability-import materializer, the
254/// future `feira app graph --capability` filter, the future per-
255/// cluster capability-scope reconciler that skips L4/L7 emission for
256/// payload-less edges, the future `mesh.pleme.io/v1alpha1/Aplicacao`
257/// CR admission webhook's per-shape histogram) reaches for exactly
258/// one typed dispatch at the substrate primitive rather than an
259/// open-coded per-consumer `!wit_shape_is_http(wit) &&
260/// !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)` triplet
261/// negation — each of which would silently misclassify a future 4th
262/// payload-arm addition (a hypothetical `wasi:sockets/*` transport-
263/// layer shape, an `oci:*` capability-import carrier per the sibling
264/// [`wit_shape_matches`] docstring's trajectory bullet) as
265/// capability without a compile-time signal at the consumer site.
266///
267/// Fourth arm on the free-function WIT-shape-predicate family — closes
268/// the {[`wit_shape_is_http`], [`wit_shape_is_pubsub`],
269/// [`wit_shape_is_store`]} trio into a 4-way partition witness on the
270/// raw `:contratos :wit` `&str` axis, mirroring the paired sibling
271/// [`WitContract`]-surface [`WitContract::is_capability`] predicate and
272/// the post-projection [`WitTarget`]-side
273/// `gen_platform::IsVariant`-derived [`WitTarget::is_capability`]
274/// (7f6aa98 `IsVariant` derive lift on the peer arm-set). Every
275/// [`WitTarget`] variant now carries a matched peer predicate on both
276/// the raw `&str` axis (this function + [`wit_shape_is_http`] /
277/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`]) and the
278/// [`WitContract`] surface (the sibling 4-arm predicate family
279/// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
280/// [`WitContract::is_store`] / [`WitContract::is_capability`]),
281/// pinned in load-bearing by the sibling
282/// [`tests::wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis`]
283/// partition-witness pin and the peer
284/// [`tests::wit_contract_shape_methods_delegate_to_free_functions`]
285/// delegation pin.
286///
287/// Prior to this lift the "not one of the three known payload shapes"
288/// classification only reached the raw `&str` axis by materializing a
289/// scratch [`WitContract`] and delegating through
290/// [`WitContract::is_capability`] — a five-field constructor at every
291/// classification point for a pure `&str → bool` question, and a
292/// dependency on the payload-carrier scalar layout the classifier
293/// does not read. Same "one canonical combinator, thin per-arm
294/// projections" discipline the peer [`wit_shape_is_http`] /
295/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] trio already
296/// established, extended to close the 4-arm partition on the raw
297/// `&str` axis.
298///
299/// Note: purely syntactic classification on the negated `:wit` prefix-
300/// set — unlike [`WitContract::target`], which additionally rejects
301/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
302/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
303/// payload-shape mismatches. An empty or structurally malformed `wit`
304/// string returns `true` here (the prefix set matches nothing), and
305/// the surrounding validate-side gate cascade is where the
306/// [`AplicacaoError::EmptyWit`] / [`AplicacaoError::ContratoWitInvalid`]
307/// diagnostic surfaces — this function is the classifier, not the
308/// validator.
309///
310/// Declared `pub const fn` — closes the 4-arm classifier family's
311/// `const`-eval-surface pass on the payload-less capability arm,
312/// peer of the sibling `pub const fn` [`wit_shape_is_http`] /
313/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] classifiers, so
314/// the raw `&str → bool` WIT-shape partition on the capability arm
315/// reaches every substrate-side `const`-context consumer through one
316/// typed dispatch. See [`wit_shape_is_http`]'s `const` posture-block
317/// for the full rationale.
318#[must_use]
319pub const fn wit_shape_is_capability(wit: &str) -> bool {
320    !wit_shape_is_http(wit) && !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)
321}
322
323// Compile-time pins on the 4-arm WIT-shape classifier family — the
324// module-scope const-eval assertions below trip at caixa-core build
325// time (not test time) if a future edit rewires any of the four
326// classifier's arm-set away from the accept-set MESH-COMPOSITION §II.3
327// pins. Anchor the `const`-eval-surface posture of the four peer
328// classifiers on canonical accept-set samples (one per WIT_*_SHAPE_PREFIXES
329// prefix) plus pairwise-exclusion samples asserting the trio partitions
330// the payload-carrying arm-set and the capability arm carries the
331// complementary payload-less remainder. Any future accidental downgrade
332// of one classifier to non-`const` fails these items at caixa-core build
333// time; any future prefix-set edit that overlaps two arms (e.g. a `kv:`
334// prefix accidentally re-emitted under `WIT_HTTP_SHAPE_PREFIXES`) trips
335// the corresponding partition-witness item. Peer of the sibling M3
336// [`PlacementStrategy::requires_shard_key`] partition pins at
337// aplicacao.rs:5121-5123 on the sibling closed-set typed-enum
338// discriminator axis.
339const _: () = assert!(wit_shape_is_http("wasi:http/proxy"));
340const _: () = assert!(wit_shape_is_http("http:incoming"));
341const _: () = assert!(wit_shape_is_pubsub("nats:events"));
342const _: () = assert!(wit_shape_is_pubsub("kafka:topic"));
343const _: () = assert!(wit_shape_is_store("wasi:keyvalue/store"));
344const _: () = assert!(wit_shape_is_store("kv:cache"));
345const _: () = assert!(wit_shape_is_capability("wasi:filesystem/preopens"));
346const _: () = assert!(wit_shape_is_capability(""));
347// Pairwise-exclusion pins — the three payload-carrying arms are
348// pairwise disjoint on the canonical accept-set samples, and the
349// capability arm is the exact-inverse disjunction of the trio
350// (the free-function classifier family's 4-way partition witness).
351const _: () = assert!(!wit_shape_is_http("nats:events"));
352const _: () = assert!(!wit_shape_is_http("kv:cache"));
353const _: () = assert!(!wit_shape_is_pubsub("wasi:http/proxy"));
354const _: () = assert!(!wit_shape_is_pubsub("wasi:keyvalue/store"));
355const _: () = assert!(!wit_shape_is_store("wasi:http/proxy"));
356const _: () = assert!(!wit_shape_is_store("nats:events"));
357const _: () = assert!(!wit_shape_is_capability("wasi:http/proxy"));
358const _: () = assert!(!wit_shape_is_capability("nats:events"));
359const _: () = assert!(!wit_shape_is_capability("wasi:keyvalue/store"));
360
361impl WitContract {
362    /// Substrate-canonical per-`:contratos` caller-Servico scalar
363    /// accessor every consumer that reads the edge's source endpoint
364    /// keys off — returns the author-declared `:contratos :de`
365    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
366    /// own [`String`] storage.
367    ///
368    /// The `:contratos :de` slot names the caller-side member Servico
369    /// on a typed inter-Servico edge (validated by
370    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
371    /// Aplicacao declares — a stray `:de` that doesn't name a member is
372    /// [`AplicacaoError::ContratoMemberMissing`], not a silent
373    /// caller-attachment miss at cluster-apply time). Peer of the
374    /// sibling [`WitContract::destination`] accessor on the same
375    /// per-`:contratos` entry — the pair `( source(), destination() )`
376    /// jointly names the typed edge every renderer that fans on the
377    /// caller-callee identity keys off (the
378    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
379    /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
380    /// map, the per-edge dedup key, the per-edge membership-lookup
381    /// diagnostic).
382    ///
383    /// Prior to this lift the `.de` byte-string was accessed inline at
384    /// four caixa-core sites (the two validate-side membership lookups
385    /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
386    /// tuple's caller-arm at
387    /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
388    /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
389    /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
390    /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
391    /// — five open-coded `.de.as_str()` field-accesses that expressed
392    /// no compile-time link back to the typed slot. A future extension
393    /// of the `:contratos :de` axis to a richer author surface (a
394    /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
395    /// canary flow, a per-cluster caller-alias table the operator pins
396    /// through a future `:placement`-scoped slot, the M4
397    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
398    /// admission-webhook that promotes the scalar to a caller-set
399    /// projection) would have had to be threaded through every
400    /// open-coded copy in lockstep or one consumer would silently
401    /// disagree with the peers on which caller Servico a given edge
402    /// resolves to. Lifting the resolution rule to a typed method on
403    /// the substrate primitive means every downstream caller-facing
404    /// consumer reaches for one typed dispatch — the resolver's
405    /// accept-set migrates as a unit on any future axis addition.
406    ///
407    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
408    /// (6db982c) accessor on the analogous per-ingress-Servico scalar
409    /// axis — same "one typed dispatch on the substrate primitive,
410    /// thin projections at each consumer" discipline extended onto the
411    /// per-`:contratos` caller-Servico byte-string axis.
412    ///
413    /// Declared `pub const fn` — the body composes exclusively through
414    /// the `pub const fn` [`String::as_str`] projection (const-stable
415    /// since Rust 1.87, well within the workspace MSRV), so every
416    /// downstream `const`-context consumer of the per-`:contratos`
417    /// caller-Servico byte-string reaches through the same substrate-
418    /// primitive dispatch at const-eval time as at runtime. Peer of
419    /// the sibling `pub const fn` [`Self::destination`] /
420    /// [`Self::world_ref`] scalar accessors on the same
421    /// per-`:contratos` byte-string trio (the family closure the
422    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
423    /// locks load-bearing), and mirror on the method-surface of the
424    /// sibling free-function [`wit_shape_matches`] +
425    /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
426    /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] `const`-
427    /// eval-surface pass (d46420c) on the raw `&str → bool` WIT-shape
428    /// dispatch family.
429    #[must_use]
430    pub const fn source(&self) -> &str {
431        self.de.as_str()
432    }
433
434    /// Substrate-canonical per-`:contratos` callee-Servico scalar
435    /// accessor every consumer that reads the edge's destination
436    /// endpoint keys off — returns the author-declared
437    /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
438    /// from the typed slot's own [`String`] storage.
439    ///
440    /// The `:contratos :para` slot names the callee-side member Servico
441    /// on a typed inter-Servico edge (validated by
442    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
443    /// Aplicacao declares — a stray `:para` that doesn't name a member
444    /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
445    /// callee-attachment miss at cluster-apply time). Callee-side twin
446    /// of the sibling [`WitContract::source`] accessor — the pair
447    /// jointly names the typed edge every renderer that fans on the
448    /// caller-callee identity keys off, and this accessor is also the
449    /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
450    /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
451    /// composes with `destination()` at every emit site that projects a
452    /// per-edge destination Servico's L4 listener port.
453    ///
454    /// Prior to this lift the `.para` byte-string was accessed inline
455    /// at five sites — four caixa-core (the validate-side membership
456    /// lookup at `!names.contains(c.para.as_str())`, the per-edge
457    /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
458    /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
459    /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
460    /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
461    /// — with no compile-time link back to the typed slot. A future
462    /// extension of the `:contratos :para` axis to a richer author
463    /// surface (a multi-callee weighted-fan-out overlay for canary /
464    /// blue-green routing on typed edges, a per-cluster callee-alias
465    /// table the operator pins through a future `:placement`-scoped
466    /// slot, the M4 CR materializer's per-CR admission-webhook that
467    /// promotes the scalar to a callee-set projection) would have had
468    /// to be threaded through every open-coded copy in lockstep or one
469    /// consumer would silently disagree on which callee Servico a given
470    /// edge resolves to (a per-CNP `endpointSelector` that names a
471    /// different destination than its L4 port resolver reads for, a
472    /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
473    /// as distinct while the adjacency map collapses them, or vice
474    /// versa). Lifting to a typed method on the substrate primitive
475    /// means every downstream callee-facing consumer reaches for one
476    /// typed dispatch.
477    ///
478    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
479    /// (6db982c) accessor — both name the "destination-Servico
480    /// byte-string" concept on their respective mesh-slot atoms (per-
481    /// ingress apex vs. per-typed-edge callee), and both extend the
482    /// substrate-primitive-owns-the-resolver discipline onto the
483    /// per-slot destination-Servico scalar axis. Composes with
484    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
485    /// emit-side per-edge L4 port reader — the composition
486    /// `spec.port_for_destination(c.destination())` pins the CNP per-
487    /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
488    /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
489    /// `spec.port_for_destination(entrada.destination())`.
490    ///
491    /// Declared `pub const fn` — sibling in `const`-eval posture to the
492    /// peer `pub const fn` [`Self::source`] / [`Self::world_ref`]
493    /// per-`:contratos` byte-string scalar accessors, all three
494    /// projecting through the `pub const fn` [`String::as_str`]
495    /// (const-stable since Rust 1.87). See [`Self::source`] for the
496    /// family-closure rationale.
497    #[must_use]
498    pub const fn destination(&self) -> &str {
499        self.para.as_str()
500    }
501
502    /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
503    /// accessor every consumer that reads the edge's WIT world
504    /// discriminator keys off — returns the author-declared
505    /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
506    /// the typed slot's own [`String`] storage.
507    ///
508    /// The `:contratos :wit` slot names the WIT world the typed edge
509    /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
510    /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
511    /// be a well-shaped WIT world reference via
512    /// [`crate::render::is_wit_world_ref`] and by
513    /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
514    /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
515    /// [`WitContract::source`] / [`WitContract::destination`] accessors
516    /// on the same per-`:contratos` entry — the triple
517    /// `( source(), destination(), world_ref() )` jointly names the
518    /// typed edge every renderer that fans on the caller-callee-shape
519    /// identity keys off (the per-edge dedup key at
520    /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
521    /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
522    /// [`caixa_mesh::cilium_network_policies`], the
523    /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
524    /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
525    /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
526    ///
527    /// Prior to this lift the `.wit` byte-string was accessed inline at
528    /// five sites — three caixa-core (the `WitContract::is_*` shape-
529    /// dispatch predicates' `&self.wit` arg, the validate-side empty
530    /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
531    /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
532    /// printer's `{}` format-slot at `c.wit`) — five open-coded
533    /// `.wit` field-accesses that expressed no compile-time link back to
534    /// the typed slot. A future extension of the `:contratos :wit` axis
535    /// to a richer author surface (an M4 promotion from `String` to a
536    /// typed WIT-world enum once the WIT registry stabilizes in tatara-
537    /// lisp per this struct's own `:wit` field docstring, a per-cluster
538    /// WIT-alias table the operator pins through a future
539    /// `:placement`-scoped slot, a canonicalization pass that lowercases
540    /// `wasi:*` prefixes) would have had to be threaded through every
541    /// open-coded copy in lockstep or one consumer would silently
542    /// disagree with the peers on which WIT shape a given edge resolves
543    /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
544    /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
545    /// empty-check that missed a whitespace-only string a peer accessor
546    /// stripped, or vice versa). Lifting to a typed method on the
547    /// substrate primitive means every downstream WIT-shape-facing
548    /// consumer reaches for one typed dispatch — the resolver's
549    /// accept-set migrates as a unit on any future axis addition.
550    ///
551    /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
552    /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
553    /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
554    /// 6db982c), per-`:membros` [`Membro::nome`] /
555    /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
556    /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
557    /// on the substrate primitive, thin projections at each consumer"
558    /// discipline extended onto the last unlifted per-`:contratos`
559    /// scalar (the WIT-world-reference arm).
560    ///
561    /// [fag]: caixa-feira/src/cmd/app.rs
562    ///
563    /// Declared `pub const fn` — sibling in `const`-eval posture to the
564    /// peer `pub const fn` [`Self::source`] / [`Self::destination`]
565    /// per-`:contratos` byte-string scalar accessors on the trio, and
566    /// the load-bearing enabler for the paired `pub const fn`
567    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
568    /// [`Self::is_capability`] WIT-shape-predicate family (each
569    /// composes as `wit_shape_is_<arm>(self.world_ref())` and inherits
570    /// the `const`-eval posture by construction once this accessor
571    /// carries it). See [`Self::source`] for the family-closure
572    /// rationale and the paired
573    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
574    /// for the load-bearing witness.
575    #[must_use]
576    pub const fn world_ref(&self) -> &str {
577        self.wit.as_str()
578    }
579
580    /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
581    /// payload-target scalar accessor every consumer that reads the
582    /// edge's L7 HTTP request path payload keys off — returns the
583    /// author-declared `:contratos :endpoint` byte-string verbatim as
584    /// an `Option<&str>`, borrowed from the typed slot's own
585    /// `Option<String>` storage; `None` when the slot is absent (the
586    /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
587    /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
588    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
589    /// [`WitTarget::Capability`] edge carries none of the three).
590    ///
591    /// The `:contratos :endpoint` slot carries the HTTP request path
592    /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
593    /// — same shape required of `:entrada :paths`, gated by the shared
594    /// [`crate::render::is_gateway_api_http_path`] predicate) that
595    /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
596    /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
597    /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
598    /// downstream consumer that reads the payload keys off this scalar
599    /// (the [`WitContract::target`] Http-arm payload extraction that
600    /// materializes [`WitTarget::Http { endpoint }`] under the paired
601    /// [`WitTarget::HTTP_FIELD_NAME`] label, the
602    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
603    /// key's endpoint arm that pins the payload as part of the six-tuple
604    /// dedup key alongside the sibling `:subject`/`:slot` arms, the
605    /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
606    /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
607    /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
608    /// emission path that lands the payload verbatim as a Cilium L7
609    /// `path:` rule).
610    ///
611    /// Prior to this lift the `.endpoint` field was accessed inline at
612    /// two production sites in `caixa-core/src/aplicacao.rs` — the
613    /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
614    /// self.endpoint.as_deref();` binding at the top of the method, and
615    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
616    /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
617    /// field-accesses that expressed no compile-time link back to the
618    /// typed slot. A future extension of the `:contratos :endpoint`
619    /// axis to a richer author surface (an M4 promotion from
620    /// `Option<String>` to a typed HTTP path-template enum once the
621    /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
622    /// this struct's own `:wit` field docstring, a per-cluster endpoint-
623    /// alias table the operator pins through a future `:placement`-
624    /// scoped slot, a canonicalization pass that percent-encodes non-
625    /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
626    /// materializer applies per-tenant) would have had to be threaded
627    /// through both open-coded copies in lockstep or the two consumers
628    /// would silently disagree on which HTTP path a given edge resolves
629    /// to — the [`WitContract::target`] payload-extraction reading
630    /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
631    /// the operator-resolved `"/tenant-a/lookup"` would silently split
632    /// the [`WitTarget::Http`]-arm rendered payload from the actual
633    /// dedup-key uniqueness axis, a two-consumer split at the validator
634    /// far from the source `caixa.lisp` with no field naming the
635    /// payload-drift root cause. Lifting the resolution rule to a typed
636    /// method on the substrate primitive means every downstream
637    /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
638    /// L7-payload surface reaches for exactly one typed dispatch — the
639    /// resolver's accept-set migrates as a unit on any future axis
640    /// addition.
641    ///
642    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
643    /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
644    /// accessors on the M3 mesh-slot family — same "one typed dispatch
645    /// on the substrate primitive, thin projections at each consumer"
646    /// discipline extended onto the per-`:contratos` HTTP-shaped
647    /// payload-carrier `Option<String>` optional-scalar axis. First
648    /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
649    /// atom — opens the "optional per-slot payload-carrier scalar"
650    /// projection pattern the sibling per-`:contratos` `:subject` /
651    /// `:slot` future lifts fold on, matching the closed
652    /// per-`:contratos` scalar-value accessor family
653    /// ([`WitContract::source`] / [`WitContract::destination`] /
654    /// [`WitContract::world_ref`]) already lifted onto the mandatory-
655    /// scalar `String` axes. Named `endpoint()` to match the storage
656    /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
657    /// author-facing label const; the accessor's identity name maps
658    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
659    /// docstring already carries.
660    #[must_use]
661    pub const fn endpoint(&self) -> Option<&str> {
662        match &self.endpoint {
663            Some(s) => Some(s.as_str()),
664            None => None,
665        }
666    }
667
668    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
669    /// payload-target scalar accessor every consumer that reads the
670    /// edge's NATS / Kafka publish subject payload keys off — returns
671    /// the author-declared `:contratos :subject` byte-string verbatim
672    /// as an `Option<&str>`, borrowed from the typed slot's own
673    /// `Option<String>` storage; `None` when the slot is absent (the
674    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
675    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
676    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
677    /// [`WitTarget::Capability`] edge carries none of the three).
678    ///
679    /// The `:contratos :subject` slot carries the NATS / Kafka publish
680    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
681    /// per-edge target selector — `orders.paid`, `events.>`, whatever
682    /// subject namespace the author names on the pub-sub edge) that
683    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
684    /// arm's `subject: &'a str` payload when the edge's `:wit` world
685    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
686    /// downstream consumer that reads the payload keys off this scalar
687    /// (the [`WitContract::target`] PubSub-arm payload extraction that
688    /// materializes [`WitTarget::PubSub { subject }`] under the paired
689    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
690    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
691    /// key's subject arm that pins the payload as part of the six-tuple
692    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
693    /// future M4 per-edge WIT registry resolver's pub-sub-arm
694    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
695    /// materializer's per-edge NATS admission webhook, the future
696    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
697    /// as a NATS subject the operator pins per-CR).
698    ///
699    /// Prior to this lift the `.subject` field was accessed inline at
700    /// two production sites in `caixa-core/src/aplicacao.rs` — the
701    /// [`WitContract::target`] payload-shape dispatch's `let subject =
702    /// self.subject.as_deref();` binding at the top of the method, and
703    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
704    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
705    /// field-accesses that expressed no compile-time link back to the
706    /// typed slot. A future extension of the `:contratos :subject` axis
707    /// to a richer author surface (an M4 promotion from `Option<String>`
708    /// to a typed NATS-subject-template enum once the WIT registry
709    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
710    /// struct's own `:wit` field docstring, a per-cluster subject-alias
711    /// table the operator pins through a future `:placement`-scoped
712    /// slot, a canonicalization pass that lowercases / dedupes wildcard
713    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
714    /// applies per-tenant) would have had to be threaded through both
715    /// open-coded copies in lockstep or the two consumers would silently
716    /// disagree on which NATS subject a given edge resolves to — the
717    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
718    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
719    /// resolved `"tenant-a.orders.paid"` would silently split the
720    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
721    /// key uniqueness axis, a two-consumer split at the validator far
722    /// from the source `caixa.lisp` with no field naming the payload-
723    /// drift root cause. Lifting the resolution rule to a typed method
724    /// on the substrate primitive means every downstream pub-sub-payload-
725    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
726    /// surface reaches for exactly one typed dispatch — the resolver's
727    /// accept-set migrates as a unit on any future axis addition.
728    ///
729    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
730    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
731    /// carrier axis — second `Option<&str>`-return accessor on the
732    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
733    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
734    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
735    /// key/value-store arm as the last unlifted per-`:contratos`
736    /// `Option<String>` axis. Named `subject()` to match the storage
737    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
738    /// author-facing label const; the accessor's identity name maps
739    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
740    /// docstring already carries.
741    #[must_use]
742    pub const fn subject(&self) -> Option<&str> {
743        match &self.subject {
744            Some(s) => Some(s.as_str()),
745            None => None,
746        }
747    }
748
749    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
750    /// shaped payload-target scalar accessor every consumer that reads
751    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
752    /// off — returns the author-declared `:contratos :slot` byte-string
753    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
754    /// own `Option<String>` storage; `None` when the slot is absent
755    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
756    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
757    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
758    /// [`WitTarget::Capability`] edge carries none of the three).
759    ///
760    /// The `:contratos :slot` slot carries the key/value store
761    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
762    /// arm's per-edge target selector — `carts/{cart_id}`,
763    /// `sessions/{tenant}/{sid}`, whatever key-template the author
764    /// names on the store edge) that [`WitContract::target`] projects
765    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
766    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
767    /// accept-set. Every downstream consumer that reads the payload
768    /// keys off this scalar (the [`WitContract::target`] Store-arm
769    /// payload extraction that materializes [`WitTarget::Store { slot }`]
770    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
771    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
772    /// key's store arm that pins the payload as part of the six-tuple
773    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
774    /// the future M4 per-edge WIT registry resolver's store-arm
775    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
776    /// materializer's per-edge key/value admission webhook, the future
777    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
778    /// as a key-template the operator pins per-CR).
779    ///
780    /// Prior to this lift the `.slot` field was accessed inline at two
781    /// production sites in `caixa-core/src/aplicacao.rs` — the
782    /// [`WitContract::target`] payload-shape dispatch's `let slot =
783    /// self.slot.as_deref();` binding at the top of the method, and
784    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
785    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
786    /// field-accesses that expressed no compile-time link back to the
787    /// typed slot. A future extension of the `:contratos :slot` axis
788    /// to a richer author surface (an M4 promotion from `Option<String>`
789    /// to a typed key-template enum once the WIT registry stabilizes
790    /// key-template parameter shapes in tatara-lisp per this struct's
791    /// own `:wit` field docstring, a per-cluster slot-alias table the
792    /// operator pins through a future `:placement`-scoped slot, a
793    /// canonicalization pass that lowercases the bucket prefix, a
794    /// per-CR fully-qualified rewrite the M4 CR materializer applies
795    /// per-tenant) would have had to be threaded through both
796    /// open-coded copies in lockstep or the two consumers would
797    /// silently disagree on which key-template a given edge resolves
798    /// to — the [`WitContract::target`] payload-extraction reading
799    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
800    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
801    /// would silently split the [`WitTarget::Store`]-arm rendered
802    /// payload from the actual dedup-key uniqueness axis, a
803    /// two-consumer split at the validator far from the source
804    /// `caixa.lisp` with no field naming the payload-drift root cause.
805    /// Lifting the resolution rule to a typed method on the substrate
806    /// primitive means every downstream store-payload-facing consumer
807    /// of the Aplicacao's per-`:contratos` payload surface reaches for
808    /// exactly one typed dispatch — the resolver's accept-set migrates
809    /// as a unit on any future axis addition.
810    ///
811    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
812    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
813    /// accessors on the M3 mesh-slot payload-carrier axis — third and
814    /// final `Option<&str>`-return accessor on the per-`:contratos`
815    /// mesh-slot atom, closes the last unlifted per-`:contratos`
816    /// `Option<String>` axis and completes the "optional per-slot
817    /// payload-carrier scalar" projection pattern the peer HTTP /
818    /// pub-sub arms established across the three payload-shape
819    /// dispatch arms. Named `slot()` to match the storage field's
820    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
821    /// author-facing label const; the accessor's identity name maps
822    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
823    /// docstring already carries.
824    #[must_use]
825    pub const fn slot(&self) -> Option<&str> {
826        match &self.slot {
827            Some(s) => Some(s.as_str()),
828            None => None,
829        }
830    }
831
832    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
833    /// caller-callee-pair accessor every consumer that constructs an
834    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
835    /// caller-callee pair keys off — returns the author-declared
836    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
837    /// owned `(String, String)` tuple, projected through the lifted
838    /// [`WitContract::source`] / [`WitContract::destination`] scalar
839    /// accessors so any future rebrand on the caller-arm / callee-arm
840    /// projection axis (an M4 per-cluster caller-alias table the
841    /// operator pins through a future `:placement`-scoped slot, a
842    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
843    /// a per-`:membros` alias overlay from the future `:membros
844    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
845    /// acknowledges) reaches every diagnostic-construction site by
846    /// construction.
847    ///
848    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
849    /// owned form" primitive every per-`:contratos` diagnostic variant on
850    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
851    /// nine variants [`AplicacaoError::EmptyWit`],
852    /// [`AplicacaoError::ContratoEndpointEmpty`],
853    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
854    /// [`AplicacaoError::ContratoEndpointInvalid`],
855    /// [`AplicacaoError::ContratoSubjectEmpty`],
856    /// [`AplicacaoError::ContratoSubjectInvalid`],
857    /// [`AplicacaoError::ContratoSlotEmpty`],
858    /// [`AplicacaoError::ContratoSlotInvalid`], and
859    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
860    /// para: String` field pair the constructor site reads verbatim off
861    /// the [`WitContract`] the diagnostic points at, so a diagnostic
862    /// whose `de:` and `para:` labels silently drift off the source
863    /// caller/callee — a per-cluster caller-alias rewrite that landed on
864    /// one variant's inline `de: c.de.clone()` field access but not on
865    /// its sibling variant's, an accidental swap of the `de:` and `para:`
866    /// arms in a copy-paste of the constructor block — would emit a
867    /// build-time error whose "which caixa is at fault" question the
868    /// operator answers wrongly, far from the source `caixa.lisp`.
869    ///
870    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
871    /// pair was inlined at seven [`WitContract::target`] error-
872    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
873    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
874    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
875    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
876    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
877    /// the [`AplicacaoError::ContratoSlotEmpty`] /
878    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
879    /// two [`AplicacaoSpec::validate`] error-construction sites (the
880    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
881    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
882    /// insert-first-seen closure) — nine open-coded `.de.clone() +
883    /// .para.clone()` pairs that expressed no compile-time contract that
884    /// the caller-arm and callee-arm arms of the same diagnostic
885    /// construction reach for the same [`WitContract`] instance or that
886    /// the `de:` and `para:` label pair binds to the fields the author
887    /// declared. Any future rebrand on the axis — an M4 per-cluster
888    /// caller/callee-alias rewrite the operator pins through a future
889    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
890    /// per-CR fully-qualified namespace prefix the M4
891    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
892    /// per-tenant, a canonicalization pass that lowercases the caller +
893    /// callee identifiers post-parse — would have had to be threaded
894    /// through every open-coded copy in lockstep or one variant's
895    /// diagnostic would silently name a different caller/callee pair
896    /// than its peer, silently degrading the "which caixa is at fault"
897    /// self-locating signal every operator-facing typed diagnostic
898    /// exists to carry. Lifting the pair to a typed method on the
899    /// substrate primitive means every downstream diagnostic-construction
900    /// site reaches for exactly one typed dispatch — the resolver's
901    /// projection migrates as a unit on any future axis addition.
902    ///
903    /// Peer of the sibling per-`:contratos` scalar accessor family
904    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
905    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
906    /// scalar-value axes — first composite-projection accessor on the
907    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
908    /// form `.clone()` field-accesses that pair the sibling
909    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
910    /// one typed dispatch. Named `edge_pair()` to reflect the identity
911    /// name of the projected tuple (the typed-edge caller-callee pair,
912    /// distinct from the sibling triple-projection
913    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
914    /// closure in [`WitContract::target`] + the paired
915    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
916    /// site's `(de, para, wit)` triple onto one typed dispatch).
917    #[must_use]
918    pub fn edge_pair(&self) -> (String, String) {
919        (self.source().to_string(), self.destination().to_string())
920    }
921
922    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
923    /// :wit)` triple every per-edge diagnostic constructor that names
924    /// all three axes threads verbatim into its `de:` / `para:` /
925    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
926    /// / missing-target / invalid-wit / capability-with-payload arms
927    /// (eight sites all shape `let (de, para, wit) = edge();
928    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
929    /// accessor landed) and the sibling
930    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
931    /// constructor (which paired `edge_pair()` for the `(de, para)`
932    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
933    /// typed-dispatch + raw-field-access shape the sibling accessor
934    /// family already flagged as a drift risk). Nine total call sites
935    /// collapse onto this helper.
936    ///
937    /// Lifted with the same one-source-of-truth discipline
938    /// [`WitContract::edge_pair`] carries on the paired
939    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
940    /// arms compose through the lifted [`WitContract::source`] /
941    /// [`WitContract::destination`] / [`WitContract::world_ref`]
942    /// scalar accessors byte-for-byte (pinned by the paired
943    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
944    /// composition-pin), so any future rebrand on the per-`:contratos`
945    /// caller / callee / world-ref axis (an M4 per-cluster
946    /// caller/callee-alias rewrite the operator pins through a future
947    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
948    /// per-CR fully-qualified namespace prefix the M4
949    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
950    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
951    /// on `source()` / `destination()`, a per-CR canonicalization pass
952    /// that lowercases the WIT world ref post-parse) migrates as a
953    /// single caixa-core edit rather than a coordinated rewrite of
954    /// nine open-coded triple-constructors.
955    ///
956    /// Peer of the sibling per-`:contratos` composite-projection
957    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
958    /// composite-value axes — closes the last unlifted owned-form
959    /// composite-tuple axis on the per-`:contratos` diagnostic-
960    /// construction surface. Named `edge_triple()` to reflect the
961    /// identity name of the projected tuple (the typed-edge
962    /// caller-callee-wit triple, sibling to the caller-callee-only
963    /// pair `edge_pair()` returns).
964    #[must_use]
965    pub fn edge_triple(&self) -> (String, String, String) {
966        (
967            self.source().to_string(),
968            self.destination().to_string(),
969            self.world_ref().to_string(),
970        )
971    }
972
973    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
974    /// dedups typed edges keys off — routes through the lifted
975    /// [`WitContract::source`] / [`WitContract::destination`] /
976    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
977    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
978    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
979    /// type alias's six axes migrate as a unit on any future axis
980    /// addition (adding a seventh field to [`WitContract`] is one
981    /// [`ContratoIdentity`] alias edit + one accessor addition + one
982    /// arm here, not a coordinated rewrite of every open-coded
983    /// six-tuple builder that dedups on the identity axis).
984    ///
985    /// Sibling of [`WitContract::edge_pair`] /
986    /// [`WitContract::edge_triple`] on the composite-projection axis:
987    /// the pair projects the caller-callee axes, the triple extends it
988    /// with the world-ref, this method extends it with the three
989    /// payload-carrier axes. Every projection returns the same six
990    /// scalar accessors' outputs; the three methods differ only in
991    /// which arms they surface.
992    #[must_use]
993    pub fn identity(&self) -> ContratoIdentity<'_> {
994        (
995            self.source(),
996            self.destination(),
997            self.world_ref(),
998            self.endpoint(),
999            self.subject(),
1000            self.slot(),
1001        )
1002    }
1003
1004    /// True when this contract targets an HTTP-shaped WIT world.
1005    ///
1006    /// Declared `pub const fn` — routes through the paired `pub const
1007    /// fn` [`Self::world_ref`] scalar accessor and the substrate's
1008    /// `pub const fn` free-function classifier [`wit_shape_is_http`]
1009    /// (d46420c). Sibling in `const`-eval posture to the peer
1010    /// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
1011    /// [`Self::is_capability`] WIT-shape-predicate family; the closed
1012    /// 4-arm partition on the raw `:contratos :wit` axis now carries
1013    /// the same `const`-eval-surface posture as the free-function
1014    /// classifier family it composes through. Pinned load-bearing by
1015    /// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
1016    /// test (a future accidental downgrade to non-`const` fires E0015
1017    /// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
1018    /// build time).
1019    #[must_use]
1020    pub const fn is_http(&self) -> bool {
1021        wit_shape_is_http(self.world_ref())
1022    }
1023
1024    /// True when this contract targets a pub-sub-shaped WIT world.
1025    ///
1026    /// Declared `pub const fn` — sibling in `const`-eval posture to
1027    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
1028    /// [`Self::is_capability`] WIT-shape-predicate family. See
1029    /// [`Self::is_http`] for the family-closure rationale.
1030    #[must_use]
1031    pub const fn is_pubsub(&self) -> bool {
1032        wit_shape_is_pubsub(self.world_ref())
1033    }
1034
1035    /// True when this contract targets a key/value-shaped WIT world.
1036    ///
1037    /// Declared `pub const fn` — sibling in `const`-eval posture to
1038    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
1039    /// [`Self::is_capability`] WIT-shape-predicate family. See
1040    /// [`Self::is_http`] for the family-closure rationale.
1041    #[must_use]
1042    pub const fn is_store(&self) -> bool {
1043        wit_shape_is_store(self.world_ref())
1044    }
1045
1046    /// True when this contract targets *none* of the three known payload-
1047    /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
1048    /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1049    /// open on the [`WitContract`] surface. Returns the exact-inverse
1050    /// disjunction of the peer trio — `true` when none of the three
1051    /// prefix-set predicates matches the raw `:contratos :wit` value; the
1052    /// author-declared WIT world is a pure typed capability edge with no
1053    /// payload selector (the shape [`WitContract::target`] projects onto
1054    /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
1055    /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
1056    ///
1057    /// The `:contratos :wit` shape-space is closed at four arms
1058    /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
1059    /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
1060    /// everything else on the payload-less capability arm), and every
1061    /// downstream consumer that must filter contratos by shape-class
1062    /// keys off the four sibling predicates (the [`WitContract::target`]
1063    /// dispatch's implicit `else` after the three payload-shape arm
1064    /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
1065    /// every future substrate-side capability-shape-only emitter — the
1066    /// M4 per-Aplicacao WIT-registry capability-import materializer, the
1067    /// future `feira app graph --capability` per-Aplicacao capability-
1068    /// column filter, the future per-cluster capability-scope reconciler
1069    /// that skips L4/L7 emission for payload-less edges since Cilium
1070    /// can't introspect WASI capability calls, the future
1071    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
1072    /// shape shape-count histogram). Every such consumer reaches for one
1073    /// typed dispatch on the substrate primitive so the "which arm
1074    /// carries the capability-only shape?" answer lives at one caixa-core
1075    /// edit rather than open-coded across per-consumer
1076    /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
1077    /// negations, each of which would silently drop a future fourth
1078    /// payload-arm addition without a compile-time signal at the
1079    /// consumer site.
1080    ///
1081    /// Prior to this lift the "not one of the three known payload
1082    /// shapes" classification sat inline at [`WitContract::target`]'s
1083    /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
1084    /// [`WitTarget::Capability`] admission arm after the three `if
1085    /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
1086    /// { … }` guards) with no named accessor for downstream consumers
1087    /// to reach through. A future substrate-side capability-only
1088    /// filter or a future capability-scope reconciler would have had to
1089    /// re-inline the same triplet negation at every emit site with no
1090    /// compile-time link back to the sibling trio, and a future arm
1091    /// addition (a hypothetical fourth payload-shape prefix set — a
1092    /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
1093    /// import carrier per the sibling [`wit_shape_matches`] docstring's
1094    /// trajectory bullet) would land the new predicate on the payload-
1095    /// carrying trio and silently misclassify the new shape as
1096    /// capability at every triplet-negation consumer site, propagating
1097    /// the drift far from the caixa-core prefix-set commit.
1098    ///
1099    /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
1100    /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
1101    /// trio into a 4-way partition witness on the raw `:contratos :wit`
1102    /// axis, mirroring the paired post-projection [`WitTarget`]
1103    /// `gen_platform::IsVariant`-derived 4-way predicate set
1104    /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
1105    /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
1106    /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
1107    /// arm-set). The two typed axes — pre-projection on the raw
1108    /// `:contratos :wit` string, post-projection on the validated typed
1109    /// view — now carry a matched 4-arm predicate discipline: every
1110    /// arm on the closed [`WitTarget`] set has a peer pre-projection
1111    /// predicate on the [`WitContract`] surface, and any future
1112    /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
1113    /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
1114    /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
1115    /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
1116    /// pre-projection axis through a matching peer prefix-set + peer
1117    /// predicate lift by construction — the compile-time exhaustiveness
1118    /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
1119    /// the post-projection accessor family stays in sync, and the sibling
1120    /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
1121    /// partition-witness pin locks the pre-projection classification in
1122    /// load-bearing so a peer prefix-set addition that widened one arm's
1123    /// accept-set without shrinking the [`Self::is_capability`] accept-set
1124    /// surfaces as a test failure at caixa-core build time rather than a
1125    /// silent per-consumer split at renderer emit time.
1126    ///
1127    /// Composes byte-for-byte through the lifted peer trio
1128    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
1129    /// any future rebrand of any prefix-set const flows through this
1130    /// method by construction without a coordinated per-consumer rewrite
1131    /// (pinned by the sibling
1132    /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
1133    /// composition-witness).
1134    ///
1135    /// Note: purely syntactic classification on the `:wit` prefix-set —
1136    /// unlike [`Self::target`], which additionally rejects value-shape-
1137    /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
1138    /// package) via [`crate::render::is_wit_world_ref`] and payload-
1139    /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
1140    /// structurally malformed returns `true` from `is_capability()` (the
1141    /// prefix set matches nothing), and the surrounding
1142    /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
1143    /// is where the [`AplicacaoError::EmptyWit`] /
1144    /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
1145    /// predicate is the classifier, not the validator.
1146    ///
1147    /// Declared `pub const fn` — closes the WIT-shape-predicate
1148    /// family's `const`-eval-surface pass at the fourth (payload-less)
1149    /// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
1150    /// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
1151    /// See [`Self::is_http`] for the family-closure rationale.
1152    #[must_use]
1153    pub const fn is_capability(&self) -> bool {
1154        wit_shape_is_capability(self.world_ref())
1155    }
1156
1157    /// True when this contract's caller equals its callee — a
1158    /// structurally degenerate typed edge that no `:contratos` entry can
1159    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
1160    /// Servico B" is an *inter*-Servico contract between two distinct
1161    /// graph nodes). A Servico contracting with itself resolves to an
1162    /// in-process call the wasm-engine never routes through the mesh at
1163    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
1164    /// per-edge policy can express the intended shape — the pub-sub
1165    /// path silently rendered a self-allow rule that is a no-op (intra-
1166    /// pod traffic bypasses the mesh entirely), and the synchronous
1167    /// paths surfaced as a misleading `ContratoCycle` whose path was
1168    /// `["cart", "cart"]` — framing a self-edge as a multi-node
1169    /// deadlock. Every downstream consumer that must reject the shape
1170    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
1171    /// gate at caixa-core/src/aplicacao.rs:5559, every future
1172    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
1173    /// axis, every future adjacency-graph builder that must skip self-
1174    /// edges rather than fold them into an incidental cycle) now keys
1175    /// off exactly one typed dispatch on the substrate primitive, so
1176    /// any future rebrand on the axis (an M4-typed-caller enum whose
1177    /// identity comparison rule the accessor could route through, an
1178    /// operator-side per-cluster caller/callee-alias table the
1179    /// materializer resolves per-CR before the equality probe, a
1180    /// promotion of the pointwise `==` to a set-membership check once
1181    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
1182    /// so a per-replica self-edge is rejected under the same predicate)
1183    /// migrates as a single caixa-core edit rather than a coordinated
1184    /// rewrite of every downstream self-edge consumer. Composes
1185    /// byte-for-byte through the lifted [`Self::source`] /
1186    /// [`Self::destination`] scalar accessors — the accessor pair every
1187    /// per-`:contratos` scalar-value axis already routes through — so
1188    /// any future rebrand of the underlying `:de` / `:para` storage
1189    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1190    /// a per-Aplicacao interning arena the M4 CR materializer authors,
1191    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1192    /// same one body without a coordinated per-consumer rewrite.
1193    ///
1194    /// Sibling in shape to the peer per-`:contratos` shape-predicate
1195    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1196    /// on the `:wit` world-ref axis — extended onto the per-edge
1197    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1198    /// partition the WIT-shape-space; `is_self_loop` partitions the
1199    /// caller-callee identity-space. Named `is_self_loop()` to reflect
1200    /// the graph-theoretic identity of the shape (a loop from a graph
1201    /// node to itself, distinct from the sibling multi-node
1202    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1203    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1204    /// variant already carrying the term.
1205    #[must_use]
1206    pub fn is_self_loop(&self) -> bool {
1207        self.source() == self.destination()
1208    }
1209
1210    /// Typed view of the contract's payload target. Enforces that the
1211    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1212    /// fields agree, and that each carried value is itself
1213    /// value-shape valid:
1214    ///
1215    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1216    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1217    ///     `PathPrefix` invariant — same shape required of `:entrada
1218    ///     :paths`)
1219    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1220    ///     non-empty (NATS / Kafka publish without a subject is a
1221    ///     no-op subscribe, never the author's intent)
1222    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1223    ///     non-empty (an empty slot template addresses the bucket
1224    ///     root, defeating the per-key isolation the slot exists for)
1225    ///   - Anything else ⇒ none of the three; the contract is a pure
1226    ///     typed capability edge with no payload selector.
1227    ///
1228    /// Translates the Apollo Federation discipline ("conflicts are
1229    /// errors at compile time, not warnings at runtime";
1230    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1231    /// a contract whose WIT shape disagrees with its target field, or
1232    /// whose target field carries a value-shape-invalid string, is a
1233    /// build error — not a silent renderer drop. The returned
1234    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1235    /// non-empty (and absolute, for `Http`); every downstream consumer
1236    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1237    /// the M4 per-edge policy resolver) can rely on that without
1238    /// re-checking.
1239    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1240        // Route the HTTP-shaped payload-target extraction through the
1241        // lifted [`WitContract::endpoint`] accessor rather than the raw
1242        // `self.endpoint.as_deref()` field access — the two production
1243        // consumers of the per-`:contratos :endpoint` HTTP-shaped
1244        // payload-carrier scalar (this method's Http-arm payload
1245        // extraction, the [`AplicacaoSpec::validate`] duplicate-
1246        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1247        // off exactly one typed dispatch on the substrate primitive, so
1248        // any future rebrand on the axis (an M4 per-cluster endpoint-
1249        // alias rewrite, a per-CR fully-qualified path prefix the M4
1250        // materializer applies per-tenant, an M4 promotion from
1251        // `Option<String>` to a typed HTTP path-template enum) migrates
1252        // as a single caixa-core edit rather than a coordinated rewrite
1253        // of the two call sites — peer of the sibling M3 per-`:placement`
1254        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1255        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1256        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1257        let endpoint = self.endpoint();
1258        let subject = self.subject();
1259        // Route the store-arm payload-carrier scalar through the
1260        // lifted [`WitContract::slot`] accessor rather than the raw
1261        // `self.slot.as_deref()` field access — the two production
1262        // consumers of the per-`:contratos :slot` key/value-store-
1263        // shaped payload-carrier scalar (this method's Store-arm
1264        // payload extraction, the [`AplicacaoSpec::validate`]
1265        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1266        // arm) now key off exactly one typed dispatch on the substrate
1267        // primitive. Closes the last unlifted per-`:contratos`
1268        // `Option<String>` axis, completing the payload-carrier
1269        // accessor family peer of the sibling per-`:contratos`
1270        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1271        // (90de675) lifts across the HTTP / pub-sub arms.
1272        let slot = self.slot();
1273        // Route the local `(de, para, wit)` triple-projection closure
1274        // through the lifted [`WitContract::edge_triple`] typed accessor
1275        // rather than re-inlining `(self.de.clone(), self.para.clone(),
1276        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1277        // triple-carrying diagnostic constructors below (wrong-target /
1278        // missing-target on all three payload arms + capability-with-
1279        // payload + invalid-wit) now key off exactly one typed dispatch
1280        // on the substrate-primitive composite projection, sibling to
1281        // the peer [`WitContract::edge_pair`]-routed
1282        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1283        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1284        // diagnostic constructors on the same per-`:contratos`
1285        // diagnostic-construction surface.
1286        let edge = || self.edge_triple();
1287
1288        // The `:wit` value drives every downstream dispatch — the
1289        // is_http/is_pubsub/is_store prefix matchers below, the
1290        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1291        // exclusion. Until this gate landed `target()` accepted any
1292        // non-empty string and silently demoted unrecognized shapes to
1293        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1294        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1295        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1296        // package, the paste-from-binary footgun a multi-line blob
1297        // accidentally landing in the slot, the un-percent-encoded
1298        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1299        // routing, got L4-only" footgun. Empty is still pre-checked at
1300        // the [`AplicacaoSpec::validate`] call site via the narrower
1301        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1302        // validate layer); the value-shape gate here picks up the
1303        // structurally-invalid non-empty cases the empty check misses,
1304        // and remains correct under direct `target()` calls outside
1305        // validate (the predicate's defensive empty arm returns a
1306        // parser-shaped reason rather than silently falling through to
1307        // the Capability arm). Same trajectory as c4213a4 (WitContract
1308        // endpoint/subject/slot value-shape gates lifted into
1309        // `target()`) on the peer payload axes.
1310        if let Err(reason) = crate::render::is_wit_world_ref(&self.wit) {
1311            let (de, para, wit) = edge();
1312            return Err(AplicacaoError::ContratoWitInvalid {
1313                de,
1314                para,
1315                wit,
1316                reason,
1317            });
1318        }
1319
1320        if self.is_http() {
1321            if subject.is_some() || slot.is_some() {
1322                let (de, para, wit) = edge();
1323                return Err(AplicacaoError::ContratoWrongTarget {
1324                    de,
1325                    para,
1326                    wit,
1327                    expected: WitTarget::HTTP_FIELD_NAME,
1328                });
1329            }
1330            let ep = endpoint.ok_or_else(|| {
1331                let (de, para, wit) = edge();
1332                AplicacaoError::ContratoMissingTarget {
1333                    de,
1334                    para,
1335                    wit,
1336                    expected: WitTarget::HTTP_FIELD_NAME,
1337                }
1338            })?;
1339            if ep.is_empty() {
1340                let (de, para) = self.edge_pair();
1341                return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
1342            }
1343            if !ep.starts_with('/') {
1344                let (de, para) = self.edge_pair();
1345                return Err(AplicacaoError::ContratoEndpointNotAbsolute {
1346                    de,
1347                    para,
1348                    endpoint: ep.to_string(),
1349                });
1350            }
1351            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1352            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1353            // API v1 HTTPPathMatch.value admission grammar with the
1354            // sibling `:entrada :paths` axis. Until this gate landed
1355            // `target()` only refused the empty string + the missing-
1356            // leading-`/` form; a structurally invalid endpoint
1357            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1358            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1359            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1360            // path-traversal segment, the >1024-byte slug) silently
1361            // passed validate and the failure surfaced at apply time
1362            // as a Cilium policy rejection / silent traffic drop, far
1363            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1364            // grammar `:entrada :paths` already gates (55410e4), now
1365            // shared with `:contratos :endpoint` through the lifted
1366            // `crate::render::is_gateway_api_http_path` predicate.
1367            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1368                let (de, para) = self.edge_pair();
1369                return Err(AplicacaoError::ContratoEndpointInvalid {
1370                    de,
1371                    para,
1372                    endpoint: ep.to_string(),
1373                    reason,
1374                });
1375            }
1376            return Ok(WitTarget::Http { endpoint: ep });
1377        }
1378        if self.is_pubsub() {
1379            if endpoint.is_some() || slot.is_some() {
1380                let (de, para, wit) = edge();
1381                return Err(AplicacaoError::ContratoWrongTarget {
1382                    de,
1383                    para,
1384                    wit,
1385                    expected: WitTarget::PUBSUB_FIELD_NAME,
1386                });
1387            }
1388            let s = subject.ok_or_else(|| {
1389                let (de, para, wit) = edge();
1390                AplicacaoError::ContratoMissingTarget {
1391                    de,
1392                    para,
1393                    wit,
1394                    expected: WitTarget::PUBSUB_FIELD_NAME,
1395                }
1396            })?;
1397            if s.is_empty() {
1398                let (de, para) = self.edge_pair();
1399                return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1400            }
1401            // The `:subject` lands at runtime as the NATS subject the
1402            // producer publishes to and the consumer subscribes from.
1403            // Until this gate landed `target()` only refused the
1404            // empty string; a structurally invalid subject
1405            // (`"foo..bar"` — empty token between separators,
1406            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1407            // server's subject parser rejects, `"foo bar"` —
1408            // un-percent-encoded whitespace, `"foo.café"` —
1409            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1410            // empty leading/trailing tokens, the >256-byte
1411            // paste-from-binary slug) silently passed validate and
1412            // the failure surfaced at runtime as a NATS server-side
1413            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1414            // a silent message drop, far from the source caixa.lisp.
1415            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1416            // trajectory `:contratos :endpoint` (4f0390b) and
1417            // `:contratos :wit` (6226bf4) already gate, now shared
1418            // with `:contratos :subject` through the lifted
1419            // `crate::render::is_nats_subject` predicate.
1420            if let Err(reason) = crate::render::is_nats_subject(s) {
1421                let (de, para) = self.edge_pair();
1422                return Err(AplicacaoError::ContratoSubjectInvalid {
1423                    de,
1424                    para,
1425                    subject: s.to_string(),
1426                    reason,
1427                });
1428            }
1429            return Ok(WitTarget::PubSub { subject: s });
1430        }
1431        if self.is_store() {
1432            if endpoint.is_some() || subject.is_some() {
1433                let (de, para, wit) = edge();
1434                return Err(AplicacaoError::ContratoWrongTarget {
1435                    de,
1436                    para,
1437                    wit,
1438                    expected: WitTarget::STORE_FIELD_NAME,
1439                });
1440            }
1441            let sl = slot.ok_or_else(|| {
1442                let (de, para, wit) = edge();
1443                AplicacaoError::ContratoMissingTarget {
1444                    de,
1445                    para,
1446                    wit,
1447                    expected: WitTarget::STORE_FIELD_NAME,
1448                }
1449            })?;
1450            if sl.is_empty() {
1451                let (de, para) = self.edge_pair();
1452                return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1453            }
1454            // Value-shape gate on the third (and last) typed payload
1455            // axis the `WitContract::target` dispatch carries — the
1456            // peer of [`crate::render::is_gateway_api_http_path`] for
1457            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1458            // for `:subject` (63e18a0). Until this gate landed
1459            // `target()` only refused the empty string; a structurally
1460            // invalid slot (`"check out/$order"` — un-percent-encoded
1461            // whitespace whose runtime behavior varies unpredictably
1462            // across kv backends, `"checkout/\x01order"` — control
1463            // character that Redis admits but corrupts on next read
1464            // and DynamoDB rejects outright, `"chéckout/$order"` —
1465            // un-percent-encoded non-ASCII byte each backend re-encodes
1466            // differently, `"checkout\n/$order"` — embedded newline,
1467            // the 513-byte paste-from-binary slug) silently passed
1468            // validate and surfaced at runtime as a per-backend kv
1469            // write rejection (DynamoDB / etcd) or as a silent
1470            // next-read corruption (Redis-via-RESP3), far from the
1471            // source caixa.lisp with no field naming which `:contratos`
1472            // edge carried the typo. The lifted predicate makes the
1473            // kv-backend intersection-floor a substrate-level
1474            // invariant at validate time, not a runtime "this passed
1475            // validate but the kv backend rejected on first write"
1476            // surprise — closes the typed payload-axis value-shape
1477            // trajectory across all three legs of the four
1478            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1479            // that caixa-mesh + the future kv emitters land in.
1480            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1481                let (de, para) = self.edge_pair();
1482                return Err(AplicacaoError::ContratoSlotInvalid {
1483                    de,
1484                    para,
1485                    slot: sl.to_string(),
1486                    reason,
1487                });
1488            }
1489            return Ok(WitTarget::Store { slot: sl });
1490        }
1491
1492        // Unrecognized WIT world — must not carry any payload target.
1493        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1494            let (de, para, wit) = edge();
1495            return Err(AplicacaoError::ContratoWrongTarget {
1496                de,
1497                para,
1498                wit,
1499                expected: WitTarget::CAPABILITY_EXPECTED,
1500            });
1501        }
1502        Ok(WitTarget::Capability)
1503    }
1504
1505    /// Substrate-canonical post-validation projection of the typed
1506    /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
1507    /// downstream of an [`AplicacaoSpec`] that has already crossed the
1508    /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
1509    /// [`typed_view`]-shaped entry point that composes `validate` into
1510    /// the projection) reaches through when it needs the typed
1511    /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
1512    /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
1513    /// coherence for every `:contratos` entry. The peer accessor to the
1514    /// [`Self::target`] `Result`-returning validator on the same
1515    /// per-`:contratos` typed-projection axis — [`Self::target`] is the
1516    /// pre-validation validator that computes the projection *and* raises
1517    /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
1518    /// (`:wit`, payload) mismatch; this method is the post-validation
1519    /// projection every downstream consumer reaches through once the
1520    /// pre-validation gate has succeeded.
1521    ///
1522    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1523    ///
1524    /// Prior to this lift the "call `.target()` then `.expect(…)` with
1525    /// the same message" pattern sat inline at two production sites with
1526    /// no compile-time link between them: the
1527    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
1528    /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
1529    /// (`c.target().expect("validated by typed_view").http_endpoint()`)
1530    /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
1531    /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
1532    /// (`c.target().expect("validated by typed_view").graph_label()`),
1533    /// each open-coding the same `.target().expect("validated by
1534    /// typed_view")` pair with the message spelled twice. A future
1535    /// vocabulary shift on the panic-message axis (a tightening from
1536    /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
1537    /// validate"` as the substrate's validator entry-point vocabulary
1538    /// sharpens, a per-consumer disambiguation, an M4 promotion of the
1539    /// panic to a `debug_assert` under a `--release` build profile) would
1540    /// have had to be threaded through both open-coded call sites in
1541    /// lockstep or one consumer would silently disagree with the peer on
1542    /// which invariant the panic message names. Same "same shape written
1543    /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
1544    /// discipline the sibling [`Self::edge_pair`] /
1545    /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
1546    /// lifts already establish on the paired composite-projection axis;
1547    /// this lift extends it onto the post-validation typed-view axis.
1548    ///
1549    /// Every future downstream consumer of the projected typed view
1550    /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
1551    /// CR materializer's per-edge admission webhook, the future
1552    /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
1553    /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
1554    /// resolver, the future `feira app graph --l7` / `--pubsub` /
1555    /// `--kv` per-shape column emitters) reaches through this one typed
1556    /// dispatch on the substrate primitive rather than an open-coded
1557    /// per-consumer `.target().expect(…)` pair with the message
1558    /// re-inlined. The invariant the accessor's panic path pins — "this
1559    /// call is only reachable after [`AplicacaoSpec::validate`] has
1560    /// succeeded on the containing spec" — is the substrate's answer to
1561    /// give exactly once, at the primitive, not once per consumer.
1562    ///
1563    /// # Panics
1564    ///
1565    /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
1566    /// would return an `Err` — i.e. if this contract's
1567    /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
1568    /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
1569    /// this accessor only from a code path that has already reached the
1570    /// containing [`AplicacaoSpec`] through a validating entry-point
1571    /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
1572    /// [`typed_view`] compose, the future M4 CR admission webhook's
1573    /// per-CR validate). Use [`Self::target`] instead on any pre-
1574    /// validation code path.
1575    ///
1576    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1577    #[must_use]
1578    pub fn target_projected(&self) -> WitTarget<'_> {
1579        self.target().expect(Self::PROJECTED_INVARIANT_MSG)
1580    }
1581
1582    /// Canonical panic message the [`Self::target_projected`]
1583    /// post-validation projection accessor threads through when the
1584    /// caller has violated the "call only after [`AplicacaoSpec::validate`]
1585    /// has succeeded" precondition. Lifted as a `pub const` on the
1586    /// [`WitContract`] surface so the byte-string lives in one place
1587    /// across the substrate — the [`Self::target_projected`] method
1588    /// body, the two prior production call sites' comments now naming
1589    /// the const, and every future consumer that must format-match the
1590    /// panic-message shape (a future test suite that asserts the panic-
1591    /// message byte-string across a fuzzed invalid-contract corpus,
1592    /// a future custom-panic hook in `caixa-operator` that surfaces the
1593    /// message with per-`:contratos` telemetry, the future admission
1594    /// webhook's per-CR validate-error report) reaches through the same
1595    /// canonical `&'static str`. A future rebrand on the panic-message
1596    /// axis (a tightening from `"validated by typed_view"` to `"validated
1597    /// by AplicacaoSpec::validate"` as the substrate's validator
1598    /// entry-point vocabulary sharpens once caixa-core grows a
1599    /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
1600    /// [`typed_view`]) lands at one caixa-core edit rather than a
1601    /// coordinated per-consumer sweep — same "one canonical declaration
1602    /// per axis, next to the accessor that reads it" discipline the peer
1603    /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
1604    /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
1605    /// const family already establishes on the paired per-consumer-axis
1606    /// diagnostic-scalar surface.
1607    pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
1608}
1609
1610/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1611/// gate (see [`AplicacaoSpec::validate`]): every field that
1612/// distinguishes one contract from another, in declaration order
1613/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1614/// with equal [`ContratoIdentity`]s are the same typed edge declared
1615/// twice — the graph-edge analogue of duplicate `:membros` /
1616/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1617/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1618/// clippy's `type_complexity` lint (and so a future axis added to
1619/// `WitContract` is one alias edit, not a coordinated rewrite of
1620/// every set instantiation).
1621pub type ContratoIdentity<'a> = (
1622    &'a str,
1623    &'a str,
1624    &'a str,
1625    Option<&'a str>,
1626    Option<&'a str>,
1627    Option<&'a str>,
1628);
1629
1630/// Typed view of a [`WitContract`]'s payload target. Each variant
1631/// carries the field its WIT shape requires; constructing a `Http`
1632/// view without an endpoint is impossible by the type system.
1633///
1634/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1635/// instead of probing `Option<String>` fields one by one — the
1636/// "which payload field is set?" question is answered once, at
1637/// validation time.
1638#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1639pub enum WitTarget<'a> {
1640    /// HTTP-shaped WIT world. Carries the configured request path.
1641    Http { endpoint: &'a str },
1642    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1643    ///
1644    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1645    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1646    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1647    /// method name byte-identical to the sibling
1648    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1649    /// arm-discriminator that routes through
1650    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1651    /// through `matches!` on the variant), so the two arm-discriminator
1652    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1653    /// every downstream consumer through the same `is_pubsub()` name.
1654    #[is_variant(name = "pubsub")]
1655    PubSub { subject: &'a str },
1656    /// Key-value-shaped WIT world. Carries the slot template.
1657    Store { slot: &'a str },
1658    /// A typed capability edge with no payload selector — the WIT
1659    /// world stands on its own (rare; reserved for plain capability
1660    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1661    Capability,
1662}
1663
1664impl<'a> WitTarget<'a> {
1665    /// Canonical author-facing `:contratos` payload field name for the
1666    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1667    /// [`AplicacaoError::ContratoMissingTarget`] /
1668    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1669    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1670    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1671    /// the `feira app graph` verb prints. Peer of
1672    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1673    /// on the payload-field-name axis; declared as a peer const next
1674    /// to the [`WitTarget::Http`] variant so a future rename on the
1675    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1676    /// :endpoint …)))` field lands in exactly one place, not scattered
1677    /// across the [`WitContract::target`] gate's six `expected:`
1678    /// literals, the label template, and every downstream consumer
1679    /// that prints a per-arm prefix. Same trajectory as the peer
1680    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1681    /// for the arm's shape, next to the variant declaration.
1682    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1683    /// Canonical author-facing `:contratos` payload field name for the
1684    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1685    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1686    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1687    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1688    /// Canonical author-facing `:contratos` payload field name for the
1689    /// key/value-store-shaped arm. Peer of
1690    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1691    /// on the payload-field-name axis; see
1692    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1693    pub const STORE_FIELD_NAME: &'static str = "slot";
1694
1695    /// Canonical stable human-readable label the payload-less
1696    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1697    /// the byte-string every consumer that formats a payload-less
1698    /// typed capability edge as text lands on (the
1699    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1700    /// naming which identical edge was declared twice, the future
1701    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1702    /// policy resolver's audit view, the operator's mesh-graph audit).
1703    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1704    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1705    /// author-facing label-scalar consts — the same
1706    /// "one canonical declaration per arm, next to the variant, so a
1707    /// future rename lands in one place" discipline extended to the
1708    /// payload-less arm. Until this lift landed the byte-string sat
1709    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1710    /// match arm, once in the pin test asserting the label's
1711    /// [`WitTarget::Capability`] output — with no compile-time link
1712    /// between the two: a rebrand on either side (an operator-facing
1713    /// vocabulary shift, a per-consumer disambiguation like
1714    /// `"(capability — no payload; typed edge only)"`) would silently
1715    /// desynchronize until a downstream consumer surfaced the drift at
1716    /// runtime.
1717    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1718
1719    /// Canonical `expected:` scalar the
1720    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1721    /// through for the payload-less [`WitTarget::Capability`] arm — the
1722    /// byte-string authors read as "this WIT world's shape is not one
1723    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1724    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1725    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1726    /// [`Self::STORE_FIELD_NAME`] consts on the
1727    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1728    /// same "which payload field name goes in the diagnostic" dispatch
1729    /// the three payload-arm consts cover, extended to the payload-less
1730    /// arm. Until this lift landed the byte-string sat twice — once
1731    /// inline in the [`Self::target`] Capability-arm rejection at the
1732    /// production dispatch, once in the pin test asserting the
1733    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1734    /// no compile-time link between the two: a rebrand on either side
1735    /// (an author-facing vocabulary shift to `"capability"` /
1736    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1737    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1738    /// [`WitTarget::Capability`] into per-shape peers) would silently
1739    /// desynchronize until a downstream consumer surfaced the drift at
1740    /// runtime. Same "one canonical declaration per arm, next to the
1741    /// variant, so a future rename lands in one place" discipline the
1742    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1743    /// established for the payload-less arm's human-readable label
1744    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1745    /// so both halves of the "how does the Capability arm surface at
1746    /// its two consumer axes (human-readable label, wrong-target
1747    /// diagnostic)" pipeline route through peer consts declared next
1748    /// to the variant.
1749    ///
1750    /// Pairwise-distinctness against the three payload-arm scalars
1751    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1752    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1753    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1754    /// test — the 4-way closure of the 3-way
1755    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1756    /// the `ContratoWrongTarget::expected` axis, matching the peer
1757    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1758    /// scalar-value distinctness discipline the sibling M3 typed-enum
1759    /// discriminator axis already carries.
1760    pub const CAPABILITY_EXPECTED: &'static str = "none";
1761
1762    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1763    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1764    /// as under [`Self::graph_label`] — the sibling
1765    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1766    /// payload-column axis (the graph verb spells payload-less as
1767    /// `(capability-only)`, distinct from the duplicate-`:contratos`
1768    /// diagnostic's `(capability — no payload)` on the human-readable
1769    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1770    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1771    /// family — extends the "one canonical declaration per arm, next to
1772    /// the variant, so a future rename lands in one place" discipline
1773    /// onto the third payload-less-arm consumer axis (`feira app graph`
1774    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1775    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1776    /// axis).
1777    ///
1778    /// Until this lift landed the byte-string sat inline in
1779    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1780    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1781    /// `"(capability-only)".to_string()` literal, with no compile-time link
1782    /// back to the [`WitTarget::Capability`] variant declaration nor to
1783    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1784    /// peer consts already carrying the "one canonical declaration per
1785    /// payload-less-arm consumer axis" discipline. A rebrand on either
1786    /// side (the graph verb's operator-facing vocabulary tightening from
1787    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1788    /// the WIT registry vocabulary sharpens, an M4 split of
1789    /// [`Self::Capability`] into per-shape peers) would silently
1790    /// desynchronize the graph-verb byte-string from the paired
1791    /// per-arm-adjacent const and land two spellings of the same axis in
1792    /// two spots.
1793    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1794
1795    /// The `(author-facing field name, payload)` pair this typed target
1796    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1797    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1798    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1799    /// [`Self::Store`], `None` for the payload-less
1800    /// [`Self::Capability`] arm.
1801    ///
1802    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1803    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1804    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1805    /// (returns the first component) route through, so a future
1806    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1807    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1808    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1809    /// exactly one new match-arm here (a compile-time exhaustiveness
1810    /// error otherwise), not a coordinated three-way rewrite of the
1811    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1812    /// + every downstream consumer that reaches for the pair.
1813    ///
1814    /// Until this lift landed the three payload arms sat in
1815    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1816    /// invocations (one per variant, each hand-quoting the paired
1817    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1818    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1819    /// "same shape, written N times" duplication THEORY.md §I.3.5
1820    /// ("Generation first, composition second, hand-authoring last;
1821    /// the duplication budget is zero") promotes to a build-time
1822    /// concern, with each per-arm site paired to its own const with no
1823    /// compile-time link between the format template and the arm's
1824    /// payload extraction.
1825    #[must_use]
1826    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1827        match *self {
1828            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1829            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1830            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1831            WitTarget::Capability => None,
1832        }
1833    }
1834
1835    /// The canonical author-facing `:contratos` payload field name
1836    /// this typed target arm carries (`Http` → `Some("endpoint")`,
1837    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1838    /// `None` for the payload-less `Capability` arm.
1839    ///
1840    /// Routes through [`Self::payload_pair`] — the single 4-arm
1841    /// dispatch [`Self::label`] also reads — so a future variant
1842    /// addition is one match-arm edit at [`Self::payload_pair`], not a
1843    /// per-consumer rewrite. Same "exhaustive-match at one canonical
1844    /// dispatch, thin projections at each consumer" trajectory the
1845    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1846    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1847    #[must_use]
1848    pub const fn field_name(&self) -> Option<&'static str> {
1849        match self.payload_pair() {
1850            Some((f, _)) => Some(f),
1851            None => None,
1852        }
1853    }
1854
1855    /// The underlying scalar the payload-carrying arm carries — the
1856    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
1857    /// subject ([`Self::PubSub`] `:subject`), or slot template
1858    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
1859    /// `&'a str` storage — or `None` on the payload-less
1860    /// [`Self::Capability`] arm.
1861    ///
1862    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
1863    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
1864    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
1865    /// the paired sub-selector axis. Both per-half accessors read from
1866    /// one authoritative match, so a future [`WitTarget`] variant
1867    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
1868    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
1869    /// on [`Self::payload_pair`] and both per-half projections + every
1870    /// downstream consumer picks the new arm up by construction — no
1871    /// coordinated N-way rewrite across the paired accessor dispatches,
1872    /// the [`Self::label`] / [`Self::graph_label`] format templates,
1873    /// and every future WIT-registry-shaped consumer.
1874    ///
1875    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
1876    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
1877    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
1878    /// both per-half projections as thin readers, every downstream
1879    /// consumer through the same match" discipline extended onto the
1880    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
1881    /// gap between the two paired-dispatch surfaces: the peer
1882    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
1883    /// the first-component projection until this lift; the second-
1884    /// component sibling now sits alongside so both halves reach every
1885    /// future consumer through the same substrate-primitive dispatch.
1886    ///
1887    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
1888    #[must_use]
1889    pub const fn payload(&self) -> Option<&'a str> {
1890        match self.payload_pair() {
1891            Some((_, p)) => Some(p),
1892            None => None,
1893        }
1894    }
1895
1896    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
1897    /// consumer that fans on the L7-HTTP-shaped payload keys off —
1898    /// returns the [`Self::Http`]-arm's author-declared request path
1899    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
1900    /// projected target is [`Self::Http { endpoint }`], `None` on the
1901    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
1902    /// [`Self::Capability`], each of which carries no HTTP endpoint by
1903    /// definition).
1904    ///
1905    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
1906    /// `path:` rule payload every substrate-side L7-introspecting
1907    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
1908    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
1909    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
1910    /// on the L7 introspection branch; every peer WIT shape stays
1911    /// L4-only because Cilium can't introspect NATS / key-value / plain
1912    /// capability edges), and every future L7-introspecting consumer
1913    /// of the projected target's HTTP endpoint (the future M4
1914    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
1915    /// materializer's per-edge L7 admission-webhook overlay, the
1916    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
1917    /// path bucket-key resolver, the future per-`:contratos`-edge
1918    /// mTLS-required overlay's HTTP-shape scope filter, the future
1919    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
1920    /// through the same typed dispatch.
1921    ///
1922    /// Prior to this lift the sole production consumer of the projected-
1923    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
1924    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
1925    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
1926    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
1927    /// }`) — reached the payload through a raw per-arm `if let` pattern-
1928    /// match that expressed no compile-time link back to the substrate
1929    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
1930    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
1931    /// scalar accessor on the peer per-`:contratos` raw-field axis but
1932    /// with no post-projection peer on the typed-view surface. A future
1933    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
1934    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
1935    /// gRPC-shaped worlds per this enum's own docstring at
1936    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
1937    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
1938    /// would have had to be threaded through the caixa-mesh L7 emit
1939    /// branch's raw `if let` in lockstep — either coalescing the two
1940    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
1941    /// emit path per-arm — with no substrate-primitive dispatch making
1942    /// the "which arms count as L7-HTTP-shaped for path-emission
1943    /// purposes" question the substrate's answer to give. Lifting the
1944    /// resolution to a typed method on the substrate primitive means
1945    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
1946    /// projected-target HTTP endpoint reaches for exactly one typed
1947    /// dispatch — the resolver's accept-set migrates as a unit on any
1948    /// future arm-family widening, and the caixa-mesh L7 emit branch
1949    /// reads through the same substrate primitive.
1950    ///
1951    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
1952    /// (7020470) `Option<&str>` scalar accessor on the raw
1953    /// `:contratos :endpoint` field-access axis — same "one typed
1954    /// dispatch on the substrate primitive, thin projections at each
1955    /// consumer" discipline extended onto the peer post-projection typed-
1956    /// view surface (the [`WitContract::endpoint`] pre-projection
1957    /// accessor returns `Some` for any author-declared `:endpoint`
1958    /// value regardless of the paired `:wit` world's HTTP-shape
1959    /// classification — the raw slot before validation crosses it —
1960    /// while this post-projection [`Self::http_endpoint`] accessor
1961    /// returns `Some` iff the target has been projected onto the
1962    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
1963    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
1964    /// coherence; the two accessors close the pre-projection /
1965    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
1966    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
1967    /// the three payload-carrying arms) — extends the per-arm
1968    /// projection family onto the [`Self::Http`] specialization axis
1969    /// that the pan-arm accessor's shape blends into a single arm-
1970    /// agnostic view; paired with [`Self::pubsub_subject`] /
1971    /// [`Self::store_slot`] on the sibling per-arm axes so every
1972    /// per-payload-arm shape carries a named post-projection accessor
1973    /// on the same shape as `http_endpoint`, closing the per-arm-shape
1974    /// accept-set the substrate primitive owns.
1975    #[must_use]
1976    pub const fn http_endpoint(&self) -> Option<&'a str> {
1977        match *self {
1978            WitTarget::Http { endpoint } => Some(endpoint),
1979            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
1980        }
1981    }
1982
1983    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
1984    /// consumer that fans on the pub-sub-shaped payload keys off —
1985    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
1986    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
1987    /// the projected target is [`Self::PubSub { subject }`], `None` on
1988    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
1989    /// [`Self::Capability`], each of which carries no NATS-shaped
1990    /// subject by definition).
1991    ///
1992    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
1993    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
1994    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
1995    /// CR materializer's `spec.subjects[]` projection, the future
1996    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
1997    /// bucket-key resolver, the future `feira app graph --pubsub`
1998    /// per-Aplicacao subject column, any future substrate-lifted
1999    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
2000    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
2001    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
2002    /// future pub-sub-shape consumer reaches for the same typed
2003    /// dispatch this accessor exposes so the "which arm carries the
2004    /// subject scalar?" answer lives at one caixa-core edit rather
2005    /// than open-coded across per-consumer `if let WitTarget::PubSub
2006    /// { subject } = c.target()…` pattern-matches.
2007    ///
2008    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2009    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2010    /// the pre-projection [`WitContract::subject`] scalar accessor on
2011    /// the raw `:contratos :subject` field-access axis — same "one
2012    /// typed dispatch on the substrate primitive, thin projections at
2013    /// each consumer" discipline extended onto the per-arm pub-sub
2014    /// post-projection axis. The pre-projection accessor returns
2015    /// `Some` for any author-declared `:subject` value regardless of
2016    /// the paired `:wit` world's pub-sub-shape classification (the raw
2017    /// slot before validation crosses it); this post-projection
2018    /// accessor returns `Some` iff the target has been projected onto
2019    /// the [`Self::PubSub`] arm, i.e. only after the
2020    /// [`WitContract::target`] gate has admitted the
2021    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2022    /// the pre-/post-projection pair on the pub-sub-subject axis to
2023    /// match the pair the [`WitContract::endpoint`] +
2024    /// [`Self::http_endpoint`] surfaces already close on the peer
2025    /// HTTP-endpoint axis.
2026    ///
2027    /// Sibling of the unified pan-arm [`Self::payload`]
2028    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2029    /// extends the per-arm projection family onto the [`Self::PubSub`]
2030    /// specialization axis that the pan-arm accessor's shape blends
2031    /// into a single arm-agnostic view; the pair
2032    /// (`pubsub_subject`, `store_slot`) closes the trio
2033    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2034    /// payload arm now carries its own per-arm-shape post-projection
2035    /// accessor.
2036    #[must_use]
2037    pub const fn pubsub_subject(&self) -> Option<&'a str> {
2038        match *self {
2039            WitTarget::PubSub { subject } => Some(subject),
2040            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2041        }
2042    }
2043
2044    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2045    /// every consumer that fans on the store-shaped payload keys off —
2046    /// returns the [`Self::Store`]-arm's author-declared slot template
2047    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2048    /// projected target is [`Self::Store { slot }`], `None` on the
2049    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2050    /// [`Self::Capability`], each of which carries no
2051    /// key/value-store slot by definition).
2052    ///
2053    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2054    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2055    /// every future substrate-side store-introspecting per-`(:de,
2056    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2057    /// namespace / prefix reconciler's per-slot projection, the future
2058    /// per-store-backend routing overlay's slot-shape gate, the future
2059    /// `feira app graph --store` per-Aplicacao slot column, any future
2060    /// substrate-lifted store-shape emitter that reads a projected
2061    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2062    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2063    /// Every future store-shape consumer reaches for the same typed
2064    /// dispatch this accessor exposes so the "which arm carries the
2065    /// slot scalar?" answer lives at one caixa-core edit rather than
2066    /// open-coded across per-consumer
2067    /// `if let WitTarget::Store { slot } = c.target()…`
2068    /// pattern-matches.
2069    ///
2070    /// Peer of the sibling [`Self::http_endpoint`] +
2071    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2072    /// axes and of the pre-projection [`WitContract::slot`] scalar
2073    /// accessor on the raw `:contratos :slot` field-access axis — same
2074    /// "one typed dispatch on the substrate primitive, thin projections
2075    /// at each consumer" discipline extended onto the per-arm store
2076    /// post-projection axis. Closes the pre-/post-projection pair on
2077    /// the store-slot axis to match the pairs the
2078    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2079    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2080    /// already close on the peer HTTP-endpoint and pub-sub-subject
2081    /// axes; the substrate-side pre-/post-projection accessor family
2082    /// now spans all three payload arms as a matched trio, so any
2083    /// future arm-shape widening (a `Rest`/`Grpc` split of
2084    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2085    /// lands one accessor without threading through the sibling
2086    /// pre-projection or the peer per-arm post-projection surfaces a
2087    /// compile-time exhaustiveness error at the substrate primitive,
2088    /// not a silent per-consumer split at renderer emit time.
2089    ///
2090    /// Sibling of the unified pan-arm [`Self::payload`]
2091    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2092    /// closes the per-arm projection family onto the [`Self::Store`]
2093    /// specialization axis that the pan-arm accessor's shape blends
2094    /// into a single arm-agnostic view. The trio
2095    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2096    /// pan-arm accept-set on every payload-carrying arm: exactly one
2097    /// per-arm accessor returns `Some(payload)` and the two peers
2098    /// return `None`, and every payload-less [`Self::Capability`]
2099    /// input returns `None` on all three — the partition the sibling
2100    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2101    /// pin locks in load-bearing.
2102    #[must_use]
2103    pub const fn store_slot(&self) -> Option<&'a str> {
2104        match *self {
2105            WitTarget::Store { slot } => Some(slot),
2106            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2107        }
2108    }
2109
2110    /// Render this typed target as a stable human-readable label
2111    /// (`:endpoint "/charge"`, `:subject "events.x"`,
2112    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2113    /// the WIT world is a pure capability edge).
2114    ///
2115    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2116    /// gate so the diagnostic names *which* identical edge was
2117    /// declared twice (not just which `(de, para, wit)` triple).
2118    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2119    /// on the payload-carrying arms (`Some((field, payload)) →
2120    /// format!(":{field} {payload:?}")`) and through the lifted
2121    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2122    /// [`Self::Capability`] arm — so a future variant addition (the
2123    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2124    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2125    /// `Queue`-shaped peer) becomes a single new match-arm on
2126    /// [`Self::payload_pair`] rather than a rewrite of this template
2127    /// (and every downstream consumer that reaches for the label
2128    /// shape: the per-edge policy resolver in M4, the `feira app
2129    /// graph` view, the operator's mesh-graph audit). Until this
2130    /// lift landed the three payload arms carried three near-identical
2131    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2132    /// [`Self::Capability`] arm carried the payload-less byte-string
2133    /// twice (once inline here, once in the pin test) — closing the
2134    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2135    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2136    /// / 4a1e490) peer-const lifts already established for the
2137    /// payload-carrying arms.
2138    #[must_use]
2139    pub fn label(&self) -> String {
2140        match self.payload_pair() {
2141            Some((field, payload)) => format!(":{field} {payload:?}"),
2142            None => Self::CAPABILITY_LABEL.to_string(),
2143        }
2144    }
2145
2146    /// Render this typed target as the `feira app graph` per-`:contratos`
2147    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2148    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2149    /// payload-less arm).
2150    ///
2151    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2152    /// on the payload-carrying arms (`Some((field, payload)) →
2153    /// format!("{field}={payload}")`) and through the lifted
2154    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2155    /// [`Self::Capability`] arm — so a future variant addition
2156    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2157    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2158    /// `Queue`-shaped peer) becomes one match-arm edit at
2159    /// [`Self::payload_pair`], propagating through this graph-verb
2160    /// projection at zero call-site cost, sibling to the peer
2161    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2162    /// same 4-arm dispatch.
2163    ///
2164    /// Until this lift landed the [`caixa-feira`]
2165    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2166    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2167    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2168    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2169    /// `format!("{}={endpoint}", ...)` template and hard-coding
2170    /// `"(capability-only)"` as a fifth payload-less scalar with no link
2171    /// back to the paired [`WitTarget::Capability`] variant declaration.
2172    /// A future variant addition would have had to be threaded through
2173    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2174    /// verb's inline match in lockstep or the two projections would
2175    /// silently disagree on the arm-set the graph verb prints — the
2176    /// duplicate-`:contratos` diagnostic reading one shape while the
2177    /// graph verb's payload column silently dropped the new arm to
2178    /// `(capability-only)`. Lifting the graph-verb projection onto the
2179    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2180    /// the axis: both projections migrate as a unit.
2181    ///
2182    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2183    /// quoting) shape is graph-verb-canonical — distinct from the
2184    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2185    /// duplicate-`:contratos` diagnostic seeds (see
2186    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2187    /// on the payload-less axis for the paired distinction).
2188    #[must_use]
2189    pub fn graph_label(&self) -> String {
2190        match self.payload_pair() {
2191            Some((field, payload)) => format!("{field}={payload}"),
2192            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2193        }
2194    }
2195}
2196
2197/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2198/// pretty-printed byte-string every consumer that formats a typed
2199/// payload target as user-facing text lands on (the
2200/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2201/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2202/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2203/// graph` per-`:contratos`-edge payload column that reaches the graph
2204/// verb through `format!("{target}")`, the future M4 per-edge policy
2205/// resolver's per-edge audit-log line, the operator's mesh-graph
2206/// per-edge inspection view) reaches for the same lifted
2207/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2208/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2209/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2210/// routes through — extending the three-path-convergence
2211/// (`Debug` for structural inspection, `Display` for user-facing text,
2212/// per-arm typed accessor for the canonical byte-string) discipline the
2213/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2214/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2215/// onto the fourth (and only remaining) typed-shape-discriminator axis
2216/// on the caixa surface.
2217///
2218/// Pre-lift the two paths were structurally independent — every consumer
2219/// reaching for a payload byte-string past the [`WitTarget::label`]
2220/// helper had to pick between three paths ([`WitTarget::label`],
2221/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2222/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2223/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2224/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2225/// that reached for `format!("{target}")` — the canonical shape every
2226/// user-facing pretty-print site on the sibling typed-enum axes already
2227/// uses — would silently land on the `Debug` derive's structural output
2228/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2229/// than the `label()` helper's stable byte-string (`:endpoint
2230/// "/charge"` — the author-facing `:contratos` keyword form) the
2231/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2232/// already threads through. The two spellings would diverge silently in
2233/// every downstream diagnostic / graph / audit line reached through
2234/// `format!` rather than through the `label()` helper. Routing
2235/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2236/// path: every `format!("{v}")` call reaches the same
2237/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2238/// and the duplicate-`:contratos` gate already route through, so a
2239/// future variant addition (the M4-and-later per-edge WIT registry may
2240/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2241/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2242/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2243/// match — rather than fanning out through hand-rolled per-arm
2244/// [`std::fmt::Display`] arms.
2245///
2246/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2247/// is the typed view returned by [`WitContract::target`], not a
2248/// closed-set discriminator enum with a gen-platform Discriminant
2249/// registration, so the `Debug` derive's structural output (which every
2250/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2251/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2252/// shape for structural inspection; `Display` (via `label`) reveals the
2253/// stable author-facing payload projection.
2254///
2255/// Pin tests
2256/// [`tests::wit_target_display_routes_through_label_helper`] and
2257/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2258/// assert the two paths agree byte-for-byte on every variant, so a
2259/// future variant addition or `label()` reimplementation that hand-rolls
2260/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2261/// build error visible at caixa-core test time, not a silent
2262/// per-consumer dispatch miss at diagnostic / audit / graph time.
2263impl std::fmt::Display for WitTarget<'_> {
2264    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2265        f.write_str(&self.label())
2266    }
2267}
2268
2269// ── one Aplicacao member ─────────────────────────────────────────────
2270
2271/// A Servico participating in the Aplicacao. Same shape as
2272/// `crate::supervisor::ChildSpec` but without a restart policy —
2273/// supervision is per-Servico (each member has its own
2274/// `:supervisor`), the Aplicacao orchestrates *placement*.
2275#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2276#[serde(rename_all = "camelCase")]
2277pub struct Membro {
2278    /// Member caixa's `:nome`. Resolves through the same dep
2279    /// resolution path as `crate::dep::Dep`.
2280    pub caixa: String,
2281
2282    /// Semver constraint.
2283    pub versao: String,
2284}
2285
2286impl Membro {
2287    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2288    /// accessor every consumer that reads the member's Servico identity
2289    /// keys off — returns the author-declared `:membros :caixa`
2290    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2291    /// own [`String`] storage.
2292    ///
2293    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2294    /// participating in the Aplicacao — validated by
2295    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2296    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2297    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2298    /// [`validate_no_self_membership`]) — and every downstream consumer
2299    /// that fans on the member's identity keys off this scalar (the
2300    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2301    /// lookup, the per-`:membros` duplicate gate's dedup key, the
2302    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2303    /// identity, the self-membership gate, the
2304    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2305    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2306    /// CR materializer's per-member resolver).
2307    ///
2308    /// Prior to this lift the `.caixa` byte-string was read inline at
2309    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2310    /// set collector at
2311    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2312    /// [`validate_membros`] validation-side member-caixa gate at
2313    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2314    /// per-member duplicate-gate dedup key at
2315    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2316    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2317    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2318    /// [`validate_no_self_membership`] self-loop gate at
2319    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2320    /// expressed no compile-time link back to the typed slot. Every
2321    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2322    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2323    /// `name:` axis, so a future extension of the `:membros :caixa`
2324    /// axis to a richer author surface — a per-cluster alias table the
2325    /// operator pins through a future `:placement`-scoped slot, a
2326    /// namespace-qualified rewrite the M4 CR materializer applies
2327    /// per-CR, a per-member overlay from the future `:membros
2328    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2329    /// acknowledges — would have had to be threaded through every
2330    /// open-coded copy in lockstep or one consumer would silently
2331    /// disagree with the peers on which caixa a given member resolves
2332    /// to. A member-set lookup that treated the name as `"cart"` while
2333    /// the peer adjacency map treated it as `"tenant-a/cart"` would
2334    /// silently split the `:contratos` membership-lookup diagnostic from
2335    /// the cycle-detector's node identity — a two-consumer split at the
2336    /// validator far from the source `caixa.lisp` with no field naming
2337    /// the identity-drift root cause. Lifting the resolution rule to a
2338    /// typed method on the substrate primitive means every downstream
2339    /// consumer of the Aplicacao's per-`:membros` identity surface
2340    /// reaches for exactly one typed dispatch — the resolver's
2341    /// accept-set migrates as a unit on any future axis addition.
2342    ///
2343    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2344    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2345    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2346    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2347    /// destination-Servico scalar accessors — same "one typed dispatch
2348    /// on the substrate primitive, thin projections at each consumer"
2349    /// discipline extended onto the per-`:membros` member-caixa `:nome`
2350    /// byte-string axis. Named `nome()` to match the tatara-lisp
2351    /// author-surface term the field's docstring already reaches for
2352    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2353    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2354    /// already carries — the accessor's name maps directly onto the
2355    /// canonical caixa-identity vocabulary rather than shadowing the
2356    /// field's storage-side `caixa` label.
2357    #[must_use]
2358    pub const fn nome(&self) -> &str {
2359        self.caixa.as_str()
2360    }
2361
2362    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2363    /// requirement scalar accessor every consumer that reads the
2364    /// member's version pin keys off — returns the author-declared
2365    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2366    /// from the typed slot's own [`String`] storage.
2367    ///
2368    /// The `:membros :versao` slot carries the Cargo-shaped semver
2369    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2370    /// pins which release of the member-caixa the Aplicacao composes
2371    /// against — the same requirement grammar the peer `:deps :versao`
2372    /// / `:children :versao` axes carry, resolved through the shared
2373    /// [`crate::render::require_valid_versao_requirement`] cascade and
2374    /// the shared [`crate::version::parse_requirement`] parser. Every
2375    /// downstream consumer that fans on the member's version pin keys
2376    /// off this scalar (the [`validate_membros`] per-member requirement
2377    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2378    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
2379    /// m.nome(), m.versao_requirement())` line, every future per-cluster
2380    /// version-lock overlay the operator pins through a future
2381    /// `:placement`-scoped slot, the future
2382    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2383    /// version resolver, the future `feira app deploy` pipeline's
2384    /// per-member lacre BLAKE3-closure lookup).
2385    ///
2386    /// Prior to this lift the `.versao` byte-string was accessed inline
2387    /// at two `&str`-shaped sites — the [`validate_membros`]
2388    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2389    /// …)` and the `feira app graph` per-member printer's `println!(
2390    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2391    /// prior to this lift) — two open-coded field-accesses that expressed
2392    /// no compile-time link back to the typed slot. A future extension of
2393    /// the `:membros :versao` axis to a richer author surface (a
2394    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2395    /// flow, a lacre-projected concrete-version rewrite the operator
2396    /// materializes at CR-admission time, a future `:membros :versao-lock`
2397    /// per-cluster override slot) would have had to be threaded through
2398    /// every open-coded copy in lockstep or one consumer would silently
2399    /// disagree with the peers on which release constraint a given
2400    /// member resolves to. Lifting the resolution rule to a typed method
2401    /// on the substrate primitive means every downstream requirement-
2402    /// facing consumer reaches for exactly one typed dispatch — the
2403    /// resolver's accept-set migrates as a unit on any future axis
2404    /// addition.
2405    ///
2406    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2407    /// member-caixa `:nome` scalar accessor — the pair
2408    /// `(nome(), versao_requirement())` jointly projects the
2409    /// `(caixa, versao)` field pair every renderer that fans on
2410    /// per-member identity + version pin keys off, closing the last
2411    /// unlifted per-`:membros` scalar axis so every downstream
2412    /// per-`:membros` reader now routes through a typed dispatch on the
2413    /// substrate primitive. Named `versao_requirement()` rather than
2414    /// `versao()` because the field's storage-side `.versao` label is
2415    /// already the author-surface term (`:versao`); the accessor's name
2416    /// carries the semantic role — the semver *requirement* string the
2417    /// shared [`crate::version::parse_requirement`] entry-point consumes
2418    /// — so a raw field access and a typed dispatch read differently at
2419    /// every consumer site.
2420    ///
2421    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2422    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2423    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2424    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2425    /// destination-Servico scalar accessors — same "one typed dispatch
2426    /// on the substrate primitive, thin projections at each consumer"
2427    /// discipline extended onto the per-`:membros` member-`:versao`
2428    /// semver-requirement byte-string axis.
2429    #[must_use]
2430    pub const fn versao_requirement(&self) -> &str {
2431        self.versao.as_str()
2432    }
2433}
2434
2435// ── mesh-level policies ──────────────────────────────────────────────
2436
2437/// Mesh policies that apply to every `:contratos` edge unless
2438/// overridden per-edge in M4. V0 is a single global policy block.
2439#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2440#[serde(rename_all = "camelCase")]
2441pub struct MeshPolicy {
2442    /// Per-call timeout. Authored as a duration string (`"30s"`).
2443    #[serde(
2444        default,
2445        skip_serializing_if = "Option::is_none",
2446        with = "supervisor::duration_codec"
2447    )]
2448    pub timeout: Option<Duration>,
2449
2450    /// Number of retries on transient failure. None = no retries.
2451    #[serde(default, skip_serializing_if = "Option::is_none")]
2452    pub retries: Option<u32>,
2453
2454    /// Circuit breaker config. Trips after N failures within W
2455    /// duration; closes after a cooldown.
2456    #[serde(default, skip_serializing_if = "Option::is_none")]
2457    pub circuit_breaker: Option<CircuitBreaker>,
2458
2459    /// Whether mTLS is required for every contrato. Default: true
2460    /// (sandboxing-by-default; explicit opt-out only).
2461    #[serde(default, skip_serializing_if = "Option::is_none")]
2462    pub mtls_required: Option<bool>,
2463
2464    /// Token-bucket rate limit. Authored as `"100/s"` or
2465    /// `"5000/m"`; stored as `(rate, window)`.
2466    #[serde(
2467        default,
2468        skip_serializing_if = "Option::is_none",
2469        with = "rate_limit_codec"
2470    )]
2471    pub rate_limit: Option<RateLimit>,
2472}
2473
2474impl MeshPolicy {
2475    /// True when no `:politicas` axis carries a value — every field is
2476    /// `None`. The same emptiness contract every other M2/M3 typed
2477    /// surface carries ([`crate::LimitsSpec::is_empty`],
2478    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2479    /// typed slot onto a cluster artifact key off this predicate to
2480    /// decide "emit the slot" vs "skip the slot entirely", so an
2481    /// authored-but-unset `:politicas (())` round-trips to a rendered
2482    /// artifact that's structurally identical to one that omits the
2483    /// slot. Lifted as a typed predicate (rather than per-renderer
2484    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2485    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2486    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2487    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2488    /// not a coordinated rewrite of every consumer that's reaching
2489    /// for the emptiness semantic.
2490    #[must_use]
2491    pub const fn is_empty(&self) -> bool {
2492        self.timeout().is_none()
2493            && self.retries().is_none()
2494            && self.circuit_breaker().is_none()
2495            && self.mtls_required().is_none()
2496            && self.rate_limit().is_none()
2497    }
2498
2499    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
2500    /// per-call-deadline scalar accessor every consumer of the
2501    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
2502    /// returns the author-declared `:politicas :timeout` typed
2503    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
2504    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
2505    /// is `Copy`, so the accessor returns by value; no borrow of
2506    /// `&self` past the call). `None` when the slot is absent (the
2507    /// "cluster default applies — typically the gateway class's
2508    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
2509    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
2510    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
2511    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
2512    /// round-trips to a rendered `HTTPRoute` structurally identical to
2513    /// one that omits the slot).
2514    ///
2515    /// The `:politicas :timeout` slot carries the "no infinite blocking"
2516    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
2517    /// the typed slot's `Option<Duration>` accept-set (zero-floor
2518    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
2519    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
2520    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
2521    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
2522    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
2523    /// Every downstream consumer that reads the per-call cap keys off
2524    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2525    /// renderers key off to decide "emit :politicas overlay" vs "skip
2526    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2527    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
2528    /// fans the deadline into every rule via
2529    /// [`crate::render::single_field_overlay`], the future M4 per-
2530    /// Aplicacao Gateway API reconciler materialization pass, the
2531    /// future per-`:contratos`-edge timeout-override overlay the
2532    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
2533    ///
2534    /// Prior to this lift the `.timeout` field was accessed inline at
2535    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
2536    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
2537    /// …)` call — two open-coded field-accesses that expressed no
2538    /// compile-time link back to the typed slot. A future extension of
2539    /// the `:politicas :timeout` axis to a richer author surface — a
2540    /// per-`:contratos`-edge timeout override the operator pins through
2541    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
2542    /// roadmap acknowledges, a per-cluster timeout-default overlay the
2543    /// M4 CR materializer resolves per-CR, a split of the single
2544    /// per-call `Duration` into a richer `{request, backendRequest}`
2545    /// pair once the Gateway API's per-rule `timeouts` block grows the
2546    /// upstream-facing backendRequest arm alongside the client-facing
2547    /// request arm — would have had to be threaded through both open-
2548    /// coded copies in lockstep or the emptiness predicate and the
2549    /// caixa-mesh emit path would silently disagree on which per-call
2550    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
2551    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
2552    /// == false` while the renderer's overlay-emit path silently read
2553    /// a drifted other value, or vice versa: an author's `:timeout
2554    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
2555    /// the emptiness predicate still classified the policy as non-
2556    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
2557    /// | grep -A2 timeouts` audit would land on a route whose author's
2558    /// typed slot value silently vanished at the renderer layer).
2559    /// Lifting the resolution to a typed method on the substrate
2560    /// primitive means every downstream consumer of the Aplicacao's
2561    /// per-`:politicas` deadline surface reaches for exactly one typed
2562    /// dispatch — the resolver's accept-set migrates as a unit on any
2563    /// future axis addition.
2564    ///
2565    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
2566    /// family (sibling of the peer per-`:politicas`
2567    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
2568    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
2569    /// `Option<bool>` accessor — same "one typed dispatch on the
2570    /// substrate primitive, thin projections at each consumer"
2571    /// discipline extended onto the peer per-`:politicas` typed-
2572    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
2573    /// numeric-Copy-T scalar" projection pattern the sibling
2574    /// `Option<u32>` / `Option<bool>` lifts opened, since every
2575    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
2576    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
2577    /// than a scalar). Named `timeout()` to match the storage field's
2578    /// name; the accessor's identity maps onto the canonical MESH-
2579    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
2580    #[must_use]
2581    pub const fn timeout(&self) -> Option<Duration> {
2582        self.timeout
2583    }
2584
2585    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
2586    /// retry-budget scalar accessor every consumer of the Aplicacao's
2587    /// Gateway API v1.x per-rule retry-cap keys off — returns the
2588    /// author-declared `:politicas :retries` typed `u32` verbatim as an
2589    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
2590    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
2591    /// value; no borrow of `&self` past the call). `None` when the slot
2592    /// is absent (the "cluster default applies — typically 'no retries
2593    /// beyond a single dispatch attempt'" arm the caixa-mesh
2594    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
2595    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
2596    /// this predicate too, so an authored-but-unset `:politicas
2597    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
2598    /// identical to one that omits the slot).
2599    ///
2600    /// The `:politicas :retries` slot carries the "transient failure
2601    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
2602    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
2603    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2604    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
2605    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
2606    /// count scalar the caixa-mesh `retry_overlay` builder writes.
2607    /// Every downstream consumer that reads the retry cap keys off this
2608    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2609    /// renderers key off to decide "emit :politicas overlay" vs "skip
2610    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2611    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
2612    /// the value into every rule via [`crate::render::single_field_overlay`],
2613    /// the future M4 per-Aplicacao Gateway API reconciler
2614    /// materialization pass, the future per-`:contratos`-edge retry-
2615    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
2616    /// acknowledges).
2617    ///
2618    /// Prior to this lift the `.retries` field was accessed inline at
2619    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
2620    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
2621    /// …)` call — two open-coded field-accesses that expressed no
2622    /// compile-time link back to the typed slot. A future extension of
2623    /// the `:politicas :retries` axis to a richer author surface — a
2624    /// per-`:contratos`-edge retry override the operator pins through a
2625    /// future `:contratos :retries` slot, a per-cluster retry-default
2626    /// overlay the M4 CR materializer resolves per-CR, a promotion of
2627    /// the plain `u32` attempt-count to a richer `{attempts, codes,
2628    /// backoff}` sub-block once the Gateway API grows the peer
2629    /// `retry.codes` / `retry.backoff` axes — would have had to be
2630    /// threaded through both open-coded copies in lockstep or the
2631    /// emptiness predicate and the caixa-mesh emit path would silently
2632    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
2633    /// (a `:politicas` block whose only axis is a `Some :retries` would
2634    /// satisfy `is_empty() == false` while the renderer's overlay-emit
2635    /// path silently read a drifted other value, or vice versa: an
2636    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
2637    /// block while the emptiness predicate still classified the policy
2638    /// as non-empty). Lifting the resolution to a typed method on the
2639    /// substrate primitive means every downstream consumer of the
2640    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
2641    /// one typed dispatch — the resolver's accept-set migrates as a
2642    /// unit on any future axis addition.
2643    ///
2644    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
2645    /// family (sibling of the peer per-`:politicas`
2646    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
2647    /// same "one typed dispatch on the substrate primitive, thin
2648    /// projections at each consumer" discipline extended onto the
2649    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
2650    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
2651    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
2652    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
2653    /// fold on). Named `retries()` to match the storage field's name;
2654    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
2655    /// §III.2 vocabulary the slot's docstring already carries.
2656    #[must_use]
2657    pub const fn retries(&self) -> Option<u32> {
2658        self.retries
2659    }
2660
2661    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
2662    /// enforcement-toggle scalar accessor every consumer of the
2663    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
2664    /// — returns the author-declared `:politicas :mtls-required` typed
2665    /// bool verbatim as an `Option<bool>`, copied out of the typed
2666    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
2667    /// the accessor returns by value; no borrow of `&self` past the
2668    /// call). `None` when the slot is absent (the "cluster default
2669    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
2670    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
2671    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
2672    /// this predicate too, so an authored-but-unset `:politicas
2673    /// (:mtls-required ())` round-trips to a rendered
2674    /// `CiliumNetworkPolicy` structurally identical to one that omits
2675    /// the slot).
2676    ///
2677    /// The `:politicas :mtls-required` slot carries the "explicit opt-
2678    /// out only, sandboxing-by-default" mTLS-enforcement toggle
2679    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
2680    /// `{None, Some(true), Some(false)}` accept-set maps onto the
2681    /// Cilium `authentication.mode` bijection through
2682    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
2683    /// handshake enforced), `Some(false) → "disabled"` (handshake
2684    /// skipped — the debug-edge opt-out), `None` → omit the block
2685    /// (cluster default applies). Every downstream consumer that
2686    /// reads the toggle keys off this scalar (the
2687    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2688    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2689    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
2690    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
2691    /// ingress rule via [`crate::render::single_field_overlay`], the
2692    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
2693    /// materialization pass, the future per-`:contratos`-edge mTLS
2694    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2695    ///
2696    /// Prior to this lift the `.mtls_required` field was accessed
2697    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2698    /// `self.mtls_required.is_none()` arm and caixa-mesh's
2699    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
2700    /// two open-coded field-accesses that expressed no compile-time
2701    /// link back to the typed slot. A future extension of the
2702    /// `:politicas :mtls-required` axis to a richer author surface —
2703    /// a per-`:contratos`-edge mTLS override the operator pins through
2704    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
2705    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
2706    /// M4 CR materializer resolves per-CR, a three-valued
2707    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
2708    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
2709    /// would have had to be threaded through both open-coded copies in
2710    /// lockstep or the emptiness predicate and the caixa-mesh emit
2711    /// path would silently disagree on which toggle a given
2712    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
2713    /// axis is a `Some`
2714    /// `:mtls-required` would satisfy `is_empty() == false` while the
2715    /// renderer's overlay-emit path silently read a drifted other
2716    /// value, or vice versa). Lifting the resolution to a typed method
2717    /// on the substrate primitive means every downstream consumer of
2718    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
2719    /// for exactly one typed dispatch — the resolver's accept-set
2720    /// migrates as a unit on any future axis addition.
2721    ///
2722    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2723    /// family (peer of the sibling per-`:placement`
2724    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2725    /// same "one typed dispatch on the substrate primitive, thin
2726    /// projections at each consumer" discipline extended onto the
2727    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2728    /// the "optional per-slot Copy-T scalar" projection pattern the
2729    /// sibling per-`:politicas` `:retries` (Option<u32>) /
2730    /// `:timeout` (Option<Duration>) future lifts fold on). Named
2731    /// `mtls_required()` to match the storage field's name; the
2732    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2733    /// §III.2 vocabulary the slot's docstring already carries.
2734    #[must_use]
2735    pub const fn mtls_required(&self) -> Option<bool> {
2736        self.mtls_required
2737    }
2738
2739    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2740    /// `local_rate_limit`-mesh token-bucket-declaration scalar
2741    /// accessor every consumer of the Aplicacao's per-`:politicas`
2742    /// per-`(rate, window)` rate-limit surface keys off — returns the
2743    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2744    /// verbatim as an `Option<RateLimit>`, copied out of the typed
2745    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2746    /// `Copy`, so the accessor returns by value; no borrow of `&self`
2747    /// past the call). `None` when the slot is absent (the "cluster
2748    /// default applies — typically 'no per-Aplicacao rate declaration,
2749    /// gateway-class per-listener default applies'" arm the future
2750    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2751    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2752    /// `rate_limit().is_none()` arm reads this predicate too, so an
2753    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2754    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2755    /// identical to one that omits the slot).
2756    ///
2757    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2758    /// token-bucket rate declaration" contract (MESH-COMPOSITION
2759    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2760    /// (rate lower-bounded by 1 through
2761    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2762    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2763    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2764    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2765    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2766    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2767    /// `:politicas` overlay emits. Every downstream consumer that
2768    /// reads the rate declaration keys off this scalar (the
2769    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2770    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2771    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2772    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2773    /// `rl.window` against [`is_canonical_rate_limit_window`], the
2774    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2775    /// the future per-`:contratos`-edge rate-limit override the
2776    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2777    ///
2778    /// Prior to this lift the `.rate_limit` field was accessed inline
2779    /// at two sites — [`MeshPolicy::is_empty`]'s
2780    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2781    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2782    /// field-accesses that expressed no compile-time link back to the
2783    /// typed slot. A future extension of the `:politicas :rate-limit`
2784    /// axis to a richer author surface — a per-`:contratos`-edge
2785    /// rate-limit override the operator pins through a future
2786    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2787    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2788    /// the M4 CR materializer resolves per-CR, a promotion of the
2789    /// plain `(rate, window)` scalar pair to a richer
2790    /// `{rate, window, burst, key}` sub-block once Envoy's
2791    /// `local_rate_limit` grows the peer `burst_size` /
2792    /// `descriptor_key` axes — would have had to be threaded through
2793    /// both open-coded copies in lockstep or the emptiness predicate
2794    /// and the validate gate would silently disagree on which rate
2795    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2796    /// block whose only axis is a `Some :rate-limit` would satisfy
2797    /// `is_empty() == false` while the validate path silently read a
2798    /// drifted other value, or vice versa: an author's
2799    /// `:rate-limit "100/s"` would omit the value-shape gate while the
2800    /// emptiness predicate still classified the policy as non-empty).
2801    /// Lifting the resolution to a typed method on the substrate
2802    /// primitive means every downstream consumer of the Aplicacao's
2803    /// per-`:politicas` rate-limit surface reaches for exactly one
2804    /// typed dispatch — the resolver's accept-set migrates as a unit
2805    /// on any future axis addition.
2806    ///
2807    /// First `Option<Copy-composite-T>`-return accessor on the M3
2808    /// mesh-slot family — closes the last un-lifted per-`:politicas`
2809    /// scalar-value axis. Peer of the sibling per-`:politicas`
2810    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2811    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2812    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2813    /// "one typed dispatch on the substrate primitive, thin
2814    /// projections at each consumer" discipline extended onto the
2815    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2816    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2817    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2818    /// sub-accessors rather than a top-level accessor because
2819    /// consumers reach for the axes not the aggregate). Named
2820    /// `rate_limit()` to match the storage field's name; the
2821    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2822    /// §III.2 vocabulary the slot's docstring already carries.
2823    #[must_use]
2824    pub const fn rate_limit(&self) -> Option<RateLimit> {
2825        self.rate_limit
2826    }
2827
2828    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2829    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2830    /// declaration scalar accessor every consumer of the Aplicacao's
2831    /// per-`:politicas` breaker declaration keys off — returns the
2832    /// author-declared `:politicas :circuit-breaker` typed
2833    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2834    /// copied out of the typed slot's own `Option<CircuitBreaker>`
2835    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2836    /// by value; no borrow of `&self` past the call). `None` when the
2837    /// slot is absent (the "cluster default applies — typically 'no
2838    /// per-Aplicacao breaker declaration, gateway-class per-listener
2839    /// default applies'" arm the future caixa-mesh
2840    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2841    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2842    /// arm reads this predicate too, so an authored-but-unset
2843    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2844    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2845    /// that omits the slot).
2846    ///
2847    /// The `:politicas :circuit-breaker` slot carries the
2848    /// "per-Aplicacao consecutive-transient-failure trip declaration"
2849    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2850    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2851    /// zero-floor rejected through
2852    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2853    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2854    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2855    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2856    /// canonical-form pinned through
2857    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2858    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2859    /// bijection the future `CiliumClusterwideEnvoyConfig`
2860    /// per-`:politicas` overlay emits. Every downstream consumer that
2861    /// reads the breaker declaration keys off this scalar (the
2862    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2863    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2864    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2865    /// that brackets `cb.max_failures()` against
2866    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2867    /// [`POLICY_BREAKER_WINDOW_MAX`] via
2868    /// [`crate::render::require_positive_canonical_bounded_duration`],
2869    /// the future M4 per-Aplicacao Envoy reconciler materialization
2870    /// pass, the future per-`:contratos`-edge breaker override the
2871    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2872    ///
2873    /// Prior to this lift the `.circuit_breaker` field was accessed
2874    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2875    /// `self.circuit_breaker.is_none()` arm and the
2876    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
2877    /// bind — two open-coded field-accesses that expressed no
2878    /// compile-time link back to the typed slot. A future extension of
2879    /// the `:politicas :circuit-breaker` axis to a richer author
2880    /// surface — a per-`:contratos`-edge breaker override the operator
2881    /// pins through a future `:contratos :circuit-breaker` slot the
2882    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
2883    /// breaker-default overlay the M4 CR materializer resolves per-CR,
2884    /// a promotion of the plain `(max_failures, window)` scalar pair to
2885    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
2886    /// sub-block once Envoy's `outlier_detection` grows the peer
2887    /// ejection-percentage / ejection-time axes — would have had to be
2888    /// threaded through both open-coded copies in lockstep or the
2889    /// emptiness predicate and the validate gate would silently
2890    /// disagree on which breaker declaration a given [`MeshPolicy`]
2891    /// resolves to (a `:politicas` block whose only axis is a
2892    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
2893    /// the validate path silently read a drifted other value, or vice
2894    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
2895    /// "60s"))` would omit the value-shape gate while the emptiness
2896    /// predicate still classified the policy as non-empty). Lifting
2897    /// the resolution to a typed method on the substrate primitive
2898    /// means every downstream consumer of the Aplicacao's
2899    /// per-`:politicas` breaker surface reaches for exactly one typed
2900    /// dispatch — the resolver's accept-set migrates as a unit on any
2901    /// future axis addition.
2902    ///
2903    /// Second `Option<Copy-composite-T>`-return accessor on the M3
2904    /// mesh-slot family (sibling of the peer per-`:politicas`
2905    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
2906    /// on the same composite-Copy shape, and of the sibling per-
2907    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
2908    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
2909    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
2910    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
2911    /// same "one typed dispatch on the substrate primitive, thin
2912    /// projections at each consumer" discipline extended onto the last
2913    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
2914    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
2915    /// match the storage field's name; the accessor's identity maps
2916    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
2917    /// docstring already carries. Closes the last unlifted
2918    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
2919    /// reader now routes through a typed dispatch on the substrate
2920    /// primitive.
2921    #[must_use]
2922    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
2923        self.circuit_breaker
2924    }
2925}
2926
2927#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
2928#[serde(rename_all = "camelCase")]
2929pub struct CircuitBreaker {
2930    pub max_failures: u32,
2931    #[serde(with = "supervisor::duration_codec_required")]
2932    pub window: Duration,
2933}
2934
2935impl CircuitBreaker {
2936    /// Substrate-canonical per-`:politicas :circuit-breaker`
2937    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
2938    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
2939    /// breaker trip-count keys off — returns the author-declared
2940    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
2941    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
2942    /// so the accessor returns by value; no borrow of `&self` past the
2943    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
2944    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
2945    /// axis; a `CircuitBreaker` past pattern-match is definitionally
2946    /// present, and its `:max-failures` field carries the trip count as a
2947    /// required-axis scalar).
2948    ///
2949    /// The `:politicas :circuit-breaker :max-failures` axis carries the
2950    /// "consecutive-transient-failure trip threshold" contract
2951    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
2952    /// (zero-floor rejected through
2953    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2954    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
2955    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
2956    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
2957    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
2958    /// Every downstream consumer that reads the trip threshold keys off
2959    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
2960    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
2961    /// canonical `require_positive_bounded_u32` helper, the future M4
2962    /// per-Aplicacao Envoy config reconciler materialization pass, the
2963    /// future per-`:contratos`-edge breaker-override overlay the
2964    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2965    ///
2966    /// Prior to this lift the `.max_failures` field was accessed inline
2967    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
2968    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
2969    /// open-coded field-access that expressed no compile-time link back
2970    /// to the typed sub-struct axis. A future extension of the
2971    /// `:max-failures` axis to a richer author surface — a
2972    /// per-`:contratos`-edge breaker override the operator pins through a
2973    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
2974    /// #3 roadmap acknowledges, a per-cluster max-failures-default
2975    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
2976    /// plain `u32` trip count to a richer
2977    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
2978    /// tuple once Envoy's `outlier_detection` block's peer axes come into
2979    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
2980    /// count arms — would have had to be threaded through every open-
2981    /// coded copy in lockstep or the validate gate and the future M4
2982    /// emit path would silently disagree on which trip threshold a given
2983    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
2984    /// would satisfy validate while the emit path silently read a drifted
2985    /// other value, or vice versa: a validated typed slot would land at
2986    /// the emit boundary as a no-op breaker whose trip threshold is
2987    /// structurally never reached). Lifting the resolution to a typed
2988    /// method on the substrate primitive means every downstream consumer
2989    /// of the Aplicacao's per-`:politicas :circuit-breaker`
2990    /// trip-threshold surface reaches for exactly one typed dispatch —
2991    /// the resolver's accept-set migrates as a unit on any future axis
2992    /// addition.
2993    ///
2994    /// First sub-struct scalar accessor on the M3 mesh-slot family
2995    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
2996    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
2997    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
2998    /// closes the last unlifted per-`:politicas` scalar-value axis after
2999    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
3000    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
3001    /// Same "one typed dispatch on the substrate primitive, thin
3002    /// projections at each consumer" discipline the peer
3003    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3004    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3005    /// [`Membro::versao_requirement`] (a40b0e3),
3006    /// [`Entrada::destination`] (6db982c) accessors carry on their
3007    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
3008    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
3009    /// match the storage field's name; the accessor's identity maps onto
3010    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3011    /// docstring already carries.
3012    #[must_use]
3013    pub const fn max_failures(&self) -> u32 {
3014        self.max_failures
3015    }
3016
3017    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
3018    /// Envoy-outlier-detection rolling-observation-interval scalar
3019    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3020    /// breaker rolling-window duration keys off — returns the
3021    /// author-declared `:politicas :circuit-breaker :window` typed
3022    /// `Duration` verbatim, copied out of the typed slot's own
3023    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
3024    /// by value; no borrow of `&self` past the call). Non-optional (the
3025    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
3026    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
3027    /// `CircuitBreaker` past pattern-match is definitionally present,
3028    /// and its `:window` field carries the rolling-observation interval
3029    /// as a required-axis scalar).
3030    ///
3031    /// The `:politicas :circuit-breaker :window` axis carries the
3032    /// "consecutive-transient-failure rolling-observation interval"
3033    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3034    /// `Duration` accept-set (zero-floor rejected through
3035    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
3036    /// residue rejected through
3037    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
3038    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
3039    /// Envoy `outlier_detection.interval` per-cluster
3040    /// ejection-observation-interval scalar (equivalently the future
3041    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3042    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3043    /// consumer that reads the rolling-observation interval keys off
3044    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3045    /// integer-millisecond canonical-form + cap bracket at
3046    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
3047    /// [`crate::render::require_positive_canonical_bounded_duration`]
3048    /// helper, the future M4 per-Aplicacao Envoy config reconciler
3049    /// materialization pass, the future per-`:contratos`-edge
3050    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3051    /// acknowledges).
3052    ///
3053    /// Prior to this lift the `.window` field was accessed inline at
3054    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
3055    /// `require_positive_canonical_bounded_duration(cb.window, …)`
3056    /// call — one open-coded field-access that expressed no compile-
3057    /// time link back to the typed sub-struct axis. A future extension
3058    /// of the `:window` axis to a richer author surface — a
3059    /// per-`:contratos`-edge window override the operator pins through
3060    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
3061    /// #3 roadmap acknowledges, a per-cluster window-default overlay
3062    /// the M4 CR materializer resolves per-CR, a promotion of the plain
3063    /// `Duration` observation interval to a richer
3064    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
3065    /// once Envoy's `outlier_detection` block's peer axes come into
3066    /// scope, a per-Envoy-cluster minimum-request-volume gate before
3067    /// the window arms — would have had to be threaded through every
3068    /// open-coded copy in lockstep or the validate gate and the future
3069    /// M4 emit path would silently disagree on which observation
3070    /// interval a given [`CircuitBreaker`] resolves to (an author's
3071    /// `:window "60s"` would satisfy validate while the emit path
3072    /// silently read a drifted other value, or vice versa: a validated
3073    /// typed slot would land at the emit boundary as a breaker whose
3074    /// observation window is structurally so wide that no realistic
3075    /// failure-rate shape can trip it). Lifting the resolution to a
3076    /// typed method on the substrate primitive means every downstream
3077    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
3078    /// observation-window surface reaches for exactly one typed
3079    /// dispatch — the resolver's accept-set migrates as a unit on any
3080    /// future axis addition.
3081    ///
3082    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
3083    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
3084    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
3085    /// required-axis, extended onto the per-sub-struct required-`Duration`
3086    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
3087    /// axis. Same "one typed dispatch on the substrate primitive, thin
3088    /// projections at each consumer" discipline the peer
3089    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3090    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3091    /// [`Membro::versao_requirement`] (a40b0e3),
3092    /// [`Entrada::destination`] (6db982c) accessors carry on their
3093    /// respective per-mesh-slot-atom scalar-value axes, extended onto
3094    /// the per-sub-struct required-`Duration` axis. Named `window()` to
3095    /// match the storage field's name; the accessor's identity maps onto
3096    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3097    /// docstring already carries.
3098    #[must_use]
3099    pub const fn window(&self) -> Duration {
3100        self.window
3101    }
3102}
3103
3104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3105pub struct RateLimit {
3106    /// Requests per window.
3107    pub rate: u32,
3108    /// Window duration.
3109    pub window: Duration,
3110}
3111
3112impl RateLimit {
3113    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
3114    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
3115    /// every consumer of the Aplicacao's per-`:contratos`-edge
3116    /// rate-limit-bucket capacity keys off — returns the author-declared
3117    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
3118    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
3119    /// returns by value; no borrow of `&self` past the call). Non-optional
3120    /// (the surrounding `Option<RateLimit>` is the "slot present?"
3121    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
3122    /// `RateLimit` past pattern-match is definitionally present, and its
3123    /// `:rate` field carries the token-bucket capacity as a required-axis
3124    /// scalar).
3125    ///
3126    /// The `:politicas :rate-limit` `:rate` axis carries the
3127    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
3128    /// the typed slot's `u32` accept-set (zero-floor rejected through
3129    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
3130    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
3131    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
3132    /// token-bucket-capacity scalar (equivalently the future
3133    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3134    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3135    /// consumer that reads the token-bucket capacity keys off this
3136    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3137    /// cap bracket that gates on the canonical
3138    /// [`crate::render::require_positive_bounded_u32`] helper, the
3139    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3140    /// emits the `<n>/<s|m|h>` author surface, the future M4
3141    /// per-Aplicacao Envoy config reconciler materialization pass, the
3142    /// future per-`:contratos`-edge rate-limit-override overlay the
3143    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3144    ///
3145    /// Prior to this lift the `.rate` field was accessed inline at three
3146    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
3147    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
3148    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
3149    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
3150    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
3151    /// field-accesses that expressed no compile-time link back to the
3152    /// typed sub-struct axis. A future extension of the `:rate` axis
3153    /// to a richer author surface — a per-`:contratos`-edge rate
3154    /// override the operator pins through a future `:contratos :rate`
3155    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
3156    /// per-cluster rate-default overlay the M4 CR materializer resolves
3157    /// per-CR, a promotion of the plain `u32` token capacity to a
3158    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
3159    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3160    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
3161    /// before the token arms — would have had to be threaded through
3162    /// every open-coded copy in lockstep or the validate gate, the
3163    /// codec's render path, and the future M4 emit path would silently
3164    /// disagree on which token capacity a given [`RateLimit`] resolves
3165    /// to (an author's `:rate-limit "100/s"` would satisfy validate
3166    /// while the render / emit paths silently read a drifted other
3167    /// value, or vice versa: a validated typed slot would land at the
3168    /// emit boundary as a no-op limiter whose token capacity is
3169    /// structurally so high that no realistic per-edge traffic shape
3170    /// can drain it). Lifting the resolution to a typed method on the
3171    /// substrate primitive means every downstream consumer of the
3172    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
3173    /// reaches for exactly one typed dispatch — the resolver's
3174    /// accept-set migrates as a unit on any future axis addition.
3175    ///
3176    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
3177    /// in shape to the peer per-`CircuitBreaker`
3178    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
3179    /// on the peer per-sub-struct required-axis, extended onto the
3180    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
3181    /// required-axis scalar" projection pattern the sibling
3182    /// [`RateLimit::window`] future lift folds on. Same "one typed
3183    /// dispatch on the substrate primitive, thin projections at each
3184    /// consumer" discipline the peer [`WitContract::source`] /
3185    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
3186    /// (0804823), [`Membro::nome`] (4a32abf),
3187    /// [`Membro::versao_requirement`] (a40b0e3),
3188    /// [`Entrada::destination`] (6db982c),
3189    /// [`CircuitBreaker::max_failures`] (3a74062),
3190    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
3191    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
3192    /// to match the storage field's name; the accessor's identity maps
3193    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3194    /// docstring already carries.
3195    #[must_use]
3196    pub const fn rate(&self) -> u32 {
3197        self.rate
3198    }
3199
3200    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
3201    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
3202    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3203    /// rate-limit-bucket refill period keys off — returns the
3204    /// author-declared `:politicas :rate-limit` typed `Duration`
3205    /// verbatim, copied out of the typed slot's own `Duration` storage
3206    /// (`Duration` is `Copy`, so the accessor returns by value; no
3207    /// borrow of `&self` past the call). Non-optional (the surrounding
3208    /// `Option<RateLimit>` is the "slot present?" projection at the
3209    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
3210    /// pattern-match is definitionally present, and its `:window`
3211    /// field carries the token-bucket refill period as a required-axis
3212    /// scalar).
3213    ///
3214    /// The `:politicas :rate-limit` `:window` axis carries the
3215    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
3216    /// — the typed slot's `Duration` accept-set (constrained to the
3217    /// three canonical windows `{1s, 60s, 3600s}` the
3218    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
3219    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
3220    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
3221    /// per-cluster token-bucket-refill-period scalar (equivalently the
3222    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3223    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3224    /// consumer that reads the token-bucket refill period keys off
3225    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
3226    /// canonical-window gate that keys off
3227    /// [`is_canonical_rate_limit_window`], the
3228    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3229    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
3230    /// [`rate_limit_window_unit`] and non-canonical fallback via
3231    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
3232    /// reconciler materialization pass, the future per-`:contratos`-
3233    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
3234    /// roadmap acknowledges).
3235    ///
3236    /// Prior to this lift the `.window` field was accessed inline at
3237    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
3238    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
3239    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
3240    /// error-payload construction on refusal, and the two
3241    /// [`rate_limit_codec::render`] arms
3242    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
3243    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
3244    /// open-coded field-accesses that expressed no compile-time link
3245    /// back to the typed sub-struct axis. A future extension of the
3246    /// `:window` axis to a richer author surface — a per-`:contratos`-
3247    /// edge window override the operator pins through a future
3248    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
3249    /// acknowledges, a per-cluster window-default overlay the M4 CR
3250    /// materializer resolves per-CR, a promotion of the plain
3251    /// `Duration` refill period to a richer
3252    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
3253    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3254    /// axis comes into scope, an addition of a `"d"` day suffix once
3255    /// Envoy's `rate_limit_action` grows daily-bucket support — would
3256    /// have had to be threaded through every open-coded copy in
3257    /// lockstep or the validate gate, the codec's render path, and
3258    /// the future M4 emit path would silently disagree on which
3259    /// refill period a given [`RateLimit`] resolves to (an author's
3260    /// `:rate-limit "100/s"` would satisfy validate while the render
3261    /// / emit paths silently read a drifted other value, or vice
3262    /// versa: a validated typed slot would land at the emit boundary
3263    /// as a limiter whose refill period is structurally so long that
3264    /// no realistic per-edge traffic shape stays inside the token
3265    /// budget). Lifting the resolution to a typed method on the
3266    /// substrate primitive means every downstream consumer of the
3267    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
3268    /// reaches for exactly one typed dispatch — the resolver's
3269    /// accept-set migrates as a unit on any future axis addition.
3270    ///
3271    /// Second sub-struct scalar accessor on the `RateLimit` axis —
3272    /// sibling in shape to the just-landed [`RateLimit::rate`]
3273    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
3274    /// required-axis, extended onto the per-sub-struct
3275    /// required-`Duration` axis; closes the last unlifted
3276    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
3277    /// per-sub-struct accessor coverage is now complete across both
3278    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
3279    /// the substrate primitive, thin projections at each consumer"
3280    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
3281    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
3282    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
3283    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
3284    /// [`Membro::nome`] (4a32abf),
3285    /// [`Membro::versao_requirement`] (a40b0e3),
3286    /// [`Entrada::destination`] (6db982c) accessors carry on their
3287    /// respective per-mesh-slot-atom scalar-value axes. Named
3288    /// `window()` to match the storage field's name; the accessor's
3289    /// identity maps onto the canonical MESH-COMPOSITION §III.2
3290    /// vocabulary the slot's docstring already carries.
3291    #[must_use]
3292    pub const fn window(&self) -> Duration {
3293        self.window
3294    }
3295
3296    /// Recognize this rate-limit's `:window` as a canonical
3297    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
3298    /// exactly matches one of the three closed-set arm-Durations
3299    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
3300    /// non-canonical magnitude the codec's round-trip would break on
3301    /// (sub-second residue, or a second-magnitude outside the set
3302    /// [`RateLimitUnit::ALL`] enumerates).
3303    ///
3304    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
3305    /// returns `Some` here — the validate gate's
3306    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
3307    /// rejects every window this accessor returns `None` on. Downstream
3308    /// consumers past validate (the codec's [`rate_limit_codec::render`]
3309    /// path, the future M4 per-Aplicacao Envoy config reconciler's
3310    /// materialization pass, the future per-`:contratos`-edge rate-limit-
3311    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3312    /// acknowledges) that read the typed unit off a validated slot can
3313    /// pattern-match on the returned `Some` without re-checking
3314    /// canonicality at the consumer layer — the typed enum surface is
3315    /// the load-bearing carrier of the canonicality invariant.
3316    ///
3317    /// Preferred over the free [`is_canonical_rate_limit_window`]
3318    /// module-private helper at any call site that has the typed
3319    /// [`RateLimit`] in hand (the codec's `render` arm at
3320    /// [`rate_limit_codec::render`], the validate gate's canonical-form
3321    /// arm in [`AplicacaoSpec::validate_politicas`], any future
3322    /// per-`:contratos` edge-override overlay resolver): those consumers
3323    /// reach for the typed enum without going through the
3324    /// `.window()` scalar-projection layer, and get the enum value
3325    /// directly (which the codec's render arm can then format via
3326    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
3327    /// "typed sub-struct scalar accessor, one dispatch on the substrate
3328    /// primitive" discipline the sibling [`RateLimit::rate`] and
3329    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
3330    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
3331    /// projection axis (the third scalar accessor on the [`RateLimit`]
3332    /// axis, first typed-enum-return projection).
3333    ///
3334    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
3335    /// the canonical [`RateLimitUnit`] arm now carries the same
3336    /// `const`-eval-surface posture the sibling `pub const fn`
3337    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
3338    /// this typed sub-struct already carry, composing through the
3339    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
3340    /// reverse-resolver in `const` context. Any downstream substrate-
3341    /// side `const`-context consumer of the typed unit (a module-scope
3342    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
3343    /// invariant pin on a typed fixture, a future M4 admission-webhook
3344    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
3345    /// resolver over a typed [`RateLimit`], any future `const fn`
3346    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3347    /// the substrate primitive) now reaches the same typed dispatch on
3348    /// the substrate primitive at const-eval time as at runtime.
3349    ///
3350    /// Pinned load-bearing at the substrate-primitive level by
3351    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
3352    /// eval-surface pin via `const fn` wrapper).
3353    #[must_use]
3354    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
3355        RateLimitUnit::from_window(self.window)
3356    }
3357}
3358
3359/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
3360/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
3361/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
3362///
3363/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
3364/// the `:politicas :rate-limit` unit surface reads from
3365/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
3366/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
3367/// [`is_canonical_rate_limit_window`] predicate the
3368/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
3369/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
3370/// projection) now lives inside this typed enum's `match self` arms — a
3371/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
3372/// `rate_limit_action` grows daily-bucket support) is one new variant
3373/// plus the exhaustiveness arms on the four methods, so every consumer
3374/// picks it up by compile-time construction rather than a runtime
3375/// table-scan miss.
3376///
3377/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
3378/// scanned via `find_map` at every projection call — an untyped runtime
3379/// walk that carried no compile-time link between the parse arm's
3380/// accepted suffixes, the render arm's emitted suffixes, and the
3381/// validate gate's accepted windows. A future rate-limit-unit addition
3382/// that landed one row without threading through the other consumers
3383/// (or a copy-paste flip that collapsed two rows onto one suffix) would
3384/// silently split the accepted-set across the three consumers — the
3385/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
3386/// for a 24h window that parse can't round-trip, the validate gate
3387/// misses one canonical window. Lifting the pairs onto a typed
3388/// closed-set enum with exhaustive `match` arms makes any such
3389/// half-landed extension a caixa-core build error (the compiler enforces
3390/// arm coverage on every method), not a silent per-consumer drift
3391/// surfacing at apply time. Same "closed-set typed-enum discriminator"
3392/// discipline the sibling [`PlacementStrategy`] (cc8f749),
3393/// [`crate::supervisor::RestartStrategy`],
3394/// [`crate::supervisor::RestartPolicy`],
3395/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
3396/// closed-set typed enums carry on their respective closed-set axes —
3397/// extended onto the seventh closed-set typed-enum discriminator axis
3398/// on the caixa typed surface (the `:politicas :rate-limit :window`
3399/// canonical-unit axis).
3400#[derive(
3401    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3402)]
3403pub enum RateLimitUnit {
3404    /// 1-second window — canonical author-surface suffix `"s"`
3405    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3406    /// with a 1s magnitude.
3407    Second,
3408    /// 1-minute window — canonical author-surface suffix `"m"`
3409    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3410    /// with a 60s magnitude.
3411    Minute,
3412    /// 1-hour window — canonical author-surface suffix `"h"`
3413    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3414    /// with a 3600s magnitude.
3415    Hour,
3416}
3417
3418impl RateLimitUnit {
3419    /// Exhaustive iteration surface for every consumer that reads the
3420    /// full canonical-unit set (the byte-parity witness against the
3421    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
3422    /// webhook's accepted-suffix listing in its rejection body, any
3423    /// future round-trip fuzz harness). A future variant addition to
3424    /// [`RateLimitUnit`] extends this slice as a single edit and every
3425    /// consumer picks up the new entry by construction — the compiler-
3426    /// checked exhaustiveness on the sibling method `match` arms is the
3427    /// build-time guarantee that no arm forgets to grow.
3428    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
3429
3430    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
3431    /// string every `<n>/<unit>` rate-limit shape carries after its
3432    /// `/` separator. The single source of truth the codec's parse and
3433    /// render arms both dispatch on: the parse arm matches an incoming
3434    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
3435    /// output; the render arm emits the entry's `as_suffix` verbatim
3436    /// after the rate magnitude.
3437    #[must_use]
3438    pub const fn as_suffix(self) -> &'static str {
3439        match self {
3440            Self::Second => "s",
3441            Self::Minute => "m",
3442            Self::Hour => "h",
3443        }
3444    }
3445
3446    /// Canonical `Duration` for this unit — the token-bucket refill
3447    /// period the [`RateLimit::window`] axis carries when the surrounding
3448    /// slot's `:rate-limit` author surface named this unit.
3449    #[must_use]
3450    pub const fn window(self) -> Duration {
3451        Duration::from_secs(match self {
3452            Self::Second => 1,
3453            Self::Minute => 60,
3454            Self::Hour => 3_600,
3455        })
3456    }
3457
3458    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
3459    /// `None` when `suffix` is outside the closed-set arm-string set
3460    /// [`Self::as_suffix`] emits. The single `str → Self` projection
3461    /// [`rate_limit_codec::parse`] consumes.
3462    #[must_use]
3463    pub fn from_suffix(suffix: &str) -> Option<Self> {
3464        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
3465    }
3466
3467    /// Recognize a canonical rate-limit `Duration` as one of the three
3468    /// arms, or `None` when `window` carries sub-second residue or a
3469    /// second-magnitude outside the closed-set arm-window set
3470    /// [`Self::window`] emits. The single `Duration → Self` projection
3471    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
3472    /// both consume.
3473    ///
3474    /// `pub const fn` — the reverse `Duration → Self` projection now
3475    /// carries the same `const`-eval-surface posture the sibling
3476    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
3477    /// projection accessors on this closed-set typed enum already
3478    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
3479    /// typed-`RateLimit`-projection sibling composes through in `const`
3480    /// context. Routes byte-for-byte through the peer `pub const fn`
3481    /// [`Self::window`] canonical-`Duration` projection so any future
3482    /// arm-magnitude edit on the sibling accessor reaches this reverse
3483    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
3484    /// per-arm probes each dispatch through one `pub const fn` on the
3485    /// substrate primitive rather than a hand-authored per-arm second-
3486    /// magnitude literal that would silently drift on any future
3487    /// [`Self::window`] arm-magnitude edit.
3488    ///
3489    /// Prior to the `const` lift the body dispatched through
3490    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
3491    /// iterator-driven linear scan whose iterator methods
3492    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
3493    /// `PartialEq` dispatch each carry non-`const` bounds on stable
3494    /// Rust 1.94, so any downstream substrate-side `const`-context
3495    /// consumer of the reverse resolver (a module-scope
3496    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
3497    /// invariant pin on a typed fixture, a future M4
3498    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
3499    /// webhook `const fn` per-`:politicas` canonical-window floor over a
3500    /// typed [`RateLimit`] scalar, any future `const fn`
3501    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3502    /// the substrate primitive that wants to fan on the canonical unit
3503    /// at compile time) surfaced as a downstream E0015 far from the
3504    /// resolver's own declaration. The `pub const fn` posture closes
3505    /// the drift structurally at caixa-core build time.
3506    ///
3507    /// Pinned load-bearing at the substrate-primitive level by
3508    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
3509    /// eval-surface pin via `const fn` wrapper) and
3510    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
3511    /// (composition-witness pin against the peer `Self::window` scalar
3512    /// dispatch).
3513    #[must_use]
3514    pub const fn from_window(window: Duration) -> Option<Self> {
3515        if window.subsec_nanos() != 0 {
3516            return None;
3517        }
3518        // Route through the peer `pub const fn` [`Self::window`]
3519        // canonical-`Duration` projection so any future arm-magnitude
3520        // edit on the sibling accessor reaches this reverse resolver by
3521        // construction — the per-arm `secs` comparison keys off
3522        // `Duration::as_secs` (`pub const fn`), not a hand-authored
3523        // per-arm second-magnitude literal that would silently drift.
3524        let secs = window.as_secs();
3525        if secs == Self::Second.window().as_secs() {
3526            Some(Self::Second)
3527        } else if secs == Self::Minute.window().as_secs() {
3528            Some(Self::Minute)
3529        } else if secs == Self::Hour.window().as_secs() {
3530            Some(Self::Hour)
3531        } else {
3532            None
3533        }
3534    }
3535
3536    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
3537    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
3538    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
3539    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
3540    /// consumes.
3541    ///
3542    /// The peer `Duration → &'static str` axis folded onto the substrate
3543    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
3544    /// production consumers ([`rate_limit_codec::render`] and
3545    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
3546    /// migrated (61421a6): the free helper's `Duration → &str` projection
3547    /// is now the two-step composition
3548    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
3549    /// reads through the typed accessor. This lift closes the peer
3550    /// `&str → Duration` axis by folding the vestigial module-private
3551    /// `rate_limit_window_from_unit` delegate onto this associated method
3552    /// — the codec's parse arm and every future wire-side consumer of the
3553    /// `&str → Duration` projection (a future admission-webhook that
3554    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
3555    /// before it's promoted to a validated typed slot, a future
3556    /// `feira lint` shape-probe that reads the author-surface bytes
3557    /// verbatim) now reach for exactly one typed dispatch on the
3558    /// substrate primitive.
3559    ///
3560    /// Same "closed-set typed-enum discriminator with canonical
3561    /// projections per axis" discipline the sibling [`Self::as_suffix`]
3562    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
3563    /// methods carry — this associated method closes the fifth (and last
3564    /// unlifted) projection axis on the arm-table, so the closed-set enum
3565    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
3566    /// consumer of the `:politicas :rate-limit :window` axis reaches
3567    /// through. A future rate-limit-unit addition (a `"d"` day suffix
3568    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
3569    /// `"ms"` sub-second window once high-throughput per-edge policies
3570    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
3571    /// variant plus one arm per method — the compiler enforces
3572    /// exhaustiveness on every consumer's `match self` arms and picks
3573    /// the new unit up by construction across all five projections.
3574    #[must_use]
3575    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
3576        Self::from_suffix(suffix).map(Self::window)
3577    }
3578}
3579
3580/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
3581/// every consumer that formats a canonical rate-limit unit as user-
3582/// facing text (future M4 admission-webhook rejection bodies naming
3583/// the accepted-suffix set, future `feira app graph` per-`:politicas`
3584/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
3585/// codec's parse arm accepts and the render arm emits. Same
3586/// as_str-through-Display convergence discipline the sibling
3587/// [`PlacementStrategy`], [`crate::CaixaKind`],
3588/// [`crate::supervisor::RestartStrategy`], and
3589/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
3590impl std::fmt::Display for RateLimitUnit {
3591    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3592        f.write_str(self.as_suffix())
3593    }
3594}
3595
3596/// Upper-bound ceiling on the `:politicas :timeout` axis — every
3597/// validated [`MeshPolicy::timeout`] past
3598/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
3599/// (inclusive on both ends, integer-millisecond magnitudes by the
3600/// canonical-form gate immediately preceding).
3601///
3602/// The typed field is `Option<Duration>` (the zero-floor arm
3603/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
3604/// `Duration::ZERO`, and the canonical-form arm
3605/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
3606/// sub-millisecond residue), so a programmatic struct literal
3607/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
3608/// 24h) and the equivalent author-surface form
3609/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
3610/// integer-hour magnitude) both round-trip cleanly through serde — a
3611/// structurally unbounded `Duration` ceiling. A `:timeout` value far
3612/// above the documented production-playbook band (Envoy default `15s`,
3613/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
3614/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
3615/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
3616/// at `~3600s`) silently degenerates the mesh-policy contract: the
3617/// per-call deadline is structurally so long that no realistic
3618/// synchronous-`:contratos` traversal can reach it, so the typed slot
3619/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
3620/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
3621/// blocking" degenerates to a nominal-only contract on the
3622/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
3623/// the sibling `:politicas :retries` axis and the
3624/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
3625/// `:politicas :circuit-breaker :max-failures` axis — all three close
3626/// the "structurally unbounded ceiling on a typed `:politicas` axis"
3627/// footgun the prior zero-floor-and-canonical-form-only checks left
3628/// open.
3629///
3630/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3631/// shared duration codec emits (`"<n>h"` for any integer-hour
3632/// magnitude) — every value in the canonical authoring form's
3633/// `<integer><unit>` grammar at or below this cap renders to a clean
3634/// canonical string. The cap sits an order of magnitude above every
3635/// documented production-playbook recommendation band (Envoy default
3636/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
3637/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
3638/// configured maximum (`proxy_read_timeout` typical max `3600s`),
3639/// below the clearly-pathological "effectively no timeout" floor
3640/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
3641/// want for a long-running synchronous workflow, but a hard wall above
3642/// which the mesh-level deadline is structurally a non-deadline.
3643/// Lifted as a typed `pub const` so the bound has exactly one source
3644/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3645/// materializer's admission webhook and the caixa-mesh-side
3646/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3647/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3648/// other typed upper bound in this crate carries
3649/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3650/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3651/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3652/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3653pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
3654
3655/// Upper-bound ceiling on the `:politicas :retries` axis — every
3656/// validated [`MeshPolicy::retries`] past
3657/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
3658///
3659/// The typed slot is `Option<u32>` (`None` = no retries on transient
3660/// failure; `Some(0)` already rejected by the
3661/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
3662/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
3663/// .. }`) and the equivalent author-surface form
3664/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
3665/// serde / the codec — a structurally unbounded `u32` ceiling. The
3666/// runtime substrate that consumes the value (Envoy's
3667/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3668/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3669/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3670/// admission cap is 10) translates a four-billion-retry policy into a
3671/// thundering-herd amplification vector on transient failure — the
3672/// caller's one request fans out to `retries` server-side calls per
3673/// edge per traversal, multiplying load by `(retries+1)^depth` across
3674/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3675/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3676/// invariant on the retry axis; both belong at the typed-slot layer.
3677///
3678/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3679/// upstream mesh-policy schema that documents one) and sits above the
3680/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3681/// every documented production playbook): a value the author can
3682/// plausibly want, but a hard wall above which the policy is
3683/// structurally a footgun. Lifted as a typed `pub const` so the bound
3684/// has exactly one source of truth — a future axis reaching for the
3685/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3686/// materializer's admission webhook, the caixa-mesh-side
3687/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3688/// one place. Same shape every other typed upper bound in this crate
3689/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3690/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3691/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3692/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3693pub const POLICY_RETRIES_MAX: u32 = 10;
3694
3695/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3696/// axis — every validated [`CircuitBreaker::max_failures`] past
3697/// [`AplicacaoSpec::validate_politicas`] lies in
3698/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3699///
3700/// The typed field is `u32` (the zero-floor arm
3701/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3702/// `0` — a breaker that trips on the first call), so a programmatic
3703/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3704/// and the equivalent author-surface form
3705/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3706/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3707/// `max_failures` value far above the documented production-playbook
3708/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3709/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3710/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3711/// typical 5–50) silently disables the breaker's protection role:
3712/// the threshold is structurally so high that no realistic
3713/// failures-per-`:window` traffic shape can reach it, so the breaker
3714/// never trips and the typed slot becomes a no-op carried on every
3715/// emitted Envoy / Cilium L7 overlay. Pairs with the
3716/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3717/// axis — both close the "structurally unbounded `u32` ceiling on a
3718/// typed policy axis" footgun the prior zero-floor-only checks left
3719/// open.
3720///
3721/// The `1000` ceiling sits an order of magnitude above every
3722/// documented upstream production-playbook recommendation band (the
3723/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3724/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3725/// the clearly-pathological "effectively no protection"
3726/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3727/// plausibly want at hyperscale, but a hard wall above which the
3728/// policy is structurally a no-op. Lifted as a typed `pub const` so
3729/// the bound has exactly one source of truth — the future M4
3730/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3731/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3732/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3733/// one place. Same shape every other typed upper bound in this crate
3734/// carries ([`POLICY_RETRIES_MAX`],
3735/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3736/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3737/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3738pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3739
3740/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3741/// every validated [`CircuitBreaker::window`] past
3742/// [`AplicacaoSpec::validate_politicas`] lies in
3743/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3744/// integer-millisecond magnitudes by the canonical-form gate
3745/// immediately preceding).
3746///
3747/// The typed field is `Duration` (the zero-floor arm
3748/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3749/// `Duration::ZERO`, and the canonical-form arm
3750/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3751/// sub-millisecond residue), so a programmatic struct literal
3752/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3753/// and the equivalent author-surface form
3754/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3755/// integer-hour magnitude) both round-trip cleanly through serde — a
3756/// structurally unbounded `Duration` ceiling. A `:window` value far
3757/// above the documented production-playbook band (Hystrix
3758/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3759/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3760/// Istio `outlierDetection.interval` default `10s`, Envoy
3761/// `outlier_detection.interval` default `10s`, AWS App Mesh
3762/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3763/// breaker's role: a rolling-window failure counter whose window is
3764/// hours long is operationally a lifetime counter, the breaker's
3765/// "recent failures" memory is structurally so long that transient
3766/// failures are never forgotten, and the typed slot becomes a no-op
3767/// trigger that trips once and stays tripped for the lifetime of the
3768/// component carried on every emitted Envoy / Cilium L7 overlay.
3769///
3770/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3771/// shared duration codec emits (`"<n>h"` for any integer-hour
3772/// magnitude) — every value in the canonical authoring form's
3773/// `<integer><unit>` grammar at or below this cap renders to a clean
3774/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3775/// cap on the first typed-`Duration` `:politicas` axis: the two
3776/// duration-typed `:politicas` axes now share a single uniform top
3777/// edge so the next typed-slot wiring (the future caixa-mesh
3778/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3779/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3780/// admission webhook) reaches for either field knowing the value is
3781/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3782/// sits two orders of magnitude above every documented upstream
3783/// production-playbook recommendation band (Hystrix / resilience4j /
3784/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3785/// and below the clearly-pathological "rolling window degenerates to
3786/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3787/// author can plausibly want for a very-low-traffic long-tail
3788/// failure-detection window, but a hard wall above which the breaker's
3789/// rolling-window contract is structurally a lifetime-counter contract.
3790/// Lifted as a typed `pub const` so the bound has exactly one source
3791/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3792/// materializer's admission webhook and the caixa-mesh-side
3793/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3794/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3795/// other typed upper bound in this crate carries
3796/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3797/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3798/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3799/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3800/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3801pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3802
3803/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3804/// every validated [`RateLimit::rate`] past
3805/// [`AplicacaoSpec::validate_politicas`] lies in
3806/// `1..=POLICY_RATE_LIMIT_MAX`.
3807///
3808/// The typed field is `u32` (the zero-floor arm
3809/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3810/// zero-rate limit denies every request, the canonical "I forgot
3811/// that 0 means deny-everything" footgun), so a programmatic struct
3812/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3813/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3814/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3815/// round-trip cleanly through serde — a structurally unbounded `u32`
3816/// ceiling. The runtime substrate consuming the value (Envoy's
3817/// `local_rate_limit.token_bucket.max_tokens`, the future
3818/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3819/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3820/// rate-limit into a no-op rate-limiter: the bucket capacity is
3821/// structurally so high no realistic per-edge traffic shape can
3822/// drain it, the limiter never trips, and the typed slot becomes a
3823/// "rate-limit declared, no enforcement" footgun — the canonical
3824/// declared-but-inert shape every other `:politicas` cap arm
3825/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3826/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3827///
3828/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3829/// above every documented upstream production-playbook recommendation
3830/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3831/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3832/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3833/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3834/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3835/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3836/// `u32::MAX`): a value the author can plausibly want at hyperscale
3837/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3838/// /h-window arm), but a hard wall above which the policy is
3839/// structurally a no-op carried verbatim on every emitted Envoy /
3840/// Cilium L7 overlay. The cap brackets all three canonical windows
3841/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3842/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3843/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3844/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3845/// has exactly one source of truth — the future M4
3846/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3847/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3848/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3849/// one place. Same shape every other typed upper bound in this crate
3850/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3851/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3852/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3853/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3854/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3855/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3856pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3857
3858// `:entrada :host` total-length and per-label cap axes route through
3859// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3860// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3861// pair of aplicacao-private aliases the previous `validate_entrada_host`
3862// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3863// = 63`) were structurally the same K8s Gateway API v1 Hostname
3864// admission-schema bounds — the total-length cap on the OpenAPI
3865// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3866// same regex — that the peer axes at the caixa-core::render level pin,
3867// so hoisting both readers onto the shared lifted constants closes the
3868// third-occurrence duplication threshold structurally: the M4
3869// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3870// label validator, the future per-`Certificate` SAN emitter, and every
3871// other per-Gateway-API-Hostname landing site reach the same one place
3872// as the `:entrada :host` gate does — no per-axis alias drift surface
3873// between them, by construction.
3874
3875/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
3876/// extractor expression — the upper bound `validate_placement_shard_key`
3877/// enforces on every well-shaped shard-key past validate. The realistic
3878/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
3879/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
3880/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
3881/// `:placement :affinity` / `:placement :clusters` identifier-shaped
3882/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
3883/// in `:shard-key`" footgun at validate time rather than at the future
3884/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
3885const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
3886
3887/// Reject `:membros :caixa` values the K8s apiserver would refuse at
3888/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3889/// that maps the shared parser-shaped reason into the
3890/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
3891/// is self-locating (the offending `caixa:` is named verbatim) and
3892/// the author can grep their caixa.lisp for `:caixa "<name>"` and
3893/// fix it in one edit. Same diagnostic shape as
3894/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
3895/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
3896fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
3897    // Empty is already gated by `MembroCaixaEmpty` at the call site;
3898    // re-checking here keeps the predicate usable from any future
3899    // call site (the M4 CR materializer) without an empty-check
3900    // footgun. The shared
3901    // [`crate::render::require_valid_dns_1123_label`] helper brackets
3902    // the empty-first + shape cascade every peer name axis
3903    // (`:placement :clusters`, `:placement :affinity`, `:contratos
3904    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
3905    // `:upgrade-from :module`) routes through, so drift between the
3906    // eight axes' accepted DNS-1123-label sets is structurally
3907    // impossible.
3908    crate::render::require_valid_dns_1123_label(
3909        caixa,
3910        || AplicacaoError::MembroCaixaEmpty,
3911        |reason| AplicacaoError::MembroCaixaInvalid {
3912            caixa: caixa.to_string(),
3913            reason,
3914        },
3915    )
3916}
3917
3918/// Reject `:placement :clusters` entries the K8s apiserver would refuse
3919/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
3920/// that maps the shared parser-shaped reason into the
3921/// [`AplicacaoError::PlacementClusterInvalid`] variant.
3922///
3923/// Cluster names land in DNS-1123-label territory across every consumer:
3924/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
3925/// the `lareira-fleet-programs` aggregator applies to scope programs to
3926/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
3927/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
3928/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
3929/// cluster identity the M4 CR materializer round-trips. Each apiserver-
3930/// side schema enforces the DNS-1123 label rule on admission; a
3931/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
3932/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
3933/// mistaken-identity slug) silently passes the prior empty-/duplicate-
3934/// only gate and the failure surfaces as a no-match at filter time —
3935/// the workload doesn't land in the named cluster, with no diagnostic
3936/// naming the offending `:clusters` entry. Lifting the gate to caixa-
3937/// build time mirrors the `:membros :caixa` value-shape trajectory
3938/// (3f9d7a0) on the peer name axis.
3939///
3940/// The diagnostic carries the offending `cluster:` verbatim plus a
3941/// parser-shaped `reason:` naming the specific violation, so the
3942/// author can grep their caixa.lisp for `:clusters` and fix it in
3943/// one edit. Same diagnostic shape as
3944/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
3945fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
3946    // Empty is already gated by `PlacementClusterEmpty` at the call
3947    // site; re-checking here keeps the predicate usable from any
3948    // future call site (the M4 CR materializer's per-cluster validator)
3949    // without an empty-check footgun. Routes through the shared
3950    // [`crate::render::require_valid_dns_1123_label`] gate the peer
3951    // name axes each land on.
3952    crate::render::require_valid_dns_1123_label(
3953        cluster,
3954        || AplicacaoError::PlacementClusterEmpty,
3955        |reason| AplicacaoError::PlacementClusterInvalid {
3956            cluster: cluster.to_string(),
3957            reason,
3958        },
3959    )
3960}
3961
3962/// Reject `:placement :affinity` hints whose shape can never legitimately
3963/// land in any downstream selector or label-keyed routing axis. Thin
3964/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
3965/// shared parser-shaped reason into the
3966/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
3967/// diagnostic is self-locating (the offending `:affinity` is named
3968/// verbatim) and the author can grep their caixa.lisp for
3969/// `:affinity "<hint>"` and fix it in one edit.
3970///
3971/// The `:affinity` slot carries a placement-engine hint — canonical
3972/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
3973/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
3974/// compression overlay and the future M4 placement-engine's per-hint
3975/// routing axis. Each downstream consumer (caixa-mesh's
3976/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
3977/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
3978/// `spec.placement.affinity` admission rule, the future M4 per-hint
3979/// node-affinity / pod-affinity rule generator keying off the same
3980/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
3981/// selector) requires the value to be a DNS-1123 label — K8s label
3982/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
3983/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
3984/// admission rule the apiserver enforces.
3985///
3986/// Until this gate landed an `:affinity "DataLocality"` (the canonical
3987/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
3988/// Python-module-name leak), `:affinity "data.locality"` (the
3989/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
3990/// `:affinity "data-locality-"` (boundary-hyphen violation),
3991/// `:affinity "data locality"` (paste-from-doc whitespace),
3992/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
3993/// 64-byte over-cap slug silently passed the empty-only check and the
3994/// failure surfaced as a no-match at the M3 Adaptive compression
3995/// overlay's filter time (`placement.affinity` carried a malformed
3996/// value, no node matched, the workload landed on the default
3997/// heuristic) — the canonical "declared-but-inert" footgun mirroring
3998/// the empty-:affinity / empty-shard-key / zero-:politicas /
3999/// empty-:contratos-target gates already close on every other
4000/// declare-but-no-opinion axis. Lifting the rejection to a build-time
4001/// gate closes the fifth typed slot on the Aplicacao surface to land
4002/// on the canonical DNS-1123 label floor (after the four Servico-name
4003/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
4004/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
4005/// b0e8748).
4006///
4007/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
4008/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
4009/// validated values are guaranteed-accepted by the apiserver without
4010/// re-validation at any downstream renderer or admission layer.
4011fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
4012    // Empty is gated separately at the call site for a self-locating
4013    // diagnostic; re-checking here keeps the predicate usable from any
4014    // future call site (the M4 CR materializer's per-affinity
4015    // validator) without an empty-check footgun. Routes through the
4016    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4017    // peer name axes each land on.
4018    crate::render::require_valid_dns_1123_label(
4019        affinity,
4020        || AplicacaoError::PlacementAffinityEmpty,
4021        |reason| AplicacaoError::PlacementAffinityInvalid {
4022            affinity: affinity.to_string(),
4023            reason,
4024        },
4025    )
4026}
4027
4028/// Reject `:placement :shard-key` extractor expressions whose shape can
4029/// never legitimately drive the future M4 Akka-style cluster-sharding
4030/// reconciler's hash-extractor pass. Maps the per-byte / length checks
4031/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
4032/// diagnostic is self-locating (the offending `:shard-key` value is
4033/// named verbatim alongside the parser-shaped reason) and the author can
4034/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
4035/// edit.
4036///
4037/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
4038/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
4039/// expression naming the message property to hash on. The realistic
4040/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
4041/// property name; `$tenantId` — Akka entity-id placeholder;
4042/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
4043/// `${tenant}` — interpolation-style template) all sit in the printable
4044/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
4045/// multi-line blob landing in `:shard-key`, an embedded space from a
4046/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
4047/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
4048/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
4049/// check and the failure surfaces at the future M4 reconciler's hash
4050/// pass as a runtime extractor-evaluation error far from the source
4051/// `caixa.lisp`, with no field naming which member's `:shard-key`
4052/// carried the offending value.
4053///
4054/// The contract — the printable ASCII single-token intersection-floor
4055/// every Akka-style entity-id extractor implementation admits:
4056///
4057///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
4058///     peer DNS-1123-label-shaped `:placement :affinity` /
4059///     `:placement :clusters` identifier axes; realistic shard-keys sit
4060///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
4061///     blob footguns at validate time;
4062///   - every byte in the printable ASCII range `0x21..=0x7E` —
4063///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
4064///     `"$tenantId\n"` from paste-from-aligned-doc /
4065///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
4066///     `\x7F` — the canonical "embedded null from a copy-paste-binary
4067///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
4068///     un-Punycode-encoded IDN that round-trips inconsistently across
4069///     NFC/NFD normalization).
4070///
4071/// The accepted set is broader than the DNS-1123 label floor the peer
4072/// `:placement :clusters` / `:placement :affinity` axes use because the
4073/// `:shard-key` value is not a K8s `metadata.name` / label-selector
4074/// landing site; it's an extractor expression the future Akka-style
4075/// reconciler reads as a property reference. The realistic forms
4076/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
4077/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
4078/// but every Akka-style entity-id extractor parses. The
4079/// printable-ASCII-token floor accepts every shape any such extractor
4080/// would accept while rejecting the cross-implementation footguns
4081/// (whitespace breaks token boundaries; non-ASCII round-trips
4082/// inconsistently across YAML emitters and NFC/NFD normalization;
4083/// control characters silently corrupt the next read).
4084///
4085/// Until this gate landed `validate_placement` only refused the
4086/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
4087/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
4088/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
4089/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
4090/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
4091/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
4092/// control character from paste-from-binary, the 64-byte over-cap
4093/// paste-from-doc multi-line slug) silently passed validate. The future
4094/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
4095/// would then surface the malformed value either as a runtime
4096/// extractor-evaluation error (whitespace breaks the extractor's token
4097/// boundary, no match) or as a silently-different shard assignment
4098/// across YAML emitters (non-ASCII normalizes differently between the
4099/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
4100/// parser, the same entity ID maps to two distinct shards on a
4101/// re-render). Lifting the shape gate to caixa-build time makes the
4102/// extractor-floor invariant a structural property of every validated
4103/// `Placement`: every `Sharded` placement past `validate_placement` has
4104/// a `:shard-key` the future M4 reconciler can hash without
4105/// re-validating at the runtime layer.
4106///
4107/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
4108/// [`AplicacaoError::ContratoSubjectInvalid`] /
4109/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
4110/// on the peer `:contratos` payload axes — each lifts the
4111/// runtime-side parser's intersection-floor to a caixa-build-time gate,
4112/// closing the canonical "this passed validate but the runtime parser
4113/// rejected it" surprise.
4114fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
4115    // Empty is gated separately at the call site via the more
4116    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
4117    // re-checking here keeps the predicate usable from any future call
4118    // site (the M4 CR materializer's per-shard-key validator) without
4119    // an empty-check footgun.
4120    if key.is_empty() {
4121        return Err(AplicacaoError::ShardedKeyEmpty);
4122    }
4123    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
4124        return Err(AplicacaoError::ShardKeyInvalid {
4125            shard_key: key.to_string(),
4126            reason: format!(
4127                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
4128                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
4129                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
4130                 well under 32 bytes, this length suggests a paste-from-doc \
4131                 multi-line blob landed in `:shard-key` instead of a single-token \
4132                 extractor expression)",
4133                key.len()
4134            ),
4135        });
4136    }
4137    for &b in key.as_bytes() {
4138        if (0x21..=0x7E).contains(&b) {
4139            continue;
4140        }
4141        let reason = if b == b' ' {
4142            "contains a space (Akka-style entity-id extractor expressions are \
4143             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
4144             whitespace breaks the extractor's token boundary at the runtime layer, \
4145             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
4146             a multi-token blob in one `:shard-key` slot)"
4147                .to_string()
4148        } else if b == b'\t' {
4149            "contains a tab character (paste-from-aligned-doc footgun; the \
4150             Akka-style entity-id extractor reads `:shard-key` as a single-token \
4151             reference, embedded whitespace breaks the token boundary at the \
4152             runtime hash-extractor pass)"
4153                .to_string()
4154        } else if b == b'\n' || b == b'\r' {
4155            format!(
4156                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
4157                 paste-from-multiline-doc footgun; the Akka-style entity-id \
4158                 extractor reads `:shard-key` as a single-token reference, embedded \
4159                 newlines either truncate the value at the YAML emitter layer or \
4160                 break the token boundary at the runtime hash-extractor pass)"
4161            )
4162        } else if b < 0x20 || b == 0x7F {
4163            format!(
4164                "contains control character 0x{b:02x} (the canonical \
4165                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
4166                 control characters silently corrupt round-trip serialization \
4167                 across YAML emitters and break the runtime hash-extractor's \
4168                 single-token parser)"
4169            )
4170        } else {
4171            format!(
4172                "contains non-ASCII byte 0x{b:02x} (the canonical \
4173                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
4174                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
4175                 across YAML emitter implementations — the same entity ID can \
4176                 silently map to two distinct shards on a re-render. Use a \
4177                 printable-ASCII extractor expression like `tenantId`, \
4178                 `$tenantId`, or `metadata.tenantId`)"
4179            )
4180        };
4181        return Err(AplicacaoError::ShardKeyInvalid {
4182            shard_key: key.to_string(),
4183            reason,
4184        });
4185    }
4186    Ok(())
4187}
4188
4189/// Reject `:contratos :de` / `:contratos :para` values whose shape
4190/// can never legitimately match a validated `:membros :caixa`. Thin
4191/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4192/// shared parser-shaped reason into the
4193/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
4194/// diagnostic is self-locating (which slot — `:de` or `:para` — and
4195/// the offending value verbatim) and the author can grep their
4196/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
4197/// one edit.
4198///
4199/// Until this gate landed an empty or DNS-1123-malformed `:de` /
4200/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
4201/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
4202/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
4203/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
4204/// un-Punycode-encoded IDN) silently passed the per-axis check and
4205/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
4206/// membership lookup — diagnostic-framed as "this caixa is not in
4207/// `:membros`" when the root cause is "this `:de` value is not a
4208/// well-shaped Servico-name identifier and could never legitimately
4209/// match any validated member". Because every `:membros :caixa` is
4210/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
4211/// `names` HashSet structurally never contains an empty / malformed
4212/// string, so the membership lookup arm misframes every empty /
4213/// malformed input. Lifting the shape arm ahead of the lookup
4214/// preserves the legitimate `ContratoMemberMissing` arm (a
4215/// well-shaped `:de` that simply isn't in `:membros` — a phantom
4216/// reference) while routing every structurally-impossible-to-match
4217/// input through the narrower self-locating shape diagnostic.
4218///
4219/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4220/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
4221/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
4222/// to land on the canonical [`crate::render::is_dns_1123_label`]
4223/// floor. The `slot: &'static str` field carries the kebab-case
4224/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
4225/// per-callback-slot diagnostic shape and the
4226/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
4227/// (85f102c) cross-list-tag pattern.
4228fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
4229    // Routes through the shared
4230    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4231    // name axes each land on. The `slot: &'static str` field flows
4232    // through both error variants so the diagnostic names which
4233    // per-edge axis (`:de` vs `:para`) the offending value came from.
4234    crate::render::require_valid_dns_1123_label(
4235        caixa,
4236        || AplicacaoError::ContratoCaixaEmpty { slot },
4237        |reason| AplicacaoError::ContratoCaixaInvalid {
4238            slot,
4239            caixa: caixa.to_string(),
4240            reason,
4241        },
4242    )
4243}
4244
4245/// Reject `:entrada :para` values whose shape can never legitimately
4246/// match a validated `:membros :caixa`. Thin wrapper around
4247/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
4248/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
4249/// variant, so the diagnostic is self-locating (the offending
4250/// `:entrada :para` value is named verbatim) and the author can grep
4251/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
4252///
4253/// Until this gate landed an empty or DNS-1123-malformed `:entrada
4254/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
4255/// ADR typo, `:para "my_cart"` the Python-module-name leak,
4256/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
4257/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
4258/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
4259/// silently passed the per-axis check and surfaced as
4260/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
4261/// — diagnostic-framed as "this caixa is not in `:membros`" when the
4262/// root cause is "this `:entrada :para` value is not a well-shaped
4263/// Servico-name identifier and could never legitimately match any
4264/// validated member". Because every `:membros :caixa` is shape-
4265/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
4266/// `HashSet` structurally never contains an empty / malformed string,
4267/// so the membership lookup arm misframes every empty / malformed
4268/// input. Lifting the shape arm ahead of the lookup preserves the
4269/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
4270/// simply isn't in `:membros` — a phantom reference) while routing
4271/// every structurally-impossible-to-match input through the narrower
4272/// self-locating shape diagnostic.
4273///
4274/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4275/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
4276/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
4277/// fourth and last Aplicacao-level Servico-name reference axis to
4278/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
4279/// No `slot: &'static str` field because there is only one axis
4280/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
4281/// the simpler shape mirrors [`validate_membro_caixa`] and
4282/// [`validate_placement_cluster`].
4283fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
4284    // Empty is gated separately at the call site for a self-locating
4285    // diagnostic; re-checking here keeps the predicate usable from any
4286    // future call site (the M4 CR materializer's per-`:entrada`
4287    // validator) without an empty-check footgun. Routes through the
4288    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4289    // peer name axes each land on.
4290    crate::render::require_valid_dns_1123_label(
4291        para,
4292        || AplicacaoError::EntradaParaEmpty,
4293        |reason| AplicacaoError::EntradaParaInvalid {
4294            para: para.to_string(),
4295            reason,
4296        },
4297    )
4298}
4299
4300/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
4301/// would refuse at admission time. The contract — exactly the regex
4302/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
4303/// and `HTTPRoute.spec.hostnames[]`,
4304/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
4305/// (max length 253; per-label max length 63):
4306///
4307///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
4308///     uppercase, no underscore, no Unicode/IDN — IDN must be
4309///     pre-encoded as Punycode `xn--…` by the author);
4310///   - exactly one optional leading wildcard label (`*.`); a wildcard
4311///     in any non-leading label position is rejected;
4312///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
4313///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
4314///   - total length 1..=253 bytes;
4315///   - no IPv4 literal (Gateway API forbids IP literals);
4316///   - no scheme (`https://`, `http://`), no port (`:8080`), no
4317///     whitespace, no path (`/`).
4318///
4319/// Lifted as a typed gate (rather than an inline cascade in
4320/// `validate()`) so the contract lives in one place — every future
4321/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4322/// materializer's host validator, the future per-`:entrada` SAN
4323/// emission for cert-manager Certificates, the multi-`:entrada`
4324/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
4325/// for the same predicate, not its own. Same compounding shape as
4326/// `is_canonical_rate_limit_window` (808017c) and
4327/// [`WitTarget::label`] (previously the free `contrato_target_label`
4328/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
4329/// per-variant label match is compiler-checked-exhaustive).
4330///
4331/// The diagnostic carries the offending `host:` verbatim plus a
4332/// parser-shaped `reason:` naming the specific violation, so the
4333/// author can grep their caixa.lisp for `:host "<host>"` and fix it
4334/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
4335/// (9888b13).
4336fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
4337    // Empty is already gated by `EmptyEntradaHost` at the call site;
4338    // re-checking here keeps the predicate usable from any future
4339    // call site (M4 CR materializer) without an empty-check footgun.
4340    if host.is_empty() {
4341        return Err(AplicacaoError::EmptyEntradaHost);
4342    }
4343    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
4344        return Err(AplicacaoError::EntradaHostInvalid {
4345            host: host.to_string(),
4346            reason: format!(
4347                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
4348                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
4349                host.len(),
4350                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
4351            ),
4352        });
4353    }
4354    if host.contains("://") {
4355        return Err(AplicacaoError::EntradaHostInvalid {
4356            host: host.to_string(),
4357            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
4358                     Gateway API takes the bare hostname)"
4359                .to_string(),
4360        });
4361    }
4362    if host.contains('/') {
4363        return Err(AplicacaoError::EntradaHostInvalid {
4364            host: host.to_string(),
4365            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
4366                     matching is in `:entrada :paths`)"
4367                .to_string(),
4368        });
4369    }
4370    // After the `://` scheme-prefix and `/` path arms have ruled out the
4371    // two `:`-bearing shapes the Gateway API actively rejects with
4372    // location-shaped diagnostics, any remaining `:` in the host body is
4373    // either the canonical "I put the port in the `:host` slot"
4374    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
4375    // slot lives one axis away on the same `:entrada` block) or an
4376    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
4377    // Hostname forbids identically to the IPv4-literal arm below. Both
4378    // shapes silently fell through the `://` and `/` arms before this
4379    // lift and surfaced as a deep `label "<rest>:<port>" contains
4380    // invalid character ':'` diagnostic from the per-byte loop near the
4381    // bottom of this predicate, which named the offending byte but not
4382    // the canonical authoring fix — for the port case the author has to
4383    // know the `:entrada` block carries a separate `:port u16` slot
4384    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
4385    // move the value over; for the IPv6 case the author has to know
4386    // Gateway API v1 forbids IP literals across the board. The contract
4387    // doc-comment above already promises "no port (`:8080`)" verbatim
4388    // in the rejected-shape enumeration but the predicate's
4389    // implementation refused the `:` only as a side-effect of the
4390    // per-label `[a-z0-9-]` character-class loop; this arm brings the
4391    // implementation in line with the documented contract by surfacing
4392    // the canonical fix at the top-level shape gate, peer with how the
4393    // `://` arm names the scheme prefix and the `/` arm names the
4394    // `:entrada :paths` axis. Same compounding trajectory the recent
4395    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
4396    // — the typed slot's rejected set matches the apiserver's rejected
4397    // set, structurally, with a self-locating diagnostic at the
4398    // offending axis instead of a deep parser-shape leak.
4399    if host.contains(':') {
4400        return Err(AplicacaoError::EntradaHostInvalid {
4401            host: host.to_string(),
4402            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
4403                     slot — a separate `u16` axis on the same `:entrada` block, \
4404                     defaulting to 8080 — not in the host body; drop the `:<port>` \
4405                     suffix and author the bare hostname. If you intended an IPv6 \
4406                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
4407                     Hostname forbids IP literals identically to the IPv4-literal \
4408                     arm — use a DNS name)"
4409                .to_string(),
4410        });
4411    }
4412    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
4413    // predicate — the same single source of truth every peer
4414    // ASCII-whitespace scan in caixa-core flows through: the four
4415    // typed-magnitude codec sites (`limits::parse_byte_size` backing
4416    // `:limits :memory`, `limits::parse_duration` backing `:limits
4417    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
4418    // `aplicacao::rate_limit_codec::parse` backing `:politicas
4419    // :rate-limit`) and the shared duration codec
4420    // (`supervisor::duration_codec::parse`) backing `:supervisor
4421    // :restart-window` / `:politicas :timeout` / `:politicas
4422    // :circuit-breaker :window`. This landing closes the last string-typed
4423    // slot in caixa-core still calling `.bytes().any(|b|
4424    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
4425    // across every typed slot now shares one predicate, so a future
4426    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
4427    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
4428    // deliberately excluded from the peer non-ASCII predicate) can
4429    // extend at this shared site in one edit rather than seven
4430    // independent scans diverging over time. Naming the offending byte
4431    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
4432    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
4433    // the offending byte verbatim" discipline every peer codec site
4434    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
4435    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
4436    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
4437        return Err(AplicacaoError::EntradaHostInvalid {
4438            host: host.to_string(),
4439            reason: format!(
4440                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
4441                 Hostname is a single-token DNS name — leading, trailing, \
4442                 or embedded whitespace breaks the K8s apiserver's Hostname \
4443                 regex at admission time; the paste-from-aligned-doc / \
4444                 paste-from-shell-history / paste-from-CSV footgun silently \
4445                 lands a multi-token blob in `:entrada :host`. Strip every \
4446                 whitespace byte and author the bare hostname — space \
4447                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
4448                 refuse identically)"
4449            ),
4450        });
4451    }
4452    // Peer of the ASCII-whitespace scan above: route the non-ASCII
4453    // subset of Unicode `White_Space` through the shared
4454    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
4455    // single source of truth every peer non-ASCII-whitespace scan in
4456    // caixa-core flows through: `limits::parse_byte_size` (`:limits
4457    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
4458    // `limits::parse_millicores` (`:limits :cpu`),
4459    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
4460    // and `supervisor::duration_codec::parse` (`:supervisor
4461    // :restart-window` / `:politicas :timeout` / `:politicas
4462    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
4463    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
4464    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
4465    // paste-from-web-doc), or an EM-SPACE-split host
4466    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
4467    // survived this predicate's ASCII byte-scan (none of the UTF-8
4468    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
4469    // `u8::is_ascii_whitespace`), then landed on the per-label
4470    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
4471    // predicate with the generic `label "…" must start and end with an
4472    // alphanumeric` diagnostic — a "far from source at build-time"
4473    // leak that names the label-shape violation but not the
4474    // paste-from-typography origin the author actually needs to fix.
4475    // Peer with the four codec sites the 1b75b38 landing pinned: the
4476    // typed slot's diagnostic axis names the offending codepoint
4477    // (`U+XXXX`) verbatim rather than laundering the value through a
4478    // downstream label-shape arm, so the author can grep their
4479    // caixa.lisp for the invisible codepoint at the surfaced position
4480    // rather than eyeball a multi-byte host for embedded NBSP / LINE
4481    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
4482    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
4483    // drift between any two typed-slot sites' non-ASCII-whitespace
4484    // rejection set becomes a single-edit fix at the shared predicate
4485    // rather than N independent inline scans diverging over time, and
4486    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
4487    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
4488    // `char::is_whitespace`" class the peer non-ASCII predicate's
4489    // doc-comment names as the follow-up trajectory) extends at the
4490    // shared predicate in one edit rather than seven.
4491    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
4492        return Err(AplicacaoError::EntradaHostInvalid {
4493            host: host.to_string(),
4494            reason: format!(
4495                "contains non-ASCII Unicode whitespace character {ch:?} \
4496                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
4497                 single-token DNS name limited to `[a-z0-9-]` labels; \
4498                 the paste-from-typography footgun silently lands an \
4499                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
4500                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
4501                 `U+3000`, and every other member of the Unicode \
4502                 `White_Space` property outside the ASCII byte range) \
4503                 in `:entrada :host`, which the K8s apiserver's \
4504                 Hostname regex refuses at admission time far from the \
4505                 caixa.lisp source line. Strip every non-ASCII \
4506                 whitespace character and author the bare hostname \
4507                 with only ASCII bytes (write \"checkout.quero.cloud\" \
4508                 verbatim)",
4509                codepoint = ch as u32,
4510            ),
4511        });
4512    }
4513
4514    // Strip the optional single leading wildcard label *before* the
4515    // trailing-dot check so the bare `"*."` form surfaces the more
4516    // self-locating "wildcard without domain" diagnostic instead of
4517    // the generic "trailing dot" one.
4518    let (had_wildcard, rest) = match host.strip_prefix("*.") {
4519        Some(r) => (true, r),
4520        None => (false, host),
4521    };
4522    if had_wildcard && rest.is_empty() {
4523        return Err(AplicacaoError::EntradaHostInvalid {
4524            host: host.to_string(),
4525            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
4526        });
4527    }
4528    if rest.contains('*') {
4529        return Err(AplicacaoError::EntradaHostInvalid {
4530            host: host.to_string(),
4531            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
4532                     no inner or trailing `*` labels"
4533                .to_string(),
4534        });
4535    }
4536    if rest.ends_with('.') {
4537        return Err(AplicacaoError::EntradaHostInvalid {
4538            host: host.to_string(),
4539            reason: "must not have a trailing `.` (Gateway API hostnames are not \
4540                     fully-qualified with a root dot; the apiserver regex rejects \
4541                     trailing dots)"
4542                .to_string(),
4543        });
4544    }
4545
4546    // Reject pure IPv4 literals: four dot-separated labels, every
4547    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
4548    // literals as Hostnames.
4549    let labels: Vec<&str> = rest.split('.').collect();
4550    if labels.len() == 4
4551        && labels
4552            .iter()
4553            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
4554    {
4555        return Err(AplicacaoError::EntradaHostInvalid {
4556            host: host.to_string(),
4557            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
4558                     literals; use a DNS name)"
4559                .to_string(),
4560        });
4561    }
4562
4563    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
4564    // hyphen, with non-hyphen at both boundaries.
4565    for label in &labels {
4566        if label.is_empty() {
4567            return Err(AplicacaoError::EntradaHostInvalid {
4568                host: host.to_string(),
4569                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
4570            });
4571        }
4572        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
4573            return Err(AplicacaoError::EntradaHostInvalid {
4574                host: host.to_string(),
4575                reason: format!(
4576                    "label {label:?} exceeds DNS-1123 label max length of \
4577                     {cap} bytes (got {} bytes)",
4578                    label.len(),
4579                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
4580                ),
4581            });
4582        }
4583        let bytes = label.as_bytes();
4584        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
4585            return Err(AplicacaoError::EntradaHostInvalid {
4586                host: host.to_string(),
4587                reason: format!(
4588                    "label {label:?} must start and end with an alphanumeric \
4589                     (no leading or trailing `-`)"
4590                ),
4591            });
4592        }
4593        for &b in bytes {
4594            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
4595            if !valid {
4596                let msg = if b.is_ascii_uppercase() {
4597                    format!(
4598                        "label {label:?} contains uppercase character {ch:?} \
4599                         (Gateway API hostnames are lowercase-only; use {lower:?})",
4600                        ch = b as char,
4601                        lower = label.to_ascii_lowercase()
4602                    )
4603                } else if b == b'_' {
4604                    format!(
4605                        "label {label:?} contains `_` (Gateway API hostnames \
4606                         allow only `[a-z0-9-]`; use `-` instead)"
4607                    )
4608                } else {
4609                    format!(
4610                        "label {label:?} contains invalid character {ch:?} \
4611                         (Gateway API hostnames allow only `[a-z0-9-]`)",
4612                        ch = b as char
4613                    )
4614                };
4615                return Err(AplicacaoError::EntradaHostInvalid {
4616                    host: host.to_string(),
4617                    reason: msg,
4618                });
4619            }
4620        }
4621    }
4622    Ok(())
4623}
4624
4625/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
4626/// would refuse at admission time. Thin wrapper around
4627/// [`crate::render::is_gateway_api_http_path`] that maps the shared
4628/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
4629/// variant, preserving the more self-locating
4630/// [`AplicacaoError::EntradaPathEmpty`] /
4631/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
4632/// path fails those narrower invariants first.
4633///
4634/// The contract is the canonical HTTP-path grammar — `1..=
4635/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
4636/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
4637/// whitespace/control/non-ASCII bytes — shared with the
4638/// `:contratos :endpoint` axis through the lifted predicate so drift
4639/// between either landing site and the K8s apiserver-side
4640/// HTTPPathMatch.value OpenAPI schema is a build error visible at
4641/// the predicate, not a per-renderer "this passed validate but failed
4642/// admission" surprise. The diagnostic carries the offending `path:`
4643/// verbatim plus a parser-shaped `reason:` naming the specific
4644/// violation, so the author can grep their caixa.lisp for `:paths`
4645/// and fix it in one edit. Same diagnostic shape as
4646/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
4647/// axis.
4648fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
4649    // Empty and missing-leading-`/` are already gated at the call
4650    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
4651    // checking here keeps the per-axis narrower diagnostics in force
4652    // when the predicate is reached directly (and `is_gateway_api_http_path`
4653    // itself defends against `bytes[0]`-style indexing on empty
4654    // input).
4655    if path.is_empty() {
4656        return Err(AplicacaoError::EntradaPathEmpty);
4657    }
4658    if !path.starts_with('/') {
4659        return Err(AplicacaoError::EntradaPathNotAbsolute {
4660            path: path.to_string(),
4661        });
4662    }
4663    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
4664        AplicacaoError::EntradaPathInvalid {
4665            path: path.to_string(),
4666            reason,
4667        }
4668    })
4669}
4670
4671mod rate_limit_codec {
4672    // `Duration` is no longer named here — the codec routes through
4673    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4674    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4675    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4676    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4677    // closed-set enum's arm-table rather than through vestigial free-helper
4678    // delegates.
4679    use super::{RateLimit, RateLimitUnit};
4680    use serde::{Deserialize, Deserializer, Serializer};
4681
4682    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4683        match v {
4684            Some(rl) => s.serialize_str(&render(*rl)),
4685            None => s.serialize_none(),
4686        }
4687    }
4688
4689    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4690        let opt: Option<String> = Option::deserialize(d)?;
4691        match opt {
4692            None => Ok(None),
4693            Some(s) => parse(&s).map(Some).map_err(serde::de::Error::custom),
4694        }
4695    }
4696
4697    fn parse(s: &str) -> Result<RateLimit, String> {
4698        // Whitespace-rejection arm — peer with the leading-`+`
4699        // (`"+100/s"`) and leading-zero (`"0100/s"`) arms below on the
4700        // same canonical-form render-determinism axis. Until this gate
4701        // landed the parser silently tolerated leading / trailing /
4702        // internal whitespace via the top-level `s.trim()` and the
4703        // per-part `rate_str.trim()` / `unit.trim()` calls, so every
4704        // whitespace-carrying shape (`" 100/s"`, `"100/s "`,
4705        // `"100 /s"`, `"100/ s"`, `"100 / s"`, `"100/s\n"`,
4706        // `"\t100/s"`) parsed to the same `RateLimit { 100, 1s }` and
4707        // serde silently round-tripped to `"100/s"` on the next emit
4708        // (a *different* canonical string) — breaking the THEORY.md
4709        // Part V render-determinism contract on the same
4710        // canonical-form-drift axis the leading-`+` arm below (the
4711        // 4eeae98 predecessor) and the leading-zero arm below (the
4712        // 4f46830 predecessor) already close.
4713        //
4714        // The canonical author shape is `<integer>/<s|m|h>` with no
4715        // whitespace bytes anywhere — every string [`render`] emits
4716        // carries none, so the parser's accepted set must match for
4717        // serialize / deserialize to round-trip losslessly. This gate
4718        // makes the pre-existing `s.trim()` / `rate_str.trim()` /
4719        // `unit.trim()` calls below strict no-ops on the accepted set
4720        // (every byte-position match they would perform is now already
4721        // trimmed away by the accepted set itself), while the arm
4722        // surfaces every rejected whitespace-carrying shape with a
4723        // self-locating diagnostic naming the offending byte and the
4724        // canonical form the author intended, peer with every prior
4725        // canonical-form-drift arm on this codec.
4726        //
4727        // Routed through the lifted
4728        // [`crate::render::find_ascii_whitespace_byte`] predicate — the
4729        // same source of truth the four peer typed-magnitude codec
4730        // sites (`limits::parse_byte_size`, `limits::parse_duration`,
4731        // `limits::parse_millicores`, `supervisor::duration_codec`)
4732        // share. `u8::is_ascii_whitespace()` at the predicate covers
4733        // the five WhatWG-conformant ASCII whitespace bytes (space,
4734        // tab, LF, FF, CR); the "single lifted predicate" discipline
4735        // the peer non-ASCII arm below carries on the strictly-
4736        // complementary Unicode `White_Space` class extends here to
4737        // the ASCII byte set as well.
4738        if let Some(b) = crate::render::find_ascii_whitespace_byte(s) {
4739            return Err(format!(
4740                "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4741                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4742                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4743                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4744                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4745                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4746                 on first serialize — breaking the THEORY.md Part V render-determinism \
4747                 contract every typed slot carries. Strip every whitespace byte (write \
4748                 `\"100/s\"` verbatim)"
4749            ));
4750        }
4751        // Non-ASCII Unicode `White_Space` arm — the strictly-
4752        // complementary class the ASCII arm above cannot see.
4753        // `str::trim` at the top of every peer codec uses
4754        // `char::is_whitespace` (Unicode `White_Space`, strictly
4755        // wider than the ASCII byte set), so an NBSP (`\u{00A0}`) /
4756        // LINE SEPARATOR (`\u{2028}`) / EM-SPACE (`\u{2003}`)
4757        // survives the byte-scan (its UTF-8 bytes are not in
4758        // `is_ascii_whitespace`), gets silently stripped by the
4759        // top-level `s.trim()` below, and the value round-trips
4760        // through `render` to a *different* canonical form
4761        // (`\"100/s\"`) on next emit — breaking the THEORY.md Part V
4762        // render-determinism contract every typed slot carries.
4763        // Closed here (`:politicas :rate-limit`) and at the three
4764        // peer codec sites (`limits::parse_byte_size`,
4765        // `limits::parse_duration`, `supervisor::duration_codec`)
4766        // through the shared
4767        // [`crate::render::find_non_ascii_whitespace_char`] predicate
4768        // — the "single lifted predicate across all four codec sites
4769        // in one follow-up run" the 24a8ad4 commit body's `Forward
4770        // compounding` bullet named as the next compounding step.
4771        if let Some(ch) = crate::render::find_non_ascii_whitespace_char(s) {
4772            return Err(format!(
4773                "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4774                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4775                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4776                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4777                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4778                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4779                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4780                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4781                 silently strips it at parse entry, and the value round-trips through \
4782                 `render` to a *different* canonical form (`\"100/s\"`) on first \
4783                 serialize — breaking the THEORY.md Part V render-determinism contract \
4784                 every typed slot carries. Strip every non-ASCII whitespace character \
4785                 (write `\"100/s\"` verbatim with only ASCII bytes)",
4786                cp = ch as u32
4787            ));
4788        }
4789        let s = s.trim();
4790        let (rate_str, unit) = s
4791            .split_once('/')
4792            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4793        let rate_trim = rate_str.trim();
4794        // The canonical authoring form for `:politicas :rate-limit` is
4795        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4796        // non-negative integer with no decimal point and no leading
4797        // sign, so the parser's accepted set must match for
4798        // serialize/deserialize to round-trip without canonical-form
4799        // drift. Until this gate landed the parser accepted any
4800        // `u32::from_str`-shaped magnitude — and current Rust
4801        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4802        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4803        // serde silently round-tripped to `"100/s"` on the next emit
4804        // (a *different* canonical string) — breaking the THEORY.md
4805        // Part V render-determinism contract on the fifth typed-codec
4806        // surface in caixa-core (peer with the four duration codecs the
4807        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4808        // already covered: `supervisor::duration_codec` backing three
4809        // typed-duration slots, `limits::parse_duration` backing
4810        // `:limits :wall-clock`, `limits::parse_byte_size` backing
4811        // `:limits :memory`). The fractional / decimal-shaped sibling
4812        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4813        // existing rejection arm, but the diagnostic is value-laundered
4814        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4815        // doesn't name the canonical-form remediation or the round-trip
4816        // drift the next emit would produce); this gate lifts the
4817        // fractional arm onto the same canonical-form diagnostic the
4818        // peer codecs carry.
4819        //
4820        // Strict canonical form: every byte of the magnitude is an
4821        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4822        // inputs the gate distinguishes "non-canonical-but-numeric"
4823        // (parses as f64 or i64 — surfaced with a self-locating
4824        // diagnostic naming the canonical authoring form and the
4825        // round-trip drift the rejected shape would produce on first
4826        // serialize) from "garbage" (parses as neither — surfaced with
4827        // the existing narrower `"not a u32"` wording so its
4828        // diagnostic shape remains stable for the parser-shape footgun
4829        // case).
4830        //
4831        // Routed through the lifted
4832        // [`crate::render::is_digit_only_magnitude`] predicate — the
4833        // same source of truth the four peer typed-magnitude codec
4834        // sites share.
4835        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4836        if !digit_only {
4837            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4838            if numeric {
4839                return Err(format!(
4840                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4841                     canonical authoring form for `:politicas :rate-limit` is \
4842                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4843                     with no decimal point and no leading `+` / `-` sign. A fractional / \
4844                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4845                     through `render` to a *different* canonical form (`\"1/s\"`, \
4846                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
4847                     THEORY.md Part V render-determinism contract every typed slot \
4848                     carries. Pick an integer rate that fits the desired window \
4849                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4850                ));
4851            }
4852            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4853        }
4854        // Leading-zero arm — peer with the prior `"+100/s"` arm above
4855        // (4eeae98's predecessor) on the same canonical-form
4856        // render-determinism axis. The digit-only gate accepts
4857        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4858        // them losslessly (= 100, 0, 7), but `render` emits the
4859        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4860        // a *different* canonical string on the next emit, breaking
4861        // the THEORY.md Part V render-determinism contract the same
4862        // way `"+100/s"` did before the leading-`+` arm landed. The
4863        // single-byte magnitude `"0"` itself round-trips losslessly
4864        // through `render` (`render(0)` emits `"0/s"`) — the
4865        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4866        // what refuses rate-zero authoring, so `"0/s"` stays in the
4867        // accepted set at this codec layer and the diagnostic
4868        // partitioning between canonical-form drift (this arm) and
4869        // semantic-zero (the downstream gate) remains stable.
4870        // Peer with the future leading-zero arms on the three peer
4871        // typed-magnitude codecs the trajectory acknowledges:
4872        // `supervisor::duration_codec`, `limits::parse_duration`,
4873        // `limits::parse_byte_size` — each carries the same
4874        // canonical-form-drift class today; this gate lands the
4875        // discipline on the fourth typed-magnitude codec in
4876        // caixa-core first because the peer `"+100/s"` arm above is
4877        // the closest predecessor on the trajectory.
4878        //
4879        // Routed through the lifted
4880        // [`crate::render::is_leading_zero_padded_magnitude`]
4881        // predicate — the same source of truth the four peer
4882        // typed-magnitude codec sites share.
4883        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4884            return Err(format!(
4885                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4886                 canonical authoring form for `:politicas :rate-limit` is \
4887                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4888                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4889                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4890                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4891                 first serialize — breaking the THEORY.md Part V render-determinism \
4892                 contract every typed slot carries. Strip the leading zeros (write \
4893                 `\"100/s\"` instead of `\"0100/s\"`)"
4894            ));
4895        }
4896        // The digit-only gate guarantees every byte is `[0-9]`, and
4897        // the leading-zero arm above guarantees the magnitude is
4898        // either the single byte `"0"` or starts with `[1-9]`, so
4899        // the only way `u32::from_str` can fail here is overflow
4900        // (the magnitude exceeds `u32::MAX`). Surface that with an
4901        // overflow-shaped wording so the diagnostic names the
4902        // offending magnitude verbatim rather than collapsing onto
4903        // the non-canonical arm. Same shape
4904        // `supervisor::duration_codec` (1c55a2a) carries on the peer
4905        // duration-codec axis.
4906        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4907            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4908        })?;
4909        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
4910        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
4911        // arm reads the `&str → Duration` projection through the
4912        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4913        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
4914        // with [`super::RateLimitUnit::window`]) rather than the vestigial
4915        // module-private `rate_limit_window_from_unit` free helper the
4916        // predecessor 61421a6 left as the last unlifted delegate on this
4917        // axis. One typed dispatch on the substrate primitive instead of
4918        // one runtime call through the free-helper delegate; the sole
4919        // production consumer of the `&str → Duration` axis (this parse
4920        // arm) now reaches for exactly one typed method on the closed-set
4921        // enum, sibling to the codec's render arm's
4922        // [`super::RateLimit::canonical_unit`] dispatch on the paired
4923        // `Duration → RateLimitUnit` axis and to the validate gate's
4924        // [`super::RateLimit::canonical_unit`] shape-probe on the
4925        // canonical-window axis. A future rate-limit-unit addition (a
4926        // `"d"` day suffix once Envoy's `rate_limit_action` grows
4927        // daily-bucket support, a `"ms"` sub-second window once
4928        // high-throughput per-edge policies come into scope per
4929        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
4930        // on the closed-set enum, and the compiler enforces exhaustiveness
4931        // on every consumer's `match self` arms — this parse arm's
4932        // accepted-suffix set, the render arm's emitted-suffix set, the
4933        // validate gate's canonical-window set, and every future
4934        // per-`:contratos`-edge rate-limit-override overlay all pick it up
4935        // by construction.
4936        let unit = unit.trim();
4937        let window = RateLimitUnit::window_from_suffix(unit)
4938            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
4939        Ok(RateLimit { rate, window })
4940    }
4941
4942    fn render(rl: RateLimit) -> String {
4943        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
4944        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
4945        // this render arm reads the `Duration → RateLimitUnit` projection
4946        // through the substrate primitive [`super::RateLimit::canonical_unit`]
4947        // (returns `None` on every non-canonical window — the sub-second /
4948        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
4949        // formats the returned typed enum through its
4950        // [`std::fmt::Display`] impl (which routes through
4951        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
4952        // the substrate primitive instead of one runtime `find_map`
4953        // walk through the free-helper delegate chain
4954        // [`super::rate_limit_window_unit`] (the vestigial free helper's
4955        // sole production consumer was this arm; every other consumer of
4956        // the `Duration → unit` axis — the validate gate below and the
4957        // future M4 per-Aplicacao Envoy config reconciler — now reads
4958        // the same typed method).
4959        //
4960        // A future rate-limit-unit addition (a `"d"` day suffix once
4961        // Envoy's `rate_limit_action` grows daily-bucket support) is
4962        // one variant + one arm per method on the closed-set enum, and
4963        // the compiler enforces exhaustiveness on every consumer's
4964        // `match self` arms — the codec's `parse` accepted-suffix set,
4965        // this render arm's emitted-suffix set, the validate gate's
4966        // canonical-window set, and every future per-`:contratos`-edge
4967        // rate-limit-override overlay all pick it up by construction.
4968        if let Some(unit) = rl.canonical_unit() {
4969            format!("{}/{unit}", rl.rate())
4970        } else {
4971            // Defensive fallback for non-canonical windows. Note:
4972            // [`AplicacaoSpec::validate_politicas`] rejects any
4973            // non-canonical `:rate-limit :window` via
4974            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
4975            // a validated `RateLimit` never reaches this branch. The
4976            // emitted `<n>/<k>s` form is *not* round-trippable through
4977            // [`parse`] (which accepts only the closed-set
4978            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
4979            // explicit count) — the validate gate is what makes the
4980            // round-trip a structural property; this branch exists only
4981            // so a programmatic non-validated serialize doesn't panic.
4982            format!("{}/{}s", rl.rate(), rl.window().as_secs())
4983        }
4984    }
4985}
4986
4987// ── placement strategy ───────────────────────────────────────────────
4988
4989/// How the Aplicacao distributes across clusters. Three options:
4990///
4991/// - `SingleNode` — one cluster runs the app at a time; takeover on
4992///   death (Erlang/OTP distributed-app semantics).
4993/// - `Replicated` — every named cluster runs an instance (active-active).
4994/// - `Sharded` — entities distribute by hash key across clusters
4995///   (Akka cluster sharding).
4996#[derive(
4997    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
4998)]
4999pub enum PlacementStrategy {
5000    SingleNode,
5001    Replicated,
5002    Sharded,
5003}
5004
5005/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
5006/// distribution-strategy default for the `:placement :estrategia` axis —
5007/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
5008/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
5009/// so every substrate-side consumer that resolves "what
5010/// [`PlacementStrategy`] variant does an author-omitted `:placement
5011/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
5012/// primitive [`PlacementStrategy`].
5013///
5014/// The `:placement :estrategia` default axis has three production
5015/// consumers on the substrate side today: the [`Default for
5016/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
5017/// impl's struct-literal `estrategia` field, and the serde-side
5018/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
5019/// author-omitted `:placement :estrategia` scalar through the [`Default
5020/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
5021/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
5022/// impl and implicit `PlacementStrategy::default()` routes at the sibling
5023/// consumers, with no compile-time link back to the paired
5024/// [`crate::manifest::Caixa::aplicacao_view`] fold's
5025/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
5026/// production consumer that resolves an author-omitted `:placement` slot
5027/// (entirely omitted, not just the `:estrategia` scalar within a declared
5028/// `:placement` block) through [`Placement::default`] which then routes
5029/// through this same discriminator. A future coherent rebrand of the
5030/// `:placement :estrategia` default (a widening to `Sharded` once the
5031/// substrate discovers hash-keyed distribution as the more common
5032/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
5033/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
5034/// names, a per-cluster overlay the operator pins through a future
5035/// `:placement-overrides` slot) would have had to migrate a lifted
5036/// discriminator on one path and open-coded discriminators on the peers
5037/// in lockstep or the four consumers would silently drift out of
5038/// pairing. Lifting the resolution rule to a typed `pub const` on the
5039/// substrate primitive means the M3-mesh-canonical `:placement
5040/// :estrategia` default migrates as one unit on any future axis change.
5041///
5042/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
5043/// §II.2's active-active-across-every-named-cluster arm — the closest
5044/// canonical M3 production reference the substrate carries, matching the
5045/// caixa-mesh default axis every M3 renderer already keys off (a
5046/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
5047/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
5048/// under the substrate's fleet-programs aggregator without an explicit
5049/// `:placement :estrategia` override). The two alternatives the closed
5050/// [`PlacementStrategy::ALL`] accept-set carries
5051/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
5052/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
5053/// Akka-style hash-keyed distribution across clusters,
5054/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
5055/// postures an author declares explicitly, never a posture an omitted
5056/// slot should silently assume.
5057///
5058/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
5059/// exactly one source of truth on the `:placement :estrategia` axis, on
5060/// the same substrate-primitive lift discipline the sibling M2
5061/// per-supervisor default set carries
5062/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
5063/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
5064/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
5065/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
5066/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
5067/// ([`crate::render::DEFAULT_NAMESPACE`],
5068/// [`crate::render::DEFAULT_LIBRARY_NAME`],
5069/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
5070/// the M3 mesh-primitive-defining slot family to converge onto the
5071/// substrate-primitive-lift discipline the M2 supervisor-slot family
5072/// already carries end-to-end.
5073pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
5074
5075impl Default for PlacementStrategy {
5076    fn default() -> Self {
5077        // Route the [`Default for PlacementStrategy`] impl through the
5078        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
5079        // `pub const` rather than a raw `Self::Replicated` arm — one
5080        // source of truth for the M3-mesh-canonical active-active-
5081        // across-every-named-cluster `:placement :estrategia` default
5082        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
5083        // lift discipline the sibling M2 per-supervisor default set
5084        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
5085        // paired halves) carries end-to-end. Pinned by
5086        // `placement_strategy_default_routes_through_lifted_default`.
5087        PLACEMENT_ESTRATEGIA_DEFAULT
5088    }
5089}
5090
5091impl PlacementStrategy {
5092    /// Exhaustive iteration surface for every consumer that reads the
5093    /// full closed-set (the future M4 admission-webhook's accepted-
5094    /// strategy listing in its rejection body, a future `feira app
5095    /// placement --list` CLI-side surfacing of the accepted arm-set,
5096    /// any future round-trip fuzz harness). A future variant addition
5097    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
5098    /// names as a trajectory item) extends this slice as a single edit
5099    /// and every consumer picks up the new entry by construction — the
5100    /// compiler-checked exhaustiveness on the sibling method `match`
5101    /// arms is the build-time guarantee that no arm forgets to grow.
5102    /// Same shape as the sibling closed-set typed enums'
5103    /// [`RateLimitUnit::ALL`] (6bce03d) and
5104    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5105    /// surfaces — the third closed-set typed enum on the caixa surface
5106    /// to converge onto the same discipline.
5107    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
5108
5109    /// Canonical camelCase-schema discriminator scalar this variant
5110    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
5111    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
5112    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5113    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
5114    /// every substrate consumer that dispatches on the strategy (the
5115    /// `lareira-fleet-programs` aggregator, the future `app-operator`
5116    /// reconciler, the M3 Adaptive compression pass) reads the same
5117    /// byte-string the `Serialize` derive emits — the pin test in
5118    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
5119    /// asserts the two paths agree.
5120    #[must_use]
5121    pub const fn as_str(self) -> &'static str {
5122        match self {
5123            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
5124            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
5125            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
5126        }
5127    }
5128
5129    /// Substrate-canonical reverse projection on the `:placement
5130    /// :estrategia` closed-set axis — parses the camelCase-schema
5131    /// discriminator scalar back to the typed variant, or `None` when
5132    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
5133    /// emits. Dispatches on the same lifted
5134    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5135    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5136    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
5137    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
5138    /// the round-trip migrate through one caixa-core edit on any future
5139    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
5140    /// §II.5 hint names as a trajectory item lands one variant + one
5141    /// arm per method and the compiler enforces exhaustiveness on every
5142    /// consumer's `match self` arms).
5143    ///
5144    /// Prior to this lift the substrate carried only the forward
5145    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
5146    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
5147    /// derive that emits the same byte-string under
5148    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
5149    /// consumer that wanted to parse a wire-form strategy scalar had to
5150    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
5151    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
5152    /// compile-time link back to the typed variant's canonical lifted
5153    /// constant. A future variant rename or a per-arm serde-attribute
5154    /// drift would silently split the wire byte-string one non-serde
5155    /// consumer parsed from the one the emitter wrote, with the
5156    /// failure surfacing at parse time far from the rebrand commit.
5157    ///
5158    /// Same closed-set-reverse-projection discipline the sibling
5159    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
5160    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
5161    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
5162    /// defining `:placement :estrategia` closed-set axis, the third
5163    /// substrate-side closed-set typed enum to converge on the two-way
5164    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
5165    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
5166    /// and side-step the [`std::str::FromStr`]-collision clippy
5167    /// (`clippy::should_implement_trait`) the plain `from_str` name
5168    /// carries; a future explicit [`std::str::FromStr`] impl can layer
5169    /// on top by delegating to this canonical arm-dispatch method.
5170    ///
5171    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
5172    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
5173    /// picks the diagnostic form appropriate for its use site — a
5174    /// future `feira app placement --set` CLI-side arg-parse that wants
5175    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
5176    /// Sharded)"` diagnostic builds one on top by iterating
5177    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
5178    /// path folds `None` onto its per-CR structured refusal body.
5179    #[must_use]
5180    pub fn from_wire(s: &str) -> Option<Self> {
5181        match s {
5182            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
5183            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
5184            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
5185            _ => None,
5186        }
5187    }
5188
5189    /// Substrate-canonical per-arm predicate naming the cross-slot
5190    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
5191    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
5192    /// consumes the paired [`Placement::shard_key`] axis (and therefore
5193    /// requires — and is the only strategy that permits — a non-empty
5194    /// `:shard-key` on the paired slot). Today the accept-set is the
5195    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
5196    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
5197    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
5198    /// distributed-app takeover — §II.1) and `Replicated` (active-active
5199    /// across every named cluster) have no hash-keyed routing axis to
5200    /// consume the slot and refuse a declared-but-inert `:shard-key`
5201    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
5202    ///
5203    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
5204    /// satisfies `placement.shard_key().is_some() ==
5205    /// placement.estrategia().requires_shard_key()` by construction — the
5206    /// cross-slot partition the pin
5207    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
5208    /// locks load-bearing, so every downstream consumer that reaches for
5209    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5210    /// CR materializer's per-CR shard-key resolver, the future
5211    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
5212    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
5213    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
5214    /// shard-key requirement probe, a future author-facing tatara-lisp
5215    /// linter that flags `(:placement (:estrategia Replicated :shard-key
5216    /// "tenantId"))` shapes before `feira lint` reaches
5217    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
5218    /// the substrate primitive — the predicate names *the cross-slot
5219    /// invariant*, not the arm identity.
5220    ///
5221    /// Prior to this lift the "does this strategy consume `:shard-key`"
5222    /// classification lived under the `gen_platform::IsVariant`-derived
5223    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
5224    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
5225    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
5226    /// } else { None }` cascade, the
5227    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
5228    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
5229    /// "tenantId".to_string())` cascade, and the
5230    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
5231    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
5232    /// cascade). Each site conflated two semantically distinct questions:
5233    /// "is the variant `Sharded`?" (arm-identity, what
5234    /// [`Self::is_sharded`] answers) and "does the variant consume
5235    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
5236    /// The two questions land on the same three-way answer under today's
5237    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
5238    /// future arm addition that consumed `:shard-key` under a different
5239    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
5240    /// §II.5 roadmap-hint names that hash-partitions across the cluster
5241    /// pool by client-IP hash rather than an author-declared extractor
5242    /// expression, a hypothetical `WeightedShard` variant that carries a
5243    /// shard-key + per-cluster weight table under a promoted M5
5244    /// adaptive-placement engine) or an addition that did *not* consume
5245    /// `:shard-key` on a semantically Sharded-shaped arm would silently
5246    /// split the two questions. Any consumer that read
5247    /// `.is_sharded().then(…)` for the shard-key requirement gate would
5248    /// silently misclassify the new arm as non-consuming — a fixture
5249    /// builder would omit `:shard-key` where the new arm required one and
5250    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
5251    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
5252    /// commit, a future M4 CR materializer would fall through the
5253    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
5254    /// silently emit an empty extractor at the Akka reconciler layer.
5255    ///
5256    /// Lifting the classification as a substrate-primitive method on the
5257    /// closed-set typed enum names the cross-slot invariant on the
5258    /// primitive that owns the partition: every future arm addition
5259    /// declares its `:shard-key` consumption in one place (this predicate's
5260    /// `match self` arm-set), and every downstream consumer that reaches
5261    /// for the paired shape reads through one typed dispatch. Same
5262    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
5263    /// per-arm predicate on the pre-projection WIT-shape axis and the
5264    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
5265    /// paired predicate on the post-projection typed-view axis — a
5266    /// per-arm semantic-classification predicate paired with the
5267    /// arm-identity predicate the derive already emits, closing the drift
5268    /// footgun on the cross-slot invariant axis.
5269    ///
5270    /// Method-named `requires_shard_key` (not `has_shard_key`, not
5271    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
5272    /// invariant reads as "this strategy *requires* the paired
5273    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
5274    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
5275    /// merely omit it. The `has_*` framing would read as an accessor
5276    /// (returning the presence of an already-carried value) rather than a
5277    /// requirement (naming the invariant the paired slot must satisfy).
5278    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
5279    /// shape as the sibling [`WitContract::is_capability`] /
5280    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
5281    /// arm-family, so every consumer reaches for `.requires_shard_key()`
5282    /// as a drop-in replacement for the `.is_sharded()` conflated read
5283    /// without a return-shape migration.
5284    #[must_use]
5285    pub const fn requires_shard_key(self) -> bool {
5286        match self {
5287            Self::Sharded => true,
5288            Self::SingleNode | Self::Replicated => false,
5289        }
5290    }
5291}
5292
5293// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5294// cross-slot-invariant per-arm predicate: the module-scope const-eval
5295// assertions below trip at caixa-core build time (not test time) if a
5296// future edit rewires the predicate's arm-set away from the singleton
5297// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5298// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5299// runtime pin covers the same truth-table with a more descriptive
5300// diagnostic on failure; these const-eval items add a build-time failure
5301// surface strictly stronger than the runtime pin (a downstream renderer's
5302// `const`-context reader that composed against a rebound predicate would
5303// still surface here before the test suite even ran) and side-step the
5304// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5305// would otherwise accumulate on the caixa-core module baseline.
5306const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5307const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5308const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5309
5310/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5311/// the pretty-printed byte-string every consumer that formats the strategy
5312/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5313/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5314/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5315/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5316/// admission-webhook rejection body) reaches for the same lifted
5317/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5318/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5319/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5320/// `Serialize` derive already emits under
5321/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5322/// [`PlacementStrategy::as_str`] helper already returns.
5323///
5324/// Until this lift landed the sibling OTP-shape typed enums —
5325/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5326/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5327/// so [`std::fmt::Display`] routes through the same discriminant string
5328/// the wire format emits) — carried a stable [`std::fmt::Display`]
5329/// surface but [`PlacementStrategy`] did not; every consumer reaching
5330/// for a strategy byte-string past the wire format had to pick between
5331/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5332/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5333/// derive), any two of which a future variant rename or
5334/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5335/// desynchronize — with the failure surfacing as a downstream renderer /
5336/// operator's per-strategy dispatch reading one spelling while the wire
5337/// format emitted another, far from the source rebrand commit and with
5338/// no field naming the drift. Routing `Display` through
5339/// [`PlacementStrategy::as_str`] makes the three paths
5340/// (`Debug` for structural inspection, `Display` for user-facing text,
5341/// `Serialize` for the wire format) converge on the same lifted
5342/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
5343/// the diagnostic byte-string, and the pretty-printed byte-string move
5344/// as a single unit through one canonical declaration each, by
5345/// construction. Same trajectory as [`PlacementStrategy::as_str`]
5346/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
5347/// closes the third path.
5348///
5349/// Pin tests
5350/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
5351/// and
5352/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
5353/// assert the three paths agree byte-for-byte on every variant, so a
5354/// future variant rename or per-arm serde attribute drift is a build
5355/// error visible at caixa-core test time, not a silent per-consumer
5356/// dispatch miss at apply / reconcile time.
5357impl std::fmt::Display for PlacementStrategy {
5358    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5359        f.write_str(self.as_str())
5360    }
5361}
5362
5363/// Where the Aplicacao runs.
5364#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5365#[serde(rename_all = "camelCase")]
5366pub struct Placement {
5367    /// Distribution strategy.
5368    #[serde(default)]
5369    pub estrategia: PlacementStrategy,
5370
5371    /// Named clusters that host this Aplicacao. Required for
5372    /// `Replicated` and `SingleNode`; for `Sharded` declares the
5373    /// shard pool.
5374    #[serde(default)]
5375    pub clusters: Vec<String>,
5376
5377    /// Optional hint to the placement engine: `"data-locality"`,
5378    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
5379    #[serde(default, skip_serializing_if = "Option::is_none")]
5380    pub affinity: Option<String>,
5381
5382    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
5383    #[serde(default, skip_serializing_if = "Option::is_none")]
5384    pub shard_key: Option<String>,
5385}
5386
5387impl Placement {
5388    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
5389    /// `:shard-key` extractor-expression scalar accessor every consumer
5390    /// of the Aplicacao's hash-keyed distribution routing keys off —
5391    /// returns the author-declared `:placement :shard-key` byte-string
5392    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
5393    /// own `Option<String>` storage; `None` when the slot is absent
5394    /// (the canonical shape under `:estrategia Replicated` /
5395    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
5396    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
5397    /// partition — `validate` refuses any `Placement` past this call
5398    /// that lands `Some` on a non-`Sharded` strategy or `None` on
5399    /// `Sharded`).
5400    ///
5401    /// The `:placement :shard-key` slot carries the Akka-style
5402    /// cluster-sharding entity-id extractor expression
5403    /// (MESH-COMPOSITION §II.4) — validated by
5404    /// [`validate_placement_shard_key`] to be a non-empty printable-
5405    /// ASCII single-token reference (`tenantId`, `$tenantId`,
5406    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
5407    /// future M4 Akka-style cluster-sharding reconciler hashes without
5408    /// re-validating at the runtime layer), and every downstream
5409    /// consumer that reads the key keys off this scalar (the
5410    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
5411    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5412    /// declared-but-inert refusal diagnostic, the caixa-mesh
5413    /// per-Aplicacao `placement.shardKey` emit path the substrate
5414    /// operator's per-entity hash-routing reader consumes, the future
5415    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5416    /// per-shard-key resolver).
5417    ///
5418    /// Prior to this lift the `.shard_key` field was accessed inline at
5419    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
5420    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
5421    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
5422    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
5423    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
5424    /// — two open-coded field-accesses that expressed no compile-time
5425    /// link back to the typed slot. A future extension of the
5426    /// `:placement :shard-key` axis to a richer author surface — a
5427    /// per-cluster override the operator pins through a future
5428    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
5429    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
5430    /// alias table the M4 CR materializer resolves per-CR, a
5431    /// per-Aplicacao dynamic `:shard-key` derivation the future
5432    /// adaptive placement engine computes from `:affinity` weights —
5433    /// would have had to be threaded through both open-coded copies in
5434    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
5435    /// arm refusal would silently disagree on which extractor
5436    /// expression a given Placement resolves to. Lifting the resolution
5437    /// rule to a typed method on the substrate primitive means every
5438    /// downstream consumer of the Aplicacao's per-`:placement`
5439    /// hash-key surface reaches for exactly one typed dispatch — the
5440    /// resolver's accept-set migrates as a unit on any future axis
5441    /// addition.
5442    ///
5443    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
5444    /// [`WitContract::destination`] / [`WitContract::world_ref`]
5445    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
5446    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
5447    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
5448    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
5449    /// typed dispatch on the substrate primitive, thin projections at
5450    /// each consumer" discipline extended onto the per-`:placement`
5451    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
5452    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
5453    /// — opens the "optional per-slot scalar" projection pattern the
5454    /// sibling per-`:placement` `:affinity`, per-`:politicas`
5455    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
5456    /// match the storage field's name; the accessor's identity name
5457    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
5458    /// slot's docstring already carries.
5459    #[must_use]
5460    pub const fn shard_key(&self) -> Option<&str> {
5461        match &self.shard_key {
5462            Some(s) => Some(s.as_str()),
5463            None => None,
5464        }
5465    }
5466
5467    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
5468    /// compression-hint scalar accessor every weighting-consumer of the
5469    /// Aplicacao's per-hint routing surface keys off — returns the
5470    /// author-declared `:placement :affinity` byte-string verbatim as
5471    /// an `Option<&str>`, borrowed from the typed slot's own
5472    /// `Option<String>` storage; `None` when the slot is absent (the
5473    /// canonical shape of an Aplicacao that leaves the compression
5474    /// weighting up to the placement engine's cluster-default arm — no
5475    /// author-authored `data-locality` / `low-latency` / etc. hint
5476    /// biases the routing).
5477    ///
5478    /// The `:placement :affinity` slot carries the M3 Adaptive-
5479    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
5480    /// by [`validate_placement_affinity`] to be a DNS-1123 label
5481    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
5482    /// K8s-conformant label-selector shape every apiserver-side pod-
5483    /// affinity / node-affinity materializer already gates on
5484    /// admission), and every downstream consumer that reads the hint
5485    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
5486    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
5487    /// `placement.affinity` overlay emit path the substrate operator's
5488    /// per-hint weighting-consumer reads, the future M4
5489    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
5490    /// pod-affinity / node-affinity selector resolver).
5491    ///
5492    /// Prior to this lift the `.affinity` field was accessed inline at
5493    /// the sole caixa-core site — the
5494    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
5495    /// `if let Some(a) = &self.placement.affinity { …
5496    /// validate_placement_affinity(a)? … }` cascade — one open-coded
5497    /// field-access that expressed no compile-time link back to the
5498    /// typed slot. A future extension of the `:placement :affinity`
5499    /// axis to a richer author surface — a per-cluster override the
5500    /// operator pins through a future `:placement :affinity-overrides`
5501    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
5502    /// tenant hint alias table the M4 CR materializer resolves per-CR,
5503    /// a per-Aplicacao dynamic `:affinity` derivation the future
5504    /// adaptive placement engine computes from `:clusters` topology —
5505    /// would have had to be threaded through the open-coded copy in
5506    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
5507    /// materializer reader that landed on the axis, or the per-hint
5508    /// value-shape gate and its downstream weighting consumers would
5509    /// silently disagree on which hint a given Placement resolves to.
5510    /// Lifting the resolution rule to a typed method on the substrate
5511    /// primitive means every downstream consumer of the Aplicacao's
5512    /// per-`:placement` compression-hint surface reaches for exactly
5513    /// one typed dispatch — the resolver's accept-set migrates as a
5514    /// unit on any future axis addition.
5515    ///
5516    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
5517    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
5518    /// optional-scalar axis — same "one typed dispatch on the substrate
5519    /// primitive, thin projections at each consumer" discipline extended
5520    /// onto the per-`:placement` M3-Adaptive-compression-hint
5521    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
5522    /// return accessor on the M3 mesh-slot family; closes the last
5523    /// un-lifted per-`:placement` `Option<String>` axis. Named
5524    /// `affinity()` to match the storage field's name; the accessor's
5525    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
5526    /// vocabulary the slot's docstring already carries.
5527    #[must_use]
5528    pub const fn affinity(&self) -> Option<&str> {
5529        match &self.affinity {
5530            Some(s) => Some(s.as_str()),
5531            None => None,
5532        }
5533    }
5534
5535    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
5536    /// strategy scalar accessor every consumer that dispatches on the
5537    /// Aplicacao's per-cluster distribution shape keys off — returns the
5538    /// author-declared `:placement :estrategia` variant verbatim as a
5539    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
5540    /// `PlacementStrategy` storage.
5541    ///
5542    /// The `:placement :estrategia` slot carries the closed-set
5543    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
5544    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
5545    /// `Replicated` — active-active across every named cluster; `Sharded`
5546    /// — Akka-style hash-keyed entity distribution across the cluster pool
5547    /// per §II.4) that every downstream consumer of the Aplicacao's
5548    /// per-cluster fan-out shape keys off. Validated by
5549    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
5550    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
5551    /// matches!(estrategia, Sharded)` — the cross-slot partition the
5552    /// [`Placement::shard_key`] accessor's docstring pins), and every
5553    /// downstream consumer that reads the strategy keys off this scalar
5554    /// (the [`AplicacaoSpec::validate_placement`]
5555    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
5556    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
5557    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
5558    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5559    /// declared-but-inert refusal's
5560    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
5561    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
5562    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
5563    /// emit path the substrate operator's per-strategy fan-out reader
5564    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5565    /// materializer's per-strategy admission-webhook resolver).
5566    ///
5567    /// Prior to this lift the `.estrategia` field was accessed inline at
5568    /// four sites — the [`AplicacaoSpec::validate_placement`]
5569    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
5570    /// `estrategia: self.placement.estrategia`, the same method's
5571    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
5572    /// partition dispatch, the non-`Sharded`-arm
5573    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
5574    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
5575    /// per-Aplicacao strategy print line at
5576    /// `println!("… {} …", spec.placement.estrategia, …)`
5577    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
5578    /// expressed no compile-time link back to the typed slot. A future
5579    /// extension of the `:placement :estrategia` axis to a richer author
5580    /// surface (a per-cluster override the operator pins through a future
5581    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
5582    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
5583    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
5584    /// derivation the future adaptive placement engine computes from
5585    /// `:affinity` + `:clusters` topology) would have had to be threaded
5586    /// through every open-coded copy in lockstep — one consumer reading
5587    /// the raw variant while a peer read the operator-resolved variant
5588    /// would silently split the `PlacementWithoutClusters` /
5589    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
5590    /// partition-dispatch input, a two-consumer split at the validator
5591    /// far from the source `caixa.lisp` with no field naming the
5592    /// strategy-drift root cause. Lifting the resolution rule to a typed
5593    /// method on the substrate primitive means every downstream consumer
5594    /// of the Aplicacao's per-`:placement` distribution-strategy surface
5595    /// reaches for exactly one typed dispatch — the resolver's accept-set
5596    /// migrates as a unit on any future axis addition.
5597    ///
5598    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
5599    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
5600    /// same "one typed dispatch on the substrate primitive, thin
5601    /// projections at each consumer" discipline extended onto the
5602    /// per-`:placement` distribution-strategy `Copy`-composite-enum
5603    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
5604    /// family; first `Copy`-return accessor on the M3 mesh-slot
5605    /// `Placement` type — companion to the sibling per-`:placement`
5606    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5607    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
5608    /// optional-scalar axes, closing the last unlifted per-`:placement`
5609    /// scalar-value axis (the closed-set `PlacementStrategy`
5610    /// distribution-strategy discriminator) so every downstream
5611    /// per-`:placement` reader now routes through a typed dispatch on
5612    /// the substrate primitive. Named `estrategia()` to match the storage
5613    /// field's name; the accessor's identity name maps onto the
5614    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
5615    /// already carries. Declared `pub const fn` (matching the peer M3
5616    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5617    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5618    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5619    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5620    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5621    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5622    /// [`RateLimit`] — every one a `pub const fn`) so every future
5623    /// substrate-side `const`-context consumer of the resolved
5624    /// distribution-strategy variant (a `const _: () = assert!(…)`
5625    /// module-scope invariant pin on a per-fixture typed [`Placement`],
5626    /// a future M4 admission-webhook `const fn` resolver over a typed
5627    /// [`Placement`], any `const fn` composer that fans on the strategy
5628    /// at compile time) reaches through the same typed dispatch on the
5629    /// substrate primitive at const-eval time as at runtime. Pinned by
5630    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
5631    /// const-eval posture at module scope via `const _:() = …` items so
5632    /// any future accidental downgrade to non-`const` trips at caixa-core
5633    /// build time.
5634    #[must_use]
5635    pub const fn estrategia(&self) -> PlacementStrategy {
5636        self.estrategia
5637    }
5638
5639    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
5640    /// per-cluster distribution-target slice accessor every consumer that
5641    /// walks the Aplicacao's declared cluster-pool keys off — returns the
5642    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
5643    /// `&[String]` slice-view, borrowed from the typed slot's own
5644    /// `Vec<String>` storage (a zero-copy slice-view over the same
5645    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5646    /// through). Non-optional: the empty slice is the load-bearing
5647    /// pre-validation sentinel every downstream consumer of the paired
5648    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
5649    /// off — every strategy in the closed
5650    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
5651    /// requires a non-empty list (`SingleNode` / `Replicated` use the
5652    /// list as hosting / takeover candidates per Erlang/OTP distributed-
5653    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
5654    /// shard pool per Akka cluster-sharding convention, §II.4), so the
5655    /// `.is_empty()` probe is the shared pre-condition every
5656    /// [`AplicacaoSpec::validate_placement`] arm heads on.
5657    ///
5658    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
5659    /// 1123-label per-cluster distribution-target list — the same
5660    /// set-not-multiset shape the sibling `:membros :caixa` /
5661    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
5662    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
5663    /// pins the shape). Every downstream consumer that fans on the list
5664    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
5665    /// pre-flight `.is_empty()` probe that trips
5666    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
5667    /// per-cluster value-shape + duplicate-detection fan-out loop, the
5668    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
5669    /// that materializes the list verbatim onto every
5670    /// programs.yaml entry the substrate operator's per-cluster
5671    /// `placement.clusters | contains .Values.cluster` filter reads,
5672    /// the `feira app graph` per-Aplicacao cluster print line, the
5673    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5674    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
5675    /// placement engine's cluster-topology reader).
5676    ///
5677    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
5678    /// inline at three production sites — the
5679    /// [`AplicacaoSpec::validate_placement`] pre-flight
5680    /// `self.placement.clusters.is_empty()` refusal probe, the same
5681    /// method's per-cluster validate loop's
5682    /// `for c in &self.placement.clusters` traversal head, and the
5683    /// `feira app graph` per-Aplicacao print line's
5684    /// `spec.placement.clusters` `{:?}` formatter argument
5685    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
5686    /// that expressed no compile-time link back to the typed slot. A
5687    /// future extension of the `:placement :clusters` axis to a richer
5688    /// author surface (a per-tenant cluster-pool overlay the operator
5689    /// pins through a future `:placement :clusters-overrides` slot the
5690    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
5691    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
5692    /// the future M5 adaptive-placement engine computes from
5693    /// `:affinity` weights + live cluster-topology probes, a promotion
5694    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
5695    /// partition once the substrate operator's cluster-membership
5696    /// reconciler comes into typed scope) would have had to be threaded
5697    /// through all three open-coded copies in lockstep or one consumer
5698    /// would silently disagree with the peers on which cluster-pool a
5699    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
5700    /// reading the raw slot while the peer per-cluster validate loop
5701    /// read an operator-resolved slot would silently split the paired
5702    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
5703    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
5704    /// input from the pre-flight input, a three-consumer split at the
5705    /// validator and formatter far from the source `caixa.lisp` with
5706    /// no field naming the cluster-pool-drift root cause. Lifting the
5707    /// resolution rule to a typed method on the substrate primitive
5708    /// means every downstream consumer of the Aplicacao's
5709    /// per-`:placement` cluster-pool surface reaches for exactly one
5710    /// typed dispatch — the resolver's accept-set migrates as a unit
5711    /// on any future axis addition.
5712    ///
5713    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
5714    /// slot — sibling to the seed M2
5715    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
5716    /// slice-return accessor on the peer per-`:supervisor` static-
5717    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
5718    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
5719    /// primitive, thin projections at each consumer" discipline. The
5720    /// three peer `Vec`-carry axes still unlifted at the time of this
5721    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
5722    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
5723    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
5724    /// [`crate::UpgradeFromEntry::instructions`]
5725    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5726    /// — inherit this accessor's discipline as future compounding runs
5727    /// migrate their consumers onto the shared slice-return shape.
5728    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
5729    /// type, sibling to the two `Option<&str>`-return
5730    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5731    /// (74ec2d3) accessors and the `Copy`-return
5732    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
5733    /// unlifted per-`:placement` field axis (the `Vec<String>`
5734    /// distribution-target-list carrier) so every downstream
5735    /// per-`:placement` reader now routes through a typed dispatch on
5736    /// the substrate primitive. Named `clusters()` to match the storage
5737    /// field's name verbatim and the tatara-lisp author-surface term
5738    /// (`:clusters`) the field's own docstring already carries; the
5739    /// accessor's identity maps onto the canonical MESH-COMPOSITION
5740    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
5741    /// for. Returns `&[String]` (not `&Vec<String>`) because every
5742    /// downstream consumer of the cluster list treats it as a read-only
5743    /// sequence — the slice-view is the narrowest borrow that supports
5744    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
5745    /// `.len()`) without leaking the backing `Vec`'s
5746    /// grow/push/reserve surface that no consumer of the typed view
5747    /// reaches for (the storage-side `Vec` remains reachable through
5748    /// the `pub clusters` field for the mutation-carrying serde
5749    /// round-trip and per-test fixture-mutation paths).
5750    #[must_use]
5751    pub fn clusters(&self) -> &[String] {
5752        self.clusters.as_slice()
5753    }
5754}
5755
5756impl Default for Placement {
5757    fn default() -> Self {
5758        Self {
5759            // Route the struct-literal `estrategia` default arm through
5760            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
5761            // typed `pub const` rather than the transitively-derived
5762            // [`PlacementStrategy::default`] route — one source of truth
5763            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
5764            // active-active-across-every-named-cluster arm
5765            // (MESH-COMPOSITION §II.2) that both this struct-literal
5766            // altitude and the sibling [`Default for PlacementStrategy`]
5767            // impl already key off through the same substrate primitive.
5768            // Pinned by
5769            // `placement_default_estrategia_routes_through_lifted_default`.
5770            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
5771            clusters: Vec::new(),
5772            affinity: None,
5773            shard_key: None,
5774        }
5775    }
5776}
5777
5778// ── external entry point ─────────────────────────────────────────────
5779
5780/// External entry point — what an outside caller sees. Renders to a
5781/// Gateway / Ingress + a route to the named member Servico.
5782#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5783#[serde(rename_all = "camelCase")]
5784pub struct Entrada {
5785    /// Public hostname (e.g. `"checkout.quero.cloud"`).
5786    pub host: String,
5787
5788    /// Member Servico the gateway routes to. Must be in `:membros`.
5789    pub para: String,
5790
5791    /// Optional path filter — if set, only matching paths route to
5792    /// this Aplicacao (the rest fall through to other route rules).
5793    #[serde(default)]
5794    pub paths: Vec<String>,
5795
5796    /// Default port on the destination Servico (the trigger.service.port).
5797    #[serde(default = "default_port")]
5798    pub port: u16,
5799}
5800
5801impl Entrada {
5802    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
5803    /// every HTTPRoute-aware renderer keys off — returns the author-
5804    /// declared `:entrada :paths` list verbatim when non-empty, and the
5805    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
5806    /// all fallback otherwise (so an Aplicacao author who declares an
5807    /// external `:entrada` block but no per-path rule surface still
5808    /// gets a route whose sole `HTTPPathMatch` matches every incoming
5809    /// request under the paired
5810    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
5811    ///
5812    /// Prior to this lift the "if `:entrada :paths` is empty use the
5813    /// substrate catch-all; else return each declared path verbatim"
5814    /// cascade lived inline at
5815    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
5816    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
5817    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
5818    /// substrate ships today, with no typed method on the substrate
5819    /// primitive that named the rule. A future path-resolution axis
5820    /// addition — a per-cluster `:entrada :default-path` override the
5821    /// operator pins through a future `:placement`-scoped slot, an
5822    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5823    /// admission-webhook floor that materializes the catch-all before
5824    /// the CR lands, a future per-`:entrada :paths` overlay from a
5825    /// per-cluster policy the future `feira app deploy` pipeline
5826    /// consumes — would have to be threaded through every renderer's
5827    /// inline copy of the cascade in lockstep or one consumer would
5828    /// silently disagree with the peers on which path list a given
5829    /// `:entrada` block resolves to. Lifting the rule to a typed
5830    /// method on the substrate primitive means every downstream
5831    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
5832    /// per-cluster overlay resolver, every future per-Aplicacao
5833    /// snapshot renderer) reaches for exactly one typed dispatch —
5834    /// the resolver's accept-set moves as a unit on any future axis
5835    /// addition.
5836    ///
5837    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
5838    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
5839    /// per-`:entrada` scalar-value axes — extends the "one typed
5840    /// dispatch on the substrate primitive, thin projections at each
5841    /// consumer" discipline onto the per-`:entrada` path-list
5842    /// resolution axis every HTTPRoute-aware renderer consumes. Same
5843    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
5844    /// sibling `:politicas` primitive — one typed method on the
5845    /// substrate primitive that names the cascade every renderer
5846    /// otherwise re-inlines.
5847    #[must_use]
5848    pub fn resolved_paths(&self) -> Vec<&str> {
5849        // Route the internal cascade-head + per-entry projection reads
5850        // through the lifted [`Self::paths`] slice accessor rather than
5851        // the raw `self.paths` field access — the substrate-primitive
5852        // per-`:entrada` path-list resolver's two internal reads now
5853        // key off the canonical raw-slot surface every downstream
5854        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
5855        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
5856        // entrada summary line's `{:?}` Debug print) routes through, so
5857        // any future rebrand on the typed slot's raw-slot reader lands
5858        // at exactly one place. Same two-consumer coherence discipline
5859        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
5860        // the peer M3 mesh-slot `Vec<String>`-carry axis.
5861        if self.paths().is_empty() {
5862            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
5863        } else {
5864            self.paths().iter().map(String::as_str).collect()
5865        }
5866    }
5867
5868    /// Substrate-canonical per-`:entrada` DNS-hostname singular
5869    /// accessor every Gateway-API `Listener.hostname` reader keys off
5870    /// — returns the author-declared `:entrada :host` byte-string
5871    /// verbatim as a `&str`, borrowed from the typed slot's own
5872    /// [`String`] storage.
5873    ///
5874    /// Named the "singular" half of the DNS-hostname resolver pair on
5875    /// the substrate primitive: the parent-Gateway per-listener
5876    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
5877    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
5878    /// hostname per listener), and this accessor is the typed dispatch
5879    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
5880    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
5881    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
5882    /// per-Aplicacao ingress-hostname surface projects onto.
5883    ///
5884    /// Prior to this lift the `entrada.host.clone()` byte-string was
5885    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
5886    /// per-listener singular `hostname:` axis
5887    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
5888    /// per-HTTPRoute plural `spec.hostnames[]` axis
5889    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
5890    /// consumers read the same `entrada.host` field but the two-site
5891    /// duplication expressed no compile-time contract that the singular
5892    /// Gateway-listener filter and the plural `HTTPRoute` filter list
5893    /// stay in lockstep on future extensions of the `:entrada` slot to
5894    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
5895    /// overlay, a per-cluster SNI fan-out the operator pins through a
5896    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
5897    /// Aplicacao` CR materializer's per-listener virtual-host filter
5898    /// admission-webhook overlay). Any such extension would have to be
5899    /// threaded through every renderer's inline copy of the resolution
5900    /// in lockstep or the Gateway listener's `hostname:` filter would
5901    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
5902    /// — a Gateway-API-conformance divergence whose apply-time symptom
5903    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
5904    /// `NoMatchingParent` — the API server rejects the route because
5905    /// its `hostnames[]` filter doesn't intersect the parent listener's
5906    /// `hostname` filter) is far from the source `caixa.lisp` and never
5907    /// surfaces in the emitted YAML. Lifting the singular and plural
5908    /// resolvers to typed methods on the substrate primitive means
5909    /// every consumer of the Aplicacao's ingress-hostname surface
5910    /// reaches for exactly one typed dispatch, and the pair-invariant
5911    /// `hostnames() == vec![hostname()]` pinned by the sibling
5912    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
5913    /// keeps the two axes in lockstep by construction.
5914    ///
5915    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
5916    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
5917    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
5918    /// the substrate primitive, thin projections at each consumer"
5919    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
5920    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
5921    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
5922    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
5923    /// `:entrada` scalar-value + list-value axes.
5924    #[must_use]
5925    pub const fn hostname(&self) -> &str {
5926        self.host.as_str()
5927    }
5928
5929    /// Substrate-canonical per-`:entrada` DNS-hostname plural
5930    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
5931    /// keys off — returns the singleton `[hostname()]` list under
5932    /// today's single-hostname-per-Aplicacao author surface, and the
5933    /// authoritative multi-hostname list under a future
5934    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
5935    ///
5936    /// Plural half of the DNS-hostname resolver pair — see the
5937    /// companion [`Entrada::hostname`] docstring for the two-consumer
5938    /// lift + pair-invariant discipline (`hostnames() ==
5939    /// vec![hostname()]`, pinned load-bearing by the sibling
5940    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
5941    /// test).
5942    ///
5943    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
5944    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
5945    /// per-rule path-list axis — same `Vec<&str>` shape, same
5946    /// substrate-primitive-owns-the-resolver discipline extended to
5947    /// the per-HTTPRoute virtual-host filter-list axis.
5948    #[must_use]
5949    pub fn hostnames(&self) -> Vec<&str> {
5950        vec![self.hostname()]
5951    }
5952
5953    /// Substrate-canonical per-`:entrada` destination-Servico scalar
5954    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
5955    /// the author-declared `:entrada :para` byte-string verbatim as a
5956    /// `&str`, borrowed from the typed slot's own [`String`] storage.
5957    ///
5958    /// The `:entrada :para` slot names the single member Servico the
5959    /// external Gateway routes to (validated by
5960    /// [`AplicacaoSpec::validate`] to be a
5961    /// [`Membro::caixa`] the Aplicacao declares — a stray
5962    /// `:para` that doesn't name a member is
5963    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
5964    /// backend-attachment miss at cluster-apply time). Under today's
5965    /// single-destination author surface `:entrada :para` is the ingress
5966    /// apex Servico's canonical identity; under a hypothetical
5967    /// future multi-backend author surface (a `:entrada
5968    /// :split :backends` weighted-fan-out overlay for canary /
5969    /// blue-green traffic-split rollouts, per-path override for
5970    /// path-based per-Servico routing beyond the single-apex model,
5971    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5972    /// per-CR admission-webhook that promotes the scalar to a
5973    /// weighted list) this accessor is the substrate primitive's typed
5974    /// dispatch every downstream `HTTPRoute`-aware consumer routes
5975    /// through, so the resolution shape migrates as a unit on one
5976    /// caixa-core edit rather than a coordinated rewrite across every
5977    /// renderer's inline field-access.
5978    ///
5979    /// Prior to this lift the `entrada.para` byte-string was accessed
5980    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
5981    /// `metadata.name` composer's per-destination discriminator arg
5982    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
5983    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
5984    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
5985    /// (`entrada.para.clone()`,
5986    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
5987    /// consumers read the same `entrada.para` field but the two-site
5988    /// duplication expressed no compile-time contract that the HTTPRoute
5989    /// name-discriminator and the per-rule backend name stay in
5990    /// lockstep on future extensions of the `:entrada` slot to a
5991    /// multi-destination author surface. Any such extension would have
5992    /// to be threaded through every renderer's inline copy of the
5993    /// destination projection in lockstep or the HTTPRoute
5994    /// `metadata.name` would silently reference a different destination
5995    /// than its own `backendRefs[]` — an operator-side
5996    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
5997    /// grep-by-name lookup would land on a route whose `backendRefs[]`
5998    /// silently point at a peer Servico, dropping every external
5999    /// `:entrada` flow at the gateway with the destination-drift root
6000    /// cause invisible in the emitted YAML.
6001    ///
6002    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
6003    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
6004    /// the per-listener singular / per-HTTPRoute plural filter axes and
6005    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
6006    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
6007    /// typed dispatch on the substrate primitive, thin projections at
6008    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6009    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6010    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6011    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
6012    /// sibling per-`:entrada` scalar-value + list-value axes — this
6013    /// accessor closes the last unlifted per-`:entrada` scalar axis
6014    /// (the destination-Servico byte-string) so every downstream
6015    /// per-`:entrada` reader now routes through a typed dispatch on
6016    /// the substrate primitive.
6017    #[must_use]
6018    pub const fn destination(&self) -> &str {
6019        self.para.as_str()
6020    }
6021
6022    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
6023    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
6024    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
6025    /// reader keys off — returns the author-declared `:entrada :port`
6026    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
6027    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
6028    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
6029    /// [`AplicacaoError::EntradaPortZero`], not a silent
6030    /// admission-webhook rejection at cluster-apply time).
6031    ///
6032    /// The `:entrada :port` slot carries the destination Servico's
6033    /// canonical in-cluster L4 listener port (`trigger.service.port` on
6034    /// the `pleme-computeunit` library chart), and every downstream
6035    /// consumer that reads the port keys off this scalar (the
6036    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
6037    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
6038    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
6039    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6040    /// CR materializer's per-Aplicacao gateway port resolver).
6041    ///
6042    /// Prior to this lift the `.port` field was accessed inline at two
6043    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
6044    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
6045    /// the [`AplicacaoSpec::port_for_destination`] resolver's
6046    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
6047    /// open-coded field-accesses that expressed no compile-time link
6048    /// back to the typed slot. A future extension of the `:entrada :port`
6049    /// axis to a richer author surface — a per-cluster override the
6050    /// operator pins through a future `:placement :default-port` slot the
6051    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
6052    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
6053    /// heterogeneous listener ports, an M4
6054    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6055    /// admission-webhook floor that promotes the scalar to a
6056    /// per-destination map — would have had to be threaded through both
6057    /// open-coded copies in lockstep or the structural-floor validator
6058    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
6059    /// silently disagree on which port a given [`Entrada`] resolves to.
6060    /// Lifting the resolution rule to a typed method on the substrate
6061    /// primitive means every downstream consumer of the Aplicacao's
6062    /// per-`:entrada` L4-port surface reaches for exactly one typed
6063    /// dispatch — the resolver's accept-set migrates as a unit on any
6064    /// future axis addition.
6065    ///
6066    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
6067    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
6068    /// accessors on the per-`:entrada` scalar-value axis — same "one
6069    /// typed dispatch on the substrate primitive, thin projections at
6070    /// each consumer" discipline extended onto the per-`:entrada`
6071    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
6072    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
6073    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
6074    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
6075    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
6076    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
6077    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
6078    /// storage field's name; the accessor's identity name maps onto the
6079    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
6080    /// already carries. Declared `pub const fn` (matching the peer M3
6081    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6082    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6083    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6084    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6085    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6086    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6087    /// [`RateLimit`], and the sibling per-`:placement`
6088    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
6089    /// enum scalar axis — every one a `pub const fn`) so every future
6090    /// substrate-side `const`-context consumer of the resolved
6091    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
6092    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
6093    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
6094    /// admission-webhook `const fn` per-CR gateway-port floor over a
6095    /// typed [`Entrada`], any `const fn` composer that fans on the port
6096    /// at compile time) reaches through the same typed dispatch on the
6097    /// substrate primitive at const-eval time as at runtime. Pinned by
6098    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
6099    /// const-eval posture at module scope via `const _:() = …` items so
6100    /// any future accidental downgrade to non-`const` trips at caixa-core
6101    /// build time.
6102    #[must_use]
6103    pub const fn port(&self) -> u16 {
6104        self.port
6105    }
6106
6107    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
6108    /// slice accessor every HTTPRoute-aware renderer keys off when it
6109    /// wants the raw author-declared path-list (not the fallback-
6110    /// applied projection [`Self::resolved_paths`] returns) — returns
6111    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
6112    /// borrowed from the typed slot's own [`Vec<String>`] storage.
6113    ///
6114    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
6115    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
6116    /// (1449891) closes the fallback-applying arm every per-Aplicacao
6117    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
6118    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
6119    /// catch-all; non-empty slot → per-entry verbatim projection); this
6120    /// accessor closes the raw-slot arm every consumer that must see the
6121    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
6122    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
6123    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
6124    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
6125    /// external-gateway summary line's `{:?}` Debug print — which must
6126    /// name the author's declaration, not the substrate's fallback, so
6127    /// an author reading their graph output can grep their caixa.lisp
6128    /// for the exact list they authored) routes through.
6129    ///
6130    /// Prior to this lift the `.paths` field was accessed inline at four
6131    /// production sites: the two internal reads in [`Self::resolved_paths`]
6132    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
6133    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
6134    /// value-shape gate's `for p in &e.paths` traversal head, and the
6135    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
6136    /// Debug print — four open-coded field-accesses that expressed no
6137    /// compile-time link back to the typed slot. A future extension of
6138    /// the `:entrada :paths` axis to a richer author surface — a
6139    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
6140    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
6141    /// spec supports through `matches[].method`), a per-path per-header
6142    /// filter overlay (`matches[].headers[]`), a per-cluster override
6143    /// the operator pins through a future `:placement :path-overlay`
6144    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6145    /// per-CR admission-webhook that normalized the list at admission
6146    /// time — would have had to be threaded through every open-coded
6147    /// copy in lockstep or the validator's per-entry gate would silently
6148    /// disagree with the renderer's per-entry emit on which list a given
6149    /// `:entrada` block resolves to. Lifting the resolution to a typed
6150    /// method on the substrate primitive means every downstream consumer
6151    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
6152    /// exactly one typed dispatch — the resolver's accept-set migrates
6153    /// as a unit on any future axis addition.
6154    ///
6155    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
6156    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
6157    /// carry axis — same "one typed dispatch on the substrate primitive,
6158    /// thin projections at each consumer" discipline extended onto the
6159    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
6160    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
6161    /// carrier) so every downstream per-`:entrada` reader now routes
6162    /// through a typed dispatch on the substrate primitive. Returns
6163    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
6164    /// treats the list as a read-only sequence — the slice-view is the
6165    /// narrowest borrow that supports every present + roadmapped consumer
6166    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
6167    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
6168    /// view reaches for (the storage-side `Vec` remains reachable through
6169    /// the `pub paths` field for the mutation-carrying serde round-trip
6170    /// and per-test fixture-mutation paths).
6171    #[must_use]
6172    pub fn paths(&self) -> &[String] {
6173        self.paths.as_slice()
6174    }
6175}
6176
6177/// Canonical default L4 port every typed Servico exposes on its
6178/// in-cluster K8s Service (the `trigger.service.port` axis the
6179/// `pleme-computeunit` library chart emits, the `:entrada :port` author
6180/// surface defaults to when the author omits the slot, and the
6181/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
6182/// `:entrada` block matches the per-`:contratos` destination Servico).
6183/// The single source of truth all three typed-port consumers reach for:
6184///
6185///   - [`Entrada::port`]'s serde default (via the
6186///     [`default_port`] helper this constant feeds); the author surface
6187///     `(:entrada (:host … :para …))` without an explicit `:port` slot
6188///     reads back as a typed [`Entrada`] carrying this exact value;
6189///   - the
6190///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
6191///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
6192///     fallback, fired when the typed `:entrada` block doesn't name
6193///     the per-`:contratos` destination Servico — the typed
6194///     `:contratos` graph carries no per-destination port axis (the
6195///     destination port is the destination Servico's
6196///     `lareira-<nome>` chart's `trigger.service.port`, which the
6197///     Aplicacao-level renderer has no visibility into without a
6198///     resolver round-trip), so the renderer falls back to the
6199///     substrate's canonical Servico-port assumption — by
6200///     construction the same value the destination's own
6201///     `pleme-computeunit` chart emits, the same value the
6202///     destination's own typed `:entrada :port` slot defaults to;
6203///   - every future per-Servico renderer the absorption-roadmap
6204///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6205///     CR materializer's per-edge port resolver, the future
6206///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
6207///     emitter's per-route bucket key, the future caixa-otel
6208///     collector-pipeline emitter's per-Servico scrape port).
6209///
6210/// Until this lift landed the value `8080` lived at two production-code
6211/// call-sites: the [`default_port`] helper at
6212/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
6213/// and the `.unwrap_or(8080)` literal at
6214/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
6215/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
6216/// resolver). A future Servico-port rebrand — the substrate moving the
6217/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
6218/// gateway grows direct `:80` listeners, to `8443` once the substrate
6219/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
6220/// override the operator pins through a future
6221/// `:placement :default-port` slot — without a coordinated edit on
6222/// both sides would silently emit Servicos listening on one port and
6223/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
6224/// The CNP's apply-time symptom (the policy is admitted but every L4
6225/// flow on the destination Servico's actual port silently drops because
6226/// it doesn't match the whitelisted port) is far from the rebrand
6227/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
6228/// in hubble traces, not in `kubectl describe`. Lifting the literal to
6229/// a shared constant closes the drift footgun structurally — both
6230/// consumers read from the same `u16`, so any rebrand reaches both
6231/// sites by construction.
6232///
6233/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
6234/// per-renderer canonical-K8s-axis constant — the namespace string
6235/// and the canonical Servico port both lived as duplicated literals
6236/// across caixa-core / caixa-mesh / caixa-flux before their respective
6237/// lifts. Same "the typed constant lives in one place" discipline the
6238/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
6239/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
6240/// shared-string axes.
6241///
6242/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
6243pub const DEFAULT_SERVICO_PORT: u16 = 8080;
6244
6245/// Structural floor for the typed `:entrada :port` axis — every
6246/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
6247/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
6248///
6249/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
6250/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
6251/// interprets as "let the kernel pick a free port at bind time", not a
6252/// well-defined destination the substrate's per-`:entrada` Gateway API
6253/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
6254/// carrying `port: 0` degenerates to a nominal-only routing target: the
6255/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
6256/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
6257/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
6258/// at build time rather than at `kubectl apply` time), and the
6259/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
6260/// (caixa-mesh/src/lib.rs:2657 through
6261/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
6262/// [`Entrada::port`] typed value — silently emits a policy whose
6263/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
6264/// actual listener, dropping every L4 flow at the eBPF data plane far
6265/// from the source caixa.lisp with no field naming the port-zero-drift
6266/// root cause.
6267///
6268/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
6269/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
6270/// on the top edge (unlike the peer capped-`u32` `:politicas` /
6271/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
6272/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
6273/// well below `u32::MAX` and therefore need explicit typed caps).
6274///
6275/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
6276/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
6277/// scalar every `(:entrada (:host … :para …))` slot without an explicit
6278/// `:port` inherits through the serde default hook; this constant names
6279/// the accept-set floor every declared port must satisfy. The pair is
6280/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
6281/// substrate's default must satisfy its own accept-set floor by
6282/// construction) — a future rebrand that accidentally moved
6283/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
6284/// negative-cast typo, a per-cluster override the operator pins through
6285/// a future `:placement :default-port` slot that lands out-of-range)
6286/// would silently invalidate the serde-default emission at every
6287/// author-side `(:entrada (:host … :para …))` slot — the compile-time
6288/// invariant pin
6289/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
6290/// closes the drift footgun at caixa-core build time.
6291///
6292/// Lifted as a typed `pub const` (rather than an inline `0` literal at
6293/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
6294/// has exactly one source of truth — the future M4
6295/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6296/// gateway resolver, the future per-Servico
6297/// `computeunit.trigger.service.port` renderer's per-CR port-value
6298/// validator, and every downstream test-fixture navigator asserting
6299/// the accept-set floor all read from one place. Same shape every
6300/// other typed bracket-floor / bracket-ceiling in this crate carries
6301/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6302/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6303/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6304/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6305/// [`POLICY_RATE_LIMIT_MAX`]).
6306pub const SERVICO_PORT_MIN: u16 = 1;
6307
6308const fn default_port() -> u16 {
6309    DEFAULT_SERVICO_PORT
6310}
6311
6312// ── the typed view ───────────────────────────────────────────────────
6313
6314/// Typed composition view of the flat Aplicacao slots on
6315/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6316/// validation + downstream renderer consumption.
6317#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6318#[serde(rename_all = "camelCase")]
6319pub struct AplicacaoSpec {
6320    pub membros: Vec<Membro>,
6321    pub contratos: Vec<WitContract>,
6322    pub politicas: MeshPolicy,
6323    pub placement: Placement,
6324    pub entrada: Option<Entrada>,
6325}
6326
6327impl AplicacaoSpec {
6328    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6329    /// per-Aplicacao member-list slice-return accessor every
6330    /// per-Aplicacao member-list reader keys off — returns the author-
6331    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6332    /// over the same backing buffer the raw `self.membros.as_slice()`
6333    /// field access borrows from.
6334    ///
6335    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6336    /// member list — the load-bearing identity of the application graph
6337    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
6338    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
6339    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
6340    /// accessor) with a `:versao` semver-requirement string (through
6341    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
6342    /// and every downstream consumer that fans on the member-set keys
6343    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
6344    /// membership-lookup `HashSet<&str>` seed's collect input, the
6345    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
6346    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
6347    /// per-member DNS-1123 / semver-requirement / duplicate-detection
6348    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
6349    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
6350    /// programs.yaml per-`:membros` fan-out emitter's per-entry
6351    /// mapping-composition loop, the `feira app graph` per-Aplicacao
6352    /// member-count print line and per-member tree traversal,
6353    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
6354    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
6355    /// placement engine's per-member weight-topology reader).
6356    ///
6357    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
6358    /// inline at six production sites — the [`AplicacaoSpec::validate`]
6359    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
6360    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
6361    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
6362    /// probe, the same method's per-member `for m in &self.membros`
6363    /// validate-loop traversal head, the
6364    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6365    /// `for m in &self.membros` adjacency-list seed, the
6366    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
6367    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
6368    /// paired with the peer `for m in &spec.membros` per-entry fan-out
6369    /// loop, and the `feira app graph` per-Aplicacao print line's
6370    /// `spec.membros.len()` count formatter argument paired with the
6371    /// peer `for m in &spec.membros` per-member tree traversal — six
6372    /// open-coded field-accesses that expressed no compile-time link
6373    /// back to the typed slot. A future extension of the `:membros`
6374    /// axis to a richer author surface (a per-cluster member-set
6375    /// overlay the operator pins through a future
6376    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
6377    /// roadmap acknowledges, a per-tenant member-alias table the M4
6378    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
6379    /// CR at admission time, a per-Aplicacao dynamic member-set
6380    /// derivation the future adaptive-placement engine computes from
6381    /// weighted membership topology, a promotion of the plain
6382    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
6383    /// Orleans-style virtual-actor dynamic-membership comes into typed
6384    /// scope) would have had to be threaded through all six open-coded
6385    /// copies in lockstep or one consumer would silently disagree with
6386    /// the peers on which member-set a given Aplicacao resolves to —
6387    /// the `HashSet<&str>` name-set seed reading the raw slot while
6388    /// the peer `.is_empty()` refusal probe read an operator-resolved
6389    /// slot would silently split the `:contratos` membership-lookup
6390    /// input from the pre-flight-refusal input, a six-consumer split
6391    /// at the validator + programs.yaml emitter + graph printer far
6392    /// from the source `caixa.lisp` with no field naming the member-
6393    /// set-drift root cause. Lifting the resolution rule to a typed
6394    /// method on the substrate primitive means every downstream
6395    /// consumer of the Aplicacao's per-`:membros` member-list surface
6396    /// reaches for exactly one typed dispatch — the resolver's accept-
6397    /// set migrates as a unit on any future axis addition.
6398    ///
6399    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
6400    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6401    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6402    /// static-child-list `Vec`-carry axis, and to the M3
6403    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6404    /// on the peer per-`:placement` distribution-target-list `Vec`-
6405    /// carry axis. Same "one typed dispatch on the substrate primitive,
6406    /// thin projections at each consumer" discipline. The two peer
6407    /// `Vec`-carry axes still unlifted at the time of this lift —
6408    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
6409    /// WIT-typed edge list) and
6410    /// [`crate::UpgradeFromEntry::instructions`]
6411    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6412    /// — inherit this accessor's discipline as future compounding runs
6413    /// migrate their consumers onto the shared slice-return shape.
6414    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
6415    /// `AplicacaoSpec` type itself, extending the discipline beyond
6416    /// the inner per-slot types ([`crate::Placement`],
6417    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
6418    /// view every renderer consumes. Named `membros()` to match the
6419    /// storage field's name verbatim and the tatara-lisp author-
6420    /// surface term (`:membros`) the field's own docstring already
6421    /// carries; the accessor's identity maps onto the canonical
6422    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
6423    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
6424    /// every downstream consumer of the member list treats it as a
6425    /// read-only sequence — the slice-view is the narrowest borrow
6426    /// that supports every present + roadmapped consumer
6427    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6428    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6429    /// the typed view reaches for (the storage-side `Vec` remains
6430    /// reachable through the `pub membros` field for the mutation-
6431    /// carrying serde round-trip and per-test fixture-mutation paths).
6432    #[must_use]
6433    pub fn membros(&self) -> &[Membro] {
6434        self.membros.as_slice()
6435    }
6436
6437    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
6438    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
6439    /// accessor every per-Aplicacao contract-list reader keys off —
6440    /// returns the author-declared `:contratos` list verbatim as a
6441    /// `&[WitContract]` slice-view over the same backing buffer the raw
6442    /// `self.contratos.as_slice()` field access borrows from.
6443    ///
6444    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
6445    /// WIT-typed edge list — the load-bearing set of directed edges
6446    /// on the application graph whose nodes are the `:membros` entries
6447    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
6448    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
6449    /// six-tuple is the edge identity every downstream duplicate gate
6450    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
6451    /// Servico caller name + a `:para` destination-Servico callee name
6452    /// (through the lifted [`WitContract::source`] +
6453    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
6454    /// caller/callee-Servico axis) with a `:wit` world-reference
6455    /// (through the lifted [`WitContract::world_ref`] (0804823)
6456    /// accessor) and the target-shape-appropriate payload-carrier
6457    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
6458    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
6459    /// (ed22b66) accessor on the per-target-shape payload-carrier
6460    /// axis). Every downstream consumer that fans on the edge-set
6461    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
6462    /// name-set / self-edge / target-shape / dedup fan-out loop, the
6463    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
6464    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
6465    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
6466    /// grouping loop, the `feira app graph` per-Aplicacao contract-
6467    /// count print line and per-contract tree traversal, every future
6468    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
6469    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
6470    /// mesh-policy overlay resolver's per-contract typed-edge weight
6471    /// reader).
6472    ///
6473    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
6474    /// accessed inline at four production sites — the
6475    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
6476    /// per-edge validate-loop traversal head (which drives every
6477    /// per-edge name-set membership lookup, self-edge check,
6478    /// target-shape dispatch, and dedup `HashSet` insert), the
6479    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6480    /// `for c in &self.contratos` adjacency-list seed head (which
6481    /// drives every per-edge sync-vs-pub-sub partition and per-edge
6482    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
6483    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
6484    /// `BTreeMap` grouping loop head (which drives every per-CNP
6485    /// fan-out emit), and the `feira app graph` per-Aplicacao print
6486    /// line's `spec.contratos.len()` count formatter argument paired
6487    /// with the peer `for c in &spec.contratos` per-contract tree
6488    /// traversal — four open-coded field-accesses that expressed no
6489    /// compile-time link back to the typed slot. A future extension
6490    /// of the `:contratos` axis to a richer author surface (a
6491    /// per-cluster contract overlay the operator pins through a
6492    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
6493    /// federation roadmap acknowledges, a per-tenant edge-policy
6494    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6495    /// materializer resolves per-CR at admission time, a per-edge
6496    /// weight scalar the future adaptive-placement engine reads to
6497    /// bias sync-subgraph routing, a promotion of the plain
6498    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
6499    /// once virtual-actor-style dynamic-edge composition comes into
6500    /// typed scope) would have had to be threaded through all four
6501    /// open-coded copies in lockstep or one consumer would silently
6502    /// disagree with the peers on which edge-set a given Aplicacao
6503    /// resolves to — the validator's per-edge dedup `HashSet` seed
6504    /// reading the raw slot while the peer sync-cycle adjacency-list
6505    /// seed read an operator-resolved slot would silently split the
6506    /// build-time edge-set gate from the runtime deadlock-detection
6507    /// gate, a four-consumer split at the validator, the cycle
6508    /// detector, the CNP emitter, and the graph printer far from
6509    /// the source `caixa.lisp` with no field naming the edge-set-
6510    /// drift root cause. Lifting the resolution rule to a typed method on the
6511    /// substrate primitive means every downstream consumer of the
6512    /// Aplicacao's per-`:contratos` edge-list surface reaches for
6513    /// exactly one typed dispatch — the resolver's accept-set
6514    /// migrates as a unit on any future axis addition.
6515    ///
6516    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
6517    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6518    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6519    /// static-child-list `Vec`-carry axis, to the M3
6520    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6521    /// on the peer per-`:placement` distribution-target-list `Vec`-
6522    /// carry axis, and to the immediately-adjacent sibling M3
6523    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
6524    /// the peer per-`:membros` node-list `Vec`-carry axis — the
6525    /// per-`:contratos` edge-list accessor is the natural pair of
6526    /// the per-`:membros` node-list accessor (graph edges over graph
6527    /// nodes; every graph-shaped consumer reads both). Same "one
6528    /// typed dispatch on the substrate primitive, thin projections
6529    /// at each consumer" discipline. The last remaining `Vec`-carry
6530    /// axis still unlifted at the time of this lift —
6531    /// [`crate::UpgradeFromEntry::instructions`]
6532    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
6533    /// list) — inherits this accessor's discipline as future
6534    /// compounding runs migrate its consumers onto the shared slice-
6535    /// return shape. Second `&[T]`-return accessor on the top-level
6536    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
6537    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
6538    /// `:contratos` are the two `Vec` fields on the outer typed
6539    /// composition view — `:politicas`, `:placement`, `:entrada` are
6540    /// scalar/option-shaped and already route through their per-slot
6541    /// accessor families). Named `contratos()` to match the storage
6542    /// field's name verbatim and the tatara-lisp author-surface term
6543    /// (`:contratos`) the field's own docstring already carries; the
6544    /// accessor's identity maps onto the canonical MESH-COMPOSITION
6545    /// §III.1 vocabulary the slot's docstring already reaches for.
6546    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
6547    /// every downstream consumer of the contract list treats it as a
6548    /// read-only sequence — the slice-view is the narrowest borrow
6549    /// that supports every present + roadmapped consumer
6550    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6551    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6552    /// the typed view reaches for (the storage-side `Vec` remains
6553    /// reachable through the `pub contratos` field for the mutation-
6554    /// carrying serde round-trip and per-test fixture-mutation paths).
6555    #[must_use]
6556    pub fn contratos(&self) -> &[WitContract] {
6557        self.contratos.as_slice()
6558    }
6559
6560    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
6561    /// per-Aplicacao mesh-policy composite-reference accessor every
6562    /// per-Aplicacao policy-block reader keys off — returns the author-
6563    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
6564    /// reference over the same backing storage the raw `&self.politicas`
6565    /// field access borrows from.
6566    ///
6567    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
6568    /// mesh-policy composite — the load-bearing container of every
6569    /// mesh-level operational-policy axis every downstream mesh-artifact
6570    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
6571    /// mesh-policy overlay is the single typed surface a
6572    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
6573    /// from). Every per-`:politicas` axis threads through a lifted
6574    /// per-slot accessor on the [`MeshPolicy`] type: the
6575    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
6576    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
6577    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
6578    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
6579    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
6580    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
6581    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
6582    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
6583    /// accessor. Every downstream consumer that reaches for a policy
6584    /// axis first passes through this outer accessor onto the composite
6585    /// and then dispatches onto the per-axis accessor — the two-level
6586    /// dispatch means every per-`:politicas` reader now routes through
6587    /// a typed dispatch on the substrate primitive at both altitudes.
6588    ///
6589    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
6590    /// accessed inline at four production sites — the
6591    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
6592    /// &self.politicas;` traversal seed (which drives every per-axis
6593    /// zero-floor + upper-cap + canonical-form bracket dispatch through
6594    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
6595    /// `p.rate_limit()` on the axis-level lifted accessors), the
6596    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
6597    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
6598    /// chain (which drives every per-`(:de, :para)` CNP
6599    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
6600    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
6601    /// timeout + retry overlay emitter's paired
6602    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
6603    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
6604    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
6605    /// open-coded outer-field accesses that expressed no compile-time
6606    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
6607    /// future extension of the `:politicas` outer axis to a richer
6608    /// author surface (a per-cluster policy overlay the operator pins
6609    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
6610    /// §V federation roadmap acknowledges, a per-tenant policy-alias
6611    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6612    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6613    /// policy-composite derivation the future adaptive-placement engine
6614    /// computes from a per-cluster load-topology reader, a promotion of
6615    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
6616    /// partition once virtual-actor-style dynamic-mesh-policy
6617    /// composition comes into typed scope) would have had to be threaded
6618    /// through all four open-coded copies in lockstep or one consumer
6619    /// would silently disagree with the peers on which mesh-policy
6620    /// composite a given Aplicacao resolves to — the validator's
6621    /// per-axis bracket-dispatch seed reading the raw slot while the
6622    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
6623    /// would silently split the build-time policy-shape gate from the
6624    /// runtime CNP-emission gate, a four-consumer split at the
6625    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
6626    /// the source `caixa.lisp` with no field naming the policy-drift
6627    /// root cause. Lifting the resolution rule to a typed method on the
6628    /// substrate primitive means every downstream consumer of the
6629    /// Aplicacao's per-`:politicas` mesh-policy composite surface
6630    /// reaches for exactly one typed dispatch — the resolver's accept-
6631    /// set migrates as a unit on any future axis addition.
6632    ///
6633    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
6634    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
6635    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6636    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
6637    /// close the two `Vec`-carry axes on the outer typed composition
6638    /// view; the outer `:politicas` composite-reference axis is the
6639    /// natural pair to the paired outer `Vec`-carry accessors on the
6640    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
6641    /// emitter reads all four axes as one unit (graph nodes + graph
6642    /// edges + mesh policy + placement pool). Peer to the same
6643    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
6644    /// slot: every M2 `SupervisorSpec`-scoped composite reader
6645    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
6646    /// `restart_window`, `children`) already routes through the M2
6647    /// `SupervisorSpec` accessor family — this lift extends the same
6648    /// "one typed dispatch on the substrate primitive at the outer
6649    /// composition altitude" discipline to the M3 mesh-slot
6650    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
6651    /// remaining peer outer-composite axes still unlifted at the time
6652    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
6653    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
6654    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
6655    /// inherit this accessor's discipline as future compounding runs
6656    /// migrate their consumers onto the shared reference-return shape.
6657    /// Named `politicas()` to match the storage field's name verbatim
6658    /// and the tatara-lisp author-surface term (`:politicas`) the
6659    /// field's own docstring already carries; the accessor's identity
6660    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
6661    /// slot's docstring already reaches for. Returns `&MeshPolicy`
6662    /// (not the owning composite by copy or clone) because every
6663    /// downstream consumer of the mesh-policy composite treats it as a
6664    /// read-only per-axis dispatch source — the reference-view is the
6665    /// narrowest borrow that supports every present + roadmapped
6666    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
6667    /// emptiness probe) without cloning the composite through every
6668    /// consumer's fast path.
6669    #[must_use]
6670    pub fn politicas(&self) -> &MeshPolicy {
6671        &self.politicas
6672    }
6673
6674    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
6675    /// per-Aplicacao distribution-composite composite-reference accessor
6676    /// every per-Aplicacao placement-block reader keys off — returns the
6677    /// author-declared `:placement` composite verbatim as a `&Placement`
6678    /// reference over the same backing storage the raw `&self.placement`
6679    /// field access borrows from.
6680    ///
6681    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
6682    /// distribution composite — the load-bearing container of every
6683    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
6684    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
6685    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
6686    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
6687    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
6688    /// `:affinity` hint). Every per-`:placement` axis threads through a
6689    /// lifted per-slot accessor on the [`Placement`] type: the
6690    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
6691    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
6692    /// per-cluster distribution-target slice-return accessor, the
6693    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
6694    /// optional-scalar accessor, and the [`Placement::shard_key`]
6695    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
6696    /// downstream consumer that reaches for a placement axis first passes
6697    /// through this outer accessor onto the composite and then dispatches
6698    /// onto the per-axis accessor — the two-level dispatch means every
6699    /// per-`:placement` reader now routes through a typed dispatch on the
6700    /// substrate primitive at both altitudes.
6701    ///
6702    /// Prior to this lift the `.placement` `Placement` composite was
6703    /// accessed inline at three production sites — the
6704    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
6705    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
6706    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
6707    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
6708    /// cluster `.clusters()` validate-loop traversal head, the per-
6709    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
6710    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
6711    /// paired with the shape-gate cascade's `.shard_key()` /
6712    /// `.estrategia()` diagnostic-carry pair), the
6713    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
6714    /// per-entry placement-block emitter's outer
6715    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
6716    /// seed (which fans onto every per-cluster `programs[]` entry as a
6717    /// self-describing distribution overlay the aggregator filters by),
6718    /// and the `feira app graph` per-Aplicacao print line's paired
6719    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
6720    /// then-inner-accessor chains (which drive the human-readable
6721    /// distribution summary of the typed Aplicacao view) — three open-
6722    /// coded outer-field accesses that expressed no compile-time link
6723    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
6724    /// extension of the `:placement` outer axis to a richer author surface
6725    /// (a per-cluster placement overlay the operator pins through a
6726    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
6727    /// federation roadmap acknowledges, a per-tenant placement-alias
6728    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6729    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6730    /// placement-composite derivation the future M5 adaptive-placement
6731    /// engine computes from a per-cluster load-topology reader, a
6732    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
6733    /// partition once Orleans-style virtual-actor dynamic-placement comes
6734    /// into typed scope) would have had to be threaded through all three
6735    /// open-coded copies in lockstep or one consumer would silently
6736    /// disagree with the peers on which placement composite a given
6737    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
6738    /// seed reading the raw slot while the peer
6739    /// `programs_for_aplicacao` emitter read an operator-resolved slot
6740    /// would silently split the build-time distribution-shape gate from
6741    /// the runtime programs.yaml distribution-annotation gate, a three-
6742    /// consumer split at the validator, the programs.yaml emitter, and
6743    /// the `feira app graph` printer far from the source `caixa.lisp`
6744    /// with no field naming the placement-drift root cause. Lifting the
6745    /// resolution rule to a typed method on the substrate primitive
6746    /// means every downstream consumer of the Aplicacao's per-
6747    /// `:placement` distribution composite surface reaches for exactly
6748    /// one typed dispatch — the resolver's accept-set migrates as a unit
6749    /// on any future axis addition.
6750    ///
6751    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
6752    /// `AplicacaoSpec` type itself — sibling to the seed
6753    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
6754    /// composite-reference accessor on the peer per-`:politicas` outer-
6755    /// composite axis, and to the paired slice-return accessors
6756    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6757    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
6758    /// the two `Vec`-carry axes on the outer typed composition view; the
6759    /// outer `:placement` composite-reference axis is the natural pair
6760    /// to the peer `:politicas` composite-reference axis on the two
6761    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
6762    /// how-to-run policy overlay, `:placement` carries the where-to-run
6763    /// distribution composite — every whole-Aplicacao mesh-artifact
6764    /// emitter reads both as one unit). Same "one typed dispatch on the
6765    /// substrate primitive, thin projections at each consumer"
6766    /// discipline the peer per-`:politicas` composite-reference axis
6767    /// already routes through. The one remaining outer-composite axis
6768    /// still unlifted at the time of this lift —
6769    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
6770    /// external-gateway composite) — inherits this accessor's discipline
6771    /// as the next compounding run migrates its consumers onto the shared
6772    /// reference-return shape, closing the outer-composite altitude on
6773    /// every M3 mesh-slot axis. Named `placement()` to match the storage
6774    /// field's name verbatim and the tatara-lisp author-surface term
6775    /// (`:placement`) the field's own docstring already carries; the
6776    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
6777    /// vocabulary the slot's docstring already reaches for. Returns
6778    /// `&Placement` (not the owning composite by copy or clone) because
6779    /// every downstream consumer of the placement composite treats it as
6780    /// a read-only per-axis dispatch source — the reference-view is the
6781    /// narrowest borrow that supports every present + roadmapped consumer
6782    /// (per-axis accessor dispatch, serde composite-serialization) without
6783    /// cloning the composite through every consumer's fast path.
6784    #[must_use]
6785    pub fn placement(&self) -> &Placement {
6786        &self.placement
6787    }
6788
6789    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
6790    /// per-Aplicacao external-gateway composite optional-composite-
6791    /// reference accessor every per-Aplicacao gateway-block reader
6792    /// keys off — returns the author-declared `:entrada` composite
6793    /// verbatim as an `Option<&Entrada>` reference over the same
6794    /// backing storage the raw `self.entrada.as_ref()` field access
6795    /// borrows from, with `None` naming the internal-only mesh shape
6796    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
6797    /// gateway_routes emitter treats as "emit nothing" and the peer
6798    /// `feira app graph` printer treats as "internal-only mesh").
6799    ///
6800    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
6801    /// external-gateway composite — the load-bearing container of
6802    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
6803    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
6804    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
6805    /// hostname axis, §III.4 for the `:para` destination-Servico
6806    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
6807    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
6808    /// axis threads through a lifted per-slot accessor on the
6809    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
6810    /// Gateway-API `Listener.hostname` scalar accessor, the paired
6811    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
6812    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
6813    /// backendRefs destination-Servico scalar accessor, the
6814    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
6815    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
6816    /// scalar accessor. Every downstream consumer that reaches for
6817    /// an entrada axis first passes through this outer accessor onto
6818    /// the composite and then dispatches onto the per-axis accessor
6819    /// — the two-level dispatch means every per-`:entrada` reader
6820    /// now routes through a typed dispatch on the substrate primitive
6821    /// at both altitudes.
6822    ///
6823    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
6824    /// was accessed inline at four production sites — the
6825    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
6826    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
6827    /// (which drives every per-axis refusal on the composite: the
6828    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
6829    /// `EntradaMemberMissing` membership lookup against the
6830    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
6831    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
6832    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
6833    /// per-path shape gate on each entry of `e.paths`), the
6834    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
6835    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
6836    /// composite-projection seed (which drives the destination-
6837    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
6838    /// backendRefs port emitter fans on), the
6839    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
6840    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
6841    /// early-return seed (which drives the "no `:entrada` ⇒ no
6842    /// external artifacts" partition on the whole-Aplicacao Gateway-
6843    /// API emitter's fan-out), and the `feira app graph` per-
6844    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
6845    /// external-gateway summary emitter (which drives the human-
6846    /// readable `entrada: host → para (paths=…, port=…)` /
6847    /// `entrada: (internal-only mesh)` partition on the typed
6848    /// Aplicacao view) — four open-coded outer-field accesses that
6849    /// expressed no compile-time link back to the typed slot at the
6850    /// [`AplicacaoSpec`] altitude. A future extension of the
6851    /// `:entrada` outer axis to a richer author surface (a
6852    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
6853    /// at admission time so an Aplicacao can expose a public-web +
6854    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
6855    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
6856    /// operator can pin a per-cluster hostname override without
6857    /// re-authoring the `caixa.lisp`, a promotion of the plain
6858    /// `Option<Entrada>` to a richer `{single, multi}` partition once
6859    /// the multi-`:entrada` roadmap lands) would have had to be
6860    /// threaded through all four open-coded copies in lockstep or one
6861    /// consumer would silently disagree with the peers on which
6862    /// entrada composite a given Aplicacao resolves to — the
6863    /// validator's per-axis bracket-dispatch seed reading the raw
6864    /// slot while the peer `gateway_routes` emitter read an
6865    /// operator-resolved slot would silently split the build-time
6866    /// gateway-shape gate from the runtime Gateway + HTTPRoute
6867    /// emission gate, a four-consumer split at the validator, the
6868    /// `port_for_destination` L4-port resolver, the `gateway_routes`
6869    /// emitter, and the `feira app graph` printer far from the
6870    /// source `caixa.lisp` with no field naming the entrada-drift
6871    /// root cause. Lifting the resolution rule to a typed method on
6872    /// the substrate primitive means every downstream consumer of
6873    /// the Aplicacao's per-`:entrada` external-gateway composite
6874    /// surface reaches for exactly one typed dispatch — the
6875    /// resolver's accept-set migrates as a unit on any future axis
6876    /// addition.
6877    ///
6878    /// Third and final `&Composite`-return accessor on the top-level
6879    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
6880    /// unlifted outer-composite axis on the outer typed composition
6881    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
6882    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
6883    /// accessor on the per-`:politicas` outer-composite axis and to
6884    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
6885    /// distribution-composite composite-reference accessor on the
6886    /// per-`:placement` outer-composite axis; extends the outer-
6887    /// composite reference-return discipline the two peers already
6888    /// route through onto the last unlifted per-`AplicacaoSpec`
6889    /// outer-composite axis. The `:entrada` outer-composite axis is
6890    /// the natural pair to the two peer outer-composite axes on the
6891    /// three operationally-symmetric M3 mesh-slot outer composites
6892    /// (`:politicas` carries the how-to-run policy overlay,
6893    /// `:placement` carries the where-to-run distribution composite,
6894    /// `:entrada` carries the who-can-reach-it external-gateway
6895    /// composite — every whole-Aplicacao mesh-artifact emitter reads
6896    /// all three as one unit). Same "one typed dispatch on the
6897    /// substrate primitive, thin projections at each consumer"
6898    /// discipline the peer outer-composite axes already route through.
6899    /// Named `entrada()` to match the storage field's name verbatim
6900    /// and the tatara-lisp author-surface term (`:entrada`) the
6901    /// field's own docstring already carries; the accessor's
6902    /// identity maps onto the canonical MESH-COMPOSITION §III.4
6903    /// vocabulary the slot's docstring already reaches for. Returns
6904    /// `Option<&Entrada>` (not the owning composite by copy or
6905    /// clone) because every downstream consumer of the entrada
6906    /// composite treats it as a read-only per-axis dispatch source
6907    /// — the reference-view is the narrowest borrow that supports
6908    /// every present + roadmapped consumer (per-axis accessor
6909    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
6910    /// port-fallback projection, early-return partition on the
6911    /// `None` arm) without cloning the composite through every
6912    /// consumer's fast path. The `Option` half of the return-type
6913    /// preserves the load-bearing "author-omitted `:entrada` ⇒
6914    /// internal-only mesh" partition (not a default composite the
6915    /// downstream must reject on emptiness) — the accessor projects
6916    /// the raw `Option<Entrada>` slot's presence bit through the
6917    /// reference-return unchanged.
6918    #[must_use]
6919    pub fn entrada(&self) -> Option<&Entrada> {
6920        self.entrada.as_ref()
6921    }
6922
6923    /// Validate the typed shape:
6924    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
6925    ///     and a non-empty `:versao`; no two entries share the same
6926    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
6927    ///     not a multiset)
6928    ///   - every `:contratos` :de + :para must be in `:membros`
6929    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
6930    ///     contract is an inter-Servico edge, so a Servico contracting
6931    ///     with itself is a build error under every WIT shape
6932    ///     (MESH-COMPOSITION §III.1)
6933    ///   - no two `:contratos` entries agree on
6934    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
6935    ///     edges are a set, not a multiset (peer of the `:membros` /
6936    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
6937    ///   - `:entrada :para` must be in `:membros`
6938    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
6939    ///     `:placement Replicated`/`SingleNode` must NOT declare
6940    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
6941    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
6942    ///     between strategy and shard-key is symmetric: every validated
6943    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
6944    ///     Sharded`
6945    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
6946    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
6947    ///     the shard pool (MESH-COMPOSITION §III.1)
6948    ///   - every `:clusters` entry is non-empty and unique
6949    ///   - `:placement :affinity`, when set, is non-empty
6950    ///   - the synchronous-`:contratos` subgraph is acyclic
6951    ///     (MESH-COMPOSITION §III.3)
6952    ///   - every declared `:politicas` value is operationally meaningful
6953    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
6954    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
6955    ///     omit the field instead to express "no policy on this axis")
6956    pub fn validate(&self) -> Result<(), AplicacaoError> {
6957        self.validate_membros()?;
6958        let names: std::collections::HashSet<&str> =
6959            self.membros().iter().map(Membro::nome).collect();
6960
6961        // Identity key for the typed-edge duplicate gate below: every
6962        // field that distinguishes one contract from another. Two
6963        // entries that agree on all six are *the same edge declared
6964        // twice*, the typed-graph analogue of duplicate `:membros` /
6965        // `:placement :clusters` / `:entrada :paths` entries (which
6966        // are already build errors at this layer). Rejecting it at the
6967        // validate gate closes a renderer-side footgun: caixa-mesh's
6968        // `cilium_network_policies` keys each emitted policy by
6969        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
6970        // (de, para) and identical payload would land as two K8s
6971        // objects with colliding `metadata.name`, rejected at apply
6972        // time far from the source caixa.lisp.
6973        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
6974            std::collections::HashSet::new();
6975        for c in self.contratos() {
6976            // Per-axis value-shape gate on every `:contratos` name
6977            // reference, before any graph-membership lookup. Empty +
6978            // DNS-1123-malformed `:de`/`:para` values silently fell
6979            // through to `ContratoMemberMissing` at the lookup arm
6980            // because every `:membros :caixa` is shape-validated
6981            // (3f9d7a0), so the `names` set structurally cannot contain
6982            // an empty / malformed string and the membership-lookup
6983            // diagnostic always misframed the root cause as
6984            // "this caixa is not in `:membros`". The shape gate runs
6985            // ahead of the lookup so structurally-impossible-to-match
6986            // inputs route through the narrower self-locating
6987            // diagnostic, preserving the legitimate "well-shaped
6988            // phantom reference" arm. `:de` runs before `:para` per
6989            // the canonical edge-direction order the existing
6990            // membership lookup, self-edge check, target dispatch,
6991            // and diagnostic strings already use.
6992            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
6993            // + the paired [`AplicacaoError::ContratoMemberMissing`]
6994            // diagnostic's `caixa:` carrier through the lifted
6995            // [`WitContract::source`] / [`WitContract::destination`]
6996            // scalar accessors rather than the raw `&c.de` / `&c.para`
6997            // `&String`-borrow arg site + the raw `c.de.clone()` /
6998            // `c.para.clone()` field-access `String`-carry sites — the
6999            // last unlifted per-`:contratos` raw-field-access sites in
7000            // the M3 mesh-slot validator's per-edge per-arm shape-gate
7001            // arg + phantom-name diagnostic wrap-envelope emit surface.
7002            // `c.source()` is byte-identical to `&c.de` (pinned by the
7003            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
7004            // + `wit_contract_source_borrows_from_de_storage` accessor
7005            // tests) and `c.destination()` is byte-identical to `&c.para`
7006            // (pinned by the sibling
7007            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
7008            // + `wit_contract_destination_borrows_from_para_storage`
7009            // accessor tests) — so a future rebrand of either underlying
7010            // storage flows through the accessor's one body without a
7011            // coordinated per-consumer rewrite across the M3 mesh
7012            // validator's per-edge shape-gate + phantom-name refusal
7013            // arms. Peer of the sibling per-`:contratos` self-loop
7014            // arm's `.source().to_string()` / `.world_ref().to_string()`
7015            // `String`-carry sites the earlier convergence lifted onto
7016            // the same accessor pair.
7017            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
7018            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
7019            if !names.contains(c.source()) {
7020                return Err(AplicacaoError::ContratoMemberMissing {
7021                    caixa: c.source().to_string(),
7022                });
7023            }
7024            if !names.contains(c.destination()) {
7025                return Err(AplicacaoError::ContratoMemberMissing {
7026                    caixa: c.destination().to_string(),
7027                });
7028            }
7029            // A `:contratos` entry is an *inter*-Servico contract
7030            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
7031            // typed edge between two distinct graph nodes. An edge whose
7032            // `:de` equals its `:para` is a Servico contracting with
7033            // itself — a degenerate edge under every WIT shape. The
7034            // synchronous shapes were caught only incidentally, and with
7035            // a misleading diagnostic: `detect_sync_cycles` reported
7036            // `cart → cart` as a `ContratoCycle` whose path is
7037            // `["cart", "cart"]` — framing a self-edge as a multi-node
7038            // deadlock. The pub-sub shape slipped through entirely
7039            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
7040            // `nats:pub-sub` edge from a member to itself silently
7041            // validated, then rendered a `CiliumNetworkPolicy` whose
7042            // endpointSelector and fromEndpoints both name the same
7043            // program — a self-allow rule that is a no-op, since
7044            // intra-pod traffic never traverses the mesh). A self-edge's
7045            // runtime meaning is an in-process call, which doesn't go
7046            // through the mesh at all, so no `:contratos` edge can carry
7047            // it. Firing the gate before the `:wit`/`target()` shape
7048            // checks means the structural "this edge can't exist" error
7049            // precedes the narrower payload-shape diagnostics, and shape-
7050            // agnostically covers all four `WitTarget` arms (HTTP / Store
7051            // / Capability / PubSub) at one point — closing the pub-sub
7052            // hole and replacing the misleading cycle diagnostic in one
7053            // gate. Peer of the duplicate-`:contratos` / duplicate-
7054            // `:membros` set gates: both reject a structurally
7055            // ill-formed graph at the typed surface, before the renderer
7056            // emits a K8s object that fails or no-ops far from the source
7057            // caixa.lisp.
7058            // Route the per-`:contratos` structural self-edge probe
7059            // through the lifted [`WitContract::is_self_loop`] typed
7060            // predicate rather than the raw `c.de == c.para` field-
7061            // equality check — the one production consumer of the per-
7062            // `:contratos` caller-equals-callee endpoint-equality axis
7063            // now keys off exactly one typed dispatch on the substrate
7064            // primitive, so any future rebrand of the axis (an M4-typed-
7065            // caller enum whose identity comparison rule the predicate
7066            // could route through, a per-cluster caller/callee-alias
7067            // table the M4 CR materializer resolves per-CR before the
7068            // equality probe) migrates as a single caixa-core edit
7069            // rather than a coordinated rewrite of the gate + every
7070            // downstream self-edge consumer. Peer of the sibling
7071            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
7072            // [`WitContract::is_store`] shape-predicate routing on the
7073            // `:wit` world-ref axis, extended onto the per-edge
7074            // endpoint-equality axis.
7075            //
7076            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
7077            // diagnostic's `caixa:` / `wit:` carriers through the
7078            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
7079            // scalar accessors rather than the raw `c.de.clone()` /
7080            // `c.wit.clone()` field-access `String`-carry sites — the
7081            // last unlifted per-`:contratos` raw-field-access
7082            // `.clone()` sites in the M3 mesh-slot validator's self-
7083            // edge refusal arm. `.source().to_string()` is byte-
7084            // identical to `.de.clone()` (pinned by the sibling
7085            // `source_returns_de_byte_equal_across_permutations` accessor
7086            // test), and `.world_ref().to_string()` is byte-identical
7087            // to `.wit.clone()` (pinned by the sibling
7088            // `world_ref_returns_wit_byte_equal_across_permutations`
7089            // accessor test) — so a future rebrand of either underlying
7090            // storage flows through the accessor's one body without a
7091            // coordinated per-consumer rewrite across the M3 mesh
7092            // validator.
7093            if c.is_self_loop() {
7094                return Err(AplicacaoError::ContratoSelfLoop {
7095                    caixa: c.source().to_string(),
7096                    wit: c.world_ref().to_string(),
7097                });
7098            }
7099            if c.world_ref().is_empty() {
7100                let (de, para) = c.edge_pair();
7101                return Err(AplicacaoError::EmptyWit { de, para });
7102            }
7103            // Shape ↔ target consistency — surfaces "HTTP wit without
7104            // :endpoint", "NATS wit with :endpoint set", etc. as named
7105            // build errors instead of silent renderer drops. Threaded
7106            // through the duplicate-edge diagnostic below (via
7107            // [`WitTarget::label`]) so the "which typed target arm did
7108            // the duplicate carry" question is answered by the typed
7109            // enum's variant discriminator, not by re-probing the raw
7110            // `Option<String>` payload fields.
7111            let target_view = c.target()?;
7112            // Contract identity: (de, para, wit, endpoint, subject, slot).
7113            // Two contracts that match on all six are the same typed edge
7114            // declared twice — author error, not a legitimate variant of
7115            // "same caller-callee pair, different payload" (e.g.
7116            // cart→catalog at /products vs /search), which keeps distinct
7117            // identity keys via the differing endpoint payloads.
7118            //
7119            // Route the six-axis dedup key through the lifted
7120            // [`WitContract::identity`] composite-projection accessor
7121            // rather than the inline six-tuple builder — the two
7122            // substrate primitives on the per-`:contratos` identity axis
7123            // (the [`ContratoIdentity`] type alias's six axes, this
7124            // dedup-key's six tuple arms) now migrate as a unit on any
7125            // future axis addition. Peer of the sibling per-`:contratos`
7126            // composite-projection [`WitContract::edge_pair`] /
7127            // [`WitContract::edge_triple`] accessors on the
7128            // caller-callee / caller-callee-wit prefix axes; extends
7129            // the discipline onto the full-identity axis that carries
7130            // the three payload-shape arms too.
7131            let key = c.identity();
7132            crate::render::insert_first_seen(&mut seen_contracts, key, || {
7133                // Route the per-`:contratos` duplicate-gate diagnostic's
7134                // `(de, para, wit)` triple through the lifted
7135                // [`WitContract::edge_triple`] typed accessor rather
7136                // than pairing `edge_pair()` for the `(de, para)` prefix
7137                // with a raw `c.wit.clone()` for the `wit:` tail — the
7138                // paired-with-raw-field-access shape was the last
7139                // per-`:contratos` diagnostic constructor bypassing the
7140                // substrate-primitive composite projection, sibling to
7141                // the eight [`AplicacaoError::Contrato*`] triple-
7142                // carrying constructors [`WitContract::target`]'s edge
7143                // closure feeds through the same accessor.
7144                let (de, para, wit) = c.edge_triple();
7145                AplicacaoError::ContratoDuplicate {
7146                    de,
7147                    para,
7148                    wit,
7149                    target: target_view.label(),
7150                }
7151            })?;
7152        }
7153
7154        // Cycles in the synchronous-edge subgraph are build errors
7155        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
7156        // are "acyclic by construction" because the publisher fires
7157        // and forgets, so no caller blocks on a downstream that loops
7158        // back to it.
7159        self.detect_sync_cycles()?;
7160
7161        if let Some(e) = self.entrada() {
7162            // Route the per-`:entrada` composite-reference read
7163            // through the lifted [`AplicacaoSpec::entrada`] accessor
7164            // rather than the raw `&self.entrada` field access — the
7165            // shape-and-membership gate's traversal head is now the
7166            // canonical read-side surface every per-Aplicacao entrada
7167            // consumer routes through, closing the fourth of four
7168            // open-coded outer-field accesses on the per-`:entrada`
7169            // outer-composite axis.
7170            //
7171            // Shape gate on `:entrada :para` runs ahead of the
7172            // membership lookup. Every `:membros :caixa` past
7173            // `validate_membro_caixa` is a valid DNS-1123 label
7174            // (3f9d7a0), so the `names` set structurally cannot
7175            // contain an empty / malformed string and the membership-
7176            // lookup diagnostic always misframed the root cause as
7177            // "this caixa is not in `:membros`". The shape gate
7178            // routes structurally-impossible-to-match inputs through
7179            // the narrower self-locating diagnostic, preserving the
7180            // legitimate "well-shaped phantom reference" arm — the
7181            // same trajectory the peer `:membros :caixa` (3f9d7a0),
7182            // `:placement :clusters` (6c8c00b), and `:contratos :de`
7183            // / `:para` (8d5af6b) axes already follow. This closes
7184            // the fourth and last Aplicacao-level Servico-name
7185            // reference axis on the canonical DNS-1123 floor.
7186            // Route the per-`:entrada :para` byte-string reads through
7187            // the lifted [`Entrada::destination`] accessor rather than
7188            // the raw `e.para` field access — the three
7189            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
7190            // (shape-gate `validate_entrada_para` arg, membership
7191            // lookup, `EntradaMemberMissing` diagnostic carry) now key
7192            // off exactly one typed dispatch on the substrate
7193            // primitive, closing the last unlifted per-`:entrada :para`
7194            // raw-field-access axis on the M3 mesh-slot validator.
7195            // The `.destination().to_string()` at the diagnostic site
7196            // is byte-identical to `.para.clone()` — pinned by the
7197            // sibling `destination_returns_entrada_para_byte_equal` +
7198            // `destination_borrows_from_entrada_para_storage` accessor
7199            // tests — so a future rebrand of the underlying `:para`
7200            // storage (a lift from `String` to a typed
7201            // `ServicoName(String)` newtype, a per-Aplicacao interning
7202            // arena the M4 CR materializer authors, a
7203            // `smol_str::SmolStr` inline-buffer swap) flows through
7204            // the accessor's one body without a coordinated
7205            // per-consumer rewrite across the M3 mesh validator.
7206            validate_entrada_para(e.destination())?;
7207            if !names.contains(e.destination()) {
7208                return Err(AplicacaoError::EntradaMemberMissing {
7209                    para: e.destination().to_string(),
7210                });
7211            }
7212            // Route the per-`:entrada :host` byte-string reads through
7213            // the lifted [`Entrada::hostname`] accessor rather than
7214            // the raw `e.host` field access — the emptiness gate and
7215            // the shape-gate `validate_entrada_host` arg now key off
7216            // exactly one typed dispatch on the substrate primitive,
7217            // closing the last unlifted per-`:entrada :host` raw-
7218            // field-access axis on the M3 mesh-slot validator. Peer
7219            // of the sibling per-`:entrada :para` convergence above
7220            // and pinned by the existing
7221            // `hostname_returns_entrada_host_byte_equal` +
7222            // `hostnames_returns_singleton_of_hostname_accessor`
7223            // accessor tests, so any future
7224            // Gateway-API-shaped host renormalization (a wildcard-
7225            // label lift, a trailing-`.` FQDN substitution, an IDNA
7226            // Punycode round-trip the SNI fan-out overlay authors)
7227            // flows through the accessor's one body without a
7228            // coordinated per-consumer rewrite across the M3 mesh
7229            // validator.
7230            if e.hostname().is_empty() {
7231                return Err(AplicacaoError::EmptyEntradaHost);
7232            }
7233            // The `:host` lands verbatim as a K8s Gateway API v1
7234            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
7235            // both apiserver-validated against the same restrictive
7236            // pattern: lowercase RFC 1123 DNS subdomain, optional
7237            // single leading wildcard label (`*.`), max length 253,
7238            // per-label max length 63, no IP literals, no scheme,
7239            // no port. Until this gate landed `validate()` only
7240            // refused the empty string (`EmptyEntradaHost`); a
7241            // structurally invalid hostname (`"https://example.com"`,
7242            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
7243            // `"_underscored.example.com"`, `"FOO.example.com"`,
7244            // `"checkout.quero.cloud."`) silently passed validate
7245            // and the apiserver `field is invalid` error surfaced at
7246            // `kubectl apply` time, far from the source caixa.lisp.
7247            // Lifting the gate to caixa-build time mirrors the
7248            // `:entrada :paths` value-shape trajectory (eb3456d) and
7249            // closes the last unstructured `:entrada` axis.
7250            validate_entrada_host(e.hostname())?;
7251            // Structural-floor gate on `:entrada :port`: every
7252            // validated `Entrada::port` past this gate lies in
7253            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
7254            // type-inferred ceiling closes the top edge, so no companion
7255            // upper-cap arm is needed here — unlike the peer capped-
7256            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
7257            // `require_positive_bounded_u32` bracket covers both edges).
7258            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
7259            // accept-set-floor const rather than the prior inline
7260            // `if e.port == 0` byte-check so a future rebrand of the
7261            // accept-set floor (a hypothetical unprivileged-only
7262            // migration lifting the floor to `1024`, a per-cluster
7263            // scoping the operator pins through a future
7264            // `:placement :port-floor` slot as the M4 typed-slot
7265            // trajectory adds it, the future
7266            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7267            // per-Aplicacao gateway resolver reaching for the same
7268            // floor) is a one-line edit on the canonical
7269            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
7270            // rewrite across the emit site + the pin test + every
7271            // future per-target renderer the substrate adds.
7272            if e.port() < SERVICO_PORT_MIN {
7273                return Err(AplicacaoError::EntradaPortZero);
7274            }
7275            // Each `:entrada :paths` entry becomes a K8s Gateway API
7276            // HTTPRoute `matches[].path.value`. The Gateway API rejects
7277            // values that don't start with `/` for `type: PathPrefix`,
7278            // and an empty value is meaningless. Surface those as build
7279            // errors (MESH-COMPOSITION §III.3) rather than apply-time
7280            // failures. Empty `:paths` itself is fine — caixa-mesh
7281            // falls back to a single `/` catch-all.
7282            let mut seen = std::collections::HashSet::new();
7283            // Route the per-entry value-shape gate's traversal head
7284            // through the lifted [`Entrada::paths`] slice accessor
7285            // rather than the raw `&e.paths` field access — the
7286            // per-Aplicacao `:entrada :paths` validate loop now keys
7287            // off the canonical raw-slot surface every downstream
7288            // per-`:entrada` path-list consumer (the sibling
7289            // [`Entrada::resolved_paths`] fallback-applying resolver
7290            // internal reads, `feira app graph`'s per-Aplicacao entrada
7291            // summary line's `{:?}` Debug print) routes through, so any
7292            // future rebrand on the typed slot's raw-slot reader lands
7293            // at exactly one place. Same convergence discipline as the
7294            // sibling [`Placement::clusters`] (a6e18d7) reader-site
7295            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
7296            // axis.
7297            for p in e.paths() {
7298                if p.is_empty() {
7299                    return Err(AplicacaoError::EntradaPathEmpty);
7300                }
7301                if !p.starts_with('/') {
7302                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
7303                }
7304                // Per-entry value-shape gate: the path lands verbatim
7305                // as a K8s Gateway API HTTPRoute `matches[].path.value`
7306                // (caixa-mesh/src/lib.rs:498), apiserver-validated
7307                // against `maxLength: 1024` + the Gateway API webhook's
7308                // path-grammar rules (no `//`, no `/./`, no `/../`, no
7309                // query/fragment separators, no whitespace, no control
7310                // characters, no non-ASCII bytes). Until this gate
7311                // landed `validate` only refused the empty string and
7312                // missing-leading-slash (eb3456d); a structurally
7313                // invalid path (`"/api?q=1"`, `"/api#frag"`,
7314                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
7315                // 1025-byte URL-shaped slug) silently passed validate
7316                // and the failure surfaced at `kubectl apply` time as
7317                // a Gateway API webhook rejection, far from the source
7318                // caixa.lisp, with no field naming the offending
7319                // `:paths` entry. Lifting the gate to caixa-build time
7320                // mirrors the `:entrada :host` value-shape trajectory
7321                // (c7d05ec) on the sibling axis — every author surface
7322                // that emits a Gateway API field now matches the
7323                // apiserver's accepted set at validate time.
7324                validate_entrada_path(p)?;
7325                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
7326                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
7327                })?;
7328            }
7329        }
7330
7331        self.validate_placement()?;
7332
7333        self.validate_politicas()?;
7334
7335        Ok(())
7336    }
7337
7338    /// Reject `:membros` values that are operationally meaningless. The
7339    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
7340    /// every entry names a Servico that participates in the Aplicacao,
7341    /// and the rendered programs.yaml fan-out emits one entry per
7342    /// `:membros`. Three authoring footguns are closed here:
7343    ///
7344    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
7345    ///     a `programs:` entry whose `name:` is the empty string, which
7346    ///     downstream `lareira-fleet-programs` rejects at template time
7347    ///     with a non-localized error;
7348    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
7349    ///     an empty semver constraint, so the failure surfaces far from
7350    ///     the source caixa.lisp;
7351    ///   - duplicate `:caixa` names — two entries with the same name
7352    ///     produce duplicate programs.yaml entries (one silently
7353    ///     overwrites the other in the cluster's HelmRelease values), and
7354    ///     contract membership lookups against `:contratos` collapse the
7355    ///     two onto one node, masking authoring mistakes.
7356    ///
7357    /// Same value-shape discipline as `:placement :clusters` (where empty
7358    /// + duplicate cluster names are rejected) and `:entrada :paths`
7359    /// (where empty + duplicate path entries are rejected). Lifting these
7360    /// invariants to the typed surface mirrors the MESH-COMPOSITION
7361    /// §III.3 promise that the `:membros` set — the load-bearing identity
7362    /// of the application graph — is well-formed by construction.
7363    fn validate_membros(&self) -> Result<(), AplicacaoError> {
7364        if self.membros().is_empty() {
7365            return Err(AplicacaoError::NoMembros);
7366        }
7367        let mut seen = std::collections::HashSet::new();
7368        for m in self.membros() {
7369            // Route the `MembroCaixaEmpty` refusal-arm's per-member
7370            // empty-`:caixa` shape-gate through the typed
7371            // [`Membro::nome`] accessor rather than the raw `.caixa`
7372            // field access — the last un-lifted `.caixa` production-
7373            // code read site on the per-`:membros` member-caixa `:nome`
7374            // axis, sibling to the six caixa-core validator read sites
7375            // (member-set collector, per-member value-shape gate,
7376            // duplicate dedup key, cycle-detector adjacency-map seed,
7377            // self-loop gate) the 4a32abf lift already routed through
7378            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
7379            // per-`programs[]` entry-`name:` `String`-carry converge.
7380            // Prior to this converge the `MembroCaixaEmpty` refusal
7381            // arm was the solitary consumer bypassing the typed
7382            // dispatch — the same-loop iteration's very next call
7383            // `validate_membro_caixa(m.nome())` already routed through
7384            // the accessor, so an author landing an empty-`:caixa`
7385            // entry hit the accessor on the shape-gate line but
7386            // bypassed it on the emptiness line one line above. A
7387            // future extension of the `:membros :caixa` axis to a
7388            // richer author surface (a per-cluster alias table pinned
7389            // through a future `:placement`-scoped slot, a namespace-
7390            // qualified rewrite the M4 CR materializer applies per-CR,
7391            // a per-member overlay from the future `:membros
7392            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
7393            // that lands on the accessor would silently disagree
7394            // between the emptiness gate and every peer consumer —
7395            // an author-declared `:caixa "checkout"` value the
7396            // accessor rewrote to `""` under a future alias arm would
7397            // pass the raw `.is_empty()` gate here while the peer
7398            // `validate_membro_caixa(m.nome())` call one line below
7399            // (and every downstream emit-side consumer routing through
7400            // the accessor) tripped on the empty-value shape far from
7401            // this diagnostic. Pinned by the drift-detection test
7402            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
7403            // below.
7404            if m.nome().is_empty() {
7405                return Err(AplicacaoError::MembroCaixaEmpty);
7406            }
7407            // Every emitted cluster artifact's `metadata.name` derives
7408            // from a `:membros :caixa` value verbatim — the rendered
7409            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
7410            // the [`crate::LABEL_PROGRAM`] label value on every CNP
7411            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
7412            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
7413            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
7414            // `metadata.name` when the member is the `:entrada :para`
7415            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
7416            // schema enforces the DNS-1123 label rule on admission;
7417            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
7418            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
7419            // mistaken-identity slug) silently passes the prior empty-/
7420            // duplicate-only gate and the failure surfaces at `kubectl
7421            // apply` time as a `metadata.name: Invalid value` rejection,
7422            // far from the source caixa.lisp, with no field naming the
7423            // offending `:membros` entry. Lifting the gate to caixa-build
7424            // time mirrors the `:entrada :host` value-shape trajectory
7425            // (c7d05ec) on the peer axis — every author surface that
7426            // emits a K8s name now matches the apiserver's accepted set
7427            // at validate time.
7428            validate_membro_caixa(m.nome())?;
7429            // The author surface for `:versao` is the same Cargo-shaped
7430            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
7431            // `"*"`) every `:deps` entry carries — and the lacre pipeline
7432            // resolves both axes through the same
7433            // [`crate::version::parse_requirement`] entry-point. The
7434            // shared [`crate::render::require_valid_versao_requirement`]
7435            // helper brackets the empty-first + parse cascade both peer
7436            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
7437            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
7438            // route through, so drift between the three axes' accepted
7439            // requirement sets is structurally impossible and the parse-
7440            // side no-op the empty-first arm closes (semver's empty
7441            // parse yields an implicit `*`) lives in exactly one
7442            // predicate.
7443            crate::render::require_valid_versao_requirement(
7444                m.versao_requirement(),
7445                || AplicacaoError::MembroVersaoEmpty {
7446                    caixa: m.nome().to_string(),
7447                },
7448                |reason| AplicacaoError::MembroVersaoInvalid {
7449                    caixa: m.nome().to_string(),
7450                    versao: m.versao_requirement().to_string(),
7451                    reason,
7452                },
7453            )?;
7454            crate::render::insert_first_seen(&mut seen, m.nome(), || {
7455                AplicacaoError::MembroDuplicate {
7456                    caixa: m.nome().to_string(),
7457                }
7458            })?;
7459        }
7460        Ok(())
7461    }
7462
7463    /// Reject `:placement` values that are operationally meaningless or
7464    /// internally contradictory. Each strategy variant has the same
7465    /// invariants on `:clusters` (non-empty list, non-empty unique
7466    /// entries) — the §III.1 author surface is uniform on this axis,
7467    /// even though the *meaning* of the list differs by strategy
7468    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
7469    /// shard pool).
7470    ///
7471    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
7472    /// are the same authoring footgun closed for `:politicas` zero
7473    /// values and `:entrada` empty paths: the field is *declared* but
7474    /// carries no meaning, so downstream renderers either skip it
7475    /// silently (cluster-fanout drops the empty entry, no diagnostic)
7476    /// or apply it literally and fail at admission time. Lifting both
7477    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
7478    /// violation is a build error" promise.
7479    ///
7480    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
7481    /// is required exactly when `:estrategia Sharded` (hash-keyed
7482    /// distribution, Akka cluster-sharding convention, §II.4) and
7483    /// refused on `:estrategia Replicated`/`SingleNode` (where no
7484    /// hash-keyed routing axis consumes it). The partition closes the
7485    /// "I think I configured sharding" footgun where an author writes
7486    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
7487    /// the typed slot's value silently vanishes at the renderer layer
7488    /// — every validated `Placement` past this call satisfies
7489    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
7490    fn validate_placement(&self) -> Result<(), AplicacaoError> {
7491        // Every strategy needs at least one named cluster: `Replicated`
7492        // and `SingleNode` use the list as hosting/takeover candidates
7493        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
7494        // §II.1), while `Sharded` uses it as the shard pool
7495        // (Akka cluster-sharding convention — §II.4). An empty list is
7496        // meaningless under any of the three.
7497        //
7498        // Route the paired pre-flight `.is_empty()` refusal probe and
7499        // the per-cluster validate loop's traversal head through the
7500        // lifted [`Placement::clusters`] slice-return accessor rather
7501        // than the raw `self.placement.clusters` field access — the
7502        // two production consumers of the per-`:placement` cluster-
7503        // pool `Vec`-carry now key off exactly one typed dispatch on
7504        // the substrate primitive, so any future rebrand on the axis
7505        // (a per-tenant cluster-pool overlay the operator pins through
7506        // a future `:placement :clusters-overrides` slot, a per-
7507        // Aplicacao dynamic cluster-pool derivation the future M5
7508        // adaptive-placement engine computes from `:affinity` weights)
7509        // migrates as a single caixa-core edit rather than a
7510        // coordinated rewrite of the paired arms — sibling of the
7511        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
7512        // arm migration on the per-`:supervisor` static-child-list
7513        // `Vec`-carry axis.
7514        //
7515        // Route the per-`:placement` outer-composite reference read
7516        // through the lifted [`AplicacaoSpec::placement`] outer accessor
7517        // rather than the raw `&self.placement` field access — the
7518        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
7519        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
7520        // axis-level lifted accessor family) now routes through the
7521        // substrate-primitive typed dispatch at the outer composition
7522        // altitude, the same shape the peer caixa-mesh
7523        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
7524        // and the sibling `feira app graph` per-Aplicacao print line
7525        // now key off after this accessor lift.
7526        let p = self.placement();
7527        if p.clusters().is_empty() {
7528            return Err(AplicacaoError::PlacementWithoutClusters {
7529                estrategia: p.estrategia(),
7530            });
7531        }
7532        let mut seen = std::collections::HashSet::new();
7533        for c in p.clusters() {
7534            // Per-entry value-shape gate: the cluster name lands in
7535            // every K8s context / `lareira-fleet-programs` aggregator
7536            // filter / future M4 CR materializer's per-cluster axis
7537            // a validated `:clusters` entry passes through, each
7538            // enforcing the DNS-1123 label rule on admission. Same
7539            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
7540            // on the peer name axis — both axes' validated values
7541            // are guaranteed-accepted by the apiserver without
7542            // re-validation at any downstream renderer or admission
7543            // layer.
7544            validate_placement_cluster(c)?;
7545            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
7546                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
7547            })?;
7548        }
7549        // Route the per-`:placement :affinity` per-hint value-shape
7550        // gate through the typed [`Placement::affinity`] accessor rather
7551        // than the raw `&self.placement.affinity` field access — the
7552        // sole open-coded field-access site on the per-`:placement`
7553        // M3-Adaptive-compression-hint axis the accessor lift now owns.
7554        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
7555        // the accessor's `Option<&str>` return type;
7556        // [`validate_placement_affinity`]'s `&str` parameter accepts
7557        // the narrower borrow without a re-allocation, so the routing
7558        // change is byte-for-byte in the pass arm and remains
7559        // byte-for-byte in every failure diagnostic
7560        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
7561        // String` field is populated inside
7562        // [`validate_placement_affinity`] via the peer `.to_string()`
7563        // path on the same borrowed slice). Peer of the sibling
7564        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
7565        // routing through [`Placement::shard_key`] at the caixa-core
7566        // site above — extends the "read `:placement` optional-scalars
7567        // through the typed accessor" discipline to the second
7568        // `Option<String>`-shape slot on the M3 mesh-slot family.
7569        //
7570        // Per-hint value-shape gate: the `:affinity` value lands
7571        // verbatim in the M3 Adaptive compression overlay
7572        // (caixa-mesh's `placement.affinity` emission) and every
7573        // future M4 placement-engine routing axis keying off the
7574        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
7575        // selector — each enforces the DNS-1123 label rule on
7576        // admission. Same typed-shape trajectory as `:placement
7577        // :clusters` (6c8c00b) on the sibling slot and the four
7578        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
7579        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
7580        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
7581        // on the Aplicacao surface to land on the canonical
7582        // [`crate::render::is_dns_1123_label`] floor.
7583        if let Some(a) = p.affinity() {
7584            validate_placement_affinity(a)?;
7585        }
7586        match p.estrategia() {
7587            // Route the `Sharded`-arm shape-gate cascade through the
7588            // typed [`Placement::shard_key`] accessor rather than the
7589            // raw `&self.placement.shard_key` field access — one of the
7590            // two open-coded field-access sites on the per-`:placement`
7591            // Akka-cluster-sharding-key axis the accessor lift now
7592            // owns. The `Some(k)`-bound `k` narrows from `&String` to
7593            // `&str` under the accessor's `Option<&str>` return type;
7594            // `str::is_empty` and [`validate_placement_shard_key`]'s
7595            // `&str` parameter both accept the narrower borrow without
7596            // a re-allocation.
7597            PlacementStrategy::Sharded => match p.shard_key() {
7598                None => return Err(AplicacaoError::ShardedWithoutKey),
7599                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
7600                // Per-axis value-shape gate on the Akka-cluster-sharding
7601                // `:shard-key` extractor expression. The shape gate runs
7602                // after the more self-locating `ShardedKeyEmpty` arm so
7603                // a `:shard-key ""` surfaces the narrower empty
7604                // diagnostic first; every non-empty `:shard-key` past
7605                // this call is guaranteed to be a printable-ASCII
7606                // single-token reference the future M4 Akka-style
7607                // cluster-sharding reconciler can hash without
7608                // re-validating at the runtime layer. Mirrors the
7609                // payload-axis shape gates on the peer `:contratos`
7610                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
7611                // 63e18a0 / c4213a4) — each lifts the runtime parser's
7612                // intersection-floor to a caixa-build-time gate.
7613                Some(k) => validate_placement_shard_key(k)?,
7614            },
7615            // `:shard-key` is the Akka-cluster-sharding axis
7616            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
7617            // across the cluster pool. `Replicated` (active-active across
7618            // every named cluster) and `SingleNode` (Erlang/OTP
7619            // distributed-app takeover/failover, §II.1) have no hash-keyed
7620            // routing axis to consume the slot; downstream renderers
7621            // (caixa-mesh's `placement.shardKey` overlay at
7622            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
7623            // sharding reconciler) ignore `:shard-key` outside the
7624            // `Sharded` arm by construction. Until this gate landed an
7625            // author who wrote `:placement (:estrategia Replicated
7626            // :shard-key "tenantId")` (an off-by-one strategy typo, a
7627            // copy-paste from a Sharded sibling caixa, the "I think I
7628            // configured sharding" footgun) silently passed validate and
7629            // the typed slot's value vanished at the renderer layer with
7630            // no diagnostic — the canonical "declared-but-inert" footgun
7631            // the empty-:affinity / empty-shard-key / zero-:politicas /
7632            // empty-:contratos-target gates already close on every other
7633            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
7634            // Lifting the rejection to a build-time gate closes the
7635            // Sharded ↔ non-Sharded partition over the typed
7636            // `:placement` slot: every validated `Placement` past this
7637            // call has `shard_key.is_some()` iff `estrategia ==
7638            // Sharded`, structurally — the future Akka reconciler can
7639            // reach for `placement.shard_key` knowing it's `Some` exactly
7640            // when the strategy consumes it, without re-deriving the
7641            // partition from inline strategy probes.
7642            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
7643                // Route the non-`Sharded`-arm declared-but-inert refusal
7644                // through the typed [`Placement::shard_key`] accessor —
7645                // the second of the two open-coded field-access sites the
7646                // accessor lift now owns. The `Some(k)`-bound `k` narrows
7647                // from `&String` to `&str`; the `AplicacaoError::
7648                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
7649                // materializes the owned `String` via `k.to_string()`
7650                // (peer to the sibling per-Membro `String`-carry sites
7651                // 4127bb6 routed through `m.nome().to_string()` /
7652                // `m.versao_requirement().to_string()`), so the whole
7653                // `Sharded` ↔ non-`Sharded` partition on the
7654                // `:shard-key` axis now flows through the same typed
7655                // dispatch as the sibling `Sharded`-arm shape gate.
7656                if let Some(k) = p.shard_key() {
7657                    return Err(AplicacaoError::ShardKeyOnNonSharded {
7658                        estrategia: p.estrategia(),
7659                        shard_key: k.to_string(),
7660                    });
7661                }
7662            }
7663        }
7664        Ok(())
7665    }
7666
7667    /// Reject `:politicas` values that are operationally meaningless.
7668    /// Each axis is optional — omitting it expresses "no policy on this
7669    /// axis". Carrying a *zero* value for a declared axis is the bug
7670    /// this function rejects: zero is either
7671    ///
7672    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
7673    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
7674    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
7675    ///     "every Aplicacao declares :politicas :timeout (no infinite
7676    ///     blocking)", or
7677    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
7678    ///     first call; a 0-rate rate-limit denies every request).
7679    ///
7680    /// Lifting these "0 means the opposite of what you think" idioms to
7681    /// the typed Aplicacao surface as build errors mirrors the §III.3
7682    /// promise that contract drift, capability leaks, and cycles are all
7683    /// build errors — not runtime surprises.
7684    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
7685        // Route the per-`:politicas` composite-reference read through
7686        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
7687        // than the raw `&self.politicas` field access — the per-axis
7688        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
7689        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
7690        // the substrate-primitive typed dispatch at the outer
7691        // composition altitude AND at every per-axis altitude, matching
7692        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
7693        // timeout/retry-overlay emitters that already key off the same
7694        // per-axis accessor family. The four-axis fan-out is now
7695        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
7696        // `p.retries` field-access sites (co-resident with the peer
7697        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
7698        // b0e741a / 21a6c3b already lifted) now route through
7699        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
7700        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
7701        // access axis on the M3 mesh-slot family.
7702        let p = self.politicas();
7703        if let Some(t) = p.timeout() {
7704            // Zero-floor + integer-millisecond canonical-form +
7705            // upper-cap bracket on the typed `:timeout` axis. See
7706            // [`crate::render::require_positive_canonical_bounded_duration`]
7707            // for the full three-arm ordering discipline (zero-floor
7708            // strictly precedes the canonical-form arm so
7709            // `Duration::ZERO` surfaces the self-locating
7710            // `PolicyTimeoutZero` diagnostic naming the omit-axis
7711            // remediation; canonical-form strictly precedes the cap
7712            // arm so a sub-millisecond above-cap `Duration` surfaces
7713            // the more fundamental round-trip-shape diagnostic first)
7714            // and the four peer typed-`Duration` sites that now share
7715            // this canonical bracket. Every validated value lies in
7716            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
7717            // granularity — the same top-and-bottom-edge discipline
7718            // [`POLICY_RETRIES_MAX`] and
7719            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
7720            // capped-`u32` `:politicas` axes.
7721            crate::render::require_positive_canonical_bounded_duration(
7722                t,
7723                POLICY_TIMEOUT_MAX,
7724                || AplicacaoError::PolicyTimeoutZero,
7725                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
7726                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
7727            )?;
7728        }
7729        if let Some(r) = p.retries() {
7730            // Zero-floor + upper-cap bracket on the typed `:retries`
7731            // axis. See [`crate::render::require_positive_bounded_u32`]
7732            // for the ordering discipline (zero-floor arm strictly
7733            // precedes cap arm so `Some(0)` surfaces the self-locating
7734            // `PolicyRetriesZero` diagnostic with its omit-axis
7735            // remediation directly named, not the misleading
7736            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
7737            // this bracket landed the top edge ran all the way to
7738            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
7739            // Some(100_000), .. }` (or the equivalent author-surface
7740            // `(:retries 100000)` / `(:retries 4294967295)` typo
7741            // landing in the slot) silently passed validate. The
7742            // runtime substrate consuming the value (Envoy's
7743            // `retry_policy.num_retries`, the future
7744            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7745            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7746            // policy into a thundering-herd amplification vector —
7747            // the caller's one request fans out to `retries`
7748            // server-side calls per edge per traversal, multiplying
7749            // load by `(retries+1)^depth` across the
7750            // synchronous-`:contratos` subgraph at the precise moment
7751            // the substrate is already failing (transient failure is
7752            // the trigger), exactly the failure mode AWS App Mesh's
7753            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
7754            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
7755            // the sibling capped-`u32` `:politicas` axes
7756            // (`max_failures`, `rate_limit.rate`) and the peer capped-
7757            // `u32` axes in `:supervisor :max-restarts` +
7758            // `:limits :cpu`; all five now route through the same
7759            // canonical bracket helper.
7760            crate::render::require_positive_bounded_u32(
7761                r,
7762                POLICY_RETRIES_MAX,
7763                || AplicacaoError::PolicyRetriesZero,
7764                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
7765            )?;
7766        }
7767        if let Some(cb) = p.circuit_breaker() {
7768            // Zero-floor + upper-cap bracket on the typed
7769            // `:max-failures` axis. See
7770            // [`crate::render::require_positive_bounded_u32`] for the
7771            // ordering discipline (zero-floor arm strictly precedes
7772            // cap arm so `max_failures == 0` surfaces the
7773            // self-locating `PolicyBreakerZeroFailures` diagnostic
7774            // with its omit-axis remediation directly named, not the
7775            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
7776            // false` cap-arm miss). Until this bracket landed the top
7777            // edge ran all the way to `u32::MAX` and a struct-literal
7778            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
7779            // equivalent author-surface `(:max-failures 100000)` /
7780            // `(:max-failures 4294967295)` typo landing in the slot)
7781            // silently passed validate. The runtime substrate
7782            // consuming the value (Envoy's
7783            // `outlier_detection.consecutive_5xx`, the future
7784            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7785            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7786            // breaker policy into a no-op — the trip threshold is
7787            // structurally so high that no realistic
7788            // failures-per-`:window` traffic shape can reach it, the
7789            // breaker never trips, and every typed-slot consumer
7790            // emits an Envoy / Cilium L7 overlay carrying a
7791            // protection that is structurally never enforced. The
7792            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
7793            // peer with `retries` and `rate_limit.rate` on the same
7794            // helper.
7795            crate::render::require_positive_bounded_u32(
7796                cb.max_failures(),
7797                POLICY_BREAKER_MAX_FAILURES_MAX,
7798                || AplicacaoError::PolicyBreakerZeroFailures,
7799                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
7800            )?;
7801            // Zero-floor + integer-millisecond canonical-form +
7802            // upper-cap bracket on the typed `:window` axis. See
7803            // [`crate::render::require_positive_canonical_bounded_duration`]
7804            // for the full three-arm ordering discipline (peer to the
7805            // `:timeout` site immediately above); every validated
7806            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
7807            // (1ms..=1h), integer-millisecond granularity — the same
7808            // top-and-bottom-edge discipline
7809            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
7810            // duration-typed `:politicas :timeout` axis.
7811            crate::render::require_positive_canonical_bounded_duration(
7812                cb.window(),
7813                POLICY_BREAKER_WINDOW_MAX,
7814                || AplicacaoError::PolicyBreakerZeroWindow,
7815                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
7816                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
7817            )?;
7818        }
7819        if let Some(rl) = p.rate_limit() {
7820            // Zero-floor + upper-cap bracket on the typed
7821            // `:rate-limit` rate axis. See
7822            // [`crate::render::require_positive_bounded_u32`] for the
7823            // ordering discipline (zero-floor arm strictly precedes
7824            // cap arm so `rl.rate == 0` surfaces the self-locating
7825            // `PolicyRateLimitZero` diagnostic with its omit-axis
7826            // remediation directly named, not the misleading
7827            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
7828            // Until this bracket landed the top edge ran all the way
7829            // to `u32::MAX` and a struct-literal
7830            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
7831            // author-surface `(:rate-limit "4294967295/s")` /
7832            // `(:rate-limit "100000000/m")` typo landing in the slot)
7833            // silently passed validate. The runtime substrate
7834            // consuming the value (Envoy's
7835            // `local_rate_limit.token_bucket.max_tokens`, the future
7836            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7837            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7838            // rate-limit policy into a no-op limiter: the bucket
7839            // capacity is structurally so high that no realistic
7840            // per-edge traffic shape can drain it, the limiter never
7841            // trips, and every typed-slot consumer emits a "rate
7842            // declared" L7 overlay carrying enforcement that is
7843            // structurally never reached — the canonical
7844            // declared-but-inert footgun the sibling
7845            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
7846            // the peer no-op-breaker shape. The bracket set is
7847            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
7848            // `max_failures` on the same helper. The rate bracket
7849            // strictly precedes the window-canonical gate so a
7850            // structurally absurd rate magnitude surfaces the more
7851            // fundamental amplification-shape diagnostic before the
7852            // narrower codec-round-trip-shape diagnostic on `:window`.
7853            crate::render::require_positive_bounded_u32(
7854                rl.rate(),
7855                POLICY_RATE_LIMIT_MAX,
7856                || AplicacaoError::PolicyRateLimitZero,
7857                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
7858            )?;
7859            // The `:rate-limit` author surface is the canonical
7860            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
7861            // accepts exactly the three-unit set (1s/60s/3600s) the
7862            // [`rate_limit_codec::render`] formatter emits the canonical
7863            // unit suffix for. A `RateLimit` whose `:window` is anything
7864            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
7865            // programmatically (struct literals in Rust + the typed
7866            // `Duration` field) but renders to a `<n>/<k>s` fragment
7867            // (the codec's fall-through) the parser then rejects on
7868            // round-trip — silently breaking the THEORY.md §V.2.7
7869            // render-determinism contract for any consumer that
7870            // serializes-then-deserializes the typed slot. Lifting the
7871            // canonical-window invariant to a build-time gate at
7872            // `validate_politicas` makes the codec's round-trip property
7873            // a structural property of the validated typed value:
7874            // every `RateLimit` past `AplicacaoSpec::validate` has a
7875            // window the codec round-trips losslessly, so the next
7876            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
7877            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
7878            // §III.2 #3) reaches for `rate_limit.window` knowing the
7879            // value is in the codec's accepted set without re-validating
7880            // at the renderer layer. Same trajectory as c4213a4 (typed
7881            // WitContract endpoint/subject/slot value-shape gates) and
7882            // the b0c8389 :behavior + :upgrade-from script-path lifts:
7883            // the typed slot's valid set matches its codec's accepted
7884            // set, structurally.
7885            // Route the canonical-window shape-gate through the substrate
7886            // primitive [`RateLimit::canonical_unit`] rather than the free
7887            // module-private [`is_canonical_rate_limit_window`] predicate:
7888            // both projections resolve `Duration → Option<RateLimitUnit>`
7889            // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
7890            // arm on the closed-set typed enum), but the accessor is the
7891            // typed method every downstream consumer of the validated slot
7892            // ([`rate_limit_codec::render`]'s canonical arm above, the
7893            // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7894            // per-`:politicas :rate-limit` admission webhook, the future
7895            // per-`:contratos`-edge rate-limit-override overlay
7896            // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
7897            // production consumers of the canonical-unit axis (the codec
7898            // render and this validate gate) now key off exactly one typed
7899            // dispatch on the substrate primitive, so any future extension
7900            // to `canonical_unit` (a per-cluster canonical-window overlay
7901            // the operator pins through a future `:contratos :rate-limit
7902            // -unit-overrides` slot, a per-tenant unit-alias table the M4
7903            // CR materializer resolves per-CR) reaches both consumers by
7904            // construction rather than a coordinated rewrite of every
7905            // free-helper call site.
7906            if rl.canonical_unit().is_none() {
7907                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
7908                    window: rl.window(),
7909                });
7910            }
7911        }
7912        Ok(())
7913    }
7914
7915    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
7916    /// A synchronous edge is any contract whose typed [`WitTarget`] is
7917    /// `Http`, `Store`, or `Capability` — the caller blocks on the
7918    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
7919    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
7920    /// block on its subscribers, so they can never close a sync loop.
7921    ///
7922    /// Iterative DFS with three-coloring; the reported cycle is the
7923    /// path of caixa names traversed from the back-edge target around
7924    /// to itself, in declaration order. Adjacency lists and DFS roots
7925    /// are visited in `BTreeMap` key order so the diagnostic is
7926    /// deterministic across runs.
7927    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
7928        use std::collections::{BTreeMap, BTreeSet};
7929
7930        #[derive(Clone, Copy, PartialEq, Eq)]
7931        enum Mark {
7932            White,
7933            Gray,
7934            Black,
7935        }
7936
7937        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
7938        for m in self.membros() {
7939            adj.entry(m.nome()).or_default();
7940        }
7941        for c in self.contratos() {
7942            // target() was already called by validate(); re-running here
7943            // keeps detect_sync_cycles self-contained for callers that
7944            // reuse it (M4 per-edge policy resolver) without revalidating.
7945            //
7946            // The pub-sub-arm check routes through the lifted
7947            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
7948            // arm-discriminator predicate rather than a raw `matches!(…,
7949            // WitTarget::PubSub { .. })` on the variant so a future
7950            // rebrand on the axis (an M4 per-edge WIT registry split of
7951            // [`WitTarget::PubSub`] into shape-specific peers, a
7952            // per-consumer rename that the accept-set already carries)
7953            // reaches this call site through the derive rather than a
7954            // scattered per-arm `matches!` rewrite — same
7955            // `IsVariant`-derived-arm-discriminator discipline the
7956            // peer closed-set typed enums ([`crate::CaixaKind`] via
7957            // f5bba80, [`PlacementStrategy`] via 766ec63,
7958            // [`crate::supervisor::RestartStrategy`] +
7959            // [`crate::supervisor::RestartPolicy`],
7960            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
7961            // already route through on the substrate's other typed-enum
7962            // arm-discriminator axes.
7963            if c.target()?.is_pubsub() {
7964                continue;
7965            }
7966            adj.entry(c.source()).or_default().insert(c.destination());
7967        }
7968
7969        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
7970        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
7971
7972        // Stable DFS root order — BTreeMap iteration is sorted by key.
7973        let roots: Vec<&str> = adj.keys().copied().collect();
7974
7975        // Frame: (node, sorted-neighbours snapshot, next-edge index).
7976        for root in roots {
7977            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
7978                continue;
7979            }
7980            let root_neighbors: Vec<&str> = adj
7981                .get(root)
7982                .map(|s| s.iter().copied().collect())
7983                .unwrap_or_default();
7984            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
7985            color.insert(root, Mark::Gray);
7986
7987            loop {
7988                // Read+advance the top frame in one borrow scope so we
7989                // can later mutate the stack (push/pop) without holding
7990                // a borrow across.
7991                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
7992                    let node = top.0;
7993                    if top.2 >= top.1.len() {
7994                        (node, None)
7995                    } else {
7996                        let nxt = top.1[top.2];
7997                        top.2 += 1;
7998                        (node, Some(nxt))
7999                    }
8000                });
8001                let Some((node, nxt_opt)) = step else { break };
8002                let Some(nxt) = nxt_opt else {
8003                    color.insert(node, Mark::Black);
8004                    stack.pop();
8005                    continue;
8006                };
8007                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
8008                match nxt_color {
8009                    Mark::Gray => {
8010                        // Reconstruct the cycle from `node` back through
8011                        // the parent chain to `nxt`, then close.
8012                        let mut cycle = Vec::new();
8013                        let mut cur = node;
8014                        cycle.push(cur.to_string());
8015                        while cur != nxt {
8016                            match parent.get(cur).copied() {
8017                                Some(p) => {
8018                                    cur = p;
8019                                    cycle.push(cur.to_string());
8020                                }
8021                                None => break,
8022                            }
8023                        }
8024                        cycle.reverse();
8025                        cycle.push(nxt.to_string());
8026                        return Err(AplicacaoError::ContratoCycle { cycle });
8027                    }
8028                    Mark::White => {
8029                        parent.insert(nxt, node);
8030                        color.insert(nxt, Mark::Gray);
8031                        let nxt_neighbors: Vec<&str> = adj
8032                            .get(nxt)
8033                            .map(|s| s.iter().copied().collect())
8034                            .unwrap_or_default();
8035                        stack.push((nxt, nxt_neighbors, 0));
8036                    }
8037                    Mark::Black => {}
8038                }
8039            }
8040        }
8041        Ok(())
8042    }
8043
8044    /// Substrate-canonical destination-facing TCP port every emitted
8045    /// per-Aplicacao artifact must key `destination`-shaped port axes
8046    /// off. Returns the typed `:entrada :port` scalar when this
8047    /// Aplicacao's `:entrada` block names `destination` under its
8048    /// `:para` axis (the destination Servico *is* the ingress apex, so
8049    /// the substrate honors the author-declared listener port
8050    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8051    /// fallback otherwise (every non-apex destination — the internal
8052    /// mesh Servicos `:contratos` reach across, the future per-edge
8053    /// policy resolver's per-destination probe targets, the
8054    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8055    /// L4 port resolver — reads the same substrate-canonical port floor
8056    /// by construction).
8057    ///
8058    /// Prior to this lift the "if :entrada matches this destination use
8059    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8060    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8061    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8062    /// prior to this lift), with no typed method on the substrate primitive
8063    /// that named the rule. A future per-destination port axis addition
8064    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8065    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8066    /// per-Servico listener ports land, a per-cluster override the operator
8067    /// pins through a future `:placement :default-port` slot — would have
8068    /// to be threaded through every renderer's inline cascade in lockstep
8069    /// or one consumer would silently disagree on which port a given
8070    /// destination Servico's ingress lands at. Lifting the rule to a
8071    /// typed method on the substrate primitive means the M4 CR
8072    /// materializer, the future per-edge policy resolver, and every
8073    /// downstream test-fixture navigator reach for exactly one typed
8074    /// dispatch — the resolver's accept-set moves as a unit on any
8075    /// future axis addition.
8076    ///
8077    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8078    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8079    /// the typed primitive, thin projections at each consumer"
8080    /// discipline lifts on the sibling `:contratos` payload / `:politicas
8081    /// :rate-limit` unit-suffix axes; extends the discipline onto the
8082    /// destination-facing port-resolution axis every per-Aplicacao
8083    /// L4-fallback renderer consumes.
8084    #[must_use]
8085    pub fn port_for_destination(&self, destination: &str) -> u16 {
8086        // Route the per-`:entrada` composite-reference read through
8087        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8088        // the raw `self.entrada.as_ref()` field access — the
8089        // per-destination L4-port fallback resolver's composite-
8090        // projection seed is now the canonical read-side surface
8091        // every per-Aplicacao entrada consumer routes through, peer
8092        // of the sibling `validate` per-`:entrada` shape-and-
8093        // membership gate migration on the same outer-composite
8094        // axis.
8095        // Route the per-`:entrada` apex-destination membership probe
8096        // through the lifted [`Entrada::destination`] accessor rather
8097        // than the raw `e.para == destination` field access — the last
8098        // un-lifted `.para` production-code read site on the per-
8099        // `:entrada` `:para` axis, sibling to the four caixa-core
8100        // consumer sites the peer 15ddd8c converge already routed
8101        // through the accessor (the three
8102        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8103        // membership gate sites: the `validate_entrada_para` DNS-1123
8104        // shape gate, the per-`:membros` membership lookup, and the
8105        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8106        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8107        // `entrada.para`-projection converge at
8108        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8109        // route-name projection site). Prior to this converge the
8110        // `port_for_destination` resolver was the solitary consumer
8111        // bypassing the typed dispatch on the `.para` axis — the two
8112        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8113        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8114        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8115        // reach through the same accessor family compose with this
8116        // resolver at the emit boundary via the apex-identity
8117        // invariant `spec.port_for_destination(entrada.destination())
8118        // == entrada.port` the sibling
8119        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8120        // pin pins across four permutations. A future extension of the
8121        // `:entrada :para` axis to a richer author surface (a per-
8122        // cluster alias overlay the operator pins through a future
8123        // `:placement`-scoped slot, a namespace-qualified rewrite the
8124        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8125        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8126        // §III.2 acknowledges) that lands on the accessor would silently
8127        // disagree between this resolver and the two `caixa-mesh` emit
8128        // sites — an author-declared `:para "cart"` value the accessor
8129        // rewrote to `"cart-v2"` under a future canary arm would leave
8130        // the resolver's membership arm falling through to
8131        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8132        // `.para`) while the peer emit-site consumers landed on the
8133        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8134        // silently disagreed on which destination port a given typed
8135        // `:entrada` resolves to at cluster-apply time. Pinned by the
8136        // drift-detection test
8137        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8138        // below.
8139        self.entrada()
8140            .filter(|e| e.destination() == destination)
8141            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8142    }
8143}
8144
8145/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8146/// entry may name the Aplicacao's own `:nome`.
8147///
8148/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8149/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8150/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8151/// Servicos that compose the app; an Aplicacao is never its own constituent),
8152/// and the lacre pipeline's closure-resolution would otherwise be handed a
8153/// node that is its own parent: a one-node cycle it either rejects far from
8154/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8155/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8156/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8157/// label + lacre closure root), a member whose `:caixa` equals the
8158/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8159/// peer.
8160///
8161/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8162/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8163/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8164/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8165/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8166/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8167/// (the Aplicacao :membros set; the supervision-tree :children list was the
8168/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8169/// every validated Supervisor's children are distinct from its `:nome`,
8170/// every validated Aplicacao's membros are distinct from its `:nome`. The
8171/// transitive consequence is that `:entrada :para` and `:contratos`
8172/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8173/// name the Aplicacao itself, without re-deriving the partition.
8174pub fn validate_no_self_membership(
8175    membros: &[Membro],
8176    parent_nome: &str,
8177) -> Result<(), AplicacaoError> {
8178    for m in membros {
8179        if m.nome() == parent_nome {
8180            return Err(AplicacaoError::MembroIsSelfAplicacao {
8181                caixa: parent_nome.to_string(),
8182            });
8183        }
8184    }
8185    Ok(())
8186}
8187
8188#[derive(Debug, Error, PartialEq, Eq)]
8189pub enum AplicacaoError {
8190    #[error("Aplicacao must declare at least one :membros entry")]
8191    NoMembros,
8192    #[error(
8193        ":membros entry has empty :caixa (every member must name a Servico; \
8194         omit the entry instead of carrying an empty name)"
8195    )]
8196    MembroCaixaEmpty,
8197    #[error(
8198        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8199         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8200         name / label value the member name lands in; use a lowercase \
8201         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8202    )]
8203    MembroCaixaInvalid { caixa: String, reason: String },
8204    #[error(
8205        ":membros entry {caixa:?} has empty :versao (every member must pin a \
8206         semver constraint that resolves through the lacre pipeline)"
8207    )]
8208    MembroVersaoEmpty { caixa: String },
8209    #[error(
8210        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8211         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8212         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8213         carries; the lacre pipeline resolves both through the same parser)"
8214    )]
8215    MembroVersaoInvalid {
8216        caixa: String,
8217        versao: String,
8218        reason: String,
8219    },
8220    #[error(
8221        ":membros entry {caixa:?} appears more than once (the graph node set \
8222         is a set, not a multiset; duplicate members produce duplicate \
8223         programs.yaml entries and ambiguous :contratos membership lookups)"
8224    )]
8225    MembroDuplicate { caixa: String },
8226    #[error(
8227        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8228         never its own constituent Servico (the application graph is a DAG rooted \
8229         at the Aplicacao; :membros names the *other* caixas that compose the \
8230         app, not the app itself). Since every :nome is a globally-unique \
8231         substrate identity, a member naming the Aplicacao's own :nome is a \
8232         one-node lacre-closure recursion, not a coincidentally-named peer; \
8233         drop the self-referential :membros entry or rename it to the actual \
8234         constituent caixa."
8235    )]
8236    MembroIsSelfAplicacao { caixa: String },
8237    #[error(
8238        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8239         caixa declared in :membros; omit the contract or fill the {slot} field with a \
8240         member name)"
8241    )]
8242    ContratoCaixaEmpty { slot: &'static str },
8243    #[error(
8244        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8245         :contratos {slot} value names a member of :membros, which is itself a \
8246         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8247         object the member name lands in — Service, Pod, identity-based Cilium \
8248         selector; use a lowercase alphanumeric + hyphen identifier like \
8249         `\"checkout\"` or `\"cart-v2\"`)"
8250    )]
8251    ContratoCaixaInvalid {
8252        slot: &'static str,
8253        caixa: String,
8254        reason: String,
8255    },
8256    #[error("contrato references caixa {caixa:?} not declared in :membros")]
8257    ContratoMemberMissing { caixa: String },
8258    #[error(
8259        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8260         entry is an inter-Servico contract whose :de and :para must name distinct \
8261         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8262         the contract, or point :para at the member it actually calls)"
8263    )]
8264    ContratoSelfLoop { caixa: String, wit: String },
8265    #[error("contrato {de:?} → {para:?} has empty :wit")]
8266    EmptyWit { de: String, para: String },
8267    #[error(
8268        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8269         {reason} (the substrate dispatches `:wit` values on the canonical \
8270         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8271         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8272         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8273         kebab-case identifier per segment)"
8274    )]
8275    ContratoWitInvalid {
8276        de: String,
8277        para: String,
8278        wit: String,
8279        reason: String,
8280    },
8281    #[error(
8282        ":entrada :para is empty (every :entrada must route to a caixa declared in \
8283         :membros; fill the :para field with a member name)"
8284    )]
8285    EntradaParaEmpty,
8286    #[error(
8287        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8288         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8289         label per the K8s apiserver's `metadata.name` rule on every object the \
8290         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8291         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8292         `\"checkout\"` or `\"cart-v2\"`)"
8293    )]
8294    EntradaParaInvalid { para: String, reason: String },
8295    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8296    EntradaMemberMissing { para: String },
8297    #[error(":entrada must declare a non-empty :host")]
8298    EmptyEntradaHost,
8299    #[error(
8300        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8301         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8302         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8303         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8304    )]
8305    EntradaHostInvalid { host: String, reason: String },
8306    #[error(":entrada :port must be in 1..=65535, got 0")]
8307    EntradaPortZero,
8308    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8309    EntradaPathEmpty,
8310    #[error(
8311        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8312    )]
8313    EntradaPathNotAbsolute { path: String },
8314    #[error(
8315        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8316         value: {reason} (the K8s apiserver enforces the same shape on \
8317         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8318         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8319         requires percent-encoding `%XX` for non-ASCII and whitespace)"
8320    )]
8321    EntradaPathInvalid { path: String, reason: String },
8322    #[error(":entrada :paths entry {path:?} appears more than once")]
8323    EntradaPathDuplicate { path: String },
8324    #[error(
8325        ":placement {estrategia} requires at least one :clusters entry \
8326         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8327    )]
8328    PlacementWithoutClusters { estrategia: PlacementStrategy },
8329    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8330    PlacementClusterEmpty,
8331    #[error(
8332        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8333         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8334         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8335         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8336         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8337         identifier like `\"rio\"` or `\"mar-east\"`)"
8338    )]
8339    PlacementClusterInvalid { cluster: String, reason: String },
8340    #[error(":placement :clusters entry {cluster:?} appears more than once")]
8341    PlacementClusterDuplicate { cluster: String },
8342    #[error(
8343        ":placement :affinity must be non-empty when set (omit :affinity to express \
8344         `no placement hint`)"
8345    )]
8346    PlacementAffinityEmpty,
8347    #[error(
8348        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8349         (placement hints land verbatim in the M3 Adaptive compression overlay's \
8350         `placement.affinity` field and in every future M4 placement-engine routing \
8351         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8352         selector — both enforce the DNS-1123 label rule on admission; use a \
8353         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8354         `\"low-latency\"`, or `\"anti-affinity\"`)"
8355    )]
8356    PlacementAffinityInvalid { affinity: String, reason: String },
8357    #[error(":placement Sharded requires :shard-key")]
8358    ShardedWithoutKey,
8359    #[error(
8360        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8361         hashes every entity onto the same shard, defeating sharding entirely)"
8362    )]
8363    ShardedKeyEmpty,
8364    #[error(
8365        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8366         entity-id extractor expression: {reason} (the future M4 Akka-style \
8367         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8368         as a single-token property reference and hashes the extracted entity ID \
8369         to compute shard placement; use a printable-ASCII extractor expression \
8370         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8371         `\"${{tenant}}\"`)"
8372    )]
8373    ShardKeyInvalid { shard_key: String, reason: String },
8374    #[error(
8375        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8376         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8377         convention); :estrategia Replicated runs every cluster active-active and \
8378         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8379         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8380         to :estrategia Sharded if hash-keyed routing is the intent"
8381    )]
8382    ShardKeyOnNonSharded {
8383        estrategia: PlacementStrategy,
8384        shard_key: String,
8385    },
8386    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8387    ContratoMissingTarget {
8388        de: String,
8389        para: String,
8390        wit: String,
8391        expected: &'static str,
8392    },
8393    #[error(
8394        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8395         expected `:{expected}` only"
8396    )]
8397    ContratoWrongTarget {
8398        de: String,
8399        para: String,
8400        wit: String,
8401        expected: &'static str,
8402    },
8403    #[error(
8404        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8405         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8406         that matches no traffic and silently drops every request)"
8407    )]
8408    ContratoEndpointEmpty { de: String, para: String },
8409    #[error(
8410        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8411         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8412         :entrada :paths)"
8413    )]
8414    ContratoEndpointNotAbsolute {
8415        de: String,
8416        para: String,
8417        endpoint: String,
8418    },
8419    #[error(
8420        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8421         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8422         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8423         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8424         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8425         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8426         and whitespace)"
8427    )]
8428    ContratoEndpointInvalid {
8429        de: String,
8430        para: String,
8431        endpoint: String,
8432        reason: String,
8433    },
8434    #[error(
8435        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8436         subject is a no-op subscribe; omit :subject only if the WIT world is not \
8437         pub-sub-shaped)"
8438    )]
8439    ContratoSubjectEmpty { de: String, para: String },
8440    #[error(
8441        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8442         NATS subject: {reason} (the NATS server's subject parser enforces the \
8443         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8444         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8445         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8446         `\"orders.*.completed\"` — a malformed subject silently drops every \
8447         message at runtime far from the source caixa.lisp)"
8448    )]
8449    ContratoSubjectInvalid {
8450        de: String,
8451        para: String,
8452        subject: String,
8453        reason: String,
8454    },
8455    #[error(
8456        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8457         addresses the bucket root, defeating the per-key isolation the slot exists \
8458         for; omit :slot only if the WIT world is not store-shaped)"
8459    )]
8460    ContratoSlotEmpty { de: String, para: String },
8461    #[error(
8462        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8463         WASI keyvalue store slot template: {reason} (the substrate enforces \
8464         the printable-ASCII intersection-floor every kv backend admits — \
8465         use a single-token path / template expression like `\"checkout/$orderId\"`, \
8466         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8467         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8468         slot either gets rejected on write by strict backends or silently \
8469         corrupts the next read on permissive ones, far from the source caixa.lisp)"
8470    )]
8471    ContratoSlotInvalid {
8472        de: String,
8473        para: String,
8474        slot: String,
8475        reason: String,
8476    },
8477    #[error(
8478        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
8479         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
8480        cycle.join(" → ")
8481    )]
8482    ContratoCycle { cycle: Vec<String> },
8483    #[error(
8484        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
8485         than once (the typed graph edges are a set, not a multiset; duplicate \
8486         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
8487         values that K8s admission rejects far from the source caixa.lisp)"
8488    )]
8489    ContratoDuplicate {
8490        de: String,
8491        para: String,
8492        wit: String,
8493        target: String,
8494    },
8495    #[error(
8496        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
8497         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
8498         express `no per-call deadline on this axis`"
8499    )]
8500    PolicyTimeoutZero,
8501    #[error(
8502        ":politicas :retries must be > 0 when set; omit :retries to express \
8503         `no retries on transient failure`"
8504    )]
8505    PolicyRetriesZero,
8506    #[error(
8507        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
8508         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
8509         retry policy into a thundering-herd amplification vector on transient \
8510         failure (one caller request fans out to `(retries+1)^depth` server-side \
8511         calls across the synchronous-:contratos subgraph), exactly the failure \
8512         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
8513         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
8514         or omit :retries to disable retries entirely"
8515    )]
8516    PolicyRetriesExceedsCap { retries: u32 },
8517    #[error(
8518        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
8519         breaker trips on the first call); omit :circuit-breaker to disable it"
8520    )]
8521    PolicyBreakerZeroFailures,
8522    #[error(
8523        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
8524         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
8525         above this cap turns the typed breaker policy into a no-op: the trip \
8526         threshold is structurally so high that no realistic failures-per-:window \
8527         traffic shape can reach it, so the breaker never trips and every typed-slot \
8528         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
8529         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
8530         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
8531         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
8532         omit :circuit-breaker to disable the breaker entirely"
8533    )]
8534    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
8535    #[error(
8536        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
8537         tracks no failures); omit :circuit-breaker to disable it"
8538    )]
8539    PolicyBreakerZeroWindow,
8540    #[error(
8541        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
8542         request); omit :rate-limit to disable rate limiting"
8543    )]
8544    PolicyRateLimitZero,
8545    #[error(
8546        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
8547         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
8548         rate-limit policy into a no-op limiter: the token-bucket capacity is \
8549         structurally so high that no realistic per-edge traffic shape can drain it, \
8550         so the limiter never trips and every typed-slot consumer (the future \
8551         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8552         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
8553         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
8554         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
8555         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
8556         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
8557         to disable rate limiting entirely"
8558    )]
8559    PolicyRateLimitExceedsCap { rate: u32 },
8560    #[error(
8561        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
8562         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
8563         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
8564         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
8565         three canonical windows)"
8566    )]
8567    PolicyRateLimitWindowNotCanonical { window: Duration },
8568    #[error(
8569        ":politicas :timeout must be an integer number of milliseconds — the canonical \
8570         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
8571         duration codec round-trips losslessly; got {timeout:?} which carries a \
8572         sub-millisecond residue that either truncates to a different `Duration` on \
8573         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
8574         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
8575         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
8576         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
8577    )]
8578    PolicyTimeoutNotCanonical { timeout: Duration },
8579    #[error(
8580        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
8581         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
8582         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
8583         overlays carry a deadline so long no realistic synchronous-:contratos \
8584         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
8585         CSE invariant degenerates to enforcement only at the per-Servico \
8586         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
8587         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
8588         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
8589         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
8590         maxes out at the same `3600s` ceiling) or omit :timeout to express \
8591         `no per-call deadline on this axis` (the synchronous-call deadline then \
8592         relies entirely on the per-Servico `:limits :wall-clock` axis)"
8593    )]
8594    PolicyTimeoutExceedsCap { timeout: Duration },
8595    #[error(
8596        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
8597         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
8598         the shared duration codec round-trips losslessly; got {window:?} which carries a \
8599         sub-millisecond residue that either truncates to a different `Duration` on \
8600         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
8601         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
8602    )]
8603    PolicyBreakerWindowNotCanonical { window: Duration },
8604    #[error(
8605        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
8606         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
8607         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
8608         is structurally so long that transient failures are never forgotten, the breaker \
8609         trips once and stays tripped for the lifetime of the component, and every typed-slot \
8610         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8611         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
8612         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
8613         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
8614         the breaker entirely"
8615    )]
8616    PolicyBreakerWindowExceedsCap { window: Duration },
8617}
8618
8619#[cfg(test)]
8620mod tests {
8621    use super::*;
8622
8623    fn membro(name: &str, ver: &str) -> Membro {
8624        Membro {
8625            caixa: name.into(),
8626            versao: ver.into(),
8627        }
8628    }
8629
8630    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
8631        WitContract {
8632            de: de.into(),
8633            para: para.into(),
8634            wit: "wasi:http/proxy".into(),
8635            endpoint: Some(ep.into()),
8636            subject: None,
8637            slot: None,
8638        }
8639    }
8640
8641    fn three_member_spec() -> AplicacaoSpec {
8642        AplicacaoSpec {
8643            membros: vec![
8644                membro("catalog", "^0.1"),
8645                membro("cart", "^0.1"),
8646                membro("payment", "^0.2"),
8647            ],
8648            contratos: vec![
8649                contract_http("cart", "catalog", "/products/:id"),
8650                contract_http("cart", "payment", "/charge"),
8651            ],
8652            politicas: MeshPolicy {
8653                timeout: Some(Duration::from_secs(30)),
8654                retries: Some(3),
8655                mtls_required: Some(true),
8656                ..Default::default()
8657            },
8658            placement: Placement {
8659                estrategia: PlacementStrategy::Replicated,
8660                clusters: vec!["rio".into(), "mar".into()],
8661                affinity: Some("data-locality".into()),
8662                shard_key: None,
8663            },
8664            entrada: Some(Entrada {
8665                host: "checkout.quero.cloud".into(),
8666                para: "cart".into(),
8667                paths: vec!["/api/cart".into(), "/api/products".into()],
8668                port: 8080,
8669            }),
8670        }
8671    }
8672
8673    #[test]
8674    fn happy_path_validates() {
8675        three_member_spec().validate().unwrap();
8676    }
8677
8678    #[test]
8679    fn rejects_empty_membros() {
8680        let mut s = three_member_spec();
8681        s.membros = vec![];
8682        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
8683    }
8684
8685    #[test]
8686    fn rejects_empty_membro_caixa() {
8687        // A `:caixa ""` entry has no name to render into programs.yaml
8688        // and no caixa.lisp to resolve at lacre time.
8689        let mut s = three_member_spec();
8690        s.membros[1].caixa = String::new();
8691        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
8692    }
8693
8694    #[test]
8695    fn rejects_empty_membro_versao() {
8696        // A `:versao ""` entry can't pin a semver constraint, so the
8697        // lacre pipeline fails far from the source.
8698        let mut s = three_member_spec();
8699        s.membros[2].versao = String::new();
8700        let err = s.validate().unwrap_err();
8701        assert!(
8702            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
8703            "got {err:?}"
8704        );
8705    }
8706
8707    #[test]
8708    fn rejects_duplicate_membro_caixa() {
8709        // Two `:membros` entries with the same `:caixa` collapse to one
8710        // node in the membership HashSet, which masks `:contratos`
8711        // membership errors and produces duplicate programs.yaml entries.
8712        let mut s = three_member_spec();
8713        s.membros.push(membro("cart", "^0.2"));
8714        let err = s.validate().unwrap_err();
8715        assert!(
8716            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8717            "got {err:?}"
8718        );
8719    }
8720
8721    #[test]
8722    fn rejects_invalid_membro_versao_requirement() {
8723        // The fail-before-pass-after pin: a non-empty but malformed
8724        // semver requirement (`"^bad-version"`) silently passed
8725        // `validate()` on every pre-gate codebase because the prior
8726        // shape only refused the empty string. The parse failure
8727        // surfaced far downstream at lacre-resolve time with a
8728        // `semver::Error` that didn't name which `:membros` entry
8729        // carried the typo. The new gate moves the check to caixa-build
8730        // time at the source caixa.lisp.
8731        let mut s = three_member_spec();
8732        s.membros[2].versao = "^bad-version".into();
8733        let err = s.validate().unwrap_err();
8734        assert!(
8735            matches!(
8736                err,
8737                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8738                    if caixa == "payment" && versao == "^bad-version"
8739            ),
8740            "got {err:?}"
8741        );
8742    }
8743
8744    #[test]
8745    fn rejects_membro_versao_with_double_caret_typo() {
8746        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
8747        // Cargo-shaped requirement on first glance but fails the parser
8748        // because semver doesn't accept stacked operators. Pin this
8749        // adjacent-shape footgun explicitly so a future relaxation that
8750        // accepts "looks-canonical-but-isn't" forms surfaces here.
8751        let mut s = three_member_spec();
8752        s.membros[0].versao = "^^0.1".into();
8753        let err = s.validate().unwrap_err();
8754        assert!(
8755            matches!(
8756                err,
8757                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8758                    if caixa == "catalog" && versao == "^^0.1"
8759            ),
8760            "got {err:?}"
8761        );
8762    }
8763
8764    #[test]
8765    fn rejects_membro_versao_with_v_prefixed_tag() {
8766        // `"v0.1"` is the canonical "git-tag-shape leaking into the
8767        // semver requirement slot" typo — an author copies the
8768        // publish-side git-tag string verbatim into `:versao`, but
8769        // Cargo's semver parser rejects the leading `v` (only digits +
8770        // canonical operators are valid in the major-version
8771        // position). The gate's diagnostic names which member entry
8772        // carried the v-prefix so the fix is one edit, not a grep
8773        // through every member's `:versao`. (Note: bare `x`-glob
8774        // shorthands like `^0.1.x` are *accepted* by the semver crate
8775        // as an `*` wildcard on the patch axis — they're a Cargo-side
8776        // valid shape, not a typo, so the gate intentionally lets them
8777        // through.)
8778        let mut s = three_member_spec();
8779        s.membros[1].versao = "v0.1".into();
8780        let err = s.validate().unwrap_err();
8781        assert!(
8782            matches!(
8783                err,
8784                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8785                    if caixa == "cart" && versao == "v0.1"
8786            ),
8787            "got {err:?}"
8788        );
8789    }
8790
8791    #[test]
8792    fn accepts_canonical_membro_versao_forms() {
8793        // The four Cargo-shaped requirement forms `:deps :versao`
8794        // already accepts via `crate::parse_requirement` must pass the
8795        // membros gate without re-validating at the resolver layer.
8796        // Pin every leg so a future tightening of the canonical set
8797        // surfaces here as a test failure.
8798        for form in [
8799            "^0.1",      // caret — minor-range pin (the most common shape)
8800            "~0.1.2",    // tilde — patch-range pin
8801            "0.1.0",     // exact — single-version pin
8802            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
8803            ">=0.1, <2", // multi-range — comma-separated comparators
8804        ] {
8805            let mut s = three_member_spec();
8806            for m in &mut s.membros {
8807                m.versao = form.into();
8808            }
8809            s.validate()
8810                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8811        }
8812    }
8813
8814    #[test]
8815    fn membro_versao_empty_takes_precedence_over_invalid() {
8816        // Order pin: the existing `MembroVersaoEmpty` diagnostic
8817        // (which doesn't try to parse) fires before the new
8818        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
8819        // `:versao` keeps its narrower error message — `parse_requirement`
8820        // would also reject `""`, but the empty-string arm is the more
8821        // self-locating diagnostic for the author.
8822        let mut s = three_member_spec();
8823        s.membros[1].versao = String::new();
8824        let err = s.validate().unwrap_err();
8825        assert!(
8826            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
8827            "got {err:?}"
8828        );
8829    }
8830
8831    #[test]
8832    fn membro_versao_invalid_fires_before_duplicate_check() {
8833        // Order pin: a malformed requirement on a non-duplicate entry
8834        // surfaces *its own* diagnostic (which names the offending
8835        // `:versao` string), even when a later entry would otherwise
8836        // collapse onto an earlier name. The per-entry shape gate runs
8837        // inline before the duplicate-key insert, parallel to
8838        // `membros_validation_runs_before_contratos_membership_check`
8839        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
8840        let mut s = three_member_spec();
8841        s.membros[0].versao = "^bad".into();
8842        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8843        let err = s.validate().unwrap_err();
8844        assert!(
8845            matches!(
8846                err,
8847                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
8848            ),
8849            "got {err:?}"
8850        );
8851    }
8852
8853    #[test]
8854    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
8855        // The diagnostic-shape pin: the error names the offending
8856        // `:versao` value verbatim so the author can grep their
8857        // caixa.lisp without re-running the build, and carries a
8858        // non-empty `reason` from `semver::VersionReq::parse` so the
8859        // parser's own wording flows through to the diagnostic.
8860        let mut s = three_member_spec();
8861        s.membros[2].versao = "not-a-req".into();
8862        let err = s.validate().unwrap_err();
8863        let AplicacaoError::MembroVersaoInvalid {
8864            caixa,
8865            versao,
8866            reason,
8867        } = err
8868        else {
8869            panic!("expected MembroVersaoInvalid, got other variant");
8870        };
8871        assert_eq!(caixa, "payment");
8872        assert_eq!(versao, "not-a-req");
8873        assert!(
8874            !reason.is_empty(),
8875            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
8876        );
8877    }
8878
8879    #[test]
8880    fn membro_versao_invalid_runs_before_contratos_check() {
8881        // A malformed `:versao` on any member must surface its own
8882        // diagnostic (which names *which* member to fix) before any
8883        // `:contratos` membership lookup raises `ContratoMemberMissing`.
8884        // The `:contratos` gate runs after `validate_membros`, so this
8885        // is structurally guaranteed — pin it explicitly so a future
8886        // refactor that reorders the gates surfaces here.
8887        let mut s = three_member_spec();
8888        s.membros[1].versao = "^^0.1".into();
8889        // Add a contrato whose `:para` doesn't exist — would normally
8890        // raise ContratoMemberMissing at the membership lookup, but
8891        // the membros gate must fire first.
8892        s.contratos
8893            .push(contract_http("cart", "phantom", "/never-reached"));
8894        let err = s.validate().unwrap_err();
8895        assert!(
8896            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
8897            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
8898        );
8899    }
8900
8901    #[test]
8902    fn membros_validation_runs_before_contratos_membership_check() {
8903        // If `:membros` carries a duplicate, the membership-collapse
8904        // would silently accept a `:contratos :para "phantom"` so long
8905        // as some entry hashes to "phantom". Pinning order: the
8906        // duplicate-membros error fires first, regardless of whether
8907        // contratos reference real members.
8908        let mut s = three_member_spec();
8909        s.membros = vec![
8910            membro("cart", "^0.1"),
8911            membro("cart", "^0.2"),
8912            membro("catalog", "^0.1"),
8913            membro("payment", "^0.1"),
8914        ];
8915        let err = s.validate().unwrap_err();
8916        assert!(
8917            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8918            "got {err:?}"
8919        );
8920    }
8921
8922    #[test]
8923    fn distinct_membros_validate() {
8924        // Pin the happy-path: every `:membros` entry has a non-empty
8925        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
8926        // The fixture already satisfies this; this test makes the
8927        // invariant explicit so a future refactor of the fixture can't
8928        // silently break the guarantee.
8929        three_member_spec().validate().unwrap();
8930    }
8931
8932    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
8933
8934    #[test]
8935    fn rejects_membro_caixa_with_uppercase() {
8936        // The canonical "I copied the Servico's display name verbatim"
8937        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
8938        // but author tools often round-trip a TitleCase or CamelCase
8939        // identifier from an ADR or a sketch. Pin the diagnostic names
8940        // the offending name and suggests the lower-cased fix in one
8941        // edit, mirroring the `rejects_entrada_host_with_uppercase`
8942        // gate's shape (c7d05ec).
8943        let mut s = three_member_spec();
8944        s.membros[1].caixa = "Cart".into();
8945        let err = s.validate().unwrap_err();
8946        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
8947            panic!("expected MembroCaixaInvalid, got other variant");
8948        };
8949        assert_eq!(caixa, "Cart");
8950        assert!(
8951            reason.contains("uppercase"),
8952            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
8953        );
8954        assert!(
8955            reason.contains("\"cart\""),
8956            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
8957        );
8958    }
8959
8960    #[test]
8961    fn rejects_membro_caixa_with_underscore() {
8962        // The canonical "I'm thinking of a Python module / Postgres
8963        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
8964        // label schema. K8s rejects `metadata.name: my_cart` at admission
8965        // time with an opaque `field is invalid` (no source-citing
8966        // diagnostic). The gate moves it to caixa-build time.
8967        let mut s = three_member_spec();
8968        s.membros[0].caixa = "my_cart".into();
8969        let err = s.validate().unwrap_err();
8970        assert!(
8971            matches!(
8972                err,
8973                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8974                    if caixa == "my_cart" && reason.contains('_')
8975            ),
8976            "got {err:?}"
8977        );
8978    }
8979
8980    #[test]
8981    fn rejects_membro_caixa_with_dot() {
8982        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
8983        // subdomain — even though K8s `metadata.name` itself accepts
8984        // dots (DNS-1123 subdomain rule), this string also lands as a
8985        // K8s Service name (DNS-1035 label — no dots) and as a label
8986        // value on identity-based Cilium selectors. The strictest floor
8987        // among the use sites wins. The "I want to namespace my member
8988        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
8989        let mut s = three_member_spec();
8990        s.membros[2].caixa = "team.cart".into();
8991        let err = s.validate().unwrap_err();
8992        assert!(
8993            matches!(
8994                err,
8995                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
8996                    if caixa == "team.cart" && reason.contains('.')
8997            ),
8998            "got {err:?}"
8999        );
9000    }
9001
9002    #[test]
9003    fn rejects_membro_caixa_with_leading_hyphen() {
9004        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
9005        // with an alphanumeric. The K8s apiserver rejects `-cart`
9006        // outright; the renderer would emit a `metadata.name: "-cart"`
9007        // that fails admission far from the source caixa.lisp.
9008        let mut s = three_member_spec();
9009        s.membros[0].caixa = "-cart".into();
9010        let err = s.validate().unwrap_err();
9011        assert!(
9012            matches!(
9013                err,
9014                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9015                    if caixa == "-cart" && reason.contains("start and end")
9016            ),
9017            "got {err:?}"
9018        );
9019    }
9020
9021    #[test]
9022    fn rejects_membro_caixa_with_trailing_hyphen() {
9023        // The symmetric arm of the boundary rule. Pin separately so
9024        // both ends of the label are covered against a future relaxation
9025        // that only checks one boundary.
9026        let mut s = three_member_spec();
9027        s.membros[1].caixa = "cart-".into();
9028        let err = s.validate().unwrap_err();
9029        assert!(
9030            matches!(
9031                err,
9032                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9033                    if caixa == "cart-"
9034            ),
9035            "got {err:?}"
9036        );
9037    }
9038
9039    #[test]
9040    fn rejects_membro_caixa_with_unicode() {
9041        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9042        // (`xn--…`) by the author before it reaches K8s. The byte-by-
9043        // byte ASCII validity check rejects multi-byte UTF-8 sequences
9044        // by the first byte that fails the `[a-z0-9-]` predicate.
9045        let mut s = three_member_spec();
9046        s.membros[2].caixa = "café".into();
9047        let err = s.validate().unwrap_err();
9048        assert!(
9049            matches!(
9050                err,
9051                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9052                    if caixa == "café"
9053            ),
9054            "got {err:?}"
9055        );
9056    }
9057
9058    #[test]
9059    fn rejects_membro_caixa_with_whitespace() {
9060        // Whitespace is the canonical "I pasted from a sketch / doc"
9061        // footgun. The apiserver rejects every `metadata.name` value
9062        // carrying whitespace; pin the gate fires at the right boundary.
9063        let mut s = three_member_spec();
9064        s.membros[0].caixa = "my cart".into();
9065        let err = s.validate().unwrap_err();
9066        assert!(
9067            matches!(
9068                err,
9069                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9070                    if caixa == "my cart"
9071            ),
9072            "got {err:?}"
9073        );
9074    }
9075
9076    #[test]
9077    fn rejects_membro_caixa_too_long() {
9078        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
9079        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
9080        // exactly. The gate's reason names both the cap and the actual
9081        // length so the author can shorten in one edit.
9082        let mut s = three_member_spec();
9083        let too_long = "a".repeat(64);
9084        s.membros[1].caixa = too_long.clone();
9085        let err = s.validate().unwrap_err();
9086        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9087            panic!("expected MembroCaixaInvalid");
9088        };
9089        assert_eq!(caixa, too_long);
9090        assert!(
9091            reason.contains("63") && reason.contains("64"),
9092            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
9093        );
9094    }
9095
9096    #[test]
9097    fn membro_caixa_max_length_validates() {
9098        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
9099        // so a future tightening (e.g. dropping to 62) surfaces here as
9100        // a regression, mirroring `entrada_host_max_length_validates`
9101        // (c7d05ec).
9102        let mut s = three_member_spec();
9103        s.membros[2].caixa = "a".repeat(63);
9104        s.entrada.as_mut().unwrap().para = "a".repeat(63);
9105        // remove contratos referencing the renamed member; they'd
9106        // raise ContratoMemberMissing otherwise
9107        s.contratos
9108            .retain(|c| c.de != "payment" && c.para != "payment");
9109        s.validate().unwrap();
9110    }
9111
9112    #[test]
9113    fn accepts_canonical_membro_caixa_forms() {
9114        // The DNS-1123 label shapes a caixa author is realistically
9115        // going to write: single-word lowercase, hyphen-joined, ending
9116        // in a digit-suffixed version (`cart-v2`), starting with a
9117        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
9118        // DNS-1035 which requires a letter at position 0), single-
9119        // character (`a` — boundary). Pin every leg so a future
9120        // tightening that bans (e.g.) digit-start identifiers surfaces
9121        // here.
9122        for form in [
9123            "checkout",
9124            "cart",
9125            "cart-v2",
9126            "a",
9127            "c0",
9128            "3rd-party-shim",
9129            "x-1-2-3-4",
9130        ] {
9131            let mut s = three_member_spec();
9132            // Renaming a member also requires updating downstream refs;
9133            // drop everything else and rebuild a minimal spec around
9134            // just the one renamed member.
9135            s.membros = vec![membro(form, "^0.1")];
9136            s.contratos = vec![];
9137            s.entrada = None;
9138            s.validate()
9139                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
9140        }
9141    }
9142
9143    #[test]
9144    fn membro_caixa_empty_takes_precedence_over_invalid() {
9145        // Order pin: the existing `MembroCaixaEmpty` diagnostic
9146        // (which doesn't try to parse) fires before the new
9147        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
9148        // `:caixa` keeps its narrower error message — the new gate
9149        // would also reject `""`, but the empty-string arm is the more
9150        // self-locating diagnostic for the author. Mirrors the
9151        // `entrada_host_empty_takes_precedence_over_invalid` pin
9152        // (c7d05ec).
9153        let mut s = three_member_spec();
9154        s.membros[1].caixa = String::new();
9155        let err = s.validate().unwrap_err();
9156        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
9157    }
9158
9159    #[test]
9160    fn membro_caixa_invalid_fires_before_versao_check() {
9161        // Order pin: an invalid-shape `:caixa` surfaces *its own*
9162        // diagnostic (which names the offending caixa name), even when
9163        // the same entry's `:versao` is also empty/invalid. The shape
9164        // gate runs first because the diagnostic is more self-locating —
9165        // an empty/invalid `:versao` on an invalid-shape caixa name is
9166        // a downstream-fix-after-the-caixa-rename concern.
9167        let mut s = three_member_spec();
9168        s.membros[1].caixa = "Cart".into();
9169        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
9170        let err = s.validate().unwrap_err();
9171        assert!(
9172            matches!(
9173                err,
9174                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
9175            ),
9176            "got {err:?}"
9177        );
9178    }
9179
9180    #[test]
9181    fn membro_caixa_invalid_fires_before_duplicate_check() {
9182        // Order pin: a malformed-shape `:caixa` on an earlier entry
9183        // surfaces *its own* diagnostic, even when a later entry would
9184        // otherwise collapse onto a duplicate name. The per-entry shape
9185        // gate runs inline before the duplicate-key insert, parallel
9186        // to `membro_versao_invalid_fires_before_duplicate_check`.
9187        let mut s = three_member_spec();
9188        s.membros[0].caixa = "Catalog".into();
9189        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
9190        let err = s.validate().unwrap_err();
9191        assert!(
9192            matches!(
9193                err,
9194                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
9195            ),
9196            "got {err:?}"
9197        );
9198    }
9199
9200    #[test]
9201    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
9202        // The diagnostic-shape pin: the error names the offending
9203        // `:caixa` value verbatim so the author can grep their
9204        // caixa.lisp without re-running the build, and carries a
9205        // non-empty `reason` naming the specific violation. Same
9206        // shape every typed-shape gate enshrines (c7d05ec's
9207        // `entrada_host_diagnostic_carries_offending_host`,
9208        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
9209        let mut s = three_member_spec();
9210        s.membros[2].caixa = "BAD_NAME".into();
9211        let err = s.validate().unwrap_err();
9212        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9213            panic!("expected MembroCaixaInvalid");
9214        };
9215        assert_eq!(caixa, "BAD_NAME");
9216        assert!(
9217            !reason.is_empty(),
9218            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
9219        );
9220    }
9221
9222    #[test]
9223    fn rejects_contrato_with_unknown_de() {
9224        let mut s = three_member_spec();
9225        s.contratos.push(contract_http("phantom", "catalog", "/x"));
9226        let err = s.validate().unwrap_err();
9227        assert!(
9228            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9229        );
9230    }
9231
9232    #[test]
9233    fn rejects_contrato_with_unknown_para() {
9234        let mut s = three_member_spec();
9235        s.contratos.push(contract_http("cart", "phantom", "/x"));
9236        let err = s.validate().unwrap_err();
9237        assert!(
9238            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9239        );
9240    }
9241
9242    #[test]
9243    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
9244        // The read-path pin: the phantom-`:de` refusal arm's
9245        // `ContratoMemberMissing.caixa` carrier must be observed through
9246        // the lifted [`WitContract::source`] accessor, not the raw
9247        // `.de.clone()` field-access `String`-carry. Peer of the sibling
9248        // per-`:contratos` self-loop arm's `.source().to_string()` /
9249        // `.world_ref().to_string()` `String`-carry sites the earlier
9250        // convergence lifted onto the same accessor pair. A future
9251        // silent detour that reintroduced the raw `.de.clone()` at the
9252        // wrap envelope while the shape-gate and membership lookup
9253        // routed through the accessor would surface here as a byte-equal
9254        // miss between the fired diagnostic's `caixa:` field and the
9255        // offending edge's `.source()` — pinning the accessor as the
9256        // sole read path across the phantom-name refusal arm's arg +
9257        // wrap-envelope emit surface.
9258        let mut s = three_member_spec();
9259        let phantom = contract_http("phantom", "catalog", "/x");
9260        s.contratos.push(phantom.clone());
9261        let err = s.validate().unwrap_err();
9262        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9263            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
9264        };
9265        assert_eq!(
9266            caixa,
9267            phantom.source(),
9268            "ContratoMemberMissing.caixa on the phantom-:de arm must \
9269             byte-equal WitContract::source — the wrap envelope must \
9270             route through the lifted accessor rather than the raw \
9271             .de.clone() field-access String-carry"
9272        );
9273    }
9274
9275    #[test]
9276    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9277        // The symmetric read-path pin on the `:para` phantom-name
9278        // refusal arm — same shape as the sibling `:de` pin above but
9279        // on the callee-Servico axis. Pins the wrap envelope's
9280        // `caixa:` field is observed through the lifted
9281        // [`WitContract::destination`] accessor, not the raw
9282        // `.para.clone()` field-access `String`-carry.
9283        let mut s = three_member_spec();
9284        let phantom = contract_http("cart", "phantom", "/x");
9285        s.contratos.push(phantom.clone());
9286        let err = s.validate().unwrap_err();
9287        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9288            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
9289        };
9290        assert_eq!(
9291            caixa,
9292            phantom.destination(),
9293            "ContratoMemberMissing.caixa on the phantom-:para arm must \
9294             byte-equal WitContract::destination — the wrap envelope \
9295             must route through the lifted accessor rather than the raw \
9296             .para.clone() field-access String-carry"
9297        );
9298    }
9299
9300    #[test]
9301    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
9302        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
9303        // refusal arm — the `validate_contrato_caixa` arg must be
9304        // observed through the lifted [`WitContract::source`] accessor,
9305        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
9306        // value routes through the shared
9307        // [`crate::render::require_valid_dns_1123_label`] floor with the
9308        // accessor-projected value; the fired
9309        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
9310        // the offending edge's `.source()`, pinning that the arg + the
9311        // downstream `caixa: caixa.to_string()` wrap route through the
9312        // same accessor's read path.
9313        let mut s = three_member_spec();
9314        let malformed = contract_http("BAD_NAME", "catalog", "/x");
9315        s.contratos.push(malformed.clone());
9316        let err = s.validate().unwrap_err();
9317        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9318            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
9319        };
9320        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9321        assert_eq!(
9322            caixa,
9323            malformed.source(),
9324            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
9325             byte-equal WitContract::source — the shape-gate arg + wrap \
9326             envelope must route through the lifted accessor rather \
9327             than the raw &c.de &String-borrow"
9328        );
9329    }
9330
9331    #[test]
9332    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9333        // Symmetric arm to the sibling `:de` malformed-shape pin above,
9334        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
9335        // route through the lifted [`WitContract::destination`]
9336        // accessor. `:para` runs after the `:de` shape gate in the
9337        // canonical edge-direction order, so the `:de` value must be
9338        // well-shaped for the `:para` gate to fire — the `cart` :de is
9339        // canonical.
9340        let mut s = three_member_spec();
9341        let malformed = contract_http("cart", "BAD_NAME", "/x");
9342        s.contratos.push(malformed.clone());
9343        let err = s.validate().unwrap_err();
9344        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9345            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
9346        };
9347        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9348        assert_eq!(
9349            caixa,
9350            malformed.destination(),
9351            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
9352             byte-equal WitContract::destination — the shape-gate arg + \
9353             wrap envelope must route through the lifted accessor \
9354             rather than the raw &c.para &String-borrow"
9355        );
9356    }
9357
9358    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
9359
9360    #[test]
9361    fn rejects_contrato_de_empty() {
9362        // `:de ""` previously fell through to `ContratoMemberMissing`
9363        // (with `caixa: ""`) because the validated `:membros :caixa`
9364        // set never contains the empty string. The narrower
9365        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
9366        // the offending slot.
9367        let mut s = three_member_spec();
9368        s.contratos.push(contract_http("", "catalog", "/x"));
9369        let err = s.validate().unwrap_err();
9370        assert_eq!(
9371            err,
9372            AplicacaoError::ContratoCaixaEmpty {
9373                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9374            },
9375            "got {err:?}"
9376        );
9377    }
9378
9379    #[test]
9380    fn rejects_contrato_para_empty() {
9381        // Symmetric arm to `:de ""` — `:para ""` previously fell
9382        // through to `ContratoMemberMissing { caixa: "" }`.
9383        let mut s = three_member_spec();
9384        s.contratos.push(contract_http("cart", "", "/x"));
9385        let err = s.validate().unwrap_err();
9386        assert_eq!(
9387            err,
9388            AplicacaoError::ContratoCaixaEmpty {
9389                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9390            },
9391            "got {err:?}"
9392        );
9393    }
9394
9395    #[test]
9396    fn rejects_contrato_de_with_uppercase() {
9397        // The canonical "I copied the Servico's TitleCase display
9398        // name from an ADR" typo. Until this gate landed `:de "Cart"`
9399        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
9400        // as "this caixa isn't in `:membros`" when the root cause is
9401        // "this `:de` value's shape can never legitimately match a
9402        // validated member (DNS-1123 labels are lowercase)". The
9403        // narrower diagnostic names the offending slot, the value
9404        // verbatim, and the parser-shaped reason.
9405        let mut s = three_member_spec();
9406        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9407        let err = s.validate().unwrap_err();
9408        let AplicacaoError::ContratoCaixaInvalid {
9409            slot,
9410            caixa,
9411            reason,
9412        } = err
9413        else {
9414            panic!("expected ContratoCaixaInvalid, got other variant");
9415        };
9416        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9417        assert_eq!(caixa, "Cart");
9418        assert!(
9419            reason.contains("uppercase"),
9420            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9421        );
9422    }
9423
9424    #[test]
9425    fn rejects_contrato_para_with_underscore() {
9426        // The canonical "I'm thinking of a Python module" leak —
9427        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9428        // Pin the `:para` axis surfaces the same diagnostic shape as
9429        // the `:de` axis on the underscore violation.
9430        let mut s = three_member_spec();
9431        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
9432        let err = s.validate().unwrap_err();
9433        assert!(
9434            matches!(
9435                err,
9436                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9437                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
9438            ),
9439            "got {err:?}"
9440        );
9441    }
9442
9443    #[test]
9444    fn rejects_contrato_de_with_dot() {
9445        // A `:contratos :de` value is a single DNS-1123 *label*, not
9446        // a subdomain — mirroring the `:membros :caixa` floor. The
9447        // strictest floor among the use sites wins.
9448        let mut s = three_member_spec();
9449        s.contratos
9450            .push(contract_http("team.cart", "catalog", "/x"));
9451        let err = s.validate().unwrap_err();
9452        assert!(
9453            matches!(
9454                err,
9455                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9456                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
9457            ),
9458            "got {err:?}"
9459        );
9460    }
9461
9462    #[test]
9463    fn rejects_contrato_para_with_unicode() {
9464        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9465        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
9466        // validity check rejects multi-byte UTF-8 by the first
9467        // non-`[a-z0-9-]` byte.
9468        let mut s = three_member_spec();
9469        s.contratos.push(contract_http("cart", "café", "/x"));
9470        let err = s.validate().unwrap_err();
9471        assert!(
9472            matches!(
9473                err,
9474                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9475                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
9476            ),
9477            "got {err:?}"
9478        );
9479    }
9480
9481    #[test]
9482    fn rejects_contrato_de_with_leading_hyphen() {
9483        // DNS-1123 boundary rule: labels must start and end with an
9484        // alphanumeric. K8s rejects `-cart` outright; the narrower
9485        // shape diagnostic now names the violation at caixa-build
9486        // time rather than the misframed membership-lookup arm.
9487        let mut s = three_member_spec();
9488        s.contratos.push(contract_http("-cart", "catalog", "/x"));
9489        let err = s.validate().unwrap_err();
9490        assert!(
9491            matches!(
9492                err,
9493                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9494                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
9495            ),
9496            "got {err:?}"
9497        );
9498    }
9499
9500    #[test]
9501    fn contrato_de_empty_takes_precedence_over_invalid() {
9502        // Order pin: the `ContratoCaixaEmpty` arm fires before the
9503        // `ContratoCaixaInvalid` parse-side arm — same empty-first
9504        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9505        // / `validate_entrada_host` already establish on their peer
9506        // name axes. The empty string is a structurally distinct
9507        // authoring footgun (the author left the field blank, vs.
9508        // typed a malformed value), so it gets its own diagnostic.
9509        let mut s = three_member_spec();
9510        s.contratos.push(contract_http("", "catalog", "/x"));
9511        let err = s.validate().unwrap_err();
9512        assert_eq!(
9513            err,
9514            AplicacaoError::ContratoCaixaEmpty {
9515                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9516            }
9517        );
9518    }
9519
9520    #[test]
9521    fn contrato_de_shape_fires_before_para_shape() {
9522        // Per-axis order pin: within one `:contratos` entry, the `:de`
9523        // shape gate fires before the `:para` shape gate — same
9524        // edge-direction order the existing `ContratoMemberMissing` /
9525        // `ContratoSelfLoop` / target-dispatch checks use, so the
9526        // diagnostic for a contract with both `:de` and `:para`
9527        // malformed is stable. Authors fixing the surfaced `:de`
9528        // first will see `:para`'s diagnostic on re-run.
9529        let mut s = three_member_spec();
9530        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
9531        let err = s.validate().unwrap_err();
9532        assert!(
9533            matches!(
9534                err,
9535                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9536                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9537            ),
9538            "got {err:?}"
9539        );
9540    }
9541
9542    #[test]
9543    fn contrato_shape_fires_before_membership_lookup() {
9544        // The load-bearing pin: an invalid-shape `:de` surfaces its
9545        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
9546        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9547        // an invalid-shape `:de` could never legitimately match any
9548        // member — the prior `ContratoMemberMissing` diagnostic was
9549        // a structural impossibility framed as a graph-membership
9550        // failure. The shape gate now routes every such input through
9551        // the narrower self-locating diagnostic.
9552        let mut s = three_member_spec();
9553        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9554        let err = s.validate().unwrap_err();
9555        assert!(
9556            matches!(
9557                err,
9558                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
9559            ),
9560            "got {err:?}"
9561        );
9562        // And the symmetric case: an invalid-shape `:para` surfaces
9563        // its own diagnostic too, even when `:de` is well-shaped.
9564        let mut s = three_member_spec();
9565        s.contratos.push(contract_http("cart", "Catalog", "/x"));
9566        let err = s.validate().unwrap_err();
9567        assert!(
9568            matches!(
9569                err,
9570                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
9571            ),
9572            "got {err:?}"
9573        );
9574    }
9575
9576    #[test]
9577    fn contrato_shape_fires_before_self_edge_check() {
9578        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
9579        // bugs: the shape violation (uppercase) and the self-edge
9580        // violation. The narrower per-axis shape diagnostic surfaces
9581        // first because fixing the shape may reveal that the author
9582        // also meant to point `:para` at a different member — the
9583        // self-edge framing is only useful once both endpoints have
9584        // valid shape.
9585        let mut s = three_member_spec();
9586        s.contratos.push(contract_http("Cart", "Cart", "/x"));
9587        let err = s.validate().unwrap_err();
9588        assert!(
9589            matches!(
9590                err,
9591                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9592                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9593            ),
9594            "got {err:?}"
9595        );
9596    }
9597
9598    #[test]
9599    fn contrato_well_shaped_phantom_still_raises_member_missing() {
9600        // Strict-improvement pin: a well-shaped `:de` that simply
9601        // isn't in `:membros` (a phantom reference — author meant
9602        // to add the member but didn't, or renamed and missed an
9603        // update) still surfaces `ContratoMemberMissing`, unchanged.
9604        // The shape gate only intercepts inputs that could never
9605        // legitimately match a validated member; legitimately-shaped
9606        // phantom references remain on the graph-membership axis.
9607        let mut s = three_member_spec();
9608        s.contratos
9609            .push(contract_http("phantom-shim", "catalog", "/x"));
9610        let err = s.validate().unwrap_err();
9611        assert!(
9612            matches!(
9613                err,
9614                AplicacaoError::ContratoMemberMissing { ref caixa }
9615                    if caixa == "phantom-shim"
9616            ),
9617            "got {err:?}"
9618        );
9619    }
9620
9621    #[test]
9622    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
9623        // The diagnostic-shape pin: the error names the offending
9624        // slot (`:de` or `:para`) verbatim and the offending value
9625        // verbatim plus a non-empty parser-shaped reason, so the
9626        // author can grep their caixa.lisp for `:de "<name>"` /
9627        // `:para "<name>"` and fix it in one edit. Same diagnostic
9628        // shape as `MembroCaixaInvalid` (3f9d7a0) and
9629        // `PlacementClusterInvalid` (6c8c00b).
9630        let mut s = three_member_spec();
9631        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
9632        let err = s.validate().unwrap_err();
9633        let AplicacaoError::ContratoCaixaInvalid {
9634            slot,
9635            caixa,
9636            reason,
9637        } = err
9638        else {
9639            panic!("expected ContratoCaixaInvalid, got {err:?}");
9640        };
9641        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9642        assert_eq!(caixa, "BAD_NAME");
9643        assert!(
9644            !reason.is_empty(),
9645            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
9646        );
9647    }
9648
9649    #[test]
9650    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
9651        // Scalar-value pin: the two author-facing kebab-case labels the
9652        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
9653        // admits on the `:contratos` per-entry endpoint-shape axis,
9654        // one arm per typed sub-slot. Mirrors the peer scalar-value
9655        // pin the sibling top-level M2 / M3 / Supervisor
9656        // author-facing-label consts carry
9657        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
9658        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
9659        // slot itself), so every altitude of the typed-slot algebra
9660        // shares the same "one canonical byte-string per arm"
9661        // discipline. A future rebrand (`:de` → `:from` matching the
9662        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
9663        // sibling, `:para` → `:to` matching the same, or
9664        // `:de`/`:para` → `:source`/`:target` matching the WIT
9665        // world's `import`/`export` half-vocabulary) lands as an
9666        // edit to exactly one const, and every consumer that reaches
9667        // for the label picks it up at build time rather than at
9668        // runtime as a downstream `ContratoCaixaEmpty` /
9669        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
9670        // diagnostic mismatch far from the rename's commit.
9671        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
9672        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
9673    }
9674
9675    #[test]
9676    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
9677        // Production-through-const pin: the two per-axis labels the
9678        // per-`:contratos` entry endpoint-shape gate at
9679        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
9680        // argument to [`validate_contrato_caixa`] route through the
9681        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
9682        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
9683        // future rebrand that reaches the const but not the gate (or
9684        // vice versa) surfaces here at build time rather than at
9685        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
9686        // `slot: <stale-kebab-case>` diagnostic far from the rename's
9687        // commit. Mirror of the peer
9688        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
9689        // pin (882f498) on the sibling M3 top-level slot axis.
9690        let mut s = three_member_spec();
9691        s.contratos.push(contract_http("", "catalog", "/x"));
9692        assert_eq!(
9693            s.validate().unwrap_err(),
9694            AplicacaoError::ContratoCaixaEmpty {
9695                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9696            }
9697        );
9698        let mut s = three_member_spec();
9699        s.contratos.push(contract_http("cart", "", "/x"));
9700        assert_eq!(
9701            s.validate().unwrap_err(),
9702            AplicacaoError::ContratoCaixaEmpty {
9703                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9704            }
9705        );
9706    }
9707
9708    #[test]
9709    fn accepts_canonical_contrato_caixa_forms() {
9710        // The DNS-1123 label shapes a caixa author is realistically
9711        // going to write on a `:contratos :de` / `:para`. Pin every
9712        // leg so a future tightening that bans (e.g.) digit-start
9713        // identifiers surfaces here, mirroring
9714        // `accepts_canonical_membro_caixa_forms` on the peer name
9715        // axis.
9716        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9717            let mut s = three_member_spec();
9718            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
9719            s.contratos = vec![contract_http("checkout", form, "/x")];
9720            s.entrada = None;
9721            s.validate().unwrap_or_else(|e| {
9722                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
9723            });
9724
9725            let mut s = three_member_spec();
9726            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9727            s.contratos = vec![contract_http(form, "catalog", "/x")];
9728            s.entrada = None;
9729            s.validate().unwrap_or_else(|e| {
9730                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
9731            });
9732        }
9733    }
9734
9735    #[test]
9736    fn rejects_empty_wit() {
9737        let mut s = three_member_spec();
9738        s.contratos.push(WitContract {
9739            de: "cart".into(),
9740            para: "catalog".into(),
9741            wit: "".into(),
9742            endpoint: None,
9743            subject: None,
9744            slot: None,
9745        });
9746        let err = s.validate().unwrap_err();
9747        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
9748    }
9749
9750    #[test]
9751    fn rejects_entrada_to_unknown_member() {
9752        let mut s = three_member_spec();
9753        s.entrada.as_mut().unwrap().para = "phantom".into();
9754        assert!(matches!(
9755            s.validate().unwrap_err(),
9756            AplicacaoError::EntradaMemberMissing { .. }
9757        ));
9758    }
9759
9760    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
9761
9762    #[test]
9763    fn rejects_entrada_para_empty() {
9764        // `:para ""` previously fell through to
9765        // `EntradaMemberMissing { para: "" }` because the validated
9766        // `:membros :caixa` set never contains the empty string. The
9767        // narrower `EntradaParaEmpty` diagnostic now names the
9768        // offending slot directly — same empty-first cascade
9769        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
9770        // `ContratoCaixaEmpty` establish on the peer name axes.
9771        let mut s = three_member_spec();
9772        s.entrada.as_mut().unwrap().para = String::new();
9773        let err = s.validate().unwrap_err();
9774        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
9775    }
9776
9777    #[test]
9778    fn rejects_entrada_para_with_uppercase() {
9779        // The canonical "I copied the Servico's TitleCase display
9780        // name from an ADR" typo. Until this gate landed `:para "Cart"`
9781        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
9782        // as "this caixa isn't in `:membros`" when the root cause is
9783        // "this `:para` value's shape can never legitimately match a
9784        // validated member (DNS-1123 labels are lowercase)". The
9785        // narrower diagnostic names the value verbatim plus the
9786        // parser-shaped reason.
9787        let mut s = three_member_spec();
9788        s.entrada.as_mut().unwrap().para = "Cart".into();
9789        let err = s.validate().unwrap_err();
9790        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9791            panic!("expected EntradaParaInvalid, got other variant");
9792        };
9793        assert_eq!(para, "Cart");
9794        assert!(
9795            reason.contains("uppercase"),
9796            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9797        );
9798    }
9799
9800    #[test]
9801    fn rejects_entrada_para_with_underscore() {
9802        // The canonical "I'm thinking of a Python module" leak —
9803        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9804        let mut s = three_member_spec();
9805        s.entrada.as_mut().unwrap().para = "my_cart".into();
9806        let err = s.validate().unwrap_err();
9807        assert!(
9808            matches!(
9809                err,
9810                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9811                    if para == "my_cart" && reason.contains('_')
9812            ),
9813            "got {err:?}"
9814        );
9815    }
9816
9817    #[test]
9818    fn rejects_entrada_para_with_dot() {
9819        // An `:entrada :para` value is a single DNS-1123 *label*, not
9820        // a subdomain — mirroring the `:membros :caixa` floor. The
9821        // strictest floor among the use sites wins.
9822        let mut s = three_member_spec();
9823        s.entrada.as_mut().unwrap().para = "team.cart".into();
9824        let err = s.validate().unwrap_err();
9825        assert!(
9826            matches!(
9827                err,
9828                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9829                    if para == "team.cart" && reason.contains('.')
9830            ),
9831            "got {err:?}"
9832        );
9833    }
9834
9835    #[test]
9836    fn rejects_entrada_para_with_unicode() {
9837        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9838        // (`xn--…`) before it reaches K8s.
9839        let mut s = three_member_spec();
9840        s.entrada.as_mut().unwrap().para = "café".into();
9841        let err = s.validate().unwrap_err();
9842        assert!(
9843            matches!(
9844                err,
9845                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
9846            ),
9847            "got {err:?}"
9848        );
9849    }
9850
9851    #[test]
9852    fn rejects_entrada_para_with_leading_hyphen() {
9853        // DNS-1123 boundary rule: labels must start and end with an
9854        // alphanumeric. K8s rejects `-cart` outright.
9855        let mut s = three_member_spec();
9856        s.entrada.as_mut().unwrap().para = "-cart".into();
9857        let err = s.validate().unwrap_err();
9858        assert!(
9859            matches!(
9860                err,
9861                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9862                    if para == "-cart" && reason.contains("start and end")
9863            ),
9864            "got {err:?}"
9865        );
9866    }
9867
9868    #[test]
9869    fn rejects_entrada_para_with_trailing_hyphen() {
9870        // Symmetric boundary arm.
9871        let mut s = three_member_spec();
9872        s.entrada.as_mut().unwrap().para = "cart-".into();
9873        let err = s.validate().unwrap_err();
9874        assert!(
9875            matches!(
9876                err,
9877                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9878                    if para == "cart-" && reason.contains("start and end")
9879            ),
9880            "got {err:?}"
9881        );
9882    }
9883
9884    #[test]
9885    fn rejects_entrada_para_too_long() {
9886        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
9887        // bytes per label. K8s rejects longer names at admission on
9888        // every `metadata.name` axis.
9889        let mut s = three_member_spec();
9890        s.entrada.as_mut().unwrap().para = "a".repeat(64);
9891        let err = s.validate().unwrap_err();
9892        assert!(
9893            matches!(
9894                err,
9895                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9896                    if para.len() == 64 && reason.contains("max length")
9897            ),
9898            "got {err:?}"
9899        );
9900    }
9901
9902    #[test]
9903    fn entrada_para_empty_takes_precedence_over_invalid() {
9904        // Order pin: the `EntradaParaEmpty` arm fires before the
9905        // `EntradaParaInvalid` parse-side arm — same empty-first
9906        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9907        // / `validate_contrato_caixa` already establish.
9908        let mut s = three_member_spec();
9909        s.entrada.as_mut().unwrap().para = String::new();
9910        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
9911    }
9912
9913    #[test]
9914    fn entrada_para_shape_fires_before_membership_lookup() {
9915        // The load-bearing pin: an invalid-shape `:para` surfaces its
9916        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
9917        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9918        // an invalid-shape `:para` could never legitimately match any
9919        // member — the prior `EntradaMemberMissing` diagnostic framed
9920        // a structural impossibility as a graph-membership failure.
9921        let mut s = three_member_spec();
9922        s.entrada.as_mut().unwrap().para = "Cart".into();
9923        let err = s.validate().unwrap_err();
9924        assert!(
9925            matches!(
9926                err,
9927                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9928            ),
9929            "got {err:?}"
9930        );
9931    }
9932
9933    #[test]
9934    fn entrada_para_shape_fires_before_host_gate() {
9935        // Per-`:entrada` order pin: the `:para` shape gate fires
9936        // before the `:host` gate, mirroring the existing
9937        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
9938        // ordering where the member-lookup arm preceded the host gate.
9939        // The shape gate slots ahead of that, so a malformed `:para`
9940        // surfaces its own diagnostic even when `:host` is also wrong.
9941        let mut s = three_member_spec();
9942        let e = s.entrada.as_mut().unwrap();
9943        e.para = "Cart".into();
9944        e.host = "BAD HOST".into();
9945        let err = s.validate().unwrap_err();
9946        assert!(
9947            matches!(
9948                err,
9949                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
9950            ),
9951            "got {err:?}"
9952        );
9953    }
9954
9955    #[test]
9956    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
9957        // Strict-improvement pin: a well-shaped `:para` that simply
9958        // isn't in `:membros` (a phantom reference — author meant to
9959        // add the member but didn't, or renamed and missed an
9960        // update) still surfaces `EntradaMemberMissing`, unchanged.
9961        // The shape gate only intercepts inputs that could never
9962        // legitimately match a validated member.
9963        let mut s = three_member_spec();
9964        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
9965        let err = s.validate().unwrap_err();
9966        assert!(
9967            matches!(
9968                err,
9969                AplicacaoError::EntradaMemberMissing { ref para }
9970                    if para == "phantom-shim"
9971            ),
9972            "got {err:?}"
9973        );
9974    }
9975
9976    #[test]
9977    fn entrada_para_invalid_diagnostic_carries_offending_para() {
9978        // The diagnostic-shape pin: the error names the offending
9979        // `:para` value verbatim plus a non-empty parser-shaped
9980        // reason, so the author can grep their caixa.lisp for
9981        // `:para "<name>"` and fix it in one edit. Same diagnostic
9982        // shape as `MembroCaixaInvalid` (3f9d7a0),
9983        // `PlacementClusterInvalid` (6c8c00b), and
9984        // `ContratoCaixaInvalid` (8d5af6b).
9985        let mut s = three_member_spec();
9986        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
9987        let err = s.validate().unwrap_err();
9988        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9989            panic!("expected EntradaParaInvalid, got {err:?}");
9990        };
9991        assert_eq!(para, "BAD_NAME");
9992        assert!(
9993            !reason.is_empty(),
9994            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
9995        );
9996    }
9997
9998    #[test]
9999    fn accepts_canonical_entrada_para_forms() {
10000        // Positive-control sweep covering the DNS-1123 label shapes a
10001        // caixa author is realistically going to write on `:entrada
10002        // :para`. Pin every leg so a future tightening that bans
10003        // (e.g.) digit-start identifiers surfaces here, mirroring
10004        // `accepts_canonical_membro_caixa_forms` and
10005        // `accepts_canonical_contrato_caixa_forms` on the peer name
10006        // axes.
10007        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
10008            let mut s = three_member_spec();
10009            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
10010            s.contratos = vec![contract_http(form, "catalog", "/x")];
10011            s.entrada = Some(Entrada {
10012                host: "checkout.quero.cloud".into(),
10013                para: form.into(),
10014                paths: vec!["/api".into()],
10015                port: 8080,
10016            });
10017            s.validate().unwrap_or_else(|e| {
10018                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
10019            });
10020        }
10021    }
10022
10023    #[test]
10024    fn rejects_replicated_without_clusters() {
10025        let mut s = three_member_spec();
10026        s.placement.clusters = vec![];
10027        assert!(matches!(
10028            s.validate().unwrap_err(),
10029            AplicacaoError::PlacementWithoutClusters { .. }
10030        ));
10031    }
10032
10033    #[test]
10034    fn rejects_sharded_without_key() {
10035        let mut s = three_member_spec();
10036        s.placement.estrategia = PlacementStrategy::Sharded;
10037        s.placement.shard_key = None;
10038        s.placement.clusters = vec!["rio".into()];
10039        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
10040    }
10041
10042    #[test]
10043    fn sharded_with_key_validates() {
10044        let mut s = three_member_spec();
10045        s.placement.estrategia = PlacementStrategy::Sharded;
10046        s.placement.shard_key = Some("$tenantId".into());
10047        s.validate().unwrap();
10048    }
10049
10050    #[test]
10051    fn round_trip_via_json_preserves_shape() {
10052        let s = three_member_spec();
10053        let json = serde_json::to_string(&s.membros).unwrap();
10054        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
10055        assert_eq!(back, s.membros);
10056
10057        let json = serde_json::to_string(&s.contratos).unwrap();
10058        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
10059        assert_eq!(back, s.contratos);
10060
10061        let json = serde_json::to_string(&s.placement).unwrap();
10062        let back: Placement = serde_json::from_str(&json).unwrap();
10063        assert_eq!(back, s.placement);
10064
10065        let json = serde_json::to_string(&s.entrada).unwrap();
10066        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
10067        assert_eq!(back, s.entrada);
10068    }
10069
10070    #[test]
10071    fn rate_limit_round_trip_seconds() {
10072        let policy = MeshPolicy {
10073            rate_limit: Some(RateLimit {
10074                rate: 100,
10075                window: Duration::from_secs(1),
10076            }),
10077            ..Default::default()
10078        };
10079        let json = serde_json::to_string(&policy).unwrap();
10080        assert!(json.contains("\"100/s\""));
10081        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10082        assert_eq!(back.rate_limit.unwrap().rate, 100);
10083        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
10084    }
10085
10086    #[test]
10087    fn rate_limit_round_trip_minutes() {
10088        let policy = MeshPolicy {
10089            rate_limit: Some(RateLimit {
10090                rate: 5000,
10091                window: Duration::from_secs(60),
10092            }),
10093            ..Default::default()
10094        };
10095        let json = serde_json::to_string(&policy).unwrap();
10096        assert!(json.contains("\"5000/m\""));
10097    }
10098
10099    #[test]
10100    fn circuit_breaker_round_trip() {
10101        let policy = MeshPolicy {
10102            circuit_breaker: Some(CircuitBreaker {
10103                max_failures: 5,
10104                window: Duration::from_secs(60),
10105            }),
10106            ..Default::default()
10107        };
10108        let json = serde_json::to_string(&policy).unwrap();
10109        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10110        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
10111        assert_eq!(
10112            back.circuit_breaker.unwrap().window,
10113            Duration::from_secs(60)
10114        );
10115    }
10116
10117    #[test]
10118    fn rejects_http_contrato_without_endpoint() {
10119        let mut s = three_member_spec();
10120        s.contratos.push(WitContract {
10121            de: "cart".into(),
10122            para: "catalog".into(),
10123            wit: "wasi:http/proxy".into(),
10124            endpoint: None,
10125            subject: None,
10126            slot: None,
10127        });
10128        let err = s.validate().unwrap_err();
10129        assert!(matches!(
10130            err,
10131            AplicacaoError::ContratoMissingTarget {
10132                expected: WitTarget::HTTP_FIELD_NAME,
10133                ..
10134            }
10135        ));
10136    }
10137
10138    #[test]
10139    fn rejects_http_contrato_with_subject() {
10140        let mut s = three_member_spec();
10141        s.contratos.push(WitContract {
10142            de: "cart".into(),
10143            para: "catalog".into(),
10144            wit: "wasi:http/proxy".into(),
10145            endpoint: Some("/x".into()),
10146            subject: Some("not.allowed.here".into()),
10147            slot: None,
10148        });
10149        let err = s.validate().unwrap_err();
10150        assert!(matches!(
10151            err,
10152            AplicacaoError::ContratoWrongTarget {
10153                expected: WitTarget::HTTP_FIELD_NAME,
10154                ..
10155            }
10156        ));
10157    }
10158
10159    #[test]
10160    fn rejects_pubsub_contrato_without_subject() {
10161        let mut s = three_member_spec();
10162        s.contratos.push(WitContract {
10163            de: "cart".into(),
10164            para: "catalog".into(),
10165            wit: "nats:pub-sub".into(),
10166            endpoint: None,
10167            subject: None,
10168            slot: None,
10169        });
10170        let err = s.validate().unwrap_err();
10171        assert!(matches!(
10172            err,
10173            AplicacaoError::ContratoMissingTarget {
10174                expected: WitTarget::PUBSUB_FIELD_NAME,
10175                ..
10176            }
10177        ));
10178    }
10179
10180    #[test]
10181    fn rejects_pubsub_contrato_with_endpoint() {
10182        let mut s = three_member_spec();
10183        s.contratos.push(WitContract {
10184            de: "cart".into(),
10185            para: "catalog".into(),
10186            wit: "kafka:topic".into(),
10187            endpoint: Some("/wrong".into()),
10188            subject: Some("topic.x".into()),
10189            slot: None,
10190        });
10191        let err = s.validate().unwrap_err();
10192        assert!(matches!(
10193            err,
10194            AplicacaoError::ContratoWrongTarget {
10195                expected: WitTarget::PUBSUB_FIELD_NAME,
10196                ..
10197            }
10198        ));
10199    }
10200
10201    #[test]
10202    fn rejects_store_contrato_without_slot() {
10203        let mut s = three_member_spec();
10204        s.contratos.push(WitContract {
10205            de: "cart".into(),
10206            para: "catalog".into(),
10207            wit: "wasi:keyvalue/store".into(),
10208            endpoint: None,
10209            subject: None,
10210            slot: None,
10211        });
10212        let err = s.validate().unwrap_err();
10213        assert!(matches!(
10214            err,
10215            AplicacaoError::ContratoMissingTarget {
10216                expected: WitTarget::STORE_FIELD_NAME,
10217                ..
10218            }
10219        ));
10220    }
10221
10222    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
10223
10224    #[test]
10225    fn rejects_http_contrato_with_empty_endpoint() {
10226        // `Some("")` for an HTTP endpoint passes the presence check
10227        // (target() previously returned WitTarget::Http { endpoint: "" })
10228        // but renders as a `path: ""` Cilium L7 rule that matches no
10229        // traffic. Same value-shape footgun closed for :entrada :paths
10230        // entries (eb3456d).
10231        let mut s = three_member_spec();
10232        s.contratos.push(WitContract {
10233            de: "cart".into(),
10234            para: "catalog".into(),
10235            wit: "wasi:http/proxy".into(),
10236            endpoint: Some(String::new()),
10237            subject: None,
10238            slot: None,
10239        });
10240        let err = s.validate().unwrap_err();
10241        assert!(
10242            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
10243                if de == "cart" && para == "catalog"),
10244            "got {err:?}"
10245        );
10246    }
10247
10248    #[test]
10249    fn rejects_http_contrato_with_relative_endpoint() {
10250        // Cilium L7 :path + Gateway API PathPrefix both require a
10251        // leading `/`. Same shape required of :entrada :paths
10252        // (eb3456d). Lifted into target() so every consumer of the
10253        // typed WitTarget view inherits the guarantee.
10254        let mut s = three_member_spec();
10255        s.contratos.push(WitContract {
10256            de: "cart".into(),
10257            para: "catalog".into(),
10258            wit: "wasi:http/proxy".into(),
10259            endpoint: Some("products/:id".into()),
10260            subject: None,
10261            slot: None,
10262        });
10263        let err = s.validate().unwrap_err();
10264        assert!(
10265            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10266                if endpoint == "products/:id"),
10267            "got {err:?}"
10268        );
10269    }
10270
10271    #[test]
10272    fn rejects_pubsub_contrato_with_empty_subject() {
10273        // NATS / Kafka publish without a subject is a no-op subscribe;
10274        // never the author's intent. Same empty-string rejection as
10275        // :membros :caixa, :placement :clusters entries, :entrada
10276        // :paths entries — every value carried by every typed slot is
10277        // value-shape-checked at validate().
10278        let mut s = three_member_spec();
10279        s.contratos.push(WitContract {
10280            de: "cart".into(),
10281            para: "catalog".into(),
10282            wit: "nats:pub-sub".into(),
10283            endpoint: None,
10284            subject: Some(String::new()),
10285            slot: None,
10286        });
10287        let err = s.validate().unwrap_err();
10288        assert!(
10289            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
10290                if de == "cart" && para == "catalog"),
10291            "got {err:?}"
10292        );
10293    }
10294
10295    #[test]
10296    fn rejects_store_contrato_with_empty_slot() {
10297        // An empty slot template addresses the bucket root, defeating
10298        // the per-key isolation the slot exists for — a footgun on
10299        // `wasi:keyvalue/store` whose closest analog is the empty
10300        // shard-key rejected on :placement Sharded (c7c7799).
10301        let mut s = three_member_spec();
10302        s.contratos.push(WitContract {
10303            de: "cart".into(),
10304            para: "catalog".into(),
10305            wit: "wasi:keyvalue/store".into(),
10306            endpoint: None,
10307            subject: None,
10308            slot: Some(String::new()),
10309        });
10310        let err = s.validate().unwrap_err();
10311        assert!(
10312            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
10313                if de == "cart" && para == "catalog"),
10314            "got {err:?}"
10315        );
10316    }
10317
10318    #[test]
10319    fn http_contrato_root_endpoint_validates() {
10320        // Pin the boundary case: a single-`/` endpoint is the catch-all
10321        // form the Gateway HTTPRoute renderer falls back to when
10322        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
10323        // must remain a valid contrato endpoint too.
10324        let mut s = three_member_spec();
10325        s.contratos.push(contract_http("cart", "catalog", "/"));
10326        s.validate().unwrap();
10327    }
10328
10329    // ── :contratos :endpoint value-shape gate ────────────────────────────
10330    //
10331    // Mirrors the `:entrada :paths` value-shape suite on the peer
10332    // HTTP-path axis. Until this gate landed `WitContract::target()`
10333    // only refused the empty string + the missing-leading-`/` form
10334    // (c4213a4); a structurally invalid endpoint passed validate and
10335    // landed verbatim as a Cilium L7 `path:` rule
10336    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
10337    // traffic or was rejected at apply time by Cilium policy admission.
10338    // Every authoring footgun the K8s Gateway API webhook / Cilium
10339    // policy validator would catch on admission now becomes a caixa-
10340    // build-time `ContratoEndpointInvalid` with the offending
10341    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
10342    // shape as `EntradaPathInvalid` on the sibling axis; same shared
10343    // predicate (`crate::render::is_gateway_api_http_path`) ensures
10344    // drift between the two axes' rule enforcement is a build error
10345    // at the predicate.
10346
10347    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
10348        // Fresh spec per call so the would-be-duplicate edge
10349        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
10350        // `three_member_spec`'s pre-existing
10351        // `(cart, catalog, …, /products/:id)` entry — only the
10352        // endpoint payload differs.
10353        let mut s = three_member_spec();
10354        s.contratos.push(contract_http("cart", "catalog", ep));
10355        s.validate().unwrap_err()
10356    }
10357
10358    #[test]
10359    fn rejects_http_contrato_endpoint_with_query() {
10360        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
10361        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
10362        // rule the L7 matcher would never satisfy.
10363        let err = contrato_endpoint_err("/charge?token=X");
10364        assert!(
10365            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10366                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
10367            "got {err:?}"
10368        );
10369    }
10370
10371    #[test]
10372    fn rejects_http_contrato_endpoint_with_fragment() {
10373        let err = contrato_endpoint_err("/charge#frag");
10374        assert!(
10375            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10376                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
10377            "got {err:?}"
10378        );
10379    }
10380
10381    #[test]
10382    fn rejects_http_contrato_endpoint_with_whitespace() {
10383        let err = contrato_endpoint_err("/foo bar");
10384        assert!(
10385            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10386                if endpoint == "/foo bar" && reason.contains("whitespace")),
10387            "got {err:?}"
10388        );
10389    }
10390
10391    #[test]
10392    fn rejects_http_contrato_endpoint_with_control_char() {
10393        let err = contrato_endpoint_err("/api/\x01bar");
10394        assert!(
10395            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10396                if endpoint == "/api/\x01bar" && reason.contains("control character")),
10397            "got {err:?}"
10398        );
10399    }
10400
10401    #[test]
10402    fn rejects_http_contrato_endpoint_with_non_ascii() {
10403        let err = contrato_endpoint_err("/api/café");
10404        assert!(
10405            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10406                if endpoint == "/api/café" && reason.contains("non-ASCII")),
10407            "got {err:?}"
10408        );
10409    }
10410
10411    #[test]
10412    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
10413        let err = contrato_endpoint_err("/api//cart");
10414        assert!(
10415            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10416                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
10417            "got {err:?}"
10418        );
10419    }
10420
10421    #[test]
10422    fn rejects_http_contrato_endpoint_with_dot_segment() {
10423        let err = contrato_endpoint_err("/api/./cart");
10424        assert!(
10425            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10426                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
10427            "got {err:?}"
10428        );
10429    }
10430
10431    #[test]
10432    fn rejects_http_contrato_endpoint_with_parent_segment() {
10433        // Path-traversal in a contrato endpoint is the canonical
10434        // "L7 rule that the workload's HTTP server's path-resolution
10435        // logic interprets differently than the policy enforcer"
10436        // footgun. Rejected outright at validate time.
10437        let err = contrato_endpoint_err("/api/../etc");
10438        assert!(
10439            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10440                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
10441            "got {err:?}"
10442        );
10443    }
10444
10445    #[test]
10446    fn rejects_http_contrato_endpoint_too_long() {
10447        // 1025-byte endpoint — one over the Gateway API
10448        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
10449        // path matcher has no inherent length limit but the policy
10450        // CR itself rides through the K8s apiserver, which enforces
10451        // ConfigMap-shaped limits; sharing the Gateway API cap is the
10452        // conservative floor.
10453        let big = format!("/api/{}", "a".repeat(1020));
10454        assert_eq!(big.len(), 1025);
10455        let err = contrato_endpoint_err(&big);
10456        assert!(
10457            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10458                if endpoint == &big && reason.contains("max length of 1024")),
10459            "got {err:?}"
10460        );
10461    }
10462
10463    #[test]
10464    fn http_contrato_endpoint_max_length_validates() {
10465        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
10466        // in the cap surfaces here and at
10467        // `rejects_http_contrato_endpoint_too_long` simultaneously,
10468        // mirroring `entrada_path_max_length_validates` on the peer
10469        // axis.
10470        let big = format!("/api/{}", "a".repeat(1019));
10471        assert_eq!(big.len(), 1024);
10472        let mut s = three_member_spec();
10473        s.contratos.push(contract_http("cart", "catalog", &big));
10474        s.validate().unwrap();
10475    }
10476
10477    #[test]
10478    fn http_contrato_endpoint_accepts_canonical_forms() {
10479        // Positive-set sweep: every canonical HTTP-path shape the
10480        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
10481        // plain paths, hidden-file-style `.config` segments distinct
10482        // from the `.` segment, digit-bearing segments, the canonical
10483        // route-template `:param` form, trailing-slash form,
10484        // percent-encoded segments, the `/foo..bar` interior-`..`-
10485        // substring forms that are NOT `..` segments) must remain a
10486        // valid contrato endpoint too. Drift between this list and
10487        // the entrada path positive sweep surfaces at the shared
10488        // `is_gateway_api_http_path` substrate-side suite — one
10489        // source of truth. Uses a fresh `(payment, catalog)` edge so
10490        // none of the swept endpoints collide with the pre-existing
10491        // `(cart, catalog, /products/:id)` / `(cart, payment,
10492        // /charge)` entries in `three_member_spec`.
10493        for ep in [
10494            "/",
10495            "/charge",
10496            "/v1/charge",
10497            "/api/.config",
10498            "/products/:id",
10499            "/api/cart/",
10500            "/api/caf%C3%A9",
10501            "/foo..bar",
10502            "/...",
10503        ] {
10504            let mut s = three_member_spec();
10505            s.contratos.push(contract_http("payment", "catalog", ep));
10506            s.validate()
10507                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
10508        }
10509    }
10510
10511    #[test]
10512    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
10513        // Ordering pin: `ContratoEndpointEmpty` is the more self-
10514        // locating diagnostic on `""` and must lead — the value-
10515        // shape gate is only reached after the empty-check fires.
10516        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
10517        // on the peer axis.
10518        let mut s = three_member_spec();
10519        s.contratos.push(WitContract {
10520            de: "cart".into(),
10521            para: "catalog".into(),
10522            wit: "wasi:http/proxy".into(),
10523            endpoint: Some(String::new()),
10524            subject: None,
10525            slot: None,
10526        });
10527        let err = s.validate().unwrap_err();
10528        assert!(
10529            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
10530            "got {err:?}"
10531        );
10532    }
10533
10534    #[test]
10535    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
10536        // Ordering pin: an endpoint without a leading `/` surfaces the
10537        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
10538        // value-shape gate is only consulted on endpoints that already
10539        // satisfy the absolute-prefix invariant. Mirrors
10540        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
10541        let err = contrato_endpoint_err("bad path");
10542        assert!(
10543            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10544                if endpoint == "bad path"),
10545            "got {err:?}"
10546        );
10547    }
10548
10549    #[test]
10550    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
10551        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
10552        // `:para` + a non-empty reason flow through verbatim so the
10553        // author can grep their caixa.lisp for the offending contrato
10554        // block and fix it in one edit. Same shape as
10555        // `entrada_path_diagnostic_carries_offending_path`.
10556        let err = contrato_endpoint_err("/api?q=1");
10557        match err {
10558            AplicacaoError::ContratoEndpointInvalid {
10559                de,
10560                para,
10561                endpoint,
10562                reason,
10563            } => {
10564                assert_eq!(de, "cart");
10565                assert_eq!(para, "catalog");
10566                assert_eq!(endpoint, "/api?q=1");
10567                assert!(!reason.is_empty(), "reason field must be non-empty");
10568            }
10569            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
10570        }
10571    }
10572
10573    #[test]
10574    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
10575        // The compounding theorem: every &str inside a WitTarget
10576        // returned by target() is non-empty (and absolute, for Http).
10577        // Renderers downstream of typed_view() can rely on this
10578        // without re-checking — the type system carries the proof.
10579        let http = contract_http("cart", "catalog", "/x");
10580        match http.target().unwrap() {
10581            WitTarget::Http { endpoint } => {
10582                assert!(!endpoint.is_empty());
10583                assert!(endpoint.starts_with('/'));
10584            }
10585            other => panic!("expected Http, got {other:?}"),
10586        }
10587        let nats = WitContract {
10588            de: "a".into(),
10589            para: "b".into(),
10590            wit: "nats:pub-sub".into(),
10591            endpoint: None,
10592            subject: Some("topic.x".into()),
10593            slot: None,
10594        };
10595        match nats.target().unwrap() {
10596            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
10597            other => panic!("expected PubSub, got {other:?}"),
10598        }
10599        let kv = WitContract {
10600            de: "a".into(),
10601            para: "b".into(),
10602            wit: "wasi:keyvalue/store".into(),
10603            endpoint: None,
10604            subject: None,
10605            slot: Some("checkout/$orderId".into()),
10606        };
10607        match kv.target().unwrap() {
10608            WitTarget::Store { slot } => assert!(!slot.is_empty()),
10609            other => panic!("expected Store, got {other:?}"),
10610        }
10611    }
10612
10613    #[test]
10614    fn target_diagnostic_names_offending_endpoint_value() {
10615        // When the malformed endpoint string is non-trivial, the
10616        // diagnostic carries the actual value back to the author —
10617        // not a generic "endpoint malformed" error.
10618        let bad = WitContract {
10619            de: "src".into(),
10620            para: "dst".into(),
10621            wit: "wasi:http/proxy".into(),
10622            endpoint: Some("api/v1/charge".into()),
10623            subject: None,
10624            slot: None,
10625        };
10626        match bad.target().unwrap_err() {
10627            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
10628                assert_eq!(de, "src");
10629                assert_eq!(para, "dst");
10630                assert_eq!(endpoint, "api/v1/charge");
10631            }
10632            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
10633        }
10634    }
10635
10636    #[test]
10637    fn rejects_unknown_wit_with_target_set() {
10638        let mut s = three_member_spec();
10639        s.contratos.push(WitContract {
10640            de: "cart".into(),
10641            para: "catalog".into(),
10642            wit: "custom:exchange".into(),
10643            endpoint: Some("/leaked".into()),
10644            subject: None,
10645            slot: None,
10646        });
10647        let err = s.validate().unwrap_err();
10648        assert!(matches!(
10649            err,
10650            AplicacaoError::ContratoWrongTarget {
10651                expected: WitTarget::CAPABILITY_EXPECTED,
10652                ..
10653            }
10654        ));
10655    }
10656
10657    #[test]
10658    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
10659        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
10660        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
10661        // fourth arm of the same "which payload field name goes in the
10662        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
10663        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10664        // consts cover on the peer HTTP / PubSub / Store arms
10665        // (`wit_target_field_name_pins_per_variant`). Until this lift
10666        // landed the byte-string sat twice — once inline in the
10667        // [`WitContract::target`] Capability-arm rejection at the
10668        // production dispatch, once in `rejects_unknown_wit_with_target_set`
10669        // pinning against the same literal — with no compile-time link
10670        // between them. Same "one canonical declaration, next to the
10671        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
10672        // lift established for the payload-less arm's human-readable
10673        // label axis; this test is the shape peer of
10674        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
10675        // pair (routes-through-const + scalar-value pin) on the
10676        // wrong-target diagnostic-scalar axis.
10677        //
10678        // Fail-before-pass-after was verified locally by mutating the
10679        // const declaration to `"capability"` — the scalar-value pin
10680        // below fires (`"capability" != "none"`) and the routes-through
10681        // assertion below still holds (production and const walk in
10682        // lockstep), which is the correct behavior: a rename on the
10683        // const drifts here first, not at a downstream consumer.
10684        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
10685
10686        let mut s = three_member_spec();
10687        s.contratos.push(WitContract {
10688            de: "cart".into(),
10689            para: "catalog".into(),
10690            wit: "custom:exchange".into(),
10691            endpoint: Some("/leaked".into()),
10692            subject: None,
10693            slot: None,
10694        });
10695        match s.validate().unwrap_err() {
10696            AplicacaoError::ContratoWrongTarget { expected, .. } => {
10697                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
10698            }
10699            other => panic!("expected ContratoWrongTarget, got {other:?}"),
10700        }
10701    }
10702
10703    #[test]
10704    fn unknown_wit_capability_only_validates() {
10705        let mut s = three_member_spec();
10706        s.contratos.push(WitContract {
10707            de: "cart".into(),
10708            para: "catalog".into(),
10709            // A WIT world we haven't yet shaped — accept it as a typed
10710            // capability edge so authors aren't blocked while the WIT
10711            // registry catches up. No payload field may be carried.
10712            wit: "custom:exchange".into(),
10713            endpoint: None,
10714            subject: None,
10715            slot: None,
10716        });
10717        s.validate().unwrap();
10718        let added = s.contratos.last().unwrap();
10719        assert_eq!(added.target().unwrap(), WitTarget::Capability);
10720    }
10721
10722    #[test]
10723    fn target_typed_view_round_trips_each_shape() {
10724        let http = contract_http("cart", "catalog", "/products/:id");
10725        assert_eq!(
10726            http.target().unwrap(),
10727            WitTarget::Http {
10728                endpoint: "/products/:id"
10729            }
10730        );
10731        let nats = WitContract {
10732            de: "a".into(),
10733            para: "b".into(),
10734            wit: "nats:pub-sub".into(),
10735            endpoint: None,
10736            subject: Some("topic.x".into()),
10737            slot: None,
10738        };
10739        assert_eq!(
10740            nats.target().unwrap(),
10741            WitTarget::PubSub { subject: "topic.x" }
10742        );
10743        let kv = WitContract {
10744            de: "a".into(),
10745            para: "b".into(),
10746            wit: "wasi:keyvalue/store".into(),
10747            endpoint: None,
10748            subject: None,
10749            slot: Some("checkout/$orderId".into()),
10750        };
10751        assert_eq!(
10752            kv.target().unwrap(),
10753            WitTarget::Store {
10754                slot: "checkout/$orderId"
10755            }
10756        );
10757    }
10758
10759    #[test]
10760    fn wit_contract_kind_predicates() {
10761        let http = contract_http("a", "b", "/x");
10762        assert!(http.is_http());
10763        assert!(!http.is_pubsub());
10764        assert!(!http.is_store());
10765        assert!(!http.is_capability());
10766
10767        let nats = WitContract {
10768            de: "a".into(),
10769            para: "b".into(),
10770            wit: "nats:pub-sub".into(),
10771            endpoint: None,
10772            subject: Some("topic.x".into()),
10773            slot: None,
10774        };
10775        assert!(nats.is_pubsub());
10776        assert!(!nats.is_http());
10777        assert!(!nats.is_capability());
10778
10779        let kv = WitContract {
10780            de: "a".into(),
10781            para: "b".into(),
10782            wit: "wasi:keyvalue/store".into(),
10783            endpoint: None,
10784            subject: None,
10785            slot: Some("checkout/$orderId".into()),
10786        };
10787        assert!(kv.is_store());
10788        assert!(!kv.is_http());
10789        assert!(!kv.is_capability());
10790
10791        // Fourth arm on the paired closed-set predicate family: the
10792        // payload-less capability edge that projects to the payload-
10793        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
10794        // Extends the 3-arm predicate sweep this test opened to cover
10795        // the closed 4-way partition [`WitContract::is_capability`]
10796        // closes on the pre-projection WIT-shape axis, matched with the
10797        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
10798        // 4-arm predicate set.
10799        let cap = WitContract {
10800            de: "a".into(),
10801            para: "b".into(),
10802            wit: "custom:capability-only".into(),
10803            endpoint: None,
10804            subject: None,
10805            slot: None,
10806        };
10807        assert!(cap.is_capability());
10808        assert!(!cap.is_http());
10809        assert!(!cap.is_pubsub());
10810        assert!(!cap.is_store());
10811    }
10812
10813    // ── :contratos :wit value-shape gate ─────────────────────────────────
10814    //
10815    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
10816    // dispatch-discriminator axis. Until this gate landed
10817    // `WitContract::target()` accepted any non-empty string and
10818    // silently demoted unrecognized shapes to a capability-only L4
10819    // edge — the canonical "I thought I had L7 HTTP routing, got
10820    // L4-only" footgun. Every authoring footgun the WIT registry's
10821    // own grammar rejects (uppercase, hyphen-for-colon typo,
10822    // whitespace, empty package, doubled `@`, …) now becomes a
10823    // caixa-build-time `ContratoWitInvalid` with the offending
10824    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
10825    // as `ContratoEndpointInvalid` on the sibling axis; same shared
10826    // predicate (`crate::render::is_wit_world_ref`) ensures drift
10827    // between any two axes' rule enforcement is a build error at the
10828    // predicate, not piecemeal across renderers.
10829
10830    fn contrato_wit_err(wit: &str) -> AplicacaoError {
10831        // Fresh spec per call so the new contract doesn't collide on
10832        // identity with `three_member_spec`'s pre-existing entries.
10833        // The new edge uses `(payment, catalog)` — a pair the fixture
10834        // doesn't already declare — with no payload field set, so the
10835        // wit-shape gate fires before any payload-shape arm.
10836        let mut s = three_member_spec();
10837        s.contratos.push(WitContract {
10838            de: "payment".into(),
10839            para: "catalog".into(),
10840            wit: wit.into(),
10841            endpoint: None,
10842            subject: None,
10843            slot: None,
10844        });
10845        s.validate().unwrap_err()
10846    }
10847
10848    #[test]
10849    fn rejects_wit_with_uppercase_namespace() {
10850        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
10851        // didn't match the lowercase `wasi:http/` prefix is_http() keys
10852        // off, so the dispatch fell through to the capability arm and
10853        // the contract silently rendered as an L4-only Cilium edge.
10854        // The new gate surfaces the uppercase typo at validate time
10855        // with the offending `:wit` named.
10856        let err = contrato_wit_err("WASI:http/proxy");
10857        assert!(
10858            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10859                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
10860            "got {err:?}"
10861        );
10862    }
10863
10864    #[test]
10865    fn rejects_wit_with_hyphen_for_colon_typo() {
10866        // The canonical "I forgot the `:` separator" typo — pre-gate
10867        // this passed as Capability silently, so the renderer emitted
10868        // an L4-only policy where the author expected L7 HTTP rules.
10869        let err = contrato_wit_err("wasi-http/proxy");
10870        assert!(
10871            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10872                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
10873            "got {err:?}"
10874        );
10875    }
10876
10877    #[test]
10878    fn rejects_wit_with_multiple_colons() {
10879        // Doubled `:` — the namespace/package split has nowhere to
10880        // anchor, so the dispatch silently demotes to Capability.
10881        let err = contrato_wit_err("wasi:http:proxy");
10882        assert!(
10883            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10884                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
10885            "got {err:?}"
10886        );
10887    }
10888
10889    #[test]
10890    fn rejects_wit_with_empty_package() {
10891        // `wasi:` — namespace alone with no package. Pre-gate this
10892        // failed neither the is_http nor is_pubsub nor is_store
10893        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
10894        // a bare `wasi:`), so it silently demoted to Capability.
10895        let err = contrato_wit_err("wasi:");
10896        assert!(
10897            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10898                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
10899            "got {err:?}"
10900        );
10901    }
10902
10903    #[test]
10904    fn rejects_wit_with_underscore() {
10905        // Underscore — WIT identifiers are kebab-case, same rule
10906        // DNS-1123 enforces on its peer axes. The diagnostic carries
10907        // the explicit "use `-` instead" remediation.
10908        let err = contrato_wit_err("wasi:http_proxy");
10909        assert!(
10910            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10911                if wit == "wasi:http_proxy" && reason.contains('_')),
10912            "got {err:?}"
10913        );
10914    }
10915
10916    #[test]
10917    fn rejects_wit_with_whitespace() {
10918        // Whitespace mid-token — the prefix check matches but the
10919        // package-and-onward parse silently demoted to Capability.
10920        let err = contrato_wit_err("wasi:http proxy");
10921        assert!(
10922            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10923                if wit == "wasi:http proxy" && reason.contains("whitespace")),
10924            "got {err:?}"
10925        );
10926    }
10927
10928    #[test]
10929    fn rejects_wit_with_non_ascii() {
10930        // Un-percent-encoded non-ASCII byte — the canonical "I copied
10931        // the package name from a doc with smart quotes / accented
10932        // characters" footgun.
10933        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
10934        assert!(
10935            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10936                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
10937            "got {err:?}"
10938        );
10939    }
10940
10941    #[test]
10942    fn rejects_wit_with_consecutive_hyphens() {
10943        // `pub--sub` — WIT identifiers join words with single hyphens.
10944        let err = contrato_wit_err("nats:pub--sub");
10945        assert!(
10946            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10947                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
10948            "got {err:?}"
10949        );
10950    }
10951
10952    #[test]
10953    fn rejects_wit_with_trailing_at_no_version() {
10954        // `wasi:http/proxy@` — the version-suffix author started to
10955        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
10956        // parser would reject this; surface it at validate time.
10957        let err = contrato_wit_err("wasi:http/proxy@");
10958        assert!(
10959            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10960                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
10961            "got {err:?}"
10962        );
10963    }
10964
10965    #[test]
10966    fn rejects_wit_too_long() {
10967        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
10968        // The legitimate-shape arms all pass (lowercase, single `:`,
10969        // kebab-case identifiers); only the cap arm fires. Surfaces
10970        // the paste-from-binary / accidental-multi-line-blob landing
10971        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
10972        // on the peer axis.
10973        let big = format!("wasi:{}", "a".repeat(124));
10974        assert_eq!(big.len(), 129);
10975        let err = contrato_wit_err(&big);
10976        assert!(
10977            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10978                if wit == &big && reason.contains("max length of 128")),
10979            "got {err:?}"
10980        );
10981    }
10982
10983    #[test]
10984    fn wit_max_length_validates() {
10985        // 128-byte WIT reference — exactly the cap. Boundary pin:
10986        // drift in the cap surfaces here and at `rejects_wit_too_long`
10987        // simultaneously, mirroring
10988        // `http_contrato_endpoint_max_length_validates` on the peer
10989        // axis.
10990        let big = format!("wasi:{}", "a".repeat(123));
10991        assert_eq!(big.len(), 128);
10992        let mut s = three_member_spec();
10993        s.contratos.push(WitContract {
10994            de: "payment".into(),
10995            para: "catalog".into(),
10996            wit: big,
10997            endpoint: None,
10998            subject: None,
10999            slot: None,
11000        });
11001        s.validate().unwrap();
11002    }
11003
11004    #[test]
11005    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
11006        // Positive-set sweep through the AplicacaoSpec::validate
11007        // surface (rather than the substrate-side predicate directly)
11008        // — pins every shape the existing test fixtures + the
11009        // checkout-aplicacao example carry, so the gate's accept-set
11010        // matches the substrate's emit-set. Drift between this list
11011        // and `render::tests::wit_world_ref_accepts_canonical_forms`
11012        // surfaces at the substrate layer's positive sweep — one
11013        // source of truth for the rule.
11014        for wit in [
11015            "wasi:http/proxy",
11016            "wasi:keyvalue/store",
11017            "nats:pub-sub",
11018            "kafka:topic",
11019            "custom:exchange",
11020            "pleme:cap/audit",
11021            "wasi:http/proxy@0.2.0",
11022        ] {
11023            // Payload field paired to the dispatched WIT shape so the
11024            // shape-↔-target arm doesn't fire instead of the wit-shape
11025            // arm we're exercising. Routes off the same
11026            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
11027            // `wit_shape_is_store` free functions the production
11028            // `WitContract::is_http` / `is_pubsub` / `is_store`
11029            // methods delegate to (both consult the lifted
11030            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
11031            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
11032            // future prefix addition to the routing accept-set
11033            // reaches this test's payload-dispatch arm by
11034            // construction — no per-test-site drift can hide a
11035            // shape-→-target-slot mismatch that would silently
11036            // demote a canonical `:wit` value to the
11037            // `(None, None, None)` capability-only arm and let the
11038            // `AplicacaoSpec::validate` positive sweep pass on a
11039            // shape it should exercise as HTTP / pub-sub / store.
11040            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
11041                (Some("/x".into()), None, None)
11042            } else if wit_shape_is_pubsub(wit) {
11043                (None, Some("topic.x".into()), None)
11044            } else if wit_shape_is_store(wit) {
11045                (None, None, Some("bucket/$key".into()))
11046            } else {
11047                (None, None, None)
11048            };
11049            let mut s = three_member_spec();
11050            s.contratos.push(WitContract {
11051                de: "payment".into(),
11052                para: "catalog".into(),
11053                wit: wit.into(),
11054                endpoint,
11055                subject,
11056                slot,
11057            });
11058            s.validate()
11059                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
11060        }
11061    }
11062
11063    #[test]
11064    fn wit_shape_predicates_accept_canonical_prefix_set() {
11065        // Positive-set sweep pinning every prefix in
11066        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
11067        // WIT_STORE_SHAPE_PREFIXES against the three free-function
11068        // dispatch predicates. The six prefixes are the load-bearing
11069        // routing keys the substrate's WIT-shape dispatch consults
11070        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
11071        // key/value-store-slot admission); any drift between the
11072        // free-function accept-set and this list surfaces here
11073        // rather than at apply time as a silent
11074        // shape-→-capability-only demotion.
11075        assert!(wit_shape_is_http("wasi:http/proxy"));
11076        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
11077        assert!(wit_shape_is_http("http:incoming"));
11078
11079        assert!(wit_shape_is_pubsub("nats:pub-sub"));
11080        assert!(wit_shape_is_pubsub("kafka:topic"));
11081
11082        assert!(wit_shape_is_store("wasi:keyvalue/store"));
11083        assert!(wit_shape_is_store("kv:cache/session"));
11084    }
11085
11086    #[test]
11087    fn wit_shape_predicates_reject_uncanonical_forms() {
11088        // Negative-set pin: the six canonical prefixes are
11089        // lowercase-only (mirrors the `is_wit_world_ref` substrate
11090        // predicate's lowercase invariant — see its docstring on the
11091        // "I thought I had L7 HTTP routing, got L4-only" footgun).
11092        // The empty string, an uppercase-prefixed form, a hyphen-
11093        // instead-of-colon typo, and a bare kebab identifier all miss
11094        // every shape arm — reachable-by-construction only via the
11095        // `is_wit_world_ref` gate that admission-checks the `:wit`
11096        // value first, but pinned here so any future
11097        // free-function change (e.g. a case-insensitive
11098        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
11099        // this unit level.
11100        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
11101            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
11102            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
11103            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
11104        }
11105    }
11106
11107    #[test]
11108    fn wit_shape_predicates_partition_canonical_set() {
11109        // Every canonical prefix routes to exactly one shape arm —
11110        // the three prefix sets are pairwise disjoint. Pins the
11111        // routing property [`WitContract::target`] relies on: an
11112        // `is_http()` return of `true` guarantees `is_pubsub()` and
11113        // `is_store()` return `false`, so the shape-→-target-slot
11114        // dispatch (endpoint vs subject vs slot) is unambiguous.
11115        // Drift (e.g. a future `"kv:"` moved into the HTTP set
11116        // without removal from the store set) would silently route
11117        // one prefix to two arms and the first-matching-arm order
11118        // becomes load-bearing — this pin surfaces it as a build
11119        // error instead.
11120        for prefix in WIT_HTTP_SHAPE_PREFIXES {
11121            let sample = format!("{prefix}x");
11122            assert!(wit_shape_is_http(&sample));
11123            assert!(!wit_shape_is_pubsub(&sample));
11124            assert!(!wit_shape_is_store(&sample));
11125        }
11126        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
11127            let sample = format!("{prefix}x");
11128            assert!(!wit_shape_is_http(&sample));
11129            assert!(wit_shape_is_pubsub(&sample));
11130            assert!(!wit_shape_is_store(&sample));
11131        }
11132        for prefix in WIT_STORE_SHAPE_PREFIXES {
11133            let sample = format!("{prefix}x");
11134            assert!(!wit_shape_is_http(&sample));
11135            assert!(!wit_shape_is_pubsub(&sample));
11136            assert!(wit_shape_is_store(&sample));
11137        }
11138    }
11139
11140    #[test]
11141    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
11142        // Positive pin: [`wit_shape_matches`] is exactly the
11143        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
11144        // parameterized on the accept-set. Two-prefix accept-set,
11145        // one-prefix accept-set, and empty accept-set (which must
11146        // reject everything, including the empty string — an empty
11147        // `any()` fold returns `false`) all pinned so a future
11148        // reimplementation that swaps `starts_with` for `contains`,
11149        // `==`, or a case-folded comparator surfaces at unit-test
11150        // time.
11151        let two = &["wasi:http/", "http:"];
11152        assert!(wit_shape_matches("wasi:http/proxy", two));
11153        assert!(wit_shape_matches("http:incoming", two));
11154        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
11155
11156        let one = &["nats:"];
11157        assert!(wit_shape_matches("nats:pub-sub", one));
11158        assert!(!wit_shape_matches("kafka:topic", one));
11159
11160        // Empty accept-set matches nothing — the identity element
11161        // for the disjunctive `any()` fold across the prefix set.
11162        // Reachable via a future `wit_shape_is_<name>` const paired
11163        // to a still-empty prefix table on a nascent shape-arm draft.
11164        let empty: &[&str] = &[];
11165        assert!(!wit_shape_matches("wasi:http/proxy", empty));
11166        assert!(!wit_shape_matches("", empty));
11167
11168        // starts_with, not contains: a prefix embedded mid-string
11169        // never matches. Pins the routing invariant [`WitContract::target`]
11170        // relies on (an authored `:wit "custom:wasi:http/"` string
11171        // does not silently route through the HTTP arm just because
11172        // it happens to contain the canonical HTTP prefix).
11173        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
11174    }
11175
11176    #[test]
11177    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
11178        // Equivalence pin: each per-shape predicate is exactly
11179        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
11180        // every canonical prefix + the empty string + one negative
11181        // sample against every peer so a future predicate that grew
11182        // its own inline `iter().any(starts_with)` (rather than
11183        // delegating through the lifted combinator) drifts loudly here
11184        // — the peer-const table's contents must agree with the
11185        // predicate's accept-set by construction.
11186        let samples = [
11187            String::new(),
11188            "wasi:http/proxy".to_string(),
11189            "http:incoming".to_string(),
11190            "nats:pub-sub".to_string(),
11191            "kafka:topic".to_string(),
11192            "wasi:keyvalue/store".to_string(),
11193            "kv:cache/session".to_string(),
11194            "custom-shape".to_string(),
11195            "WASI:HTTP/proxy".to_string(),
11196        ];
11197        for wit in &samples {
11198            assert_eq!(
11199                wit_shape_is_http(wit),
11200                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11201                "wit_shape_is_http drifted from combinator on {wit:?}",
11202            );
11203            assert_eq!(
11204                wit_shape_is_pubsub(wit),
11205                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
11206                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
11207            );
11208            assert_eq!(
11209                wit_shape_is_store(wit),
11210                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
11211                "wit_shape_is_store drifted from combinator on {wit:?}",
11212            );
11213        }
11214    }
11215
11216    #[test]
11217    fn wit_contract_shape_methods_delegate_to_free_functions() {
11218        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
11219        // `is_store` are `&self` conveniences on top of the free
11220        // functions — for every canonical prefix the method's return
11221        // matches its free-function peer. Sweeps the union of the
11222        // three prefix sets so a future method that grew its own
11223        // inline prefix logic (rather than delegating) drifts loudly
11224        // here on the first prefix the free function accepts and the
11225        // method doesn't.
11226        for shape_set in [
11227            WIT_HTTP_SHAPE_PREFIXES,
11228            WIT_PUBSUB_SHAPE_PREFIXES,
11229            WIT_STORE_SHAPE_PREFIXES,
11230        ] {
11231            for prefix in shape_set {
11232                let c = WitContract {
11233                    de: "cart".into(),
11234                    para: "catalog".into(),
11235                    wit: format!("{prefix}x"),
11236                    endpoint: None,
11237                    subject: None,
11238                    slot: None,
11239                };
11240                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
11241                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
11242                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
11243                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11244            }
11245        }
11246        // Capability-arm delegation sweep: two representative
11247        // Capability-shaped `:wit` values (a bare non-prefix-matching
11248        // WIT world, the deliberately-shaped empty string
11249        // [`WitContract::is_capability`]'s docstring calls out as
11250        // syntactically Capability). Extends the free-function
11251        // delegation pin onto the fourth arm so a future
11252        // [`WitContract::is_capability`] rewrite that grew an inline
11253        // prefix-set scan (rather than delegating through
11254        // [`wit_shape_is_capability`]) drifts loudly here on the first
11255        // Capability-shaped sample.
11256        for wit in ["custom:capability-only", ""] {
11257            let c = WitContract {
11258                de: "cart".into(),
11259                para: "catalog".into(),
11260                wit: wit.into(),
11261                endpoint: None,
11262                subject: None,
11263                slot: None,
11264            };
11265            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11266        }
11267    }
11268
11269    #[test]
11270    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
11271        // 4-way partition-witness pin on the raw `&str` axis: for every
11272        // canonical prefix in the three payload-arm accept-sets,
11273        // exactly one of the four [`wit_shape_is_http`] /
11274        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11275        // [`wit_shape_is_capability`] free functions returns `true` and
11276        // the other three return `false` — the four-arm partition
11277        // witness that locks the free-function WIT-shape-classifier
11278        // family into a partition of the `:contratos :wit` axis
11279        // load-bearing. Peer of the sibling [`WitContract`]-surface
11280        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
11281        // partition pin — extends the discipline onto the raw `&str`
11282        // axis so any future arm addition (a hypothetical
11283        // `wasi:sockets/*` transport-layer shape, an `oci:*`
11284        // capability-import carrier per the sibling
11285        // [`wit_shape_matches`] docstring's trajectory bullet) that
11286        // landed on one of the payload-arm free functions without
11287        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
11288        // here as two arms returning `true` simultaneously at
11289        // caixa-core build time rather than a silent per-consumer
11290        // misclassification at renderer emit time.
11291        for shape_set in [
11292            WIT_HTTP_SHAPE_PREFIXES,
11293            WIT_PUBSUB_SHAPE_PREFIXES,
11294            WIT_STORE_SHAPE_PREFIXES,
11295        ] {
11296            for prefix in shape_set {
11297                let wit = format!("{prefix}x");
11298                let hits = [
11299                    wit_shape_is_http(&wit),
11300                    wit_shape_is_pubsub(&wit),
11301                    wit_shape_is_store(&wit),
11302                    wit_shape_is_capability(&wit),
11303                ]
11304                .iter()
11305                .filter(|&&b| b)
11306                .count();
11307                assert_eq!(
11308                    hits,
11309                    1,
11310                    "raw-&str WIT-shape 4-way predicate partition must \
11311                     admit exactly one arm per canonical prefix; got {hits} \
11312                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
11313                     is_capability={})",
11314                    wit_shape_is_http(&wit),
11315                    wit_shape_is_pubsub(&wit),
11316                    wit_shape_is_store(&wit),
11317                    wit_shape_is_capability(&wit),
11318                );
11319            }
11320        }
11321        // Capability-arm sweep on the raw `&str` axis: two
11322        // representative Capability-shaped `:wit` values (a bare non-
11323        // prefix-matching WIT world, the deliberately-shaped empty
11324        // string the pure classifier still admits per
11325        // [`wit_shape_is_capability`]'s docstring). Both must land on
11326        // the fourth arm exclusively so the partition witness holds
11327        // across the full 4-arm closure on the raw `&str` axis.
11328        for wit in ["custom:capability-only", ""] {
11329            let hits = [
11330                wit_shape_is_http(wit),
11331                wit_shape_is_pubsub(wit),
11332                wit_shape_is_store(wit),
11333                wit_shape_is_capability(wit),
11334            ]
11335            .iter()
11336            .filter(|&&b| b)
11337            .count();
11338            assert_eq!(
11339                hits, 1,
11340                "raw-&str WIT-shape 4-way predicate partition must \
11341                 admit exactly one arm on Capability-shaped wit={wit:?}"
11342            );
11343            assert!(
11344                wit_shape_is_capability(wit),
11345                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
11346            );
11347        }
11348    }
11349
11350    #[test]
11351    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
11352        // Composition-witness pin: [`wit_shape_is_capability`] is the
11353        // exact-inverse disjunction of the sibling payload-arm free-
11354        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
11355        // / [`wit_shape_is_store`]. A future reimplementation that
11356        // grew its own prefix-set scan (e.g. inlining a fourth
11357        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
11358        // not own today) rather than delegating to the sibling trio
11359        // would drift loudly here — the composition contract binds the
11360        // fourth-arm free-function predicate to the exact-inverse of
11361        // the three payload-arm free-function predicates, so any
11362        // rebrand of any prefix-set const flows through
11363        // [`wit_shape_is_capability`] by construction without a
11364        // coordinated per-consumer rewrite. Peer of the sibling
11365        // [`WitContract`]-surface
11366        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
11367        // composition pin — extends the discipline onto the raw
11368        // `&str` axis.
11369        let mut cases: Vec<String> = Vec::new();
11370        for shape_set in [
11371            WIT_HTTP_SHAPE_PREFIXES,
11372            WIT_PUBSUB_SHAPE_PREFIXES,
11373            WIT_STORE_SHAPE_PREFIXES,
11374        ] {
11375            for prefix in shape_set {
11376                cases.push(format!("{prefix}x"));
11377            }
11378        }
11379        cases.push("custom:capability-only".to_string());
11380        cases.push(String::new());
11381        for wit in cases {
11382            assert_eq!(
11383                wit_shape_is_capability(&wit),
11384                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
11385                "wit_shape_is_capability must equal \
11386                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
11387                 at wit={wit:?}"
11388            );
11389        }
11390    }
11391
11392    #[test]
11393    fn wit_shape_classifier_family_is_const_fn() {
11394        // Fail-before-pass-after pin on the 4-arm free-function WIT-
11395        // shape classifier family's `const`-eval posture. Each of the
11396        // four peer classifiers ([`wit_shape_is_http`] /
11397        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11398        // [`wit_shape_is_capability`]) and the underlying combinator
11399        // [`wit_shape_matches`] must be `pub const fn` — any future
11400        // accidental downgrade to non-`const` fails the `const fn`
11401        // wrappers below at caixa-core build time with E0015
11402        // (`cannot call non-const function`), strictly stronger than
11403        // a runtime `assert!` and strictly stronger than the module-
11404        // scope `const _: () = assert!(…)` pins immediately after the
11405        // classifier declarations (those anchor specific accept-set
11406        // truth-table entries; this pin anchors the `const` posture
11407        // itself via `const fn` wrappers that are only well-formed
11408        // when the callee is itself `const fn`).
11409        //
11410        // Verified fail-before-pass-after by locally reverting
11411        // `pub const fn` → `pub fn` on each classifier and observing
11412        // E0015 at every corresponding wrapper call site (build
11413        // error, no test-time surface), then restoring `pub const fn`
11414        // and observing the pin pass at test time. Peer of the
11415        // sibling M3
11416        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11417        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11418        // M2
11419        // [`child_spec_restart_accessor_is_const_fn`] /
11420        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11421        // and M3
11422        // [`placement_estrategia_accessor_is_const_fn`] /
11423        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11424        // sibling `const`-eval-surface-pass axes.
11425        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
11426            wit_shape_matches(wit, prefixes)
11427        }
11428        const fn http_via_const_fn(wit: &str) -> bool {
11429            wit_shape_is_http(wit)
11430        }
11431        const fn pubsub_via_const_fn(wit: &str) -> bool {
11432            wit_shape_is_pubsub(wit)
11433        }
11434        const fn store_via_const_fn(wit: &str) -> bool {
11435            wit_shape_is_store(wit)
11436        }
11437        const fn capability_via_const_fn(wit: &str) -> bool {
11438            wit_shape_is_capability(wit)
11439        }
11440        // Sweep one canonical accept-set sample per arm plus the
11441        // payload-less/empty capability samples, asserting the
11442        // wrapper and direct dispatches agree byte-for-byte across
11443        // the closed 4-arm partition.
11444        let cases: [(&str, bool, bool, bool, bool); 6] = [
11445            ("wasi:http/proxy", true, false, false, false),
11446            ("http:incoming", true, false, false, false),
11447            ("nats:events", false, true, false, false),
11448            ("kafka:topic", false, true, false, false),
11449            ("wasi:keyvalue/store", false, false, true, false),
11450            ("kv:cache", false, false, true, false),
11451        ];
11452        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
11453            assert_eq!(
11454                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
11455                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11456                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
11457            );
11458            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
11459            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
11460            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
11461            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11462            assert_eq!(wit_shape_is_http(wit), is_http);
11463            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
11464            assert_eq!(wit_shape_is_store(wit), is_store);
11465        }
11466        // Payload-less capability arm (the 4th partition arm).
11467        let capability_samples: [&str; 3] =
11468            ["wasi:filesystem/preopens", "custom:capability-only", ""];
11469        for wit in capability_samples {
11470            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11471            assert!(wit_shape_is_capability(wit));
11472            assert!(!wit_shape_is_http(wit));
11473            assert!(!wit_shape_is_pubsub(wit));
11474            assert!(!wit_shape_is_store(wit));
11475        }
11476    }
11477
11478    #[test]
11479    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
11480        // Composition-witness pin: [`wit_shape_matches`] agrees with
11481        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
11482        // dispatch (the prior non-`const` implementation) across
11483        // boundary lengths — empty `wit`, empty prefix, one-byte
11484        // slack, prefix longer than `wit`, one-byte trailing slack.
11485        // The rewrite to a byte-level manual starts_with loop (the
11486        // enabler for the `pub const fn` posture) must not change any
11487        // truth-table entry on the canonical accept-set — this pin
11488        // sweeps a targeted boundary corpus and asserts byte-for-byte
11489        // agreement, locking the const-fn rewrite's semantics against
11490        // the prior iterator body by construction.
11491        let prefixes = &["wasi:http/", "http:"][..];
11492        let cases: [(&str, bool); 12] = [
11493            ("wasi:http/proxy", true),
11494            ("wasi:http/", true), // exact-length match on prefix
11495            ("wasi:http", false), // one byte short
11496            ("http:", true),
11497            ("http:incoming", true),
11498            ("http", false), // one byte short
11499            ("", false),
11500            ("wasi:https/proxy", false),
11501            ("nats:events", false),
11502            ("HTTPS:", false), // uppercase — no case-fold in classifier
11503            ("wasi:HTTP/proxy", false),
11504            ("wasi:http", false),
11505        ];
11506        for (wit, expected) in cases {
11507            assert_eq!(
11508                wit_shape_matches(wit, prefixes),
11509                expected,
11510                "wit_shape_matches disagrees with reference at wit={wit:?}",
11511            );
11512            // Byte-equal to the iterator body it replaced.
11513            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
11514            assert_eq!(
11515                wit_shape_matches(wit, prefixes),
11516                via_iter,
11517                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
11518            );
11519        }
11520        // Empty prefix set → always false regardless of `wit`.
11521        let empty: &[&str] = &[];
11522        assert!(!wit_shape_matches("", empty));
11523        assert!(!wit_shape_matches("wasi:http/proxy", empty));
11524        // Empty prefix inside a non-empty set → always true (every
11525        // string starts with the empty string, matching the
11526        // iterator body's semantics on `str::starts_with("")`).
11527        let contains_empty: &[&str] = &["nats:", ""];
11528        assert!(wit_shape_matches("", contains_empty));
11529        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
11530    }
11531
11532    #[test]
11533    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
11534        // 4-way partition-witness pin: for every canonical prefix in
11535        // the payload-arm accept-sets, exactly one of the four
11536        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11537        // [`WitContract::is_store`] / [`WitContract::is_capability`]
11538        // predicates returns `true` and the other three return `false`
11539        // — the four-arm partition witness that locks the substrate's
11540        // WIT-shape-space closure on the pre-projection axis load-
11541        // bearing. A future arm addition (a hypothetical fourth
11542        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
11543        // shape) that landed on one of the payload-arm predicates
11544        // without shrinking [`WitContract::is_capability`]'s accept-set
11545        // would surface here as two arms returning `true` simultaneously
11546        // — a partition-witness break the pin catches at caixa-core
11547        // build time rather than a silent per-consumer misclassification
11548        // at renderer emit time. Peer of the sibling `WitTarget`-side
11549        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
11550        // partition-witness pin on the post-projection payload-scalar
11551        // arm-set — extends the discipline onto the pre-projection
11552        // 4-arm shape-space.
11553        for shape_set in [
11554            WIT_HTTP_SHAPE_PREFIXES,
11555            WIT_PUBSUB_SHAPE_PREFIXES,
11556            WIT_STORE_SHAPE_PREFIXES,
11557        ] {
11558            for prefix in shape_set {
11559                let c = WitContract {
11560                    de: "cart".into(),
11561                    para: "catalog".into(),
11562                    wit: format!("{prefix}x"),
11563                    endpoint: None,
11564                    subject: None,
11565                    slot: None,
11566                };
11567                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11568                    .iter()
11569                    .filter(|&&b| b)
11570                    .count();
11571                assert_eq!(
11572                    hits,
11573                    1,
11574                    "WitContract WIT-shape 4-way predicate partition must \
11575                     admit exactly one arm per canonical prefix; got {hits} \
11576                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
11577                     is_capability={})",
11578                    c.wit,
11579                    c.is_http(),
11580                    c.is_pubsub(),
11581                    c.is_store(),
11582                    c.is_capability(),
11583                );
11584            }
11585        }
11586        // Capability-arm sweep: two representative capability shapes
11587        // (a bare WIT world outside the three payload-arm prefix sets,
11588        // and the deliberately-shaped empty string that
11589        // [`crate::render::is_wit_world_ref`] rejects at
11590        // [`WitContract::target`] time but which the pure classifier
11591        // still admits — see the method docstring's "purely syntactic
11592        // classification" note). Both must land on the fourth arm
11593        // exclusively, so the partition witness holds across the full
11594        // 4-arm closure.
11595        for wit in ["custom:capability-only", ""] {
11596            let c = WitContract {
11597                de: "cart".into(),
11598                para: "catalog".into(),
11599                wit: wit.into(),
11600                endpoint: None,
11601                subject: None,
11602                slot: None,
11603            };
11604            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11605                .iter()
11606                .filter(|&&b| b)
11607                .count();
11608            assert_eq!(
11609                hits, 1,
11610                "WitContract WIT-shape 4-way predicate partition must \
11611                 admit exactly one arm on Capability-shaped wit={wit:?}"
11612            );
11613            assert!(
11614                c.is_capability(),
11615                "wit={wit:?} must project onto the Capability arm"
11616            );
11617        }
11618    }
11619
11620    #[test]
11621    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
11622        // Composition-witness pin: [`WitContract::is_capability`] is the
11623        // exact-inverse disjunction of the sibling payload-arm predicate
11624        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11625        // [`WitContract::is_store`]. A future reimplementation that
11626        // grew its own prefix-set scan (e.g. inlining a fourth
11627        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
11628        // own today) rather than delegating to the sibling trio would
11629        // drift loudly here — the composition contract binds the
11630        // fourth-arm predicate to the exact-inverse of the three
11631        // payload-arm predicates, so any rebrand of any prefix-set const
11632        // flows through this method by construction without a
11633        // coordinated per-consumer rewrite. Sweeps the union of the
11634        // three payload-arm prefix sets plus two Capability-shaped
11635        // shapes (a bare non-prefix-matching WIT world, the deliberately-
11636        // empty string the pure classifier still admits per the method
11637        // docstring's "purely syntactic classification" note).
11638        let mut cases: Vec<String> = Vec::new();
11639        for shape_set in [
11640            WIT_HTTP_SHAPE_PREFIXES,
11641            WIT_PUBSUB_SHAPE_PREFIXES,
11642            WIT_STORE_SHAPE_PREFIXES,
11643        ] {
11644            for prefix in shape_set {
11645                cases.push(format!("{prefix}x"));
11646            }
11647        }
11648        cases.push("custom:capability-only".to_string());
11649        cases.push(String::new());
11650        for wit in cases {
11651            let c = WitContract {
11652                de: "cart".into(),
11653                para: "catalog".into(),
11654                wit: wit.clone(),
11655                endpoint: None,
11656                subject: None,
11657                slot: None,
11658            };
11659            assert_eq!(
11660                c.is_capability(),
11661                !c.is_http() && !c.is_pubsub() && !c.is_store(),
11662                "WitContract::is_capability must equal \
11663                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
11664            );
11665        }
11666    }
11667
11668    #[test]
11669    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
11670        // Cross-projection-witness pin: whenever [`WitContract::target`]
11671        // succeeds, the pre-projection [`WitContract::is_capability`]
11672        // classification agrees with the post-projection
11673        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
11674        // predicate — the 4-arm typed partition on the substrate's
11675        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
11676        // partition on the pre-projection axis line up by construction.
11677        // A future divergence between the two axes (a peer
11678        // [`WitTarget`] variant addition that landed on the typed-view
11679        // surface without a peer prefix-set + [`WitContract`] predicate
11680        // extension, or vice versa) would surface here at caixa-core
11681        // build time rather than a silent per-consumer split at renderer
11682        // emit time. Peer of the sibling pre-/post-projection
11683        // agreement pins the payload-carrier trio
11684        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
11685        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
11686        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
11687        // post-projection — b11bb49 trio lift) already carry across the
11688        // three payload arms — this pin closes the pair on the fourth
11689        // payload-less arm.
11690        let http = WitContract {
11691            de: "cart".into(),
11692            para: "catalog".into(),
11693            wit: "wasi:http/proxy".into(),
11694            endpoint: Some("/x".into()),
11695            subject: None,
11696            slot: None,
11697        };
11698        assert!(!http.is_capability());
11699        assert!(!http.target().unwrap().is_capability());
11700
11701        let nats = WitContract {
11702            de: "cart".into(),
11703            para: "catalog".into(),
11704            wit: "nats:pub-sub".into(),
11705            endpoint: None,
11706            subject: Some("events.x".into()),
11707            slot: None,
11708        };
11709        assert!(!nats.is_capability());
11710        assert!(!nats.target().unwrap().is_capability());
11711
11712        let kv = WitContract {
11713            de: "cart".into(),
11714            para: "catalog".into(),
11715            wit: "wasi:keyvalue/store".into(),
11716            endpoint: None,
11717            subject: None,
11718            slot: Some("checkout/$orderId".into()),
11719        };
11720        assert!(!kv.is_capability());
11721        assert!(!kv.target().unwrap().is_capability());
11722
11723        let cap = WitContract {
11724            de: "cart".into(),
11725            para: "catalog".into(),
11726            wit: "custom:capability-only".into(),
11727            endpoint: None,
11728            subject: None,
11729            slot: None,
11730        };
11731        assert!(cap.is_capability());
11732        assert!(cap.target().unwrap().is_capability());
11733    }
11734
11735    #[test]
11736    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
11737        // Fail-before-pass-after pin on the [`WitContract`] pre-
11738        // projection accessor family's `const`-eval-surface posture.
11739        // Each of the three per-`:contratos` byte-string scalar
11740        // accessors ([`WitContract::source`] / [`WitContract::destination`]
11741        // / [`WitContract::world_ref`], each projecting through
11742        // `String::as_str` — const-stable since Rust 1.87, well within
11743        // the workspace MSRV) and each of the four peer WIT-shape
11744        // predicates ([`WitContract::is_http`] /
11745        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
11746        // [`WitContract::is_capability`], each composing
11747        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
11748        // free-function classifier family the sibling
11749        // [`wit_shape_classifier_family_is_const_fn`] pin already
11750        // anchors on the raw `&str → bool` axis) must be `pub const fn`
11751        // — any future accidental downgrade to non-`const` fails the
11752        // `const fn` wrappers below at caixa-core build time with E0015
11753        // (`cannot call non-const function`), strictly stronger than a
11754        // runtime `assert!` and strictly stronger than a
11755        // module-scope `const _: () = assert!(…)` pin (which cannot be
11756        // formed on a `&WitContract` fixture because the type's
11757        // `String` / `Option<String>` carriers rule out `const`-context
11758        // construction; the `const fn` wrapper is the load-bearing
11759        // shape that side-steps the destructor-in-const restriction on
11760        // the value axis while still pinning the `const`-fn posture on
11761        // the callee).
11762        //
11763        // Peer of the sibling free-function classifier pin
11764        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
11765        // raw `&str → bool` axis — this pin extends the same
11766        // `const`-eval-surface discipline onto the peer method surface
11767        // that composes through those free-function classifiers, and
11768        // simultaneously onto the underlying per-`:contratos`
11769        // byte-string scalar-accessor trio each predicate reads
11770        // through. Sibling of the peer M3
11771        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11772        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11773        // M2
11774        // [`child_spec_restart_accessor_is_const_fn`] /
11775        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11776        // and M3
11777        // [`placement_estrategia_accessor_is_const_fn`] /
11778        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11779        // sibling `const`-eval-surface-pass axes.
11780        const fn source_via_const_fn(c: &WitContract) -> &str {
11781            c.source()
11782        }
11783        const fn destination_via_const_fn(c: &WitContract) -> &str {
11784            c.destination()
11785        }
11786        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
11787            c.world_ref()
11788        }
11789        const fn is_http_via_const_fn(c: &WitContract) -> bool {
11790            c.is_http()
11791        }
11792        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
11793            c.is_pubsub()
11794        }
11795        const fn is_store_via_const_fn(c: &WitContract) -> bool {
11796            c.is_store()
11797        }
11798        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
11799            c.is_capability()
11800        }
11801        // Sweep one canonical accept-set sample per WIT-shape arm plus
11802        // a payload-less capability sample, asserting the wrapper and
11803        // direct dispatches agree byte-for-byte across the closed
11804        // 4-arm partition on both the scalar-accessor trio and the
11805        // WIT-shape-predicate family.
11806        for (wit, is_http, is_pubsub, is_store, is_capability) in [
11807            ("wasi:http/proxy", true, false, false, false),
11808            ("http:incoming", true, false, false, false),
11809            ("nats:events", false, true, false, false),
11810            ("kafka:topic", false, true, false, false),
11811            ("wasi:keyvalue/store", false, false, true, false),
11812            ("kv:cache", false, false, true, false),
11813            ("custom:capability-only", false, false, false, true),
11814            ("", false, false, false, true),
11815        ] {
11816            let c = WitContract {
11817                de: "cart".into(),
11818                para: "catalog".into(),
11819                wit: wit.into(),
11820                endpoint: None,
11821                subject: None,
11822                slot: None,
11823            };
11824            assert_eq!(source_via_const_fn(&c), c.source());
11825            assert_eq!(destination_via_const_fn(&c), c.destination());
11826            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
11827            assert_eq!(is_http_via_const_fn(&c), c.is_http());
11828            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
11829            assert_eq!(is_store_via_const_fn(&c), c.is_store());
11830            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
11831            assert_eq!(c.source(), "cart");
11832            assert_eq!(c.destination(), "catalog");
11833            assert_eq!(c.world_ref(), wit);
11834            assert_eq!(c.is_http(), is_http);
11835            assert_eq!(c.is_pubsub(), is_pubsub);
11836            assert_eq!(c.is_store(), is_store);
11837            assert_eq!(c.is_capability(), is_capability);
11838        }
11839    }
11840
11841    #[test]
11842    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
11843        // Fail-before-pass-after pin on the four M3 mesh-slot
11844        // `String → &str` scalar accessors ([`Membro::nome`] /
11845        // [`Membro::versao_requirement`] on the per-`:membros` axis,
11846        // [`Entrada::hostname`] / [`Entrada::destination`] on the
11847        // per-`:entrada` axis) — each projects the typed slot's
11848        // [`String`] storage through the `pub const fn`
11849        // [`String::as_str`] (const-stable since Rust 1.87, well
11850        // within the workspace MSRV) and any future accidental
11851        // downgrade to non-`const` fails the corresponding
11852        // `<name>_via_const_fn` wrapper at caixa-core build time with
11853        // E0015 (`cannot call non-const method`), strictly stronger
11854        // than a runtime `assert!` and strictly stronger than a
11855        // module-scope `const _: () = assert!(…)` pin (which cannot
11856        // be formed on `&Membro` / `&Entrada` fixtures because the
11857        // types' `String` carriers rule out `const`-context value
11858        // construction; the `const fn` wrapper is the load-bearing
11859        // shape that side-steps the destructor-in-const restriction
11860        // on the value axis while still pinning the `const`-fn
11861        // posture on the callee — mirror of the sibling
11862        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
11863        // (279823b) pin on the per-`:contratos` axis). Peer of the
11864        // sibling per-M2/M3/universal-axis `String → &str` accessor
11865        // family pins on the sibling `const`-eval-surface passes
11866        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
11867        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
11868        // typed-newtype wrapper,
11869        // [`crate::supervisor::ChildSpec::nome`] /
11870        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
11871        // M2 supervisor-tree axis,
11872        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
11873        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
11874        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
11875        // axis, and the sibling per-`:contratos`
11876        // [`WitContract::source`] / [`WitContract::destination`] /
11877        // [`WitContract::world_ref`] trio at 279823b).
11878        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
11879            m.nome()
11880        }
11881        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
11882            m.versao_requirement()
11883        }
11884        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
11885            e.hostname()
11886        }
11887        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
11888            e.destination()
11889        }
11890        for (caixa, versao) in [
11891            ("cart", "^0.1"),
11892            ("catalog-v2", "~0.2.3"),
11893            ("checkout", "*"),
11894        ] {
11895            let m = Membro {
11896                caixa: caixa.into(),
11897                versao: versao.into(),
11898            };
11899            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
11900            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
11901            assert_eq!(m.nome(), caixa);
11902            assert_eq!(m.versao_requirement(), versao);
11903        }
11904        for (host, para) in [
11905            ("cart.example.com", "cart"),
11906            ("api.checkout.io", "checkout"),
11907        ] {
11908            let e = Entrada {
11909                host: host.into(),
11910                para: para.into(),
11911                paths: vec![],
11912                port: DEFAULT_SERVICO_PORT,
11913            };
11914            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
11915            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
11916            assert_eq!(e.hostname(), host);
11917            assert_eq!(e.destination(), para);
11918        }
11919    }
11920
11921    #[test]
11922    fn m3_option_string_scalar_accessor_family_is_const_fn() {
11923        // Fail-before-pass-after pin on the five M3 mesh-slot
11924        // `Option<String> → Option<&str>` scalar accessors
11925        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
11926        // [`WitContract::slot`] on the per-`:contratos` HTTP /
11927        // pub-sub / key-value payload-carrier trio,
11928        // [`Placement::shard_key`] / [`Placement::affinity`] on the
11929        // per-`:placement` Akka-sharding-key + Adaptive-compression-
11930        // hint pair). Each accessor destructures the typed slot's
11931        // `Option<String>` storage through the `match &self.<field> {
11932        // Some(s) => Some(s.as_str()), None => None }` shape —
11933        // routing through [`String::as_str`] (const-stable since Rust
11934        // 1.87, well within the workspace MSRV) rather than the
11935        // non-const [`Option::as_deref`] the pre-lift bodies carried
11936        // — and any future accidental downgrade to non-`const` fails
11937        // the corresponding `<name>_via_const_fn` wrapper at
11938        // caixa-core build time with E0015 (`cannot call non-const
11939        // method`), strictly stronger than a runtime `assert!` and
11940        // strictly stronger than a module-scope `const _: () =
11941        // assert!(…)` pin (which cannot be formed on `&WitContract`
11942        // / `&Placement` fixtures because the types' `String` /
11943        // `Option<String>` carriers rule out `const`-context value
11944        // construction; the `const fn` wrapper is the load-bearing
11945        // shape that side-steps the destructor-in-const restriction
11946        // on the value axis while still pinning the `const`-fn
11947        // posture on the callee — mirror of the sibling
11948        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
11949        // (279823b) and
11950        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
11951        // (29c5d7e) pins on the peer `String → &str` axes at the same
11952        // structs).
11953        //
11954        // Peer of the sibling per-`Caixa` `Option<String> →
11955        // Option<&str>` accessor family pin
11956        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
11957        // on the top-level manifest's optional universal-axis surface
11958        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
11959        // `:restart-window`).
11960        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
11961            w.endpoint()
11962        }
11963        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
11964            w.subject()
11965        }
11966        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
11967            w.slot()
11968        }
11969        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
11970            p.shard_key()
11971        }
11972        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
11973            p.affinity()
11974        }
11975        // Sweep every closed shape-arm partition on the
11976        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
11977        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
11978        // pair None), key-value (`:slot` Some, sibling pair None),
11979        // and Capability (all three None) so each accessor's
11980        // Some/None arm carries a pin through the const dispatch.
11981        for (wit, endpoint, subject, slot) in [
11982            ("wasi:http/proxy", Some("/api"), None, None),
11983            ("nats:pub-sub", None, Some("orders.paid"), None),
11984            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
11985            ("custom:capability-only", None, None, None),
11986        ] {
11987            let c = WitContract {
11988                de: "cart".into(),
11989                para: "catalog".into(),
11990                wit: wit.into(),
11991                endpoint: endpoint.map(str::to_string),
11992                subject: subject.map(str::to_string),
11993                slot: slot.map(str::to_string),
11994            };
11995            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
11996            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
11997            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
11998            assert_eq!(c.endpoint(), endpoint);
11999            assert_eq!(c.subject(), subject);
12000            assert_eq!(c.slot(), slot);
12001        }
12002        // Sweep both `Some`/`None` arms on each per-`:placement`
12003        // optional-scalar so the shard-key + affinity pair carries a
12004        // const-dispatch pin on both arms.
12005        for (shard_key, affinity) in [
12006            (Some("tenantId"), Some("data-locality")),
12007            (Some("$tenantId"), None),
12008            (None, Some("low-latency")),
12009            (None, None),
12010        ] {
12011            let p = Placement {
12012                estrategia: PlacementStrategy::default(),
12013                clusters: vec![],
12014                affinity: affinity.map(str::to_string),
12015                shard_key: shard_key.map(str::to_string),
12016            };
12017            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
12018            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
12019            assert_eq!(p.shard_key(), shard_key);
12020            assert_eq!(p.affinity(), affinity);
12021        }
12022    }
12023
12024    #[test]
12025    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
12026        // Load-bearing contract pin: on every canonical
12027        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
12028        // [`WitContract::target_projected`] returns byte-equal to
12029        // [`WitContract::target`]`().unwrap()` — the post-validation
12030        // projection accessor is a thin panicking wrapper over the
12031        // pre-validation validator, no extra work in the projection
12032        // path. Any future divergence (a validator-side normalization
12033        // the projection doesn't route through, an accessor-side
12034        // caching layer the validator doesn't populate) would surface
12035        // here at caixa-core build time rather than a silent per-consumer
12036        // split at renderer emit time. Sweeps the closed 4-arm
12037        // [`WitTarget`] partition ([`WitTarget::Http`] /
12038        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
12039        // [`WitTarget::Capability`]) so every arm carries a byte-equality
12040        // pin on the two-accessor pair.
12041        for (wit, endpoint, subject, slot) in [
12042            ("wasi:http/proxy", Some("/x"), None, None),
12043            ("nats:pub-sub", None, Some("events.x"), None),
12044            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
12045            ("custom:capability-only", None, None, None),
12046        ] {
12047            let c = WitContract {
12048                de: "cart".into(),
12049                para: "catalog".into(),
12050                wit: wit.into(),
12051                endpoint: endpoint.map(str::to_string),
12052                subject: subject.map(str::to_string),
12053                slot: slot.map(str::to_string),
12054            };
12055            assert_eq!(
12056                c.target_projected(),
12057                c.target().unwrap(),
12058                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
12059            );
12060        }
12061    }
12062
12063    #[test]
12064    #[should_panic(expected = "validated by typed_view")]
12065    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
12066        // Panic-path pin: [`WitContract::target_projected`] threads the
12067        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
12068        // through its expect-panic when called on a contract whose
12069        // (`:wit`, payload) shape has not been crossed by
12070        // [`AplicacaoSpec::validate`] — a contract with a structurally-
12071        // invalid `:wit` (hyphen-for-colon typo) that would surface
12072        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
12073        // A future rebrand on the panic-message axis would land at one
12074        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
12075        // and this pin's [`should_panic(expected = …)`] literal would
12076        // migrate alongside — the pin catches drift between the const
12077        // and the accessor's `expect(…)` call by construction.
12078        let c = WitContract {
12079            de: "cart".into(),
12080            para: "catalog".into(),
12081            // Hyphen-for-colon typo: `WitContract::target` returns
12082            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
12083            // driving the [`WitContract::target_projected`] expect-panic.
12084            wit: "wasi-http/proxy".into(),
12085            endpoint: Some("/x".into()),
12086            subject: None,
12087            slot: None,
12088        };
12089        let _ = c.target_projected();
12090    }
12091
12092    #[test]
12093    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
12094        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
12095        // carries the exact byte-string the two prior open-coded
12096        // `.target().expect("validated by typed_view")` production
12097        // consumers threaded through inline before this lift converged
12098        // them onto [`WitContract::target_projected`] — the caixa-mesh
12099        // per-`(:de, :para)` CNP L7 introspection branch at
12100        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
12101        // graph` per-`:contratos` payload-column printer at
12102        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
12103        // byte-string load-bearing so a well-meaning const-side rebrand
12104        // that didn't carry a matched pin migration would surface here
12105        // at caixa-core build time rather than a silent per-consumer
12106        // panic-message drift at cluster-apply time. Peer of the
12107        // sibling [`WitTarget::CAPABILITY_LABEL`] /
12108        // [`WitTarget::CAPABILITY_EXPECTED`] /
12109        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
12110        // the paired payload-less-arm scalar-const family.
12111        assert_eq!(
12112            WitContract::PROJECTED_INVARIANT_MSG,
12113            "validated by typed_view"
12114        );
12115    }
12116
12117    #[test]
12118    fn empty_wit_takes_precedence_over_invalid() {
12119        // Ordering pin: `EmptyWit` is the more self-locating
12120        // diagnostic on `""` and must lead — the value-shape gate is
12121        // only reached after the empty-check fires. Mirrors
12122        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12123        // the peer payload axis.
12124        let mut s = three_member_spec();
12125        s.contratos.push(WitContract {
12126            de: "payment".into(),
12127            para: "catalog".into(),
12128            wit: String::new(),
12129            endpoint: None,
12130            subject: None,
12131            slot: None,
12132        });
12133        let err = s.validate().unwrap_err();
12134        assert!(
12135            matches!(err, AplicacaoError::EmptyWit { .. }),
12136            "got {err:?}"
12137        );
12138    }
12139
12140    #[test]
12141    fn wit_invalid_fires_before_payload_shape_arm() {
12142        // Ordering pin: a malformed `:wit` surfaces *its own*
12143        // diagnostic (which names the offending wit verbatim) before
12144        // any payload-field check — a contrato whose wit is
12145        // structurally invalid AND carries a wrong target field
12146        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
12147        // because the dispatch on the wit is what decides which
12148        // payload field is "right" in the first place. Without this
12149        // ordering, the author would see "wrong target field" for a
12150        // wit that hasn't even been parsed, which doesn't name the
12151        // root cause.
12152        let mut s = three_member_spec();
12153        s.contratos.push(WitContract {
12154            de: "payment".into(),
12155            para: "catalog".into(),
12156            // Hyphen-for-colon typo + endpoint set: pre-gate this
12157            // raised `ContratoWrongTarget { expected: "none" }` (the
12158            // Capability arm rejecting the endpoint), masking the
12159            // real authoring mistake (the wit isn't `wasi:http/proxy`).
12160            wit: "wasi-http/proxy".into(),
12161            endpoint: Some("/x".into()),
12162            subject: None,
12163            slot: None,
12164        });
12165        let err = s.validate().unwrap_err();
12166        assert!(
12167            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
12168                if wit == "wasi-http/proxy"),
12169            "got {err:?}"
12170        );
12171    }
12172
12173    #[test]
12174    fn wit_invalid_diagnostic_carries_offending_wit() {
12175        // Diagnostic-shape pin — the offending `:wit` + `:de` +
12176        // `:para` + a non-empty reason flow through verbatim so the
12177        // author can grep their caixa.lisp for the offending contrato
12178        // block and fix it in one edit. Same shape as
12179        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
12180        let err = contrato_wit_err("WASI:HTTP/proxy");
12181        match err {
12182            AplicacaoError::ContratoWitInvalid {
12183                de,
12184                para,
12185                wit,
12186                reason,
12187            } => {
12188                assert_eq!(de, "payment");
12189                assert_eq!(para, "catalog");
12190                assert_eq!(wit, "WASI:HTTP/proxy");
12191                assert!(!reason.is_empty(), "reason field must be non-empty");
12192            }
12193            other => panic!("expected ContratoWitInvalid, got {other:?}"),
12194        }
12195    }
12196
12197    // ── :contratos :subject value-shape gate ─────────────────────────────
12198    //
12199    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
12200    // suites on the peer payload axes. Until this gate landed
12201    // `WitContract::target()` only refused the empty string; a
12202    // structurally invalid subject silently passed validate and the
12203    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
12204    // Subject'` on publish / subscribe, or as a silent message drop,
12205    // far from the source caixa.lisp. Every authoring footgun the
12206    // NATS server's subject parser would catch on admission now
12207    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
12208    // offending `:subject` + `:de` + `:para` named verbatim. Same
12209    // diagnostic shape as `ContratoEndpointInvalid` /
12210    // `ContratoWitInvalid` on the peer payload axes; same shared
12211    // predicate (`crate::render::is_nats_subject`) ensures drift
12212    // between any two axes' rule enforcement is a build error at the
12213    // predicate, not piecemeal across renderers.
12214
12215    fn contrato_subject_err(subject: &str) -> AplicacaoError {
12216        // Fresh spec per call so the new contract doesn't collide on
12217        // identity with `three_member_spec`'s pre-existing entries.
12218        // The new edge uses `(payment, catalog)` — a pair the fixture
12219        // doesn't already declare — with `:wit "nats:pub-sub"` and the
12220        // varying `:subject`, so the subject-shape gate fires cleanly
12221        // after the wit-shape gate (which `"nats:pub-sub"` passes).
12222        let mut s = three_member_spec();
12223        s.contratos.push(WitContract {
12224            de: "payment".into(),
12225            para: "catalog".into(),
12226            wit: "nats:pub-sub".into(),
12227            endpoint: None,
12228            subject: Some(subject.into()),
12229            slot: None,
12230        });
12231        s.validate().unwrap_err()
12232    }
12233
12234    #[test]
12235    fn rejects_pubsub_contrato_subject_with_whitespace() {
12236        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
12237        // landed at the NATS server as a malformed subject the parser
12238        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
12239        // source caixa.lisp.
12240        let err = contrato_subject_err("foo bar");
12241        assert!(
12242            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12243                if subject == "foo bar" && reason.contains("whitespace")),
12244            "got {err:?}"
12245        );
12246    }
12247
12248    #[test]
12249    fn rejects_pubsub_contrato_subject_with_control_char() {
12250        let err = contrato_subject_err("foo\x01bar");
12251        assert!(
12252            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12253                if subject == "foo\x01bar" && reason.contains("control character")),
12254            "got {err:?}"
12255        );
12256    }
12257
12258    #[test]
12259    fn rejects_pubsub_contrato_subject_with_non_ascii() {
12260        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12261        // the subject from a doc with smart quotes / accented
12262        // characters" footgun.
12263        let err = contrato_subject_err("foo.caf\u{e9}");
12264        assert!(
12265            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12266                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
12267            "got {err:?}"
12268        );
12269    }
12270
12271    #[test]
12272    fn rejects_pubsub_contrato_subject_with_leading_dot() {
12273        // Empty leading token — NATS rejects.
12274        let err = contrato_subject_err(".foo");
12275        assert!(
12276            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12277                if subject == ".foo" && reason.contains("must not start with `.`")),
12278            "got {err:?}"
12279        );
12280    }
12281
12282    #[test]
12283    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
12284        // Empty trailing token — NATS rejects. The remediation
12285        // (use `>` instead) is in the reason string.
12286        let err = contrato_subject_err("foo.");
12287        assert!(
12288            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12289                if subject == "foo." && reason.contains("must not end with `.`")),
12290            "got {err:?}"
12291        );
12292    }
12293
12294    #[test]
12295    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
12296        // The canonical "I forgot to fill in the middle segment"
12297        // typo — `"foo..bar"`. NATS rejects empty tokens.
12298        let err = contrato_subject_err("foo..bar");
12299        assert!(
12300            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12301                if subject == "foo..bar" && reason.contains("consecutive `.`")),
12302            "got {err:?}"
12303        );
12304    }
12305
12306    #[test]
12307    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
12308        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
12309        // as the final segment. Pre-gate this passed as a typed edge
12310        // and surfaced at runtime as a NATS subscribe rejection.
12311        let err = contrato_subject_err("foo.>.bar");
12312        assert!(
12313            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12314                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
12315            "got {err:?}"
12316        );
12317    }
12318
12319    #[test]
12320    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
12321        // `foo*.bar` — NATS wildcards are standalone tokens. The
12322        // remediation is in the reason string.
12323        let err = contrato_subject_err("foo*.bar");
12324        assert!(
12325            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12326                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
12327            "got {err:?}"
12328        );
12329    }
12330
12331    #[test]
12332    fn rejects_pubsub_contrato_subject_with_invalid_char() {
12333        // `foo,bar` — comma is not a valid NATS subject character.
12334        // Pinned separately from the wildcard arms so the invalid-
12335        // character diagnostic is in force.
12336        let err = contrato_subject_err("foo,bar");
12337        assert!(
12338            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12339                if subject == "foo,bar" && reason.contains("invalid character")),
12340            "got {err:?}"
12341        );
12342    }
12343
12344    #[test]
12345    fn rejects_pubsub_contrato_subject_too_long() {
12346        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
12347        // The legitimate-shape arms all pass (one all-`a` token, no
12348        // `.`, no wildcards); only the cap arm fires. Surfaces the
12349        // paste-from-binary / accidental-multi-line-blob landing
12350        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
12351        // on the peer axis.
12352        let big = "a".repeat(257);
12353        assert_eq!(big.len(), 257);
12354        let err = contrato_subject_err(&big);
12355        assert!(
12356            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12357                if subject == &big && reason.contains("max length of 256")),
12358            "got {err:?}"
12359        );
12360    }
12361
12362    #[test]
12363    fn pubsub_contrato_subject_max_length_validates() {
12364        // 256-byte subject — exactly the cap. Boundary pin: drift in
12365        // the cap surfaces here and at
12366        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
12367        // mirroring `http_contrato_endpoint_max_length_validates` and
12368        // `wit_max_length_validates` on the peer axes.
12369        let big = "a".repeat(256);
12370        assert_eq!(big.len(), 256);
12371        let mut s = three_member_spec();
12372        s.contratos.push(WitContract {
12373            de: "payment".into(),
12374            para: "catalog".into(),
12375            wit: "nats:pub-sub".into(),
12376            endpoint: None,
12377            subject: Some(big),
12378            slot: None,
12379        });
12380        s.validate().unwrap();
12381    }
12382
12383    #[test]
12384    fn pubsub_contrato_subject_accepts_canonical_forms() {
12385        // Positive-set sweep: every canonical NATS subject shape the
12386        // substrate-side `is_nats_subject` predicate accepts (the
12387        // multi-dot `events.order.charged`, the snake_case / kebab-
12388        // case / mixed-case tokens, the digit-bearing tokens, the
12389        // single-token wildcard `*` at every segment position, and
12390        // the trailing `>` multi-token wildcard) must remain a valid
12391        // contrato subject too. Drift between this list and the
12392        // substrate-side `nats_subject_accepts_canonical_forms` sweep
12393        // surfaces at the shared predicate — one source of truth.
12394        // Uses a fresh `(payment, catalog)` edge so none of the swept
12395        // subjects collide with the pre-existing entries in
12396        // `three_member_spec`.
12397        for subject in [
12398            "checkout.events.charge.failed",
12399            "rio.events.order.charged",
12400            "orders",
12401            "orders.123",
12402            "snake_case.token",
12403            "kebab-case.token",
12404            "MixedCase.Token",
12405            "orders.*.charged",
12406            "*.events.*",
12407            "orders.>",
12408        ] {
12409            let mut s = three_member_spec();
12410            s.contratos.push(WitContract {
12411                de: "payment".into(),
12412                para: "catalog".into(),
12413                wit: "nats:pub-sub".into(),
12414                endpoint: None,
12415                subject: Some(subject.into()),
12416                slot: None,
12417            });
12418            s.validate()
12419                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
12420        }
12421    }
12422
12423    #[test]
12424    fn contrato_subject_empty_takes_precedence_over_invalid() {
12425        // Ordering pin: `ContratoSubjectEmpty` is the more self-
12426        // locating diagnostic on `""` and must lead — the value-shape
12427        // gate is only reached after the empty-check fires. Mirrors
12428        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12429        // the peer payload axis.
12430        let mut s = three_member_spec();
12431        s.contratos.push(WitContract {
12432            de: "payment".into(),
12433            para: "catalog".into(),
12434            wit: "nats:pub-sub".into(),
12435            endpoint: None,
12436            subject: Some(String::new()),
12437            slot: None,
12438        });
12439        let err = s.validate().unwrap_err();
12440        assert!(
12441            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
12442            "got {err:?}"
12443        );
12444    }
12445
12446    #[test]
12447    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
12448        // Diagnostic-shape pin — the offending `:subject` + `:de` +
12449        // `:para` + a non-empty reason flow through verbatim so the
12450        // author can grep their caixa.lisp for the offending contrato
12451        // block and fix it in one edit. Same shape as
12452        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12453        // and `wit_invalid_diagnostic_carries_offending_wit`.
12454        let err = contrato_subject_err("foo..bar");
12455        match err {
12456            AplicacaoError::ContratoSubjectInvalid {
12457                de,
12458                para,
12459                subject,
12460                reason,
12461            } => {
12462                assert_eq!(de, "payment");
12463                assert_eq!(para, "catalog");
12464                assert_eq!(subject, "foo..bar");
12465                assert!(!reason.is_empty(), "reason field must be non-empty");
12466            }
12467            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
12468        }
12469    }
12470
12471    #[test]
12472    fn target_view_pubsub_subject_passes_through_to_typed_view() {
12473        // The compounding theorem on the pub-sub axis: every
12474        // `WitTarget::PubSub { subject }` returned by `target()` carries
12475        // a NATS-server-accepted subject. Renderers downstream of
12476        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
12477        // NATS Stream/Consumer CR emitter, the future `feira app graph`
12478        // view's subject labeller) can rely on this without re-checking
12479        // — the type system carries the proof. Mirrors
12480        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
12481        // on the peer axes.
12482        let nats = WitContract {
12483            de: "a".into(),
12484            para: "b".into(),
12485            wit: "nats:pub-sub".into(),
12486            endpoint: None,
12487            subject: Some("orders.events.*.charged".into()),
12488            slot: None,
12489        };
12490        match nats.target().unwrap() {
12491            WitTarget::PubSub { subject } => {
12492                assert_eq!(subject, "orders.events.*.charged");
12493            }
12494            other => panic!("expected PubSub, got {other:?}"),
12495        }
12496    }
12497
12498    // ── :contratos :slot value-shape gate ────────────────────────────────
12499    //
12500    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
12501    // (63e18a0) value-shape suites on the peer payload axes. Until this
12502    // gate landed `WitContract::target()` only refused the empty string
12503    // for the Store arm; a structurally invalid slot (raw whitespace,
12504    // control character, non-ASCII byte, paste-from-binary multi-line
12505    // blob) silently passed validate and surfaced at runtime as a
12506    // per-backend kv write rejection or a silent next-read corruption,
12507    // far from the source caixa.lisp with no field naming which
12508    // `:contratos` edge carried the typo. Every authoring footgun the
12509    // kv backend intersection-floor would catch on write now becomes a
12510    // caixa-build-time `ContratoSlotInvalid` with the offending
12511    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
12512    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
12513    // peer payload axes; same shared predicate
12514    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
12515    // any two axes' rule enforcement is a build error at the
12516    // predicate, not piecemeal across renderers. Closes the typed
12517    // payload-axis value-shape trajectory across all three legs of the
12518    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
12519
12520    fn contrato_slot_err(slot: &str) -> AplicacaoError {
12521        // Fresh spec per call so the new contract doesn't collide on
12522        // identity with `three_member_spec`'s pre-existing entries
12523        // and doesn't close a synchronous cycle the cycle detector
12524        // would reject before the slot-shape gate fires. The new edge
12525        // uses `(payment, catalog)` — a pair the fixture doesn't
12526        // already declare in either direction (the fixture carries
12527        // `cart -> catalog` and `cart -> payment`, so `payment ->
12528        // catalog` doesn't form a cycle on the sync subgraph) — with
12529        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
12530        // slot-shape gate fires cleanly after the wit-shape gate
12531        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
12532        // peer `contrato_subject_err` helper uses (63e18a0).
12533        let mut s = three_member_spec();
12534        s.contratos.push(WitContract {
12535            de: "payment".into(),
12536            para: "catalog".into(),
12537            wit: "wasi:keyvalue/store".into(),
12538            endpoint: None,
12539            subject: None,
12540            slot: Some(slot.into()),
12541        });
12542        s.validate().unwrap_err()
12543    }
12544
12545    #[test]
12546    fn rejects_store_contrato_slot_with_whitespace() {
12547        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
12548        // silently landed at the kv backend with whitespace whose
12549        // runtime behavior varies unpredictably across backends (etcd
12550        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
12551        // rejects on write). Now caught at the source caixa.lisp.
12552        let err = contrato_slot_err("check out/$order");
12553        assert!(
12554            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12555                if slot == "check out/$order" && reason.contains("whitespace")),
12556            "got {err:?}"
12557        );
12558    }
12559
12560    #[test]
12561    fn rejects_store_contrato_slot_with_tab() {
12562        // Tab byte arm-pinned separately from the space arm so a
12563        // future relaxation that admits one but not the other surfaces
12564        // here.
12565        let err = contrato_slot_err("check\tout");
12566        assert!(
12567            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12568                if slot == "check\tout" && reason.contains("whitespace")),
12569            "got {err:?}"
12570        );
12571    }
12572
12573    #[test]
12574    fn rejects_store_contrato_slot_with_control_char() {
12575        // SOH (0x01) — distinct from the whitespace arm. Redis admits
12576        // and corrupts on RESP protocol framing; DynamoDB rejects on
12577        // write.
12578        let err = contrato_slot_err("checkout/\x01order");
12579        assert!(
12580            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12581                if slot == "checkout/\x01order" && reason.contains("control character")),
12582            "got {err:?}"
12583        );
12584    }
12585
12586    #[test]
12587    fn rejects_store_contrato_slot_with_newline() {
12588        // Embedded newline — the canonical "the paste-from-binary slug
12589        // spans multiple lines" footgun. Distinct from the whitespace
12590        // arm because `\n` is a control character (0x0A).
12591        let err = contrato_slot_err("checkout\norder");
12592        assert!(
12593            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12594                if slot == "checkout\norder" && reason.contains("control character")),
12595            "got {err:?}"
12596        );
12597    }
12598
12599    #[test]
12600    fn rejects_store_contrato_slot_with_non_ascii() {
12601        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12602        // the slot from a doc with accented characters" footgun. Each
12603        // kv backend re-encodes non-ASCII differently (etcd preserves
12604        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
12605        // rejects), so the typed slot's value set is the intersection-
12606        // floor every backend admits identically (printable ASCII).
12607        let err = contrato_slot_err("ch\u{e9}ckout/$order");
12608        assert!(
12609            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12610                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
12611            "got {err:?}"
12612        );
12613    }
12614
12615    #[test]
12616    fn rejects_store_contrato_slot_too_long() {
12617        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
12618        // legitimate-shape arms all pass (a single all-`a` token, no
12619        // separators); only the cap arm fires. Surfaces the paste-
12620        // from-binary / accidental-multi-line-blob landing footgun.
12621        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
12622        // `rejects_http_contrato_endpoint_too_long` on the peer
12623        // payload axes.
12624        let big = "a".repeat(513);
12625        assert_eq!(big.len(), 513);
12626        let err = contrato_slot_err(&big);
12627        assert!(
12628            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12629                if slot == &big && reason.contains("max length of 512")),
12630            "got {err:?}"
12631        );
12632    }
12633
12634    #[test]
12635    fn store_contrato_slot_max_length_validates() {
12636        // 512-byte slot — exactly the cap. Boundary pin: drift in the
12637        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
12638        // simultaneously, mirroring
12639        // `pubsub_contrato_subject_max_length_validates` and
12640        // `http_contrato_endpoint_max_length_validates` on the peer
12641        // payload axes.
12642        let big = "a".repeat(512);
12643        assert_eq!(big.len(), 512);
12644        let mut s = three_member_spec();
12645        s.contratos.push(WitContract {
12646            de: "payment".into(),
12647            para: "catalog".into(),
12648            wit: "wasi:keyvalue/store".into(),
12649            endpoint: None,
12650            subject: None,
12651            slot: Some(big),
12652        });
12653        s.validate().unwrap();
12654    }
12655
12656    #[test]
12657    fn store_contrato_slot_accepts_canonical_forms() {
12658        // Positive-set sweep: every canonical kv slot template the
12659        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
12660        // (single-token identifiers, path-namespaced `$`-templates,
12661        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
12662        // snake_case / kebab-case / MixedCase tokens, digit-bearing
12663        // tokens, percent-encoded fragments) must remain valid
12664        // contrato slots too. Drift between this list and the
12665        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
12666        // surfaces at the shared predicate — one source of truth.
12667        // Uses a fresh `(payment, catalog)` edge so none of the swept
12668        // slots collide with the pre-existing entries in
12669        // `three_member_spec`.
12670        for slot in [
12671            "checkout",
12672            "checkout/$orderId",
12673            "users:{tenant}/{id}",
12674            "session.<sid>",
12675            "session.tokens.<sid>",
12676            "snake_case_key",
12677            "kebab-case-key",
12678            "MixedCase",
12679            "shard0",
12680            "v2/key",
12681            "users/caf%C3%A9",
12682        ] {
12683            let mut s = three_member_spec();
12684            s.contratos.push(WitContract {
12685                de: "payment".into(),
12686                para: "catalog".into(),
12687                wit: "wasi:keyvalue/store".into(),
12688                endpoint: None,
12689                subject: None,
12690                slot: Some(slot.into()),
12691            });
12692            s.validate()
12693                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
12694        }
12695    }
12696
12697    #[test]
12698    fn contrato_slot_empty_takes_precedence_over_invalid() {
12699        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
12700        // diagnostic on `""` and must lead — the value-shape gate is
12701        // only reached after the empty-check fires. Mirrors
12702        // `contrato_subject_empty_takes_precedence_over_invalid` and
12703        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12704        // the peer payload axes.
12705        let mut s = three_member_spec();
12706        s.contratos.push(WitContract {
12707            de: "payment".into(),
12708            para: "catalog".into(),
12709            wit: "wasi:keyvalue/store".into(),
12710            endpoint: None,
12711            subject: None,
12712            slot: Some(String::new()),
12713        });
12714        let err = s.validate().unwrap_err();
12715        assert!(
12716            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
12717            "got {err:?}"
12718        );
12719    }
12720
12721    #[test]
12722    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
12723        // Diagnostic-shape pin — the offending `:slot` + `:de` +
12724        // `:para` + a non-empty reason flow through verbatim so the
12725        // author can grep their caixa.lisp for the offending contrato
12726        // block and fix it in one edit. Same shape as
12727        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
12728        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12729        // on the peer payload axes.
12730        let err = contrato_slot_err("check out/$order");
12731        match err {
12732            AplicacaoError::ContratoSlotInvalid {
12733                de,
12734                para,
12735                slot,
12736                reason,
12737            } => {
12738                assert_eq!(de, "payment");
12739                assert_eq!(para, "catalog");
12740                assert_eq!(slot, "check out/$order");
12741                assert!(!reason.is_empty(), "reason field must be non-empty");
12742            }
12743            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
12744        }
12745    }
12746
12747    #[test]
12748    fn target_view_store_slot_passes_through_to_typed_view() {
12749        // The compounding theorem on the store axis: every
12750        // `WitTarget::Store { slot }` returned by `target()` carries a
12751        // kv-backend-accepted slot template. Renderers downstream of
12752        // `typed_view()` (the future per-Servico `:capabilities
12753        // wasi:keyvalue/store` axis emitter, the future `feira app
12754        // graph` view's slot labeller, the future kv-provider CR
12755        // materializer) can rely on this without re-checking — the
12756        // type system carries the proof. Mirrors
12757        // `target_view_pubsub_subject_passes_through_to_typed_view` on
12758        // the peer payload axis.
12759        let store = WitContract {
12760            de: "a".into(),
12761            para: "b".into(),
12762            wit: "wasi:keyvalue/store".into(),
12763            endpoint: None,
12764            subject: None,
12765            slot: Some("checkout/$orderId".into()),
12766        };
12767        match store.target().unwrap() {
12768            WitTarget::Store { slot } => {
12769                assert_eq!(slot, "checkout/$orderId");
12770            }
12771            other => panic!("expected Store, got {other:?}"),
12772        }
12773    }
12774
12775    #[test]
12776    fn rejects_self_loop_in_synchronous_contratos() {
12777        // A synchronous self-edge (`cart → cart` over HTTP) is now
12778        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
12779        // "this edge is degenerate" diagnostic — rather than incidentally
12780        // by the cycle detector framing it as a `["cart", "cart"]`
12781        // multi-node deadlock.
12782        let mut s = three_member_spec();
12783        s.contratos.push(contract_http("cart", "cart", "/loop"));
12784        let err = s.validate().unwrap_err();
12785        match err {
12786            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
12787                assert_eq!(caixa, "cart");
12788                assert_eq!(wit, "wasi:http/proxy");
12789            }
12790            other => panic!("expected ContratoSelfLoop, got {other:?}"),
12791        }
12792    }
12793
12794    #[test]
12795    fn rejects_self_loop_in_pubsub_contratos() {
12796        // The cycle detector excludes pub-sub edges (acyclic by
12797        // construction), so before the explicit gate a `nats:pub-sub`
12798        // self-edge silently validated and rendered a self-allow CNP.
12799        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
12800        let mut s = three_member_spec();
12801        s.contratos.push(WitContract {
12802            de: "payment".into(),
12803            para: "payment".into(),
12804            wit: "nats:pub-sub".into(),
12805            endpoint: None,
12806            subject: Some("rio.events.payment".into()),
12807            slot: None,
12808        });
12809        let err = s.validate().unwrap_err();
12810        match err {
12811            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
12812                assert_eq!(caixa, "payment");
12813                assert_eq!(wit, "nats:pub-sub");
12814            }
12815            other => panic!("expected ContratoSelfLoop, got {other:?}"),
12816        }
12817    }
12818
12819    #[test]
12820    fn self_loop_fires_before_payload_shape_check() {
12821        // The structural "this edge can't exist" error precedes the
12822        // narrower payload-shape diagnostics: a self-edge carrying an
12823        // otherwise-malformed endpoint still reports ContratoSelfLoop,
12824        // not ContratoEndpointInvalid.
12825        let mut s = three_member_spec();
12826        s.contratos.push(WitContract {
12827            de: "cart".into(),
12828            para: "cart".into(),
12829            wit: "wasi:http/proxy".into(),
12830            endpoint: Some("not-absolute".into()),
12831            subject: None,
12832            slot: None,
12833        });
12834        match s.validate().unwrap_err() {
12835            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
12836            other => panic!("expected ContratoSelfLoop, got {other:?}"),
12837        }
12838    }
12839
12840    #[test]
12841    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
12842        // A self-edge naming a non-member reports the more fundamental
12843        // ContratoMemberMissing first (the member doesn't exist), so the
12844        // self-loop gate is reached only once both endpoints resolve.
12845        let mut s = three_member_spec();
12846        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
12847        match s.validate().unwrap_err() {
12848            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
12849            other => panic!("expected ContratoMemberMissing, got {other:?}"),
12850        }
12851    }
12852
12853    #[test]
12854    fn rejects_two_node_synchronous_cycle() {
12855        let mut s = three_member_spec();
12856        // existing edges: cart → catalog, cart → payment
12857        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
12858        s.contratos
12859            .push(contract_http("catalog", "cart", "/refresh"));
12860        let err = s.validate().unwrap_err();
12861        match err {
12862            AplicacaoError::ContratoCycle { cycle } => {
12863                // Cycle traversal should mention both endpoints, with
12864                // the back-edge target appearing as both first and last
12865                // element to close the loop.
12866                assert!(cycle.len() >= 3);
12867                assert_eq!(cycle.first(), cycle.last());
12868                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
12869                assert!(body.contains("cart"));
12870                assert!(body.contains("catalog"));
12871            }
12872            other => panic!("expected ContratoCycle, got {other:?}"),
12873        }
12874    }
12875
12876    #[test]
12877    fn rejects_three_node_synchronous_cycle() {
12878        let mut s = three_member_spec();
12879        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
12880        s.contratos = vec![
12881            contract_http("catalog", "cart", "/x"),
12882            contract_http("cart", "payment", "/y"),
12883            contract_http("payment", "catalog", "/z"),
12884        ];
12885        let err = s.validate().unwrap_err();
12886        match err {
12887            AplicacaoError::ContratoCycle { cycle } => {
12888                assert_eq!(cycle.first(), cycle.last());
12889                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
12890                assert_eq!(body.len(), 3);
12891                assert!(body.contains("cart"));
12892                assert!(body.contains("catalog"));
12893                assert!(body.contains("payment"));
12894            }
12895            other => panic!("expected ContratoCycle, got {other:?}"),
12896        }
12897    }
12898
12899    #[test]
12900    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
12901        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
12902        // "acyclic by construction" — so a cycle whose closing edge
12903        // is pub-sub should NOT raise ContratoCycle.
12904        let mut s = three_member_spec();
12905        s.contratos = vec![
12906            contract_http("catalog", "cart", "/x"),
12907            contract_http("cart", "payment", "/y"),
12908            // Closing edge is pub-sub — async; not a sync deadlock.
12909            WitContract {
12910                de: "payment".into(),
12911                para: "catalog".into(),
12912                wit: "nats:pub-sub".into(),
12913                endpoint: None,
12914                subject: Some("checkout.events.charge.completed".into()),
12915                slot: None,
12916            },
12917        ];
12918        s.validate().expect("pub-sub edge breaks the sync cycle");
12919    }
12920
12921    #[test]
12922    fn store_edge_counts_as_synchronous_for_cycle_detection() {
12923        // wasi:keyvalue/store is request/response; a cycle through one
12924        // *is* a sync deadlock, just like HTTP.
12925        let mut s = three_member_spec();
12926        s.contratos = vec![
12927            contract_http("catalog", "cart", "/x"),
12928            WitContract {
12929                de: "cart".into(),
12930                para: "catalog".into(),
12931                wit: "wasi:keyvalue/store".into(),
12932                endpoint: None,
12933                subject: None,
12934                slot: Some("session/$id".into()),
12935            },
12936        ];
12937        let err = s.validate().unwrap_err();
12938        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
12939    }
12940
12941    #[test]
12942    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
12943        // Capability-only edges (unknown WIT shape, no payload) default
12944        // to synchronous — safer; authors with truly async capability
12945        // semantics can model them as pub-sub explicitly.
12946        let mut s = three_member_spec();
12947        s.contratos = vec![
12948            contract_http("catalog", "cart", "/x"),
12949            WitContract {
12950                de: "cart".into(),
12951                para: "catalog".into(),
12952                wit: "custom:exchange".into(),
12953                endpoint: None,
12954                subject: None,
12955                slot: None,
12956            },
12957        ];
12958        let err = s.validate().unwrap_err();
12959        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
12960    }
12961
12962    #[test]
12963    fn long_acyclic_chain_validates() {
12964        // A long sync chain (no back-edges) must validate even when
12965        // every node is reachable from the first.
12966        let mut s = three_member_spec();
12967        s.membros = vec![
12968            membro("a", "^0.1"),
12969            membro("b", "^0.1"),
12970            membro("c", "^0.1"),
12971            membro("d", "^0.1"),
12972            membro("e", "^0.1"),
12973        ];
12974        s.contratos = vec![
12975            contract_http("a", "b", "/1"),
12976            contract_http("b", "c", "/2"),
12977            contract_http("c", "d", "/3"),
12978            contract_http("d", "e", "/4"),
12979        ];
12980        s.entrada.as_mut().unwrap().para = "a".into();
12981        s.validate().unwrap();
12982    }
12983
12984    #[test]
12985    fn diamond_acyclic_validates() {
12986        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
12987        let mut s = three_member_spec();
12988        s.membros = vec![
12989            membro("a", "^0.1"),
12990            membro("b", "^0.1"),
12991            membro("c", "^0.1"),
12992            membro("d", "^0.1"),
12993        ];
12994        s.contratos = vec![
12995            contract_http("a", "b", "/1"),
12996            contract_http("a", "c", "/2"),
12997            contract_http("b", "d", "/3"),
12998            contract_http("c", "d", "/4"),
12999        ];
13000        s.entrada.as_mut().unwrap().para = "a".into();
13001        s.validate().unwrap();
13002    }
13003
13004    // ── duplicate-`:contratos` build-error gate ──────────────────────────
13005
13006    #[test]
13007    fn rejects_duplicate_http_contrato() {
13008        // Fail-before-pass-after pin: the fixture's `cart → catalog`
13009        // HTTP edge appears once. Push an identical entry — same
13010        // (de, para, wit, endpoint) — and validate() must reject it.
13011        // Until this gate landed the typed surface accepted the
13012        // duplicate silently and caixa-mesh's `cilium_network_policies`
13013        // emitted two ``CiliumNetworkPolicy`` objects with identical
13014        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
13015        // admission rejects on `kubectl apply` far from the source.
13016        let mut s = three_member_spec();
13017        s.contratos
13018            .push(contract_http("cart", "catalog", "/products/:id"));
13019        let err = s.validate().unwrap_err();
13020        assert!(
13021            matches!(
13022                err,
13023                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13024                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
13025            ),
13026            "got {err:?}"
13027        );
13028    }
13029
13030    #[test]
13031    fn rejects_duplicate_pubsub_contrato() {
13032        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
13033        // edges with identical (de, para, subject) are degenerate;
13034        // pin that the typed surface refuses both at validate time.
13035        let mut s = three_member_spec();
13036        let pubsub = WitContract {
13037            de: "payment".into(),
13038            para: "cart".into(),
13039            wit: "nats:pub-sub".into(),
13040            endpoint: None,
13041            subject: Some("checkout.events.charge.failed".into()),
13042            slot: None,
13043        };
13044        s.contratos.push(pubsub.clone());
13045        s.contratos.push(pubsub);
13046        let err = s.validate().unwrap_err();
13047        assert!(
13048            matches!(
13049                err,
13050                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13051                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
13052            ),
13053            "got {err:?}"
13054        );
13055    }
13056
13057    #[test]
13058    fn rejects_duplicate_store_contrato() {
13059        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
13060        // edges with identical (de, para, slot) collapse to one mesh-
13061        // policy edge; pin the build error.
13062        let mut s = three_member_spec();
13063        let store = WitContract {
13064            de: "cart".into(),
13065            para: "payment".into(),
13066            wit: "wasi:keyvalue/store".into(),
13067            endpoint: None,
13068            subject: None,
13069            slot: Some("checkout/$orderId".into()),
13070        };
13071        // Drop the conflicting HTTP `cart → payment` edge from the
13072        // fixture so the duplicate-store pair is the only one
13073        // distinguishable on this pair.
13074        s.contratos
13075            .retain(|c| !(c.de == "cart" && c.para == "payment"));
13076        s.contratos.push(store.clone());
13077        s.contratos.push(store);
13078        let err = s.validate().unwrap_err();
13079        assert!(
13080            matches!(
13081                err,
13082                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13083                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
13084            ),
13085            "got {err:?}"
13086        );
13087    }
13088
13089    #[test]
13090    fn rejects_duplicate_capability_contrato() {
13091        // Same gate on the pure-capability axis (no payload selector).
13092        // Two contracts with identical (de, para, wit) and no
13093        // endpoint/subject/slot are duplicate edges; pin so a future
13094        // `target_label` change can't accidentally collapse the
13095        // capability arm into a None-shaped key that compares equal
13096        // to a populated one.
13097        let mut s = three_member_spec();
13098        let capability = WitContract {
13099            de: "cart".into(),
13100            para: "catalog".into(),
13101            wit: "pleme:cap/audit".into(),
13102            endpoint: None,
13103            subject: None,
13104            slot: None,
13105        };
13106        s.contratos.push(capability.clone());
13107        s.contratos.push(capability);
13108        let err = s.validate().unwrap_err();
13109        match err {
13110            AplicacaoError::ContratoDuplicate {
13111                de,
13112                para,
13113                wit,
13114                target,
13115            } => {
13116                assert_eq!(de, "cart");
13117                assert_eq!(para, "catalog");
13118                assert_eq!(wit, "pleme:cap/audit");
13119                assert!(
13120                    target.contains("capability"),
13121                    "capability-edge duplicate diagnostic must surface the \
13122                     no-payload shape (got target = {target:?})"
13123                );
13124            }
13125            other => panic!("expected ContratoDuplicate, got {other:?}"),
13126        }
13127    }
13128
13129    #[test]
13130    fn accepts_distinct_http_paths_between_same_pair() {
13131        // Negative pin: two HTTP contracts cart → catalog at distinct
13132        // endpoints (`/products/:id` and `/search`) are *not*
13133        // duplicates — they're distinct typed edges differing on the
13134        // payload axis. The duplicate-gate must not over-match here,
13135        // since the cart-calls-catalog-on-multiple-paths shape is the
13136        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
13137        // example: cart calls catalog at /products/:id, payment at
13138        // /charge — same shape extends to two paths on one para).
13139        let mut s = three_member_spec();
13140        s.contratos
13141            .push(contract_http("cart", "catalog", "/search"));
13142        s.validate()
13143            .expect("distinct endpoints between same (de, para) must validate");
13144    }
13145
13146    #[test]
13147    fn accepts_same_endpoint_on_different_pairs() {
13148        // Negative pin: the same `/charge` endpoint reused on two
13149        // different (de, para) pairs is two distinct edges, not a
13150        // duplicate. Pinning this shape so the gate's identity key
13151        // includes both `de` and `para` (not just `(wit, endpoint)`).
13152        let mut s = three_member_spec();
13153        s.contratos
13154            .push(contract_http("payment", "catalog", "/charge"));
13155        s.validate()
13156            .expect("same endpoint reused on distinct (de, para) must validate");
13157    }
13158
13159    #[test]
13160    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
13161        // Pin the diagnostic shape: the duplicate-edge error names
13162        // *which* target field carried the conflict, so the author
13163        // doesn't have to re-grep the source caixa.lisp to find it.
13164        // Same self-locating diagnostic discipline as
13165        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
13166        let mut s = three_member_spec();
13167        s.contratos
13168            .push(contract_http("cart", "catalog", "/products/:id"));
13169        let err = s.validate().unwrap_err();
13170        let msg = format!("{err}");
13171        assert!(
13172            msg.contains("\"/products/:id\""),
13173            "duplicate-contrato diagnostic must name the offending \
13174             :endpoint payload (got: {msg:?})"
13175        );
13176        assert!(
13177            msg.contains("cart") && msg.contains("catalog"),
13178            "diagnostic must name both endpoints of the duplicate edge \
13179             (got: {msg:?})"
13180        );
13181    }
13182
13183    #[test]
13184    fn duplicate_contrato_gate_runs_after_membership_check() {
13185        // Order pin: a duplicate contract whose `:de` is *also* not in
13186        // `:membros` surfaces the membership error first — the
13187        // missing-member diagnostic is more locating than the
13188        // duplicate-edge one (the author has to fix the membership
13189        // before the duplicate is meaningful). Same ordering
13190        // discipline as `membros_validation_runs_before_contratos_membership_check`.
13191        let mut s = three_member_spec();
13192        s.contratos.push(contract_http("phantom", "catalog", "/x"));
13193        s.contratos.push(contract_http("phantom", "catalog", "/x"));
13194        let err = s.validate().unwrap_err();
13195        assert!(
13196            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
13197            "membership-missing must fire before duplicate-edge (got {err:?})"
13198        );
13199    }
13200
13201    #[test]
13202    fn duplicate_contrato_gate_runs_after_target_shape_check() {
13203        // Order pin: a contract with a malformed target (e.g. an HTTP
13204        // wit world with an empty :endpoint) surfaces the target-shape
13205        // error first, not the duplicate one. Even when two such
13206        // malformed entries are identical, the per-contract `target()`
13207        // check fires inside the loop *before* the duplicate-key
13208        // insert, so the diagnostic remains the most-locating one.
13209        let mut s = three_member_spec();
13210        let malformed = WitContract {
13211            de: "cart".into(),
13212            para: "catalog".into(),
13213            wit: "wasi:http/proxy".into(),
13214            endpoint: Some(String::new()),
13215            subject: None,
13216            slot: None,
13217        };
13218        s.contratos.push(malformed.clone());
13219        s.contratos.push(malformed);
13220        let err = s.validate().unwrap_err();
13221        assert!(
13222            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
13223            "endpoint-empty must fire before duplicate-edge (got {err:?})"
13224        );
13225    }
13226
13227    #[test]
13228    fn wit_target_label_pins_per_variant_format() {
13229        // Label format is the single source of truth every duplicate-
13230        // `:contratos` diagnostic + every future `feira app graph`
13231        // consumer routes through. Pin the shape per variant so a
13232        // future edit to `WitTarget::label` (e.g. a JSON emitter that
13233        // strips the leading `:`, or a rename from `endpoint` →
13234        // `path`) surfaces as a red-red test rather than as a silent
13235        // downstream diagnostic drift. Together with the exhaustive
13236        // `match` on `WitTarget` inside `label()`, adding a future
13237        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
13238        // peer, per-edge WIT registry variants) is a compile error at
13239        // the label site — not a fall-through into the `Capability`
13240        // "no payload" default the prior raw-field-probe helper
13241        // silently landed on.
13242        assert_eq!(
13243            WitTarget::Http {
13244                endpoint: "/charge",
13245            }
13246            .label(),
13247            "\
13248:endpoint \"/charge\""
13249        );
13250        assert_eq!(
13251            WitTarget::PubSub {
13252                subject: "events.checkout.paid",
13253            }
13254            .label(),
13255            "\
13256:subject \"events.checkout.paid\""
13257        );
13258        assert_eq!(
13259            WitTarget::Store {
13260                slot: "checkout/$order",
13261            }
13262            .label(),
13263            "\
13264:slot \"checkout/$order\""
13265        );
13266        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
13267        // Capability-arm label routes through the lifted
13268        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
13269        // declaration per arm, next to the variant" discipline the
13270        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
13271        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13272        // consts already carry extends to the payload-less arm; the
13273        // byte-string equality pin below plus this label-routes-
13274        // through-the-const pin make a future rebrand on either the
13275        // const declaration or the `label()` template a build error
13276        // here rather than a downstream consumer surprise.
13277        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
13278        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
13279    }
13280
13281    #[test]
13282    fn wit_target_display_routes_through_label_helper() {
13283        // Fail-before-pass-after pin on the fourth (and only remaining)
13284        // typed-shape-discriminator axis to converge onto the
13285        // three-path-convergence discipline the sibling M3
13286        // [`PlacementStrategy`] (0a2f653) and M2
13287        // [`crate::supervisor::RestartStrategy`] /
13288        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
13289        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
13290        // through [`WitTarget::label`], so every consumer reaching for
13291        // `format!("{v}")` on a typed payload target lands on the same
13292        // stable author-facing byte-string [`WitTarget::label`] returns
13293        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
13294        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
13295        // `:contratos` gate seeds via [`WitTarget::label`] at
13296        // aplicacao.rs:5491 already threads through.
13297        //
13298        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
13299        // through to the `Debug` derive's structural output
13300        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
13301        // rather than the [`WitTarget::label`] helper's stable byte-
13302        // string (`:endpoint "/charge"` — the author-facing `:contratos`
13303        // keyword form). Every future consumer that reaches for
13304        // `format!("{target}")` — the canonical shape every user-facing
13305        // pretty-print site on the sibling typed-enum axes
13306        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
13307        // [`crate::supervisor::RestartPolicy`]) already uses — would
13308        // silently land under a different byte-string than the
13309        // [`WitTarget::label`] callers that the duplicate-`:contratos`
13310        // diagnostic already threads through, with the mismatch
13311        // surfacing as a downstream diagnostic / graph / audit line
13312        // reading one spelling while the substrate's own gate emitted
13313        // another.
13314        //
13315        // Pin the routing here so a future
13316        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
13317        // that hand-rolls the per-arm formatting instead of delegating
13318        // to [`WitTarget::label`] fails at caixa-core build time.
13319        for variant in [
13320            WitTarget::Http {
13321                endpoint: "/charge",
13322            },
13323            WitTarget::PubSub {
13324                subject: "events.checkout.paid",
13325            },
13326            WitTarget::Store {
13327                slot: "checkout/$order",
13328            },
13329            WitTarget::Capability,
13330        ] {
13331            assert_eq!(
13332                variant.to_string(),
13333                variant.label(),
13334                "WitTarget::{variant:?} Display must route through \
13335                 WitTarget::label (single source of truth: the lifted \
13336                 payload_pair 4-arm dispatch the label helper already \
13337                 threads through)"
13338            );
13339        }
13340    }
13341
13342    #[test]
13343    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
13344        // Consumer-side pin on the three-path convergence:
13345        // [`std::fmt::Display`] agrees byte-for-byte with the
13346        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
13347        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
13348        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
13349        // Pre-lift the two paths were structurally independent — the
13350        // substrate-side gate reached for `target_view.label()` while a
13351        // future downstream diagnostic / graph / audit line reaching
13352        // for `format!("{target}")` would silently land on the `Debug`
13353        // derive's structural output. Pin the two paths byte-for-byte
13354        // here so any future variant addition (M4 `Rest`/`Grpc` split
13355        // of [`WitTarget::Http`], `Queue`-shaped peer of
13356        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
13357        // match error at [`WitTarget::payload_pair`] rather than a
13358        // silent per-consumer dispatch miss.
13359        for variant in [
13360            WitTarget::Http {
13361                endpoint: "/charge",
13362            },
13363            WitTarget::PubSub {
13364                subject: "events.checkout.paid",
13365            },
13366            WitTarget::Store {
13367                slot: "checkout/$order",
13368            },
13369            WitTarget::Capability,
13370        ] {
13371            assert_eq!(
13372                format!("{variant}"),
13373                variant.label(),
13374                "WitTarget::{variant:?} Display byte-string must match \
13375                 the AplicacaoError::ContratoDuplicate `target:` carrier \
13376                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
13377                 seeds via WitTarget::label — three-path convergence: \
13378                 Display + label + payload_pair all resolve to the same \
13379                 per-arm byte-string"
13380            );
13381        }
13382    }
13383
13384    #[test]
13385    fn wit_target_payload_pair_pins_per_variant() {
13386        // Pin the per-arm `(field-name, payload)` pair single-sourced
13387        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
13388        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
13389        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
13390        // and [`WitTarget::field_name`] (returns the first component)
13391        // route through. Until this lift landed [`WitTarget::label`]
13392        // dispatched on the same three arms with a per-arm
13393        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
13394        // paired [`WitTarget::HTTP_FIELD_NAME`] /
13395        // [`WitTarget::PUBSUB_FIELD_NAME`] /
13396        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
13397        // canonical "same shape, written N times" duplication
13398        // THEORY.md §I.3.5 promotes to a build-time concern. A future
13399        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
13400        // [`WitTarget::Http`], `Queue`-shaped peer of
13401        // [`WitTarget::Store`]) is one match-arm edit at
13402        // [`WitTarget::payload_pair`], visible here as a compile-time
13403        // exhaustiveness error on both this pin and the label-format
13404        // pin above.
13405        assert_eq!(
13406            WitTarget::Http {
13407                endpoint: "/charge"
13408            }
13409            .payload_pair(),
13410            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
13411        );
13412        assert_eq!(
13413            WitTarget::PubSub {
13414                subject: "events.x",
13415            }
13416            .payload_pair(),
13417            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
13418        );
13419        assert_eq!(
13420            WitTarget::Store {
13421                slot: "checkout/$order",
13422            }
13423            .payload_pair(),
13424            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
13425        );
13426        assert_eq!(WitTarget::Capability.payload_pair(), None);
13427    }
13428
13429    #[test]
13430    fn wit_target_field_name_pins_per_variant() {
13431        // Pin the per-arm author-facing `:contratos` payload field
13432        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
13433        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13434        // + returned by [`WitTarget::field_name`]. Every downstream
13435        // consumer (the [`WitContract::target`] gate's `expected:`
13436        // scalar, the [`WitTarget::label`] template's keyword prefix,
13437        // the `feira app graph` verb's `endpoint=…` prefix) routes
13438        // through the same three peer consts, so a rename on the
13439        // author-surface `(defcaixa … :contratos ((:de … :para …
13440        // :wit … :endpoint …)))` field lands in exactly one place.
13441        assert_eq!(
13442            WitTarget::Http {
13443                endpoint: "/charge"
13444            }
13445            .field_name(),
13446            Some(WitTarget::HTTP_FIELD_NAME),
13447        );
13448        assert_eq!(
13449            WitTarget::PubSub {
13450                subject: "events.x",
13451            }
13452            .field_name(),
13453            Some(WitTarget::PUBSUB_FIELD_NAME),
13454        );
13455        assert_eq!(
13456            WitTarget::Store {
13457                slot: "checkout/$order",
13458            }
13459            .field_name(),
13460            Some(WitTarget::STORE_FIELD_NAME),
13461        );
13462        // Capability arm carries no payload field — the diagnostic
13463        // never reports `expected: "capability"` because the gate's
13464        // Capability arm accepts no payload at all (it fires the
13465        // "expected: none" WrongTarget error instead), so the field-
13466        // name method returns None here rather than a placeholder.
13467        assert_eq!(WitTarget::Capability.field_name(), None);
13468
13469        // Peer const scalar values pinned so a rename on either side
13470        // (author-surface field name in the `(defcaixa …)` DSL, or
13471        // the diagnostic's `expected:` scalar) can't drift without
13472        // failing here first.
13473        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
13474        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
13475        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
13476    }
13477
13478    #[test]
13479    fn wit_target_payload_pins_per_variant() {
13480        // Pin the per-arm payload scalar single-sourced onto the
13481        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
13482        // [`WitTarget::payload`] — the peer per-half projection to
13483        // [`WitTarget::field_name`] on the paired sub-selector axis. The
13484        // three payload-carrying arms round-trip their author-declared
13485        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
13486        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
13487        // the payload-less [`WitTarget::Capability`] arm returns `None`.
13488        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
13489        // (c6ec2af) pin on the Component-0 projection axis, extended
13490        // onto the Component-1 projection axis so both per-half readers
13491        // on the paired dispatch carry their own byte-shape pin.
13492        assert_eq!(
13493            WitTarget::Http {
13494                endpoint: "/charge",
13495            }
13496            .payload(),
13497            Some("/charge"),
13498        );
13499        assert_eq!(
13500            WitTarget::PubSub {
13501                subject: "events.x",
13502            }
13503            .payload(),
13504            Some("events.x"),
13505        );
13506        assert_eq!(
13507            WitTarget::Store {
13508                slot: "checkout/$order",
13509            }
13510            .payload(),
13511            Some("checkout/$order"),
13512        );
13513        assert_eq!(WitTarget::Capability.payload(), None);
13514    }
13515
13516    #[test]
13517    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
13518        // Per-variant equivalence pin: for every arm of [`WitTarget`],
13519        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
13520        // byte-for-byte. Guards the drift surface where a future refactor
13521        // that split one accessor off the shared match onto its own
13522        // dispatch — a well-meaning "inline the pair back into per-half
13523        // fields for one crate-internal caller who only wanted one half"
13524        // or a scratch `impl` shadowing the derived projection — would
13525        // silently desynchronize [`WitTarget::payload`] from the
13526        // authoritative [`WitTarget::payload_pair`] dispatch, and every
13527        // downstream consumer that thinks "the payload half of the pair"
13528        // would drift from the diagnostic / graph consumers reading the
13529        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
13530        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
13531        // per-half projection pin (`gitrefspec_ref_pair_projects_
13532        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
13533        // FluxCD source-controller `spec.ref.<field>` axis — same "one
13534        // paired dispatch, both per-half projections agree byte-for-
13535        // byte" discipline extended onto the M3 `:contratos` payload-
13536        // arm surface.
13537        for variant in [
13538            WitTarget::Http {
13539                endpoint: "/charge",
13540            },
13541            WitTarget::PubSub {
13542                subject: "events.checkout.paid",
13543            },
13544            WitTarget::Store {
13545                slot: "checkout/$order",
13546            },
13547            WitTarget::Capability,
13548        ] {
13549            let via_projection = variant.payload();
13550            let via_pair = variant.payload_pair().map(|(_, p)| p);
13551            assert_eq!(
13552                via_projection, via_pair,
13553                "WitTarget::{variant:?} payload() must equal \
13554                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
13555                 regression that splits the two per-half projections off \
13556                 their shared match would silently desynchronize the \
13557                 payload accessor from the paired dispatch every \
13558                 diagnostic / graph consumer reads through",
13559            );
13560        }
13561    }
13562
13563    #[test]
13564    fn wit_target_http_endpoint_pins_per_variant() {
13565        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
13566        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
13567        // substrate-primitive per-arm post-projection accessor every
13568        // L7-HTTP-facing consumer routes through, sibling to the peer
13569        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
13570        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
13571        // arm round-trips its author-declared endpoint verbatim as
13572        // `Some("/charge")`; the three sibling arms
13573        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
13574        // [`WitTarget::Capability`]) each return `None` because they
13575        // carry no HTTP endpoint by definition. Same fail-before-pass-
13576        // after per-variant discipline as the sibling
13577        // `wit_target_payload_pins_per_variant` (5d6dc92) /
13578        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
13579        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
13580        // the peer pan-arm / per-half projection axes — extended onto
13581        // the per-arm HTTP-shape post-projection axis so a future
13582        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
13583        // [`WitTarget::Http`], a `Queue`-shaped peer of
13584        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
13585        // error on the sibling [`WitTarget::http_endpoint`] match arms
13586        // whose payload the L7-HTTP-shape accept-set is meant to bound.
13587        assert_eq!(
13588            WitTarget::Http {
13589                endpoint: "/charge",
13590            }
13591            .http_endpoint(),
13592            Some("/charge"),
13593        );
13594        assert_eq!(
13595            WitTarget::PubSub {
13596                subject: "events.checkout.paid",
13597            }
13598            .http_endpoint(),
13599            None,
13600        );
13601        assert_eq!(
13602            WitTarget::Store {
13603                slot: "checkout/$order",
13604            }
13605            .http_endpoint(),
13606            None,
13607        );
13608        assert_eq!(WitTarget::Capability.http_endpoint(), None);
13609    }
13610
13611    #[test]
13612    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
13613        // Per-variant coherence pin: for every arm of [`WitTarget`],
13614        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
13615        // arm (both project the same author-declared request-path
13616        // scalar), and returns `None` on every sibling arm regardless of
13617        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
13618        // Store carry their own payload the pan-arm accessor surfaces,
13619        // but that payload is not an HTTP endpoint — the per-arm
13620        // accessor must not leak it through the HTTP-shape channel).
13621        // Guards the drift surface where a future refactor that
13622        // conflated the per-arm HTTP projection with the pan-arm
13623        // [`WitTarget::payload`] projection — a well-meaning "one
13624        // accessor for the L7 branch, one for the graph" collapse that
13625        // routes both through the same 4-arm dispatch — would silently
13626        // widen the L7-HTTP-shape accept-set onto pub-sub / store
13627        // payloads at the caixa-mesh L7 emit branch, admitting a
13628        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
13629        // rule with the operator-side apply-time symptom (Cilium's
13630        // eBPF data-plane rejects every ingress edge whose L7 filter
13631        // doesn't match the wire-format HTTP request line) far from
13632        // the source refactor. Sibling to the peer
13633        // `wit_target_payload_matches_payload_pair_second_component_
13634        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
13635        // extended onto the per-arm HTTP specialization axis so both
13636        // the pan-arm and the per-arm projections carry their own
13637        // byte-shape coherence witness against the substrate's typed
13638        // arm-family accept-set.
13639        for variant in [
13640            WitTarget::Http {
13641                endpoint: "/charge",
13642            },
13643            WitTarget::PubSub {
13644                subject: "events.checkout.paid",
13645            },
13646            WitTarget::Store {
13647                slot: "checkout/$order",
13648            },
13649            WitTarget::Capability,
13650        ] {
13651            let per_arm = variant.http_endpoint();
13652            let pan_arm = variant.payload();
13653            if variant.is_http() {
13654                assert_eq!(
13655                    per_arm, pan_arm,
13656                    "WitTarget::{variant:?} http_endpoint() must equal \
13657                     payload() on the Http arm — a per-arm-vs-pan-arm \
13658                     split would silently drift the L7 emit branch's \
13659                     path-scalar source from the graph verb's payload \
13660                     scalar source",
13661                );
13662            } else {
13663                assert_eq!(
13664                    per_arm, None,
13665                    "WitTarget::{variant:?} http_endpoint() must return \
13666                     None on non-Http arms — a leak that surfaced a \
13667                     pub-sub :subject or a key/value :slot through the \
13668                     HTTP-endpoint accessor would silently widen the \
13669                     Cilium L7 HTTP `path:` rule accept-set onto \
13670                     protocol shapes Cilium's eBPF data-plane can't \
13671                     introspect",
13672                );
13673            }
13674        }
13675    }
13676
13677    #[test]
13678    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
13679        // Per-variant coherence pin: for every arm of [`WitTarget`],
13680        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
13681        // drift surface where a future extension of the
13682        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
13683        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
13684        // accessor to cover both peers) landed without a paired
13685        // extension of the [`gen_platform::IsVariant`]-derived
13686        // `is_http()` predicate's accept-set, or vice versa — a
13687        // regression that split the "which arms count as HTTP-shaped
13688        // for L7-path emission?" answer between two dispatch surfaces
13689        // the substrate ships. Sibling to the peer
13690        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
13691        // on the paired dispatch axis — extended onto the per-arm
13692        // predicate-vs-accessor coherence axis so the gen-platform
13693        // IsVariant predicate and the substrate-lifted per-arm
13694        // accessor carry one shared answer to "is this the HTTP arm?".
13695        for variant in [
13696            WitTarget::Http {
13697                endpoint: "/charge",
13698            },
13699            WitTarget::PubSub {
13700                subject: "events.checkout.paid",
13701            },
13702            WitTarget::Store {
13703                slot: "checkout/$order",
13704            },
13705            WitTarget::Capability,
13706        ] {
13707            assert_eq!(
13708                variant.http_endpoint().is_some(),
13709                variant.is_http(),
13710                "WitTarget::{variant:?} http_endpoint().is_some() must \
13711                 equal is_http() — a drift would split the L7 emit \
13712                 branch's arm-set gate from the substrate-derived \
13713                 shape-discrimination predicate on the same axis",
13714            );
13715        }
13716    }
13717
13718    #[test]
13719    fn wit_target_pubsub_subject_pins_per_variant() {
13720        // Fail-before-pass-after pin: the substrate-canonical per-arm
13721        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
13722        // is the single dispatch every future pub-sub-facing consumer
13723        // routes through, sibling to the peer [`WitContract::subject`]
13724        // (63e18a0) pre-projection scalar accessor on the raw-field
13725        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
13726        // post-projection per-arm accessor on the sibling HTTP-shape
13727        // axis. The [`WitTarget::PubSub`] arm round-trips its
13728        // author-declared subject verbatim as
13729        // `Some("events.checkout.paid")`; the three sibling arms each
13730        // return `None` because they carry no NATS-shaped subject by
13731        // definition. Same fail-before-pass-after per-variant discipline
13732        // as the sibling `wit_target_http_endpoint_pins_per_variant`
13733        // pin on the peer per-arm axis — extended onto the per-arm
13734        // pub-sub-shape post-projection axis so a future [`WitTarget`]
13735        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
13736        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
13737        // compile-time exhaustiveness error on the sibling
13738        // [`WitTarget::pubsub_subject`] match arms whose payload the
13739        // pub-sub-shape accept-set is meant to bound.
13740        assert_eq!(
13741            WitTarget::PubSub {
13742                subject: "events.checkout.paid",
13743            }
13744            .pubsub_subject(),
13745            Some("events.checkout.paid"),
13746        );
13747        assert_eq!(
13748            WitTarget::Http {
13749                endpoint: "/charge",
13750            }
13751            .pubsub_subject(),
13752            None,
13753        );
13754        assert_eq!(
13755            WitTarget::Store {
13756                slot: "checkout/$order",
13757            }
13758            .pubsub_subject(),
13759            None,
13760        );
13761        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
13762    }
13763
13764    #[test]
13765    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
13766        // Per-variant coherence pin: for every arm of [`WitTarget`],
13767        // `.pubsub_subject()` equals `.payload()` on the
13768        // [`WitTarget::PubSub`] arm (both project the same
13769        // author-declared subject scalar), and returns `None` on every
13770        // sibling arm regardless of whether [`WitTarget::payload`]
13771        // itself returns `Some` (Http / Store carry their own payload
13772        // the pan-arm accessor surfaces, but that payload is not a
13773        // pub-sub subject — the per-arm accessor must not leak it
13774        // through the pub-sub-shape channel). Sibling to the peer
13775        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
13776        // coherence pin on the per-arm HTTP-shape axis — extended onto
13777        // the per-arm pub-sub specialization axis so both per-arm
13778        // projections carry their own byte-shape coherence witness
13779        // against the substrate's typed arm-family accept-set.
13780        for variant in [
13781            WitTarget::Http {
13782                endpoint: "/charge",
13783            },
13784            WitTarget::PubSub {
13785                subject: "events.checkout.paid",
13786            },
13787            WitTarget::Store {
13788                slot: "checkout/$order",
13789            },
13790            WitTarget::Capability,
13791        ] {
13792            let per_arm = variant.pubsub_subject();
13793            let pan_arm = variant.payload();
13794            if variant.is_pubsub() {
13795                assert_eq!(
13796                    per_arm, pan_arm,
13797                    "WitTarget::{variant:?} pubsub_subject() must equal \
13798                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
13799                     split would silently drift the pub-sub-shape emit \
13800                     branch's subject-scalar source from the graph verb's \
13801                     payload scalar source",
13802                );
13803            } else {
13804                assert_eq!(
13805                    per_arm, None,
13806                    "WitTarget::{variant:?} pubsub_subject() must return \
13807                     None on non-PubSub arms — a leak that surfaced an \
13808                     HTTP :endpoint or a key/value :slot through the \
13809                     pub-sub-subject accessor would silently widen the \
13810                     downstream NATS-shape accept-set onto protocol \
13811                     shapes NATS servers can't route",
13812                );
13813            }
13814        }
13815    }
13816
13817    #[test]
13818    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
13819        // Per-variant coherence pin: for every arm of [`WitTarget`],
13820        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
13821        // drift surface where a future extension of the
13822        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
13823        // without a paired extension of the [`gen_platform::IsVariant`]-
13824        // derived `is_pubsub()` predicate's accept-set, or vice versa
13825        // — a regression that split the "which arms count as pub-sub-
13826        // shaped for subject emission?" answer between two dispatch
13827        // surfaces the substrate ships. Sibling to the peer
13828        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
13829        // pin on the per-arm HTTP-shape axis — extended onto the
13830        // per-arm pub-sub predicate-vs-accessor coherence axis so the
13831        // gen-platform IsVariant predicate and the substrate-lifted
13832        // per-arm accessor carry one shared answer to "is this the
13833        // PubSub arm?".
13834        for variant in [
13835            WitTarget::Http {
13836                endpoint: "/charge",
13837            },
13838            WitTarget::PubSub {
13839                subject: "events.checkout.paid",
13840            },
13841            WitTarget::Store {
13842                slot: "checkout/$order",
13843            },
13844            WitTarget::Capability,
13845        ] {
13846            assert_eq!(
13847                variant.pubsub_subject().is_some(),
13848                variant.is_pubsub(),
13849                "WitTarget::{variant:?} pubsub_subject().is_some() must \
13850                 equal is_pubsub() — a drift would split the pub-sub \
13851                 emit branch's arm-set gate from the substrate-derived \
13852                 shape-discrimination predicate on the same axis",
13853            );
13854        }
13855    }
13856
13857    #[test]
13858    fn wit_target_store_slot_pins_per_variant() {
13859        // Fail-before-pass-after pin: the substrate-canonical per-arm
13860        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
13861        // is the single dispatch every future store-facing consumer
13862        // routes through, sibling to the peer [`WitContract::slot`]
13863        // pre-projection scalar accessor on the raw-field axis and to
13864        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
13865        // [`WitTarget::pubsub_subject`] post-projection per-arm
13866        // accessors on the sibling per-payload-arm axes. The
13867        // [`WitTarget::Store`] arm round-trips its author-declared
13868        // slot verbatim as `Some("checkout/$order")`; the three
13869        // sibling arms each return `None` because they carry no
13870        // WASI-key/value slot by definition. Same fail-before-pass-
13871        // after per-variant discipline as the sibling
13872        // `wit_target_http_endpoint_pins_per_variant` +
13873        // `wit_target_pubsub_subject_pins_per_variant` pins on the
13874        // peer per-arm axes — extended onto the per-arm store-shape
13875        // post-projection axis so a future [`WitTarget`] variant
13876        // addition trips a compile-time exhaustiveness error on the
13877        // sibling [`WitTarget::store_slot`] match arms whose payload
13878        // the store-shape accept-set is meant to bound.
13879        assert_eq!(
13880            WitTarget::Store {
13881                slot: "checkout/$order",
13882            }
13883            .store_slot(),
13884            Some("checkout/$order"),
13885        );
13886        assert_eq!(
13887            WitTarget::Http {
13888                endpoint: "/charge",
13889            }
13890            .store_slot(),
13891            None,
13892        );
13893        assert_eq!(
13894            WitTarget::PubSub {
13895                subject: "events.checkout.paid",
13896            }
13897            .store_slot(),
13898            None,
13899        );
13900        assert_eq!(WitTarget::Capability.store_slot(), None);
13901    }
13902
13903    #[test]
13904    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
13905        // Per-variant coherence pin: for every arm of [`WitTarget`],
13906        // `.store_slot()` equals `.payload()` on the
13907        // [`WitTarget::Store`] arm (both project the same
13908        // author-declared slot scalar), and returns `None` on every
13909        // sibling arm regardless of whether [`WitTarget::payload`]
13910        // itself returns `Some`. Sibling to the peer
13911        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
13912        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
13913        // pins on the per-arm HTTP and PubSub axes — closes the
13914        // per-arm-vs-pan-arm byte-shape coherence trio across all
13915        // three payload arms.
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            WitTarget::Capability,
13927        ] {
13928            let per_arm = variant.store_slot();
13929            let pan_arm = variant.payload();
13930            if variant.is_store() {
13931                assert_eq!(
13932                    per_arm, pan_arm,
13933                    "WitTarget::{variant:?} store_slot() must equal \
13934                     payload() on the Store arm — a per-arm-vs-pan-arm \
13935                     split would silently drift the store-shape emit \
13936                     branch's slot-scalar source from the graph verb's \
13937                     payload scalar source",
13938                );
13939            } else {
13940                assert_eq!(
13941                    per_arm, None,
13942                    "WitTarget::{variant:?} store_slot() must return \
13943                     None on non-Store arms — a leak that surfaced an \
13944                     HTTP :endpoint or a NATS :subject through the \
13945                     key/value-slot accessor would silently widen the \
13946                     downstream WASI-key/value slot accept-set onto \
13947                     protocol shapes the kv backends can't route",
13948                );
13949            }
13950        }
13951    }
13952
13953    #[test]
13954    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
13955        // Per-variant coherence pin: for every arm of [`WitTarget`],
13956        // `.store_slot().is_some()` iff `.is_store()`. Guards the
13957        // drift surface where a future extension of the
13958        // [`WitTarget::store_slot`] accessor's accept-set landed
13959        // without a paired extension of the [`gen_platform::IsVariant`]-
13960        // derived `is_store()` predicate's accept-set. Sibling to the
13961        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
13962        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
13963        // pins — closes the per-arm predicate-vs-accessor coherence
13964        // trio across all three payload arms so the gen-platform
13965        // IsVariant predicate and the substrate-lifted per-arm
13966        // accessor carry one shared answer to "is this the Store arm?".
13967        for variant in [
13968            WitTarget::Http {
13969                endpoint: "/charge",
13970            },
13971            WitTarget::PubSub {
13972                subject: "events.checkout.paid",
13973            },
13974            WitTarget::Store {
13975                slot: "checkout/$order",
13976            },
13977            WitTarget::Capability,
13978        ] {
13979            assert_eq!(
13980                variant.store_slot().is_some(),
13981                variant.is_store(),
13982                "WitTarget::{variant:?} store_slot().is_some() must \
13983                 equal is_store() — a drift would split the store-shape \
13984                 emit branch's arm-set gate from the substrate-derived \
13985                 shape-discrimination predicate on the same axis",
13986            );
13987        }
13988    }
13989
13990    #[test]
13991    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
13992        // Fail-before-pass-after cross-axis pin on the trio
13993        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
13994        // payload-carrying arm of [`WitTarget`], exactly one per-arm
13995        // accessor returns `Some(payload)` and the two peers return
13996        // `None`; and on the payload-less [`WitTarget::Capability`]
13997        // arm, all three return `None`. Guards the drift surface where
13998        // a future extension of one per-arm accessor's accept-set (e.g.
13999        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
14000        // that widened `http_endpoint` to cover both peers without
14001        // narrowing the peer `pubsub_subject` / `store_slot` accept-
14002        // sets to keep the partition mutually exclusive) landed without
14003        // threading through the peer per-arm accessors — the resulting
14004        // silent overlap would land the same edge's payload on two
14005        // downstream per-shape emit branches at once, or leak a
14006        // pub-sub subject through the store-slot channel, at renderer
14007        // emit time far from the substrate primitive's arm-widening
14008        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
14009        // 3-way pin on the payload-field-name axis — extended onto the
14010        // per-arm-accessor payload-projection axis so the substrate-
14011        // owned partition invariant is load-bearing at every per-arm
14012        // consumer's read site.
14013        let payload_variants = [
14014            (
14015                WitTarget::Http {
14016                    endpoint: "/charge",
14017                },
14018                "http",
14019            ),
14020            (
14021                WitTarget::PubSub {
14022                    subject: "events.checkout.paid",
14023                },
14024                "pubsub",
14025            ),
14026            (
14027                WitTarget::Store {
14028                    slot: "checkout/$order",
14029                },
14030                "store",
14031            ),
14032        ];
14033        for (variant, own_arm_label) in payload_variants {
14034            let own_arm_hit = match own_arm_label {
14035                "http" => variant.is_http(),
14036                "pubsub" => variant.is_pubsub(),
14037                "store" => variant.is_store(),
14038                other => panic!("unknown own-arm label {other:?}"),
14039            };
14040            let per_arm_results = [
14041                ("http_endpoint", variant.http_endpoint()),
14042                ("pubsub_subject", variant.pubsub_subject()),
14043                ("store_slot", variant.store_slot()),
14044            ];
14045            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
14046            assert_eq!(
14047                some_count, 1,
14048                "WitTarget::{variant:?} must land exactly one per-arm \
14049                 post-projection accessor's Some result — the trio \
14050                 (http_endpoint, pubsub_subject, store_slot) must \
14051                 partition the payload arm-set; got {per_arm_results:?}",
14052            );
14053            assert!(
14054                own_arm_hit,
14055                "WitTarget::{variant:?} own-arm gen-platform predicate \
14056                 must return true on its own arm — a partition failure \
14057                 upstream of this pin",
14058            );
14059            assert!(
14060                variant.payload().is_some(),
14061                "WitTarget::{variant:?} pan-arm payload() must return \
14062                 Some on every payload-carrying arm the trio partitions",
14063            );
14064        }
14065        // The payload-less Capability arm must return None on every
14066        // per-arm accessor — the partition's terminal-fallback shape.
14067        let cap = WitTarget::Capability;
14068        assert_eq!(cap.http_endpoint(), None);
14069        assert_eq!(cap.pubsub_subject(), None);
14070        assert_eq!(cap.store_slot(), None);
14071        assert_eq!(
14072            cap.payload(),
14073            None,
14074            "WitTarget::Capability pan-arm payload() must return None — \
14075             the trio's payload-less-arm coherence witness",
14076        );
14077    }
14078
14079    #[test]
14080    fn wit_target_field_names_are_pairwise_distinct() {
14081        // Distinctness pin: if any two of the three payload-field-name
14082        // scalars ever collapse (e.g. an accidental `endpoint` copy-
14083        // paste over the `subject` const), the [`WitContract::target`]
14084        // gate's diagnostic would point authors at the wrong field —
14085        // an "expected `:endpoint`" error on a pub-sub edge would
14086        // silently misroute the fix. Same cross-axis-distinctness
14087        // discipline as the peer M3 `:placement :estrategia` variant-
14088        // discriminator scalar-value pins (cc8f749) applied to the
14089        // payload-field-name axis.
14090        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
14091        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
14092        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
14093    }
14094
14095    #[test]
14096    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
14097        // Fail-before-pass-after pin: the graph-verb payload column's
14098        // per-arm `{field}={payload}` byte-string is derived through the
14099        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
14100        // payload-carrying arms, not through a hand-rolled per-arm match
14101        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
14102        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14103        // inline. A future variant addition — the M4-and-later per-edge
14104        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
14105        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
14106        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
14107        // and both [`WitTarget::label`] (duplicate-`:contratos`
14108        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
14109        // payload column) pick up the new arm from the same dispatch.
14110        // Prior to this lift the graph verb open-coded the 4-arm match
14111        // in caixa-feira, so a variant addition would have to be threaded
14112        // through both projections in lockstep or the graph verb would
14113        // silently drop the new arm to `(capability-only)`.
14114        for variant in [
14115            WitTarget::Http {
14116                endpoint: "/charge",
14117            },
14118            WitTarget::PubSub {
14119                subject: "events.checkout.paid",
14120            },
14121            WitTarget::Store {
14122                slot: "checkout/$order",
14123            },
14124        ] {
14125            let (field, payload) = variant
14126                .payload_pair()
14127                .expect("payload arm must expose (field, payload)");
14128            assert_eq!(
14129                variant.graph_label(),
14130                format!("{field}={payload}"),
14131                "WitTarget::{variant:?} graph_label must route the \
14132                 `{{field}}={{payload}}` template through payload_pair — \
14133                 a regression to a hand-rolled per-arm match at the graph \
14134                 verb would silently disagree with a future variant \
14135                 addition landed only at payload_pair"
14136            );
14137        }
14138    }
14139
14140    #[test]
14141    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
14142        // Fail-before-pass-after pin on the payload-less arm: the graph
14143        // verb's `(capability-only)` byte-string routes through the
14144        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
14145        // [`WitTarget::Capability`] arm, not through an inline
14146        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
14147        // per-`:contratos` payload column. Peer of the sibling
14148        // [`wit_target_label_pins_per_variant_format`] Capability-arm
14149        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
14150        // extended here onto the third payload-less-arm consumer axis
14151        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
14152        // axis and the wrong-target diagnostic axis).
14153        assert_eq!(
14154            WitTarget::Capability.graph_label(),
14155            WitTarget::CAPABILITY_GRAPH_LABEL,
14156        );
14157        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
14158    }
14159
14160    #[test]
14161    fn wit_target_capability_graph_label_distinct_from_capability_label() {
14162        // Cross-consumer-axis distinctness pin: the graph-verb
14163        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
14164        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
14165        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
14166        // payload)`) surface the payload-less arm on two distinct
14167        // consumer axes; a collapse (an accidental rebrand that lands
14168        // one spelling on both consts, a copy-paste that unifies them
14169        // "for consistency") would silently merge the two byte-strings
14170        // and lose the vocabulary distinction the graph verb's
14171        // compact-column form and the diagnostic's descriptive-clause
14172        // form each carry on purpose. Peer of the sibling 4-way
14173        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
14174        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
14175        // extended here onto the cross-consumer-axis distinctness of the
14176        // two payload-less-arm consts.
14177        assert_ne!(
14178            WitTarget::CAPABILITY_GRAPH_LABEL,
14179            WitTarget::CAPABILITY_LABEL,
14180            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
14181             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
14182             diagnostic) must remain distinct — a collapse would silently \
14183             merge two consumer axes onto one spelling"
14184        );
14185    }
14186
14187    #[test]
14188    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
14189        // 4-way distinctness pin extending the sibling
14190        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
14191        // (which covers only the HTTP / PubSub / Store payload arms)
14192        // onto the fourth scalar the shared
14193        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
14194        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
14195        // (`"none"`), the payload-less Capability-arm rejection scalar.
14196        //
14197        // All four [`WitTarget::HTTP_FIELD_NAME`] /
14198        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14199        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
14200        // dispatch surface [`WitContract::target`] writes onto the
14201        // `ContratoWrongTarget::expected` field — the same `&'static
14202        // str` axis authors read as "this WIT world's shape admits
14203        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
14204        // downstream consumers rely on: an `expected: "endpoint"`
14205        // diagnostic on a Capability-shaped edge tells the author to
14206        // add a `:endpoint "…"` slot to a WIT world that admits none,
14207        // silently misrouting the fix. Until this pin landed the three
14208        // payload-arm consts were distinctness-guarded by the sibling
14209        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
14210        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
14211        // author-facing vocabulary shift from `"none"` to `"endpoint"`
14212        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
14213        // into per-shape peers) would have silently landed one
14214        // Capability-arm rejection on a payload-arm's `expected:` byte-
14215        // string and desynchronized the diagnostic from the author's
14216        // typed shape.
14217        //
14218        // Same 4-way pairwise-distinctness pin discipline as the peer
14219        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
14220        // (cc8f749) applies on the sibling M3 closed-set typed-enum
14221        // scalar-value dispatch axis; extends the pin trajectory the
14222        // sibling `wit_target_field_names_are_pairwise_distinct`
14223        // 3-way pin opened to cover the last unguarded corner on the
14224        // `ContratoWrongTarget::expected` scalar-value axis.
14225        //
14226        // Fail-before-pass-after locally verified by mutating
14227        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
14228        // — this pin fires as expected; restoring passes.
14229        let all = [
14230            WitTarget::HTTP_FIELD_NAME,
14231            WitTarget::PUBSUB_FIELD_NAME,
14232            WitTarget::STORE_FIELD_NAME,
14233            WitTarget::CAPABILITY_EXPECTED,
14234        ];
14235        for (i, a) in all.iter().enumerate() {
14236            for (j, b) in all.iter().enumerate() {
14237                if i != j {
14238                    assert_ne!(
14239                        a, b,
14240                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
14241                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
14242                         pairwise distinct — got duplicate {a:?} at indices \
14243                         {i} and {j}; all four scalars thread through the \
14244                         shared `AplicacaoError::ContratoWrongTarget::expected` \
14245                         &'static str axis, so a collapse silently misdirects \
14246                         the diagnostic on which typed shape the WIT world admits",
14247                    );
14248                }
14249            }
14250        }
14251    }
14252
14253    #[test]
14254    fn wit_target_is_variant_predicates_partition_the_arm_set() {
14255        // Fail-before-pass-after pin on the
14256        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
14257        // each of the four variants exactly one of the generated
14258        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
14259        // predicates returns `true` and the other three return
14260        // `false`. Prior to this derive the only production
14261        // arm-discriminator on [`WitTarget`] — the sync-cycle
14262        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
14263        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
14264        // the variant that expressed no compile-time link back to
14265        // the closed-set typed dispatch a future fifth
14266        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
14267        // split of [`WitTarget::PubSub`] into shape-specific peers,
14268        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
14269        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
14270        // to thread through in lockstep or the DFS exclusion would
14271        // silently disagree with the peer diagnostic templates on
14272        // which arms carry sync-versus-async semantics. Peer of the
14273        // sibling [`crate::CaixaKind`] (f5bba80),
14274        // [`PlacementStrategy`] (766ec63),
14275        // [`crate::supervisor::RestartStrategy`],
14276        // [`crate::supervisor::RestartPolicy`], and
14277        // [`crate::upgrade::UpgradeInstruction`] (915a934)
14278        // `IsVariant` derives on the sibling closed-set typed-enum
14279        // discriminator axes — extends the same one-typed-dispatch-
14280        // per-variant discipline onto the last unlifted closed-set
14281        // typed-enum discriminator on the caixa surface (the M3
14282        // mesh-slot per-`:contratos` target-arm axis), closing the
14283        // arm-discriminator convergence trajectory across every
14284        // closed-set typed enum in caixa-core.
14285        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
14286            (
14287                WitTarget::Http { endpoint: "/x" },
14288                [true, false, false, false],
14289            ),
14290            (
14291                WitTarget::PubSub {
14292                    subject: "events.x",
14293                },
14294                [false, true, false, false],
14295            ),
14296            (
14297                WitTarget::Store { slot: "kv/x" },
14298                [false, false, true, false],
14299            ),
14300            (WitTarget::Capability, [false, false, false, true]),
14301        ];
14302        for (variant, expected) in rows {
14303            let observed = [
14304                variant.is_http(),
14305                variant.is_pubsub(),
14306                variant.is_store(),
14307                variant.is_capability(),
14308            ];
14309            assert_eq!(
14310                observed, expected,
14311                "WitTarget::{variant:?} is_* predicates must partition \
14312                 the arm set (http, pubsub, store, capability); got {observed:?}"
14313            );
14314        }
14315    }
14316
14317    #[test]
14318    fn wit_target_is_variant_predicates_are_const_fn() {
14319        // The [`gen_platform::IsVariant`] derive emits `const fn`
14320        // predicates on the peer [`crate::CaixaKind`] +
14321        // [`crate::upgrade::UpgradeInstruction`] +
14322        // [`crate::supervisor::RestartStrategy`] +
14323        // [`crate::supervisor::RestartPolicy`] +
14324        // [`PlacementStrategy`] closed-set typed enums — pin the
14325        // same posture on [`WitTarget`] so a future accidental
14326        // downgrade to non-`const` (an added runtime helper reachable
14327        // only from a non-`const` context, a manual hand-rolled
14328        // `impl` that shadows the derive-generated method) trips at
14329        // caixa-core build time rather than surfacing as a downstream
14330        // `const`-context regression far from the derive declaration.
14331        //
14332        // Unlike the peer unit-variant enums (`CaixaKind` /
14333        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
14334        // whose `const` constructors need no arguments, the three
14335        // payload-carrying [`WitTarget`] arms are const-constructed
14336        // through `&'static str` payloads — the same `'static`
14337        // lifetime the closed-set typed enum's four-arm partition
14338        // pin above already threads through.
14339        const HTTP: WitTarget<'static> = WitTarget::Http { endpoint: "/x" };
14340        const PUBSUB: WitTarget<'static> = WitTarget::PubSub { subject: "e" };
14341        const STORE: WitTarget<'static> = WitTarget::Store { slot: "kv/x" };
14342        const CAPABILITY: WitTarget<'static> = WitTarget::Capability;
14343        const IS_HTTP: bool = HTTP.is_http();
14344        const IS_PUBSUB: bool = PUBSUB.is_pubsub();
14345        const IS_STORE: bool = STORE.is_store();
14346        const IS_CAPABILITY: bool = CAPABILITY.is_capability();
14347        assert!(IS_HTTP);
14348        assert!(IS_PUBSUB);
14349        assert!(IS_STORE);
14350        assert!(IS_CAPABILITY);
14351    }
14352
14353    #[test]
14354    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
14355        // Consumer-side pin on the sole production converge site:
14356        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
14357        // edges from the synchronous-subgraph DFS via the lifted
14358        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
14359        // predicate (rebound from the prior raw
14360        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
14361        // variant). Byte-equivalent today (`is_pubsub` is the
14362        // derive-generated `matches!(self, Self::PubSub { .. })` by
14363        // construction, the `#[is_variant(name = "pubsub")]` override
14364        // aliasing the auto-derived `is_pub_sub` back to the sibling
14365        // [`WitContract::is_pubsub`] name); pin the behavior so a
14366        // future accidental drift (a rebind onto a peer arm
14367        // predicate, a manual hand-rolled `impl` that shadows the
14368        // derive-generated method with different semantics, a peer
14369        // arm rename that shifts which variant carries sync-versus-
14370        // async semantics) trips at caixa-core test time rather than
14371        // at some downstream operator's runtime dispatch far from the
14372        // rebind commit.
14373        //
14374        // The fixture constructs a two-Servico Aplicacao with one
14375        // pub-sub edge that would close a sync-cycle if the DFS did
14376        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
14377        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
14378        // edge, which is not a cycle. A regression in the converge
14379        // (a rebind that reads the pub-sub arm as sync) would report
14380        // `AplicacaoError::ContratoCycle`.
14381        let s = AplicacaoSpec {
14382            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
14383            contratos: vec![
14384                // Pub-sub edge: DFS must skip via is_pubsub().
14385                WitContract {
14386                    de: "a".into(),
14387                    para: "b".into(),
14388                    wit: "nats:pub-sub".into(),
14389                    endpoint: None,
14390                    subject: Some("events.x".into()),
14391                    slot: None,
14392                },
14393                // HTTP edge: DFS must include.
14394                WitContract {
14395                    de: "b".into(),
14396                    para: "a".into(),
14397                    wit: "wasi:http/proxy".into(),
14398                    endpoint: Some("/x".into()),
14399                    subject: None,
14400                    slot: None,
14401                },
14402            ],
14403            politicas: MeshPolicy::default(),
14404            placement: Placement {
14405                estrategia: PlacementStrategy::Replicated,
14406                clusters: vec!["rio".into()],
14407                affinity: None,
14408                shard_key: None,
14409            },
14410            entrada: None,
14411        };
14412        s.validate()
14413            .expect("pub-sub edge must be excluded from sync-cycle DFS");
14414    }
14415
14416    #[test]
14417    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
14418        // Consumer-side pin: the same three peer consts thread through
14419        // both the [`WitTarget::label`] template (leading-`:` keyword
14420        // prefix in the duplicate-`:contratos` diagnostic) and the
14421        // [`WitContract::target`] gate's [`AplicacaoError::
14422        // ContratoMissingTarget`] `expected:` scalar (the field the
14423        // author needs to add). Pin both routes at once so a future
14424        // refactor can't accidentally split them onto separate string
14425        // literals — the "one place, everywhere reaches for it"
14426        // invariant the peer const set carries.
14427        let http_label = WitTarget::Http { endpoint: "/x" }.label();
14428        assert!(
14429            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
14430            "label must lead with :{} keyword (got {http_label:?})",
14431            WitTarget::HTTP_FIELD_NAME,
14432        );
14433
14434        let mut s = three_member_spec();
14435        s.contratos.push(WitContract {
14436            de: "cart".into(),
14437            para: "catalog".into(),
14438            wit: "kafka:topic".into(),
14439            endpoint: None,
14440            subject: None,
14441            slot: None,
14442        });
14443        match s.validate().unwrap_err() {
14444            AplicacaoError::ContratoMissingTarget { expected, .. } => {
14445                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
14446            }
14447            other => panic!("expected ContratoMissingTarget, got {other:?}"),
14448        }
14449    }
14450
14451    #[test]
14452    fn duplicate_pubsub_diagnostic_names_offending_subject() {
14453        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
14454        // on the pub-sub target axis: the duplicate-edge diagnostic
14455        // must name the `:subject` payload verbatim (not just the
14456        // `(de, para, wit)` triple). Prior to lifting the label onto
14457        // [`WitTarget::label`] the diagnostic derived the label from
14458        // raw [`WitContract`] `Option<String>` probes — a future
14459        // `WitTarget` variant addition (M4 per-edge WIT registry)
14460        // would silently fall through to the `Capability` "no
14461        // payload" default without a compiler warning. Pinning the
14462        // pub-sub arm's format closes the second of three
14463        // payload-carrying `WitTarget` arms this diagnostic threads
14464        // through.
14465        let mut s = three_member_spec();
14466        let pubsub = WitContract {
14467            de: "payment".into(),
14468            para: "cart".into(),
14469            wit: "nats:pub-sub".into(),
14470            endpoint: None,
14471            subject: Some("events.checkout.paid".into()),
14472            slot: None,
14473        };
14474        s.contratos.push(pubsub.clone());
14475        s.contratos.push(pubsub);
14476        let err = s.validate().unwrap_err();
14477        let msg = format!("{err}");
14478        assert!(
14479            msg.contains(":subject \"events.checkout.paid\""),
14480            "duplicate-pubsub diagnostic must name the offending \
14481             :subject payload (got: {msg:?})"
14482        );
14483    }
14484
14485    #[test]
14486    fn duplicate_store_diagnostic_names_offending_slot() {
14487        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
14488        // key-value target axis: the diagnostic must name the `:slot`
14489        // payload verbatim. Third of three payload-carrying
14490        // `WitTarget` arms this diagnostic threads through, closing
14491        // the per-arm label pin trilogy (`Http` — 6841,
14492        // `PubSub` + `Store` — this test + peer above).
14493        let mut s = three_member_spec();
14494        let store = WitContract {
14495            de: "cart".into(),
14496            para: "payment".into(),
14497            wit: "wasi:keyvalue/store".into(),
14498            endpoint: None,
14499            subject: None,
14500            slot: Some("checkout/$orderId".into()),
14501        };
14502        s.contratos
14503            .retain(|c| !(c.de == "cart" && c.para == "payment"));
14504        s.contratos.push(store.clone());
14505        s.contratos.push(store);
14506        let err = s.validate().unwrap_err();
14507        let msg = format!("{err}");
14508        assert!(
14509            msg.contains(":slot \"checkout/$orderId\""),
14510            "duplicate-store diagnostic must name the offending :slot \
14511             payload (got: {msg:?})"
14512        );
14513    }
14514
14515    #[test]
14516    fn rejects_entrada_path_without_leading_slash() {
14517        let mut s = three_member_spec();
14518        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
14519        let err = s.validate().unwrap_err();
14520        assert!(
14521            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
14522            "got {err:?}"
14523        );
14524    }
14525
14526    #[test]
14527    fn rejects_empty_entrada_path() {
14528        let mut s = three_member_spec();
14529        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "".into()];
14530        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14531    }
14532
14533    #[test]
14534    fn rejects_duplicate_entrada_paths() {
14535        let mut s = three_member_spec();
14536        s.entrada.as_mut().unwrap().paths = vec![
14537            "/api/cart".into(),
14538            "/api/products".into(),
14539            "/api/cart".into(),
14540        ];
14541        let err = s.validate().unwrap_err();
14542        assert!(
14543            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
14544            "got {err:?}"
14545        );
14546    }
14547
14548    #[test]
14549    fn rejects_zero_entrada_port() {
14550        let mut s = three_member_spec();
14551        s.entrada.as_mut().unwrap().port = 0;
14552        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
14553    }
14554
14555    // ── :entrada :paths value-shape gate ─────────────────────────────
14556    //
14557    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
14558    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
14559    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
14560    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
14561    // time now becomes a caixa-build-time `EntradaPathInvalid` with
14562    // the offending `:paths` entry named verbatim.
14563
14564    #[test]
14565    fn rejects_entrada_path_with_query() {
14566        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
14567        // silently passed validate and the Gateway API webhook
14568        // rejected it at apply time with no source citation.
14569        let mut s = three_member_spec();
14570        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
14571        let err = s.validate().unwrap_err();
14572        assert!(
14573            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14574                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
14575            "got {err:?}"
14576        );
14577    }
14578
14579    #[test]
14580    fn rejects_entrada_path_with_fragment() {
14581        let mut s = three_member_spec();
14582        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
14583        let err = s.validate().unwrap_err();
14584        assert!(
14585            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14586                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
14587            "got {err:?}"
14588        );
14589    }
14590
14591    #[test]
14592    fn rejects_entrada_path_with_space() {
14593        let mut s = three_member_spec();
14594        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
14595        let err = s.validate().unwrap_err();
14596        assert!(
14597            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14598                if path == "/api/my cart" && reason.contains("whitespace")),
14599            "got {err:?}"
14600        );
14601    }
14602
14603    #[test]
14604    fn rejects_entrada_path_with_tab() {
14605        let mut s = three_member_spec();
14606        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
14607        let err = s.validate().unwrap_err();
14608        assert!(
14609            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14610                if path == "/api/\tcart" && reason.contains("whitespace")),
14611            "got {err:?}"
14612        );
14613    }
14614
14615    #[test]
14616    fn rejects_entrada_path_with_control_char() {
14617        // 0x01 (SOH) — a non-whitespace control char surfaces the
14618        // distinct "control character" reason arm, separate from
14619        // the whitespace arm. Pinned so a future refactor that
14620        // collapses the two arms can't accidentally drop the more
14621        // self-locating diagnostic.
14622        let mut s = three_member_spec();
14623        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
14624        let err = s.validate().unwrap_err();
14625        assert!(
14626            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14627                if path == "/api/\x01cart" && reason.contains("control character")),
14628            "got {err:?}"
14629        );
14630    }
14631
14632    #[test]
14633    fn rejects_entrada_path_with_non_ascii() {
14634        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
14635        // unreserved-set rule rejects. The Gateway API webhook
14636        // rejects literal non-ASCII bytes; percent-encoding is the
14637        // only way to author non-ASCII in a path.
14638        let mut s = three_member_spec();
14639        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
14640        let err = s.validate().unwrap_err();
14641        assert!(
14642            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14643                if path == "/api/café" && reason.contains("non-ASCII")),
14644            "got {err:?}"
14645        );
14646    }
14647
14648    #[test]
14649    fn rejects_entrada_path_with_consecutive_slashes() {
14650        let mut s = three_member_spec();
14651        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
14652        let err = s.validate().unwrap_err();
14653        assert!(
14654            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14655                if path == "/api//cart" && reason.contains("consecutive `/`")),
14656            "got {err:?}"
14657        );
14658    }
14659
14660    #[test]
14661    fn rejects_entrada_path_with_dot_segment() {
14662        let mut s = three_member_spec();
14663        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
14664        let err = s.validate().unwrap_err();
14665        assert!(
14666            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14667                if path == "/api/./cart" && reason.contains("`.` segment")),
14668            "got {err:?}"
14669        );
14670    }
14671
14672    #[test]
14673    fn rejects_entrada_path_with_trailing_dot_segment() {
14674        // The bare `/.` and the trailing `/foo/.` are both rejected
14675        // by the Gateway API webhook; pinned separately so a future
14676        // narrowing that catches only the inner form surfaces here.
14677        let mut s = three_member_spec();
14678        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
14679        let err = s.validate().unwrap_err();
14680        assert!(
14681            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14682                if path == "/api/." && reason.contains("`.` segment")),
14683            "got {err:?}"
14684        );
14685    }
14686
14687    #[test]
14688    fn rejects_entrada_path_with_parent_segment() {
14689        let mut s = three_member_spec();
14690        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
14691        let err = s.validate().unwrap_err();
14692        assert!(
14693            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14694                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
14695            "got {err:?}"
14696        );
14697    }
14698
14699    #[test]
14700    fn rejects_entrada_path_with_trailing_parent_segment() {
14701        // Trailing `/..` — symmetric arm of the parent-segment rule,
14702        // pinned separately so a future relaxation that only checks
14703        // the inner form (`/../`) surfaces here.
14704        let mut s = three_member_spec();
14705        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
14706        let err = s.validate().unwrap_err();
14707        assert!(
14708            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14709                if path == "/api/.." && reason.contains("`..` parent-segment")),
14710            "got {err:?}"
14711        );
14712    }
14713
14714    #[test]
14715    fn rejects_entrada_path_too_long() {
14716        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
14717        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
14718        // ASCII-alphanumeric body so only the length rule fires.
14719        let mut s = three_member_spec();
14720        let big = format!("/api/{}", "a".repeat(1020));
14721        assert_eq!(big.len(), 1025);
14722        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
14723        let err = s.validate().unwrap_err();
14724        assert!(
14725            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14726                if path == &big && reason.contains("max length of 1024")),
14727            "got {err:?}"
14728        );
14729    }
14730
14731    #[test]
14732    fn entrada_path_max_length_validates() {
14733        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
14734        // maxLength cap. Boundary pin: drift in the cap surfaces here
14735        // and at `rejects_entrada_path_too_long` simultaneously.
14736        let mut s = three_member_spec();
14737        let big = format!("/api/{}", "a".repeat(1019));
14738        assert_eq!(big.len(), 1024);
14739        s.entrada.as_mut().unwrap().paths = vec![big];
14740        s.validate().unwrap();
14741    }
14742
14743    #[test]
14744    fn entrada_accepts_canonical_paths() {
14745        // Positive-control sweep — every form the Gateway API
14746        // apiserver accepts must round-trip through validate. Covers
14747        // the root catch-all, plain paths, dot-prefixed segments
14748        // (hidden-file-style, distinct from `.` and `..` segments
14749        // which are rejected), digit-bearing segments, the canonical
14750        // route-template `:param` form (`:` is RFC 3986 reserved-set
14751        // valid in paths), trailing-slash form, percent-encoded
14752        // segments, and an interior `..` *substring* (`/foo..bar` is
14753        // not the `..` segment and is allowed).
14754        for path in [
14755            "/",
14756            "/api/cart",
14757            "/healthz",
14758            "/api/.config",
14759            "/v1/products",
14760            "/products/:id",
14761            "/api/cart/",
14762            "/api/caf%C3%A9",
14763            "/foo..bar",
14764            "/...",
14765        ] {
14766            let mut s = three_member_spec();
14767            s.entrada.as_mut().unwrap().paths = vec![path.into()];
14768            s.validate()
14769                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
14770        }
14771    }
14772
14773    #[test]
14774    fn entrada_path_empty_takes_precedence_over_invalid() {
14775        // Ordering pin: `EntradaPathEmpty` is the more self-locating
14776        // diagnostic on `""` and must lead — `validate_entrada_path`
14777        // is only reached after the empty-check fires at the call
14778        // site. (The predicate itself defends against direct
14779        // invocation by returning the same error on `""`.)
14780        let mut s = three_member_spec();
14781        s.entrada.as_mut().unwrap().paths = vec!["".into()];
14782        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14783    }
14784
14785    #[test]
14786    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
14787        // Ordering pin: a path without a leading `/` surfaces the
14788        // narrower `EntradaPathNotAbsolute` diagnostic first; the
14789        // value-shape gate is only consulted on paths that already
14790        // satisfy the absolute-prefix invariant.
14791        let mut s = three_member_spec();
14792        // `bad path` would fire the whitespace rule under the
14793        // value-shape gate, but missing-leading-`/` is the more
14794        // self-locating diagnostic.
14795        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
14796        let err = s.validate().unwrap_err();
14797        assert!(
14798            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
14799            "got {err:?}"
14800        );
14801    }
14802
14803    #[test]
14804    fn entrada_path_invalid_fires_before_duplicate_check() {
14805        // Ordering pin: a malformed path on the *first* entry of a
14806        // would-be duplicate pair fires the value-shape gate before
14807        // the duplicate gate, mirroring the
14808        // `placement_cluster_invalid_fires_before_duplicate_check`
14809        // (6cbb900) pattern on the peer axis.
14810        let mut s = three_member_spec();
14811        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
14812        let err = s.validate().unwrap_err();
14813        assert!(
14814            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
14815            "got {err:?}"
14816        );
14817    }
14818
14819    #[test]
14820    fn entrada_path_diagnostic_carries_offending_path() {
14821        // Diagnostic-shape pin — the offending path + a non-empty
14822        // reason flow through verbatim so the author can grep their
14823        // caixa.lisp for `:paths` and fix it in one edit. Same shape
14824        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
14825        let mut s = three_member_spec();
14826        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
14827        let err = s.validate().unwrap_err();
14828        match err {
14829            AplicacaoError::EntradaPathInvalid { path, reason } => {
14830                assert_eq!(path, "/api?q=1");
14831                assert!(!reason.is_empty(), "reason field must be non-empty");
14832            }
14833            other => panic!("expected EntradaPathInvalid, got {other:?}"),
14834        }
14835    }
14836
14837    #[test]
14838    fn rejects_entrada_path_with_curly_brace_template_form() {
14839        // Per-axis pin on the shared `is_gateway_api_http_path`
14840        // reserved-byte arm: the canonical "I wrote an OpenAPI
14841        // path-template `{id}` instead of the Gateway API `:id` form"
14842        // footgun the K8s apiserver would otherwise catch at admission
14843        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
14844        // landing site, far from the caixa.lisp. Surfaces as
14845        // `EntradaPathInvalid` carrying the offending path verbatim
14846        // plus the canonical `%7B`/`%7D` percent-encoding remediation
14847        // — the substrate-side `gateway_api_http_path_rejects_every_
14848        // reserved_printable_ascii_byte` predicate-level sweep pins the
14849        // full eleven-byte set; this per-axis pin confirms the
14850        // diagnostic flows through to the `EntradaPathInvalid` variant.
14851        let mut s = three_member_spec();
14852        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
14853        let err = s.validate().unwrap_err();
14854        assert!(
14855            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14856                if path == "/api/cart/{id}"
14857                    && reason.contains("reserved character")
14858                    && reason.contains("'{'")
14859                    && reason.contains("%7B")),
14860            "got {err:?}"
14861        );
14862    }
14863
14864    #[test]
14865    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
14866        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
14867        // template_form` on the sibling `:contratos :endpoint` axis.
14868        // Same shared `is_gateway_api_http_path` reserved-byte arm
14869        // fires through `ContratoEndpointInvalid`, with the offending
14870        // endpoint + `:de` + `:para` + reason flowing through verbatim.
14871        // Pins that the lifted predicate's tightening lands on both
14872        // caller axes simultaneously — one source of truth for the
14873        // Gateway API HTTPPathMatch.value accepted set.
14874        let err = contrato_endpoint_err("/api/cart/{id}");
14875        assert!(
14876            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
14877                if endpoint == "/api/cart/{id}"
14878                    && reason.contains("reserved character")
14879                    && reason.contains("'{'")
14880                    && reason.contains("%7B")),
14881            "got {err:?}"
14882        );
14883    }
14884
14885    // ── :entrada :host value-shape gate ──────────────────────────────
14886    //
14887    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
14888    // the sibling `:host` axis. Every authoring footgun the K8s
14889    // Gateway API v1 apiserver would catch at admission time becomes
14890    // a caixa-build-time `EntradaHostInvalid` with the offending
14891    // `:host` named verbatim. Same diagnostic shape as
14892    // `MembroVersaoInvalid` (9888b13).
14893
14894    #[test]
14895    fn rejects_entrada_host_with_scheme() {
14896        // Fail-before-pass-after pin — pre-gate codebases silently
14897        // accepted `https://…` and the apiserver rejected it at apply
14898        // time with no source citation.
14899        let mut s = three_member_spec();
14900        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
14901        let err = s.validate().unwrap_err();
14902        assert!(
14903            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14904                if host == "https://checkout.quero.cloud"),
14905            "got {err:?}"
14906        );
14907    }
14908
14909    #[test]
14910    fn rejects_entrada_host_with_port() {
14911        // The `:8080` port suffix is the canonical "I forgot the port
14912        // belongs in `:entrada :port`" footgun. The top-level `:` arm
14913        // (introduced after the per-label loop-only impl silently
14914        // surfaced a deep "label \"cloud:8080\" contains invalid
14915        // character ':'" leak) names the canonical fix verbatim — the
14916        // `:entrada :port` slot.
14917        let mut s = three_member_spec();
14918        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
14919        let err = s.validate().unwrap_err();
14920        assert!(
14921            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14922                if host == "checkout.quero.cloud:8080"
14923                && reason.contains(":entrada :port")),
14924            "got {err:?}"
14925        );
14926    }
14927
14928    #[test]
14929    fn rejects_entrada_host_with_trailing_colon() {
14930        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
14931        // edit) — the per-label loop would land it as a deep
14932        // "label \"com:\" must start and end with an alphanumeric"
14933        // / "contains invalid character ':'" leak. The top-level
14934        // `:` arm pre-empts with the canonical `:port` slot
14935        // diagnostic.
14936        let mut s = three_member_spec();
14937        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
14938        let err = s.validate().unwrap_err();
14939        assert!(
14940            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14941                if host == "checkout.quero.cloud:"
14942                && reason.contains(":entrada :port")),
14943            "got {err:?}"
14944        );
14945    }
14946
14947    #[test]
14948    fn rejects_entrada_host_unbracketed_ipv6_literal() {
14949        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
14950        // literals across the board (peer with `rejects_entrada_host_
14951        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
14952        // Before this top-level `:` arm landed the per-label loop
14953        // surfaced a single-label byte-class diagnostic that named the
14954        // `:` byte but not the IP-literal prohibition. The top-level
14955        // `:` arm names both the `:port` slot and the IP-literal
14956        // prohibition verbatim, so an author whose `:host "2001:..."`
14957        // value lands here gets a self-locating fix either way.
14958        let mut s = three_member_spec();
14959        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
14960        let err = s.validate().unwrap_err();
14961        assert!(
14962            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14963                if host == "2001:db8::1"
14964                && reason.contains("IPv6")),
14965            "got {err:?}"
14966        );
14967    }
14968
14969    #[test]
14970    fn rejects_entrada_host_wildcard_with_port() {
14971        // Wildcard host with port suffix — the `*.` strip and the
14972        // per-label loop on `["foo", "quero", "cloud:8080"]` would
14973        // surface the deep byte-class leak. The top-level `:` arm sits
14974        // upstream of the `*.` strip, so it names the canonical `:port`
14975        // fix verbatim regardless of whether the host is wildcard-led.
14976        let mut s = three_member_spec();
14977        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
14978        let err = s.validate().unwrap_err();
14979        assert!(
14980            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
14981                if host == "*.quero.cloud:8080"
14982                && reason.contains(":entrada :port")),
14983            "got {err:?}"
14984        );
14985    }
14986
14987    #[test]
14988    fn rejects_entrada_host_with_path() {
14989        let mut s = three_member_spec();
14990        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
14991        let err = s.validate().unwrap_err();
14992        assert!(
14993            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
14994                if host == "checkout.quero.cloud/api"),
14995            "got {err:?}"
14996        );
14997    }
14998
14999    #[test]
15000    fn rejects_entrada_host_with_uppercase() {
15001        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
15002        // rejected, not silently lower-cased.
15003        let mut s = three_member_spec();
15004        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
15005        let err = s.validate().unwrap_err();
15006        assert!(
15007            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15008                if reason.contains("uppercase")),
15009            "got {err:?}"
15010        );
15011    }
15012
15013    #[test]
15014    fn rejects_entrada_host_with_underscore() {
15015        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
15016        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
15017        let mut s = three_member_spec();
15018        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
15019        let err = s.validate().unwrap_err();
15020        assert!(
15021            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15022                if reason.contains('_')),
15023            "got {err:?}"
15024        );
15025    }
15026
15027    #[test]
15028    fn rejects_entrada_host_ipv4_literal() {
15029        // Gateway API v1 explicitly forbids IP literals as Hostnames.
15030        let mut s = three_member_spec();
15031        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
15032        let err = s.validate().unwrap_err();
15033        assert!(
15034            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15035                if reason.contains("IPv4")),
15036            "got {err:?}"
15037        );
15038    }
15039
15040    #[test]
15041    fn rejects_entrada_host_with_trailing_dot() {
15042        // The Gateway API regex anchors at end-of-string with no
15043        // trailing `.` allowance — the FQDN root-dot form is rejected.
15044        let mut s = three_member_spec();
15045        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
15046        let err = s.validate().unwrap_err();
15047        assert!(
15048            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15049                if host == "checkout.quero.cloud."),
15050            "got {err:?}"
15051        );
15052    }
15053
15054    #[test]
15055    fn rejects_entrada_host_with_leading_dot() {
15056        let mut s = three_member_spec();
15057        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
15058        let err = s.validate().unwrap_err();
15059        assert!(
15060            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15061                if reason.contains("empty label")),
15062            "got {err:?}"
15063        );
15064    }
15065
15066    #[test]
15067    fn rejects_entrada_host_with_consecutive_dots() {
15068        let mut s = three_member_spec();
15069        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
15070        let err = s.validate().unwrap_err();
15071        assert!(
15072            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15073                if reason.contains("empty label")),
15074            "got {err:?}"
15075        );
15076    }
15077
15078    #[test]
15079    fn rejects_entrada_host_with_leading_hyphen_label() {
15080        let mut s = three_member_spec();
15081        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
15082        let err = s.validate().unwrap_err();
15083        assert!(
15084            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15085                if reason.contains("alphanumeric")),
15086            "got {err:?}"
15087        );
15088    }
15089
15090    #[test]
15091    fn rejects_entrada_host_with_trailing_hyphen_label() {
15092        let mut s = three_member_spec();
15093        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
15094        let err = s.validate().unwrap_err();
15095        assert!(
15096            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15097                if reason.contains("alphanumeric")),
15098            "got {err:?}"
15099        );
15100    }
15101
15102    #[test]
15103    fn rejects_entrada_host_with_inner_wildcard() {
15104        // Gateway API allows `*` only as the first label (`*.foo`);
15105        // any inner or trailing `*` is rejected.
15106        let mut s = three_member_spec();
15107        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
15108        let err = s.validate().unwrap_err();
15109        assert!(
15110            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15111                if reason.contains("wildcard")),
15112            "got {err:?}"
15113        );
15114    }
15115
15116    #[test]
15117    fn rejects_entrada_host_bare_wildcard() {
15118        // `*.` with no domain is meaningless; Gateway API rejects it.
15119        let mut s = three_member_spec();
15120        s.entrada.as_mut().unwrap().host = "*.".into();
15121        let err = s.validate().unwrap_err();
15122        assert!(
15123            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15124                if reason.contains("wildcard")),
15125            "got {err:?}"
15126        );
15127    }
15128
15129    #[test]
15130    fn rejects_entrada_host_with_whitespace() {
15131        let mut s = three_member_spec();
15132        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15133        let err = s.validate().unwrap_err();
15134        assert!(
15135            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15136                if reason.contains("whitespace")),
15137            "got {err:?}"
15138        );
15139    }
15140
15141    #[test]
15142    fn rejects_entrada_host_space_names_offending_byte() {
15143        // Embedded space in the `:entrada :host` axis surfaces the
15144        // byte-naming diagnostic through the lifted
15145        // `find_ascii_whitespace_byte` predicate. Peer with the
15146        // sibling `parse_rejects_leading_whitespace` pins on
15147        // `supervisor::duration_codec` (a7ae622) — same "the
15148        // diagnostic carries the offending byte's `0x{b:02x}` shape"
15149        // discipline extended from the shared duration codec to the
15150        // Gateway API v1 Hostname axis.
15151        let mut s = three_member_spec();
15152        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15153        let err = s.validate().unwrap_err();
15154        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15155            panic!("expected EntradaHostInvalid, got {err:?}");
15156        };
15157        assert!(
15158            reason.contains("ASCII whitespace byte"),
15159            "expected byte-naming diagnostic, got {reason:?}"
15160        );
15161        assert!(
15162            reason.contains("0x20"),
15163            "expected offending space byte 0x20, got {reason:?}"
15164        );
15165    }
15166
15167    #[test]
15168    fn rejects_entrada_host_tab_names_offending_byte() {
15169        // Embedded tab byte in the `:entrada :host` axis — the
15170        // canonical paste-from-YAML-block-scalar / paste-from-
15171        // indented-doc footgun. Pins that the lifted predicate covers
15172        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
15173        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
15174        // not just the leading-space case the pre-lift `.bytes().any`
15175        // arm's opaque "must not contain whitespace" reason already
15176        // covered. Peer with `parse_rejects_tab_byte` on
15177        // `supervisor::duration_codec` (a7ae622).
15178        let mut s = three_member_spec();
15179        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
15180        let err = s.validate().unwrap_err();
15181        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15182            panic!("expected EntradaHostInvalid, got {err:?}");
15183        };
15184        assert!(
15185            reason.contains("ASCII whitespace byte"),
15186            "expected byte-naming diagnostic, got {reason:?}"
15187        );
15188        assert!(
15189            reason.contains("0x09"),
15190            "expected offending tab byte 0x09, got {reason:?}"
15191        );
15192    }
15193
15194    #[test]
15195    fn rejects_entrada_host_lf_names_offending_byte() {
15196        // Embedded LF byte in the `:entrada :host` axis — the
15197        // canonical paste-from-shell-heredoc / paste-from-multiline-
15198        // doc footgun the caixa-mesh YAML emitter would silently
15199        // reinterpret at the Gateway API v1 HTTPRoute admission
15200        // layer (an embedded LF byte in a YAML plain scalar either
15201        // truncates the value at the emitter or crashes the parser
15202        // on the k8s-apiserver side). Pins the third representative
15203        // of the full ASCII-whitespace set through the shared
15204        // predicate.
15205        let mut s = three_member_spec();
15206        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
15207        let err = s.validate().unwrap_err();
15208        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15209            panic!("expected EntradaHostInvalid, got {err:?}");
15210        };
15211        assert!(
15212            reason.contains("ASCII whitespace byte"),
15213            "expected byte-naming diagnostic, got {reason:?}"
15214        );
15215        assert!(
15216            reason.contains("0x0a"),
15217            "expected offending LF byte 0x0a, got {reason:?}"
15218        );
15219    }
15220
15221    #[test]
15222    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
15223        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
15224        // axis — the canonical paste-from-typography /
15225        // paste-from-word-processor footgun. Before the non-ASCII
15226        // Unicode `White_Space` scan lifted through the shared
15227        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
15228        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
15229        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
15230        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
15231        // with the far-from-source `label "…" must start and end
15232        // with an alphanumeric` diagnostic — burying the
15233        // paste-from-typography origin under a label-shape leak.
15234        // Peer with the sibling non-ASCII-whitespace pins at
15235        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
15236        // — 1b75b38), `limits::parse_duration`,
15237        // `limits::parse_millicores`, and the shared duration codec
15238        // — same "the diagnostic carries the offending Unicode
15239        // codepoint's `U+XXXX` shape" discipline extended from every
15240        // typed-magnitude codec to the Gateway API v1 Hostname axis.
15241        let mut s = three_member_spec();
15242        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
15243        let err = s.validate().unwrap_err();
15244        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15245            panic!("expected EntradaHostInvalid, got {err:?}");
15246        };
15247        assert!(
15248            reason.contains("non-ASCII Unicode whitespace character"),
15249            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15250        );
15251        assert!(
15252            reason.contains("U+00A0"),
15253            "expected offending NBSP codepoint U+00A0, got {reason:?}"
15254        );
15255    }
15256
15257    #[test]
15258    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
15259        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
15260        // `:entrada :host` axis — the canonical paste-from-web-doc /
15261        // paste-from-published-HTML footgun. `char::is_whitespace`
15262        // returns true for `U+2028` per the Unicode `White_Space`
15263        // property, so `str::trim` at any downstream site would
15264        // silently strip it — same drift class as NBSP but on a
15265        // different codepoint region. Pins the second representative
15266        // (non-Latin-1 `char::is_whitespace` member) through the
15267        // shared predicate. Peer with
15268        // `parse_byte_size_rejects_internal_line_separator` on
15269        // `limits::parse_byte_size` (1b75b38).
15270        let mut s = three_member_spec();
15271        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
15272        let err = s.validate().unwrap_err();
15273        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15274            panic!("expected EntradaHostInvalid, got {err:?}");
15275        };
15276        assert!(
15277            reason.contains("non-ASCII Unicode whitespace character"),
15278            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15279        );
15280        assert!(
15281            reason.contains("U+2028"),
15282            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
15283        );
15284    }
15285
15286    #[test]
15287    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
15288        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
15289        // labels in the `:entrada :host` axis — the canonical
15290        // paste-from-CJK-typography footgun (CJK IMEs default to
15291        // full-width whitespace when the space bar is pressed in
15292        // Japanese / Chinese input modes). Pins the third
15293        // representative of the non-ASCII Unicode `White_Space` set
15294        // through the shared predicate: the CJK block, distinct from
15295        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
15296        // SEPARATOR `U+2028` — covering the same axis breadth the
15297        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
15298        // (1b75b38) pins on `limits::parse_byte_size`.
15299        let mut s = three_member_spec();
15300        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
15301        let err = s.validate().unwrap_err();
15302        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15303            panic!("expected EntradaHostInvalid, got {err:?}");
15304        };
15305        assert!(
15306            reason.contains("non-ASCII Unicode whitespace character"),
15307            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15308        );
15309        assert!(
15310            reason.contains("U+3000"),
15311            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
15312        );
15313    }
15314
15315    #[test]
15316    fn rejects_entrada_host_too_long() {
15317        // Total length cap = 253; build a 254-byte host out of two
15318        // 63-byte labels + one 62-byte label + dots.
15319        let mut s = three_member_spec();
15320        let big = format!(
15321            "{}.{}.{}.{}",
15322            "a".repeat(63),
15323            "b".repeat(63),
15324            "c".repeat(63),
15325            "d".repeat(254 - 63 * 3 - 3)
15326        );
15327        assert_eq!(big.len(), 254);
15328        s.entrada.as_mut().unwrap().host = big;
15329        let err = s.validate().unwrap_err();
15330        assert!(
15331            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15332                if reason.contains("max length of 253")),
15333            "got {err:?}"
15334        );
15335    }
15336
15337    #[test]
15338    fn rejects_entrada_host_label_too_long() {
15339        let mut s = three_member_spec();
15340        // 64-byte label — one over the per-label cap.
15341        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
15342        let err = s.validate().unwrap_err();
15343        assert!(
15344            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15345                if reason.contains("label max length of 63")),
15346            "got {err:?}"
15347        );
15348    }
15349
15350    #[test]
15351    fn entrada_host_diagnostic_carries_offending_host() {
15352        // Diagnostic-shape pin — the offending host + a non-empty
15353        // reason flow through verbatim so the author can grep their
15354        // caixa.lisp for `:host "<host>"` and fix it in one edit.
15355        let mut s = three_member_spec();
15356        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
15357        let err = s.validate().unwrap_err();
15358        match err {
15359            AplicacaoError::EntradaHostInvalid { host, reason } => {
15360                assert_eq!(host, "checkout.quero.cloud:8080");
15361                assert!(!reason.is_empty(), "reason field must be non-empty");
15362            }
15363            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15364        }
15365    }
15366
15367    #[test]
15368    fn entrada_host_empty_takes_precedence_over_invalid() {
15369        // Ordering pin: `EmptyEntradaHost` is the more self-locating
15370        // diagnostic on `""` and must lead — `validate_entrada_host`
15371        // is only reached after the empty-check fires at the call
15372        // site. (The predicate itself defends against direct
15373        // invocation by returning the same error on `""`.)
15374        let mut s = three_member_spec();
15375        s.entrada.as_mut().unwrap().host = String::new();
15376        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
15377    }
15378
15379    #[test]
15380    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
15381        // Ordering pin: a missing :para member is the more
15382        // self-locating diagnostic and fires before the host gate.
15383        let mut s = three_member_spec();
15384        let e = s.entrada.as_mut().unwrap();
15385        e.para = "ghost".into();
15386        e.host = "BAD HOST".into();
15387        let err = s.validate().unwrap_err();
15388        assert!(
15389            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
15390            "got {err:?}"
15391        );
15392    }
15393
15394    #[test]
15395    fn entrada_host_invalid_fires_before_port_zero() {
15396        // Ordering pin: the host gate fires before the port gate so
15397        // a malformed host is named even when the port is also wrong.
15398        let mut s = three_member_spec();
15399        let e = s.entrada.as_mut().unwrap();
15400        e.host = "Checkout.quero.cloud".into();
15401        e.port = 0;
15402        let err = s.validate().unwrap_err();
15403        assert!(
15404            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15405                if host == "Checkout.quero.cloud"),
15406            "got {err:?}"
15407        );
15408    }
15409
15410    #[test]
15411    fn entrada_accepts_canonical_hosts() {
15412        // Positive-control sweep — every form the Gateway API
15413        // apiserver accepts must round-trip through validate. Covers
15414        // a plain DNS subdomain, a leading wildcard, a single-label
15415        // host (cluster-internal), a max-length-edge label, a
15416        // hyphen-bearing label, and a Punycode IDN label.
15417        for host in [
15418            "checkout.quero.cloud",
15419            "*.quero.cloud",
15420            "checkout",
15421            // 63-byte label — exactly the per-label cap.
15422            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
15423            "foo-bar.quero.cloud",
15424            // Punycode IDN — valid because the author pre-encoded.
15425            "xn--bcher-kva.example.com",
15426        ] {
15427            let mut s = three_member_spec();
15428            s.entrada.as_mut().unwrap().host = host.into();
15429            s.validate()
15430                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
15431        }
15432    }
15433
15434    #[test]
15435    fn entrada_host_max_length_validates() {
15436        // 253-byte host is the cap exactly — must validate. Build a
15437        // 253-byte host out of three 63-byte labels + one 61-byte
15438        // label + 3 dots = 252 bytes, then pad one byte to 253.
15439        let mut s = three_member_spec();
15440        let host = format!(
15441            "{}.{}.{}.{}",
15442            "a".repeat(63),
15443            "b".repeat(63),
15444            "c".repeat(63),
15445            "d".repeat(253 - 63 * 3 - 3)
15446        );
15447        assert_eq!(host.len(), 253);
15448        s.entrada.as_mut().unwrap().host = host;
15449        s.validate().unwrap();
15450    }
15451
15452    #[test]
15453    fn entrada_host_total_length_cap_threads_lifted_render_const() {
15454        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
15455        // total-length gate now reads the K8s Gateway API v1 Hostname
15456        // `maxLength: 253` cap from the lifted
15457        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
15458        // of truth — the same constant every future Gateway-API-Hostname
15459        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
15460        // materializer's per-host validator, the future per-`Certificate`
15461        // SAN emitter for cert-manager, the multi-`:entrada`
15462        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
15463        // from. Before the lift, the aplicacao-side reader consumed a
15464        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
15465        // 253-byte value as the peer render-side canonical bounds
15466        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
15467        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
15468        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
15469        // module boundary — a future 253-byte drift on either side would
15470        // silently split into two axes' worth of admission-schema mismatch
15471        // without a build-time signal. Pin the cap through a fresh 254-
15472        // byte host that hits the total-length arm, then read the reason
15473        // for the exact byte count the shared constant carries: any future
15474        // regression on the lift (a private alias reintroduced, a hard-
15475        // coded literal at the arm, a mismatch between the aplicacao-side
15476        // and render-side canonicals) surfaces as this pin's diagnostic
15477        // failing to match, not as a per-cluster admission rejection far
15478        // from the caixa.lisp source line.
15479        let mut s = three_member_spec();
15480        let over_cap = format!(
15481            "{}.{}.{}.{}",
15482            "a".repeat(63),
15483            "b".repeat(63),
15484            "c".repeat(63),
15485            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
15486        );
15487        assert_eq!(
15488            over_cap.len(),
15489            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
15490        );
15491        s.entrada.as_mut().unwrap().host = over_cap;
15492        let err = s.validate().unwrap_err();
15493        match err {
15494            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15495                let needle = format!(
15496                    "max length of {} bytes",
15497                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
15498                );
15499                assert!(
15500                    reason.contains(&needle),
15501                    "diagnostic must name the lifted \
15502                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
15503                );
15504            }
15505            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15506        }
15507    }
15508
15509    #[test]
15510    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
15511        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
15512        // on the per-label-cap axis. Before the lift, the aplicacao-side
15513        // per-label arm consumed a private const alias
15514        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
15515        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
15516        // split from it at the module boundary — every `.`-separated
15517        // label in a Gateway API v1 Hostname is a DNS-1123 label under
15518        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
15519        // so the private alias's 63 and the canonical const's 63 were
15520        // pinning the same underlying rule twice. Pin the cap through a
15521        // 64-byte label that hits the per-label arm, then read the reason
15522        // for the exact byte count the shared constant carries: any
15523        // future drift on either side (a private alias reintroduced, a
15524        // hard-coded literal at the arm, a mismatch between the two
15525        // 63-byte pins) surfaces at this pin's diagnostic rather than at
15526        // a per-cluster admission rejection whose "field is invalid"
15527        // opacity misframes the root cause.
15528        let mut s = three_member_spec();
15529        let over_cap_label = format!(
15530            "{}.quero.cloud",
15531            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
15532        );
15533        s.entrada.as_mut().unwrap().host = over_cap_label;
15534        let err = s.validate().unwrap_err();
15535        match err {
15536            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15537                let needle = format!(
15538                    "label max length of {} bytes",
15539                    crate::render::DNS_1123_LABEL_MAX_LEN,
15540                );
15541                assert!(
15542                    reason.contains(&needle),
15543                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
15544                     cap verbatim on the per-label arm, got: {reason:?}",
15545                );
15546            }
15547            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15548        }
15549    }
15550
15551    #[test]
15552    fn entrada_with_empty_paths_validates() {
15553        // Empty `:paths` is the documented "match every path" form;
15554        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
15555        let mut s = three_member_spec();
15556        s.entrada.as_mut().unwrap().paths = vec![];
15557        s.validate().unwrap();
15558    }
15559
15560    #[test]
15561    fn entrada_root_path_validates() {
15562        // The author-supplied bare-root `:entrada :paths` entry is the
15563        // same byte-shape the peer emit-side catch-all constant
15564        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
15565        // the author's `:paths` list is empty — sweeping the test-side
15566        // probe literal onto the lifted const closes the two-axis pin
15567        // (author-side admit + emit-side canonical fallback) around
15568        // one `&'static str`, so a future rebrand of the catch-all
15569        // reaches both consumers by construction. Peer to
15570        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
15571        // on the canonical-literal pin surface.
15572        let mut s = three_member_spec();
15573        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
15574        s.validate().unwrap();
15575    }
15576
15577    #[test]
15578    fn placement_strategy_variants_round_trip() {
15579        for s in [
15580            PlacementStrategy::SingleNode,
15581            PlacementStrategy::Replicated,
15582            PlacementStrategy::Sharded,
15583        ] {
15584            let p = Placement {
15585                estrategia: s,
15586                clusters: vec!["rio".into()],
15587                affinity: None,
15588                // Route the paired `:shard-key` fixture-builder through the
15589                // typed cross-slot invariant predicate
15590                // [`PlacementStrategy::requires_shard_key`] rather than the
15591                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
15592                // arm-identity predicate — the two answer the same
15593                // question under today's closed accept-set but a future
15594                // arm addition that consumed `:shard-key` under a
15595                // non-`Sharded` name would silently mis-attach the
15596                // fixture's `:shard-key` if the builder read through the
15597                // arm-identity predicate. The cross-slot-invariant
15598                // predicate migrates through one caixa-core edit on any
15599                // future arm addition; the fixture keeps producing a
15600                // `validate()`-passing round-trip by construction.
15601                shard_key: if s.requires_shard_key() {
15602                    Some("$key".into())
15603                } else {
15604                    None
15605                },
15606            };
15607            let json = serde_json::to_string(&p).unwrap();
15608            let back: Placement = serde_json::from_str(&json).unwrap();
15609            assert_eq!(back, p);
15610        }
15611    }
15612
15613    #[test]
15614    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
15615        // The fail-before-pass-after pin: pre-lift there was no
15616        // single-source binding between the [`PlacementStrategy`]
15617        // variant name the `Serialize` derive emits and the byte-
15618        // string every downstream cluster-side dispatcher (the
15619        // `lareira-fleet-programs` aggregator's per-entry strategy
15620        // branch, the future `app-operator` reconciler, the M3
15621        // Adaptive compression pass's per-strategy weighting) probes
15622        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
15623        // future `#[serde(rename_all = "kebab-case")]` attribute on
15624        // the enum — or a variant rename in the source — would
15625        // silently rebrand the emitted scalar under one spelling
15626        // while every downstream dispatcher still probed the other,
15627        // with the failure surfacing at the aggregator's dispatch
15628        // step or the operator's reconcile posture (workloads coming
15629        // up under the `default()` `Replicated` arm rather than the
15630        // typed slot's declared strategy) far from the source
15631        // rebrand commit and with no field naming the drift. Pinning
15632        // the two paths (the `Serialize` derive's serialized string
15633        // AND the [`PlacementStrategy::as_str`] helper) to the same
15634        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
15635        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15636        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
15637        // makes any future drift on either endpoint fail here at
15638        // caixa-core build time.
15639        for (variant, expected) in [
15640            (
15641                PlacementStrategy::SingleNode,
15642                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15643            ),
15644            (
15645                PlacementStrategy::Replicated,
15646                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15647            ),
15648            (
15649                PlacementStrategy::Sharded,
15650                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15651            ),
15652        ] {
15653            let json = serde_json::to_string(&variant).unwrap();
15654            assert_eq!(
15655                json,
15656                format!("\"{expected}\""),
15657                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
15658            );
15659            assert_eq!(
15660                variant.as_str(),
15661                expected,
15662                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
15663                 M3_PLACEMENT_ESTRATEGIA_* constant"
15664            );
15665        }
15666    }
15667
15668    #[test]
15669    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
15670        // Cross-arm drift-detection pin on the M3
15671        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
15672        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15673        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
15674        // scalar-value pentad: a future collapse of two canonical
15675        // variant byte-strings onto the same value (an accidental
15676        // copy-paste flip of
15677        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
15678        // read `"SingleNode"`, a per-arm rebrand that lands one const
15679        // without touching its paired peer) would silently reroute
15680        // every downstream operator's per-strategy dispatch onto the
15681        // sibling arm's reconcile branch and pass every
15682        // propagation-probe test that expected only the stale arm's
15683        // value — a `Replicated`-declared Aplicacao would come up
15684        // under the `SingleNode` primary-and-standby reconcile
15685        // posture, so every-cluster active-active workload would
15686        // silently collapse onto one-cluster-runs-at-a-time takeover
15687        // semantics against its declared strategy, with no field
15688        // naming the strategy-value drift root cause. Peer of the
15689        // sibling
15690        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
15691        // (09ffb2d) /
15692        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
15693        // (ccdf955) /
15694        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
15695        // (d739850) distinctness pins on the sibling OTP-shape /
15696        // caixa-kind closed-set typed-enum discriminator axes — the
15697        // fourth (and structurally the M3 mesh-primitive-defining)
15698        // closed-set typed-enum axis to converge on the same
15699        // "pairwise-distinct-by-construction" discipline.
15700        //
15701        // Fail-before-pass-after locally verified by mutating
15702        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
15703        // also read `"SingleNode"` — this pin fires as expected;
15704        // restoring passes.
15705        let all = [
15706            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15707            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15708            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15709        ];
15710        for (i, a) in all.iter().enumerate() {
15711            for (j, b) in all.iter().enumerate() {
15712                if i != j {
15713                    assert_ne!(
15714                        a, b,
15715                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
15716                         distinct — got duplicate {a:?} at indices {i} and {j}",
15717                    );
15718                }
15719            }
15720        }
15721    }
15722
15723    #[test]
15724    fn placement_strategy_display_routes_through_as_str_helper() {
15725        // The fail-before-pass-after pin: pre-lift the sibling
15726        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
15727        // / [`crate::supervisor::RestartPolicy`] both carried a stable
15728        // [`std::fmt::Display`] surface via their
15729        // `#[discriminant(also_display)]` gen-platform derive, but
15730        // [`PlacementStrategy`] did not — every consumer reaching for
15731        // a strategy byte-string past the wire format had to pick
15732        // between three paths ([`PlacementStrategy::as_str`], the
15733        // `Serialize` derive's serialized string, or `format!("{v:?}")`
15734        // on the `Debug` derive), any two of which a future variant
15735        // rename or `#[serde(rename_all = "kebab-case")]` attribute
15736        // would silently desynchronize. Wiring [`std::fmt::Display`]
15737        // through [`PlacementStrategy::as_str`] closes the third path:
15738        // every `format!("{v}")` call reaches the same lifted
15739        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
15740        // and the [`PlacementStrategy::as_str`] helper already route
15741        // through, so a future variant rename lands at exactly one
15742        // place. Pin the routing here so a future
15743        // `impl std::fmt::Display for PlacementStrategy` reimplementation
15744        // that hand-rolls the arms instead of delegating to
15745        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
15746        for variant in [
15747            PlacementStrategy::SingleNode,
15748            PlacementStrategy::Replicated,
15749            PlacementStrategy::Sharded,
15750        ] {
15751            assert_eq!(
15752                variant.to_string(),
15753                variant.as_str(),
15754                "PlacementStrategy::{variant:?} Display must route through \
15755                 PlacementStrategy::as_str (single source of truth: the lifted \
15756                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
15757            );
15758        }
15759    }
15760
15761    #[test]
15762    fn placement_strategy_display_matches_serialized_wire_byte_string() {
15763        // The fail-before-pass-after pin on the second half of the
15764        // three-path convergence: `Display` (user-facing text) agrees
15765        // byte-for-byte with the `Serialize` derive's wire format
15766        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
15767        // scalar) on every variant. Pre-lift the two paths were
15768        // structurally independent — a future
15769        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
15770        // would silently rebrand the emitted wire scalar
15771        // (`single-node`, `replicated`, `sharded`) while every consumer
15772        // that pretty-prints the strategy (the M3 diagnostic templates,
15773        // the future `feira app graph` per-Aplicacao strategy line,
15774        // the future M4 CR materializer's admission-webhook rejection
15775        // body) would still emit the TitleCase form the `as_str` /
15776        // `Display` route returns, with the mismatch surfacing at
15777        // consumer parse time / operator dispatch time far from the
15778        // source rebrand commit. Pin the two paths byte-for-byte here
15779        // so any future serde-attribute or variant-rename drift is a
15780        // caixa-core-build-time test failure at this call, not a
15781        // silent per-consumer dispatch miss.
15782        for variant in [
15783            PlacementStrategy::SingleNode,
15784            PlacementStrategy::Replicated,
15785            PlacementStrategy::Sharded,
15786        ] {
15787            let wire = serde_json::to_string(&variant).unwrap();
15788            // Strip the outer `"…"` the JSON string form carries — the
15789            // wire scalar the K8s / YAML apiserver consumes is the
15790            // enclosed byte-string, not the quote wrapper.
15791            let unquoted = wire
15792                .strip_prefix('"')
15793                .and_then(|s| s.strip_suffix('"'))
15794                .expect("serialized PlacementStrategy is a JSON string");
15795            assert_eq!(
15796                variant.to_string(),
15797                unquoted,
15798                "PlacementStrategy::{variant:?} Display byte-string must match the \
15799                 Serialize derive's wire byte-string (three-path convergence: \
15800                 Display + as_str + Serialize all resolve to the same \
15801                 M3_PLACEMENT_ESTRATEGIA_* const)"
15802            );
15803        }
15804    }
15805
15806    #[test]
15807    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
15808        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
15809        // derive on [`PlacementStrategy`]: for each of the three variants
15810        // exactly one of the generated `is_single_node` / `is_replicated`
15811        // / `is_sharded` predicates returns `true` and the other two
15812        // return `false`. Prior to this derive the three per-arm
15813        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
15814        // (the `placement_strategy_variants_round_trip` fixture, the
15815        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
15816        // fixture, and the
15817        // `validate_placement_reads_through_lifted_estrategia_accessor`
15818        // fixture) each open-coded a per-arm PartialEq compare against
15819        // the enum variant — three sites that expressed no compile-time
15820        // link back to the closed-set typed dispatch a future fourth
15821        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
15822        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
15823        // would have to thread through in lockstep or one fixture would
15824        // silently disagree with the others on which arms consume the
15825        // `:shard-key` axis. Peer of the sibling
15826        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
15827        // / [`crate::supervisor::RestartPolicy`] /
15828        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
15829        // the sibling closed-set typed-enum discriminator axes — extends
15830        // the same one-typed-dispatch-per-variant discipline onto the
15831        // fifth (and only remaining) closed-set typed-enum discriminator
15832        // on the caixa surface, closing the axis on the M3 mesh-slot
15833        // family.
15834        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
15835            (PlacementStrategy::SingleNode, [true, false, false]),
15836            (PlacementStrategy::Replicated, [false, true, false]),
15837            (PlacementStrategy::Sharded, [false, false, true]),
15838        ];
15839        for (variant, expected) in rows {
15840            let observed = [
15841                variant.is_single_node(),
15842                variant.is_replicated(),
15843                variant.is_sharded(),
15844            ];
15845            assert_eq!(
15846                observed, expected,
15847                "PlacementStrategy::{variant:?} is_* predicates must partition \
15848                 the arm set (single_node, replicated, sharded); got {observed:?}"
15849            );
15850        }
15851    }
15852
15853    #[test]
15854    fn placement_strategy_is_variant_predicates_are_const_fn() {
15855        // The [`gen_platform::IsVariant`] derive emits `const fn`
15856        // predicates on the peer [`crate::CaixaKind`] +
15857        // [`crate::upgrade::UpgradeInstruction`] +
15858        // [`crate::supervisor::RestartStrategy`] +
15859        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
15860        // pin the same posture on [`PlacementStrategy`] so a future
15861        // accidental downgrade to non-`const` (an added runtime helper
15862        // reachable only from a non-`const` context, a manual hand-rolled
15863        // `impl` that shadows the derive-generated method) trips at
15864        // caixa-core build time rather than surfacing as a downstream
15865        // `const`-context regression far from the derive declaration.
15866        const IS_SINGLE_NODE: bool = PlacementStrategy::SingleNode.is_single_node();
15867        const IS_REPLICATED: bool = PlacementStrategy::Replicated.is_replicated();
15868        const IS_SHARDED: bool = PlacementStrategy::Sharded.is_sharded();
15869        assert!(IS_SINGLE_NODE);
15870        assert!(IS_REPLICATED);
15871        assert!(IS_SHARDED);
15872    }
15873
15874    #[test]
15875    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
15876        // Fail-before-pass-after pin on the substrate-lifted
15877        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
15878        // per-arm predicate: for each variant in the closed accept-set the
15879        // predicate returns `true` iff the variant consumes the paired
15880        // [`Placement::shard_key`] axis under
15881        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
15882        // partition. Today the accept-set is the singleton `{Sharded}` —
15883        // `Sharded` is the Akka-style hash-keyed distribution arm
15884        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
15885        // §II.1) and `Replicated` (active-active) refuse the axis through
15886        // [`AplicacaoError::ShardKeyOnNonSharded`].
15887        //
15888        // Pins the per-arm truth-table so a future arm addition (an
15889        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
15890        // roadmap names, a `WeightedShard` promotion the future M5
15891        // adaptive-placement engine acknowledges) that landed a variant
15892        // without extending this predicate's arm-set would surface as a
15893        // caixa-core build-time exhaustiveness error at the
15894        // `match self { … }` arm-fan below rather than a silent per-consumer
15895        // mis-classification at renderer emit time. The paired
15896        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
15897        // predicate stays a distinct question — arm-identity (which the
15898        // sibling
15899        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
15900        // pin already locks) is not cross-slot-invariant consumption; today
15901        // they trip on the same singleton but the pair migrates through
15902        // one caixa-core edit on any future arm addition.
15903        //
15904        // Peer of the sibling per-arm classifier pins
15905        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
15906        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
15907        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
15908        // derived paired predicate on the post-projection typed-view axis
15909        // — same "per-arm semantic-classification predicate paired with
15910        // the arm-identity predicate the derive already emits" discipline
15911        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
15912        // `:placement :shard-key` cross-slot-invariant axis.
15913        let rows: [(PlacementStrategy, bool); 3] = [
15914            (PlacementStrategy::SingleNode, false),
15915            (PlacementStrategy::Replicated, false),
15916            (PlacementStrategy::Sharded, true),
15917        ];
15918        for (variant, expected) in rows {
15919            assert_eq!(
15920                variant.requires_shard_key(),
15921                expected,
15922                "PlacementStrategy::{variant:?}.requires_shard_key() must \
15923                 be {expected} (the substrate-canonical cross-slot invariant \
15924                 on the :placement :shard-key axis; today `Sharded` is the \
15925                 singleton consuming arm — MESH-COMPOSITION §II.4)",
15926            );
15927        }
15928    }
15929
15930    #[test]
15931    fn placement_strategy_requires_shard_key_is_const_fn() {
15932        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
15933        // invariant per-arm predicate is declared `#[must_use] pub const
15934        // fn` — pin the `const`-eval posture here so a future accidental
15935        // downgrade to non-`const` (an added runtime helper reachable
15936        // only from a non-`const` context, a manual hand-rolled `impl`
15937        // that shadows the current three-arm `match self { … }` dispatch)
15938        // trips at caixa-core build time rather than surfacing as a
15939        // downstream `const`-context regression far from the declaration.
15940        // Same shape as the sibling
15941        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
15942        // the peer [`gen_platform::IsVariant`]-derived arm-identity
15943        // predicate axis, but here the load-bearing assertions live in
15944        // module-scope `const _: () = assert!(…)` items so a violation
15945        // fails at compile time (const-eval trip) rather than test time —
15946        // strictly stronger than the runtime `assert!(CONST)` pattern the
15947        // sibling pin uses, and side-steps the
15948        // `clippy::assertions_on_constants` lint the runtime pattern
15949        // otherwise accumulates on the module baseline.
15950        //
15951        // The test body simply witnesses that the module-scope items
15952        // compiled and the runtime dispatch agrees with the const-eval
15953        // dispatch on every arm — the runtime read gives the test a
15954        // failure surface (rather than an empty test body clippy would
15955        // flag as a no-op).
15956        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
15957        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
15958        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
15959        assert_eq!(
15960            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
15961            [
15962                PlacementStrategy::SingleNode.requires_shard_key(),
15963                PlacementStrategy::Replicated.requires_shard_key(),
15964                PlacementStrategy::Sharded.requires_shard_key(),
15965            ],
15966            "runtime and const-eval dispatch on \
15967             PlacementStrategy::requires_shard_key must agree on every arm",
15968        );
15969    }
15970
15971    #[test]
15972    fn placement_estrategia_accessor_is_const_fn() {
15973        // The [`Placement::estrategia`] per-`:placement` distribution-
15974        // strategy `Copy`-return scalar accessor is declared
15975        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
15976        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
15977        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
15978        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
15979        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
15980        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
15981        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
15982        // [`RateLimit`], every one a `pub const fn`). Pin the
15983        // `const`-eval posture here so a future accidental downgrade to
15984        // non-`const` (an added runtime helper reachable only from a
15985        // non-`const` context, a slot promotion to a non-`Copy` return
15986        // that would silently drop the `const` qualifier, a manual
15987        // hand-rolled shadow) trips at caixa-core build time rather
15988        // than surfacing as a downstream `const`-context regression far
15989        // from the declaration.
15990        //
15991        // Same shape as the sibling
15992        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
15993        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
15994        // predicate axis — the load-bearing witness lives in the
15995        // module-scope `const fn` wrapper `estrategia_via_const_fn`
15996        // below: a body that calls [`Placement::estrategia`] under a
15997        // `const fn` signature is well-formed only when the callee is
15998        // itself `const fn`, so any future accidental downgrade of
15999        // [`Placement::estrategia`] to non-`const` fails at caixa-core
16000        // build time (const-eval E0015 / E0658 depending on the arm),
16001        // strictly stronger than a runtime `assert!(CONST)` and
16002        // side-stepping the destructor-in-const restriction that
16003        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
16004        // items on `Placement`'s `Vec<String>` / `Option<String>`
16005        // carriers.
16006        //
16007        // The runtime body witnesses that the const-eval-shaped
16008        // wrapper agrees with a direct call on every closed-set arm.
16009        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
16010            p.estrategia()
16011        }
16012        for estrategia in [
16013            PlacementStrategy::SingleNode,
16014            PlacementStrategy::Replicated,
16015            PlacementStrategy::Sharded,
16016        ] {
16017            let placement = Placement {
16018                estrategia,
16019                clusters: Vec::new(),
16020                affinity: None,
16021                shard_key: None,
16022            };
16023            assert_eq!(
16024                estrategia_via_const_fn(&placement),
16025                placement.estrategia(),
16026                "const-fn-wrapped and direct dispatch on \
16027                 Placement::estrategia must agree for {estrategia:?}",
16028            );
16029        }
16030    }
16031
16032    #[test]
16033    fn entrada_port_accessor_is_const_fn() {
16034        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
16035        // scalar accessor is declared `#[must_use] pub const fn` —
16036        // matching the peer M3 mesh-slot `Copy`-return accessor family
16037        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
16038        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
16039        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
16040        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
16041        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
16042        // [`RateLimit::window`] on the sibling [`RateLimit`], the
16043        // sibling per-`:placement` [`Placement::estrategia`] pinned by
16044        // [`placement_estrategia_accessor_is_const_fn`] above — every
16045        // one a `pub const fn`). Pin the `const`-eval posture here so
16046        // a future accidental downgrade to non-`const` (an added
16047        // runtime helper reachable only from a non-`const` context, an
16048        // `Option<u16>`-shape migration once the substrate grows
16049        // per-`:membros` heterogeneous listener ports that would
16050        // silently drop the `const` qualifier, a manual hand-rolled
16051        // shadow) trips at caixa-core build time rather than surfacing
16052        // as a downstream `const`-context regression far from the
16053        // declaration.
16054        //
16055        // Same shape as the sibling
16056        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
16057        // load-bearing witness lives in the module-scope `const fn`
16058        // wrapper `port_via_const_fn`: a body that calls
16059        // [`Entrada::port`] under a `const fn` signature is well-formed
16060        // only when the callee is itself `const fn`, side-stepping the
16061        // destructor-in-const restriction that would otherwise block a
16062        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
16063        // `String` / `Vec<String>` carriers.
16064        //
16065        // The runtime body sweeps a representative port set spanning
16066        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
16067        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
16068        // ceiling — the const-fn-wrapped call must agree with a direct
16069        // call on every fixture (a violation trips the test) and every
16070        // returned scalar must byte-equal the input `port` (a violation
16071        // means the accessor stopped being a raw field-return copy).
16072        const fn port_via_const_fn(e: &Entrada) -> u16 {
16073            e.port()
16074        }
16075        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
16076            let entrada = Entrada {
16077                host: String::new(),
16078                para: String::new(),
16079                port,
16080                paths: Vec::new(),
16081            };
16082            assert_eq!(
16083                port_via_const_fn(&entrada),
16084                entrada.port(),
16085                "const-fn-wrapped and direct dispatch on Entrada::port \
16086                 must agree for port={port}",
16087            );
16088            assert_eq!(
16089                entrada.port(),
16090                port,
16091                "Entrada::port must return the storage-side u16 verbatim \
16092                 for port={port}",
16093            );
16094        }
16095    }
16096
16097    #[test]
16098    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
16099        // Load-bearing cross-slot-partition pin closing the loop between
16100        // the substrate-lifted
16101        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
16102        // the closed-set typed enum and the actual
16103        // [`AplicacaoSpec::validate_placement`] runtime behavior across
16104        // the paired `:placement :shard-key` axis: every validated
16105        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
16106        // satisfies `placement.shard_key().is_some() ==
16107        // placement.estrategia().requires_shard_key()`. The four-cell
16108        // shape witness sweeps every combination of (variant in the
16109        // closed accept-set, `:shard-key` Some/None) and pins:
16110        //
16111        //   * variant.requires_shard_key() && shard_key.is_some() →
16112        //     validate() passes; the paired shape is the sole
16113        //     `requires_shard_key` arm-family accepted shape.
16114        //   * variant.requires_shard_key() && shard_key.is_none() →
16115        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
16116        //     the paired shape is the refused missing-key shape on
16117        //     Sharded-family arms.
16118        //   * !variant.requires_shard_key() && shard_key.is_some() →
16119        //     validate() fails with
16120        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
16121        //     is the refused declared-but-inert shape on non-Sharded-
16122        //     family arms.
16123        //   * !variant.requires_shard_key() && shard_key.is_none() →
16124        //     validate() passes; the paired shape is the sole
16125        //     non-`requires_shard_key` arm-family accepted shape.
16126        //
16127        // The compile-time-exhaustive `match p.estrategia()` dispatch at
16128        // [`AplicacaoSpec::validate_placement`] preserves its structural
16129        // arm-fan (a future arm addition still surfaces a build-time
16130        // exhaustiveness error there); this pin closes the semantic loop
16131        // between the arm-fan's shape-gate cascades and the substrate-
16132        // canonical predicate every downstream consumer of the paired
16133        // shape reads through. Fail-before-pass-after locally verified by
16134        // mutating the predicate's `Sharded => true` arm to `false` — the
16135        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
16136        // `validate() must pass` assertion; restoring passes. Same "close
16137        // the loop between the typed predicate and the runtime behavior"
16138        // discipline as the sibling
16139        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
16140        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
16141        // per-arm classifier axis.
16142        for variant in [
16143            PlacementStrategy::SingleNode,
16144            PlacementStrategy::Replicated,
16145            PlacementStrategy::Sharded,
16146        ] {
16147            for present in [false, true] {
16148                let mut spec = three_member_spec();
16149                spec.placement.estrategia = variant;
16150                spec.placement.shard_key = present.then(|| "tenantId".into());
16151                let expects_ok = variant.requires_shard_key() == present;
16152                let result = spec.validate();
16153                match (expects_ok, &result) {
16154                    (true, Ok(())) => {}
16155                    (false, Err(err)) => {
16156                        // Cross-check the refusal diagnostic names the
16157                        // right cell of the four-cell shape witness — the
16158                        // `requires_shard_key && !present` cell must trip
16159                        // [`AplicacaoError::ShardedWithoutKey`]; the
16160                        // `!requires_shard_key && present` cell must trip
16161                        // [`AplicacaoError::ShardKeyOnNonSharded`].
16162                        match (variant.requires_shard_key(), present, err) {
16163                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
16164                            (
16165                                false,
16166                                true,
16167                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
16168                            ) => {
16169                                assert_eq!(
16170                                    *e, variant,
16171                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
16172                                     the paired PlacementStrategy",
16173                                );
16174                            }
16175                            _ => panic!(
16176                                "unexpected refusal for estrategia={variant:?} \
16177                                 present={present}: {err:?}"
16178                            ),
16179                        }
16180                    }
16181                    (true, Err(err)) => panic!(
16182                        "validate() must pass for estrategia={variant:?} \
16183                         present={present} (requires_shard_key={} == present={present}), \
16184                         got {err:?}",
16185                        variant.requires_shard_key(),
16186                    ),
16187                    (false, Ok(())) => panic!(
16188                        "validate() must fail for estrategia={variant:?} \
16189                         present={present} (requires_shard_key={} != present={present})",
16190                        variant.requires_shard_key(),
16191                    ),
16192                }
16193            }
16194        }
16195    }
16196
16197    #[test]
16198    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
16199        // Pin the M3 diagnostic template routes through the typed
16200        // [`PlacementStrategy`] Display byte-string (rebound from the
16201        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
16202        // routes emitted identical bytes (the `Debug` derive on a
16203        // unit variant emits the variant name verbatim, exactly what
16204        // `as_str` returns), but the two paths were structurally
16205        // independent — a future `#[serde(rename_all = "…")]`
16206        // attribute or variant rename would coordinate the wire /
16207        // `Display` / `as_str` triple through the lifted const but
16208        // leave the `Debug` route on the compiler-derived variant name,
16209        // silently desynchronizing the diagnostic byte-string from the
16210        // wire byte-string. Rebinding the template onto `Display`
16211        // ties the diagnostic to the same lifted
16212        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
16213        // emits — drift becomes structurally impossible. Pin the
16214        // byte-string here so a future edit that reverts the template
16215        // to `{estrategia:?}` is caught at caixa-core test time, not
16216        // at consumer dispatch time.
16217        for (variant, expected_scalar) in [
16218            (
16219                PlacementStrategy::SingleNode,
16220                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16221            ),
16222            (
16223                PlacementStrategy::Replicated,
16224                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16225            ),
16226            (
16227                PlacementStrategy::Sharded,
16228                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16229            ),
16230        ] {
16231            let err = AplicacaoError::PlacementWithoutClusters {
16232                estrategia: variant,
16233            };
16234            let msg = err.to_string();
16235            assert!(
16236                msg.starts_with(&format!(":placement {expected_scalar} requires")),
16237                "PlacementWithoutClusters diagnostic for {variant:?} must open \
16238                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16239            );
16240        }
16241    }
16242
16243    #[test]
16244    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
16245        // Peer of
16246        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
16247        // on the second M3 diagnostic that carries the typed
16248        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
16249        // diagnostics now route the strategy scalar through the same
16250        // [`std::fmt::Display`] surface, tying the diagnostic
16251        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
16252        // const set the wire format also emits. The two non-Sharded
16253        // arms are exercised here (the diagnostic exists to flag a
16254        // `:shard-key` slot the current strategy will never consume);
16255        // the peer `Sharded` arm never reaches this diagnostic (the
16256        // `Sharded` strategy consumes `:shard-key` — the
16257        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
16258        // slot instead).
16259        for (variant, expected_scalar) in [
16260            (
16261                PlacementStrategy::SingleNode,
16262                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16263            ),
16264            (
16265                PlacementStrategy::Replicated,
16266                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16267            ),
16268        ] {
16269            let err = AplicacaoError::ShardKeyOnNonSharded {
16270                estrategia: variant,
16271                shard_key: "$tenantId".into(),
16272            };
16273            let msg = err.to_string();
16274            assert!(
16275                msg.starts_with(&format!(":placement {expected_scalar} carries")),
16276                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
16277                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16278            );
16279        }
16280    }
16281
16282    #[test]
16283    fn placement_strategy_all_enumerates_every_variant_once() {
16284        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
16285        // exhaustive-iteration surface: every variant appears exactly
16286        // once, and the slice length matches the arm count of the
16287        // closed set. Every consumer that walks the accepted-strategy
16288        // set (a future `feira app placement --list` CLI-side surfacing,
16289        // a future M4 admission-webhook's rejection body naming the
16290        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
16291        // reverse-projection consumers that iterate the accept-set for
16292        // a "did you mean" hint) reads through this slice, so a future
16293        // variant addition (an `Anycast` mesh-anycast arm the
16294        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
16295        // grows the enum but forgets to grow [`Self::ALL`] silently
16296        // truncates every downstream consumer's accept-set at the same
16297        // pre-addition boundary — this pin fails at caixa-core build
16298        // time on the pairwise-distinct + arm-count invariants.
16299        //
16300        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
16301        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
16302        // pins on the peer closed-set typed-enum axes.
16303        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
16304        assert_eq!(
16305            all.len(),
16306            3,
16307            "PlacementStrategy::ALL must enumerate every variant of the \
16308             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
16309        );
16310        for (i, a) in all.iter().enumerate() {
16311            for (j, b) in all.iter().enumerate() {
16312                if i != j {
16313                    assert_ne!(
16314                        a, b,
16315                        "PlacementStrategy::ALL must carry every variant exactly \
16316                         once — got duplicate {a:?} at indices {i} and {j}"
16317                    );
16318                }
16319            }
16320        }
16321        for variant in [
16322            PlacementStrategy::SingleNode,
16323            PlacementStrategy::Replicated,
16324            PlacementStrategy::Sharded,
16325        ] {
16326            assert!(
16327                all.contains(&variant),
16328                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
16329                 addition that grows the enum but forgets to grow the ALL slice \
16330                 silently truncates every downstream consumer's accept-set at the \
16331                 pre-addition boundary"
16332            );
16333        }
16334    }
16335
16336    #[test]
16337    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
16338        // Fail-before-pass-after pin on the forward accept-set of the
16339        // [`PlacementStrategy::from_wire`] reverse projection: every
16340        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
16341        // constant the [`PlacementStrategy::as_str`] emitter walks
16342        // parses back to its paired variant. Any future arm addition
16343        // that grows the emitter's `as_str` match but forgets to grow
16344        // the parser's `from_str` match silently splits the two halves
16345        // of the round-trip — the wire byte-string one non-serde
16346        // consumer parses from the one the emitter wrote — with the
16347        // failure surfacing at parse time far from the rebrand commit.
16348        // Pinning the three-arm accept-set here catches the drift at
16349        // caixa-core build time.
16350        //
16351        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
16352        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
16353        // closed-set typed-enum `str → Self` axes.
16354        for (wire, expected) in [
16355            (
16356                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16357                PlacementStrategy::SingleNode,
16358            ),
16359            (
16360                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16361                PlacementStrategy::Replicated,
16362            ),
16363            (
16364                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16365                PlacementStrategy::Sharded,
16366            ),
16367        ] {
16368            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16369                panic!(
16370                    "PlacementStrategy::from_wire({wire:?}) must accept every \
16371                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
16372                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
16373                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
16374                )
16375            });
16376            assert_eq!(
16377                parsed, expected,
16378                "PlacementStrategy::from_wire({wire:?}) must return \
16379                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
16380            );
16381        }
16382    }
16383
16384    #[test]
16385    fn placement_strategy_from_wire_round_trips_through_as_str() {
16386        // Fail-before-pass-after pin on the closed round-trip between
16387        // the forward [`PlacementStrategy::as_str`] emitter and the
16388        // reverse [`PlacementStrategy::from_wire`] parser: for every
16389        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
16390        // output must return exactly the same variant. Any per-arm
16391        // divergence — a future arm added to `as_str` but not
16392        // `from_str`, an accidental copy-paste flip in one but not the
16393        // other — silently splits the emit and parse halves and the
16394        // failure surfaces at consumer parse time far from the drift
16395        // site. The `ALL`-iterating shape means a future variant
16396        // addition picks up the coverage by construction.
16397        //
16398        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
16399        // [`crate::CaixaKind::from_wire`] and the
16400        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
16401        // sibling round-trip pin on [`RateLimitUnit`].
16402        for &variant in PlacementStrategy::ALL {
16403            let wire = variant.as_str();
16404            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16405                panic!(
16406                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16407                     must be Some({variant:?}) — the two halves of the round-trip \
16408                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
16409                     got None on wire byte-string {wire:?}"
16410                )
16411            });
16412            assert_eq!(
16413                parsed, variant,
16414                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16415                 must round-trip to the same variant; got {parsed:?}"
16416            );
16417        }
16418    }
16419
16420    #[test]
16421    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
16422        // Fail-before-pass-after pin on the closed-set refusal
16423        // discipline of [`PlacementStrategy::from_wire`]: every
16424        // byte-string outside the three-arm accept-set returns `None`
16425        // rather than silently collapsing onto the [`Default`]
16426        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
16427        // exercised here sweeps the load-bearing drift shapes: the
16428        // empty string (a stripped serde-attribute drift), an all-
16429        // whitespace string (the canonical text-editor accidental
16430        // padding shape), the lowercased kebab-case forms a future
16431        // `#[serde(rename_all = "kebab-case")]` attribute would emit
16432        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
16433        // coincidentally match the accepted canonical scalars, so only
16434        // `"single-node"` fires as a refusal, but pinning the case-
16435        // sensitivity of the accepted arms via the peer [`SingleNode`]
16436        // assertion in the round-trip pin makes the discipline
16437        // structurally clear), the lowercased single-word forms
16438        // (`"singlenode"`), the padded canonical scalar
16439        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
16440        // (`"Sharded\n"`), and a pointer-different `&'static str` that
16441        // happens to alias a canonical byte-string by content but not
16442        // by identity (validated implicitly by the emitter's routing
16443        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
16444        // identity a paired [`crate::assert_str_reexport_identity`] pin
16445        // in caixa-core's per-const declaration surface would catch).
16446        //
16447        // Peer of the sibling
16448        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
16449        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
16450        for bad in [
16451            "",
16452            " ",
16453            "\n",
16454            "\t",
16455            "single-node",
16456            "singlenode",
16457            "SingleNodes",
16458            "single_node",
16459            "single node",
16460            "SINGLENODE",
16461            "SingleNode ",
16462            " SingleNode",
16463            " Sharded ",
16464            "Sharded\n",
16465            "replicated ",
16466            "sharded",
16467            "REPLICATED",
16468            "Anycast",
16469            "Global",
16470            "?",
16471        ] {
16472            assert!(
16473                PlacementStrategy::from_wire(bad).is_none(),
16474                "PlacementStrategy::from_wire({bad:?}) must return None — the \
16475                 parser's accept-set is exactly the three PlacementStrategy::as_str \
16476                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
16477                 is outside that closed set"
16478            );
16479        }
16480    }
16481
16482    #[test]
16483    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
16484        // Fail-before-pass-after pin on the third path of the four-path
16485        // convergence: `from_str` (the reverse projection) inverts the
16486        // `Serialize` derive's wire byte-string on every variant.
16487        // Together with the pre-existing three-path convergence
16488        // (`Display` + `as_str` + `Serialize` all resolve to the same
16489        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
16490        // the peer
16491        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
16492        // this closes the round-trip: the wire byte-string the
16493        // `Serialize` derive emits parses back to the same variant
16494        // through `from_str`, so any future serde-attribute or variant-
16495        // rename drift on the emit half now surfaces as a matched drift
16496        // on the parse half at caixa-core build time — the two halves
16497        // migrate as a unit through the lifted consts on any future
16498        // rename, and the round-trip cannot silently split.
16499        //
16500        // Peer of the sibling
16501        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
16502        // wire-format pin — extends the three-path convergence
16503        // (`Display` + `as_str` + `Serialize`) onto the fourth path
16504        // (`from_str`), closing the `str ↔ Self` round-trip on the
16505        // M3 `:placement :estrategia` closed-set axis.
16506        for &variant in PlacementStrategy::ALL {
16507            let wire = serde_json::to_string(&variant).unwrap();
16508            let unquoted = wire
16509                .strip_prefix('"')
16510                .and_then(|s| s.strip_suffix('"'))
16511                .expect("serialized PlacementStrategy is a JSON string");
16512            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
16513                panic!(
16514                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
16515                     Serialize derive's wire byte-string for \
16516                     PlacementStrategy::{variant:?} — the four-path convergence \
16517                     (Display + as_str + Serialize + from_str) resolves through \
16518                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
16519                )
16520            });
16521            assert_eq!(
16522                parsed, variant,
16523                "PlacementStrategy::from_wire of the Serialize derive's wire \
16524                 byte-string for PlacementStrategy::{variant:?} must round-trip \
16525                 to the same variant; got {parsed:?}"
16526            );
16527        }
16528    }
16529
16530    #[test]
16531    fn rejects_zero_policy_timeout() {
16532        let mut s = three_member_spec();
16533        s.politicas.timeout = Some(Duration::ZERO);
16534        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
16535    }
16536
16537    #[test]
16538    fn rejects_zero_policy_retries() {
16539        let mut s = three_member_spec();
16540        s.politicas.retries = Some(0);
16541        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
16542    }
16543
16544    #[test]
16545    fn rejects_policy_retries_above_cap() {
16546        // The fail-before-pass-after pin: `Some(11)` is structurally
16547        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
16548        // passed validate on every pre-gate codebase because the
16549        // typed slot's only check was the zero-floor arm. The
16550        // thundering-herd amplification vector only surfaced at the
16551        // runtime substrate (Envoy / Cilium L7 retry overlay)
16552        // far from the source caixa.lisp with no field naming the
16553        // offending policy.
16554        let mut s = three_member_spec();
16555        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
16556        assert_eq!(
16557            s.validate().unwrap_err(),
16558            AplicacaoError::PolicyRetriesExceedsCap {
16559                retries: POLICY_RETRIES_MAX + 1
16560            }
16561        );
16562    }
16563
16564    #[test]
16565    fn rejects_policy_retries_far_above_cap() {
16566        // The `u32::MAX` worst case — the four-billion-retry policy
16567        // a typo (`(:retries 4294967295)`) or struct-literal
16568        // copy-paste lands in the slot. Pin the cap arm's coverage
16569        // explicitly across the full `u32` overflow so a future
16570        // relaxation that drops the upper bound surfaces here.
16571        let mut s = three_member_spec();
16572        s.politicas.retries = Some(u32::MAX);
16573        assert_eq!(
16574            s.validate().unwrap_err(),
16575            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
16576        );
16577    }
16578
16579    #[test]
16580    fn accepts_policy_retries_at_cap() {
16581        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
16582        // must validate. The cap is inclusive on the top edge,
16583        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16584        // discipline on the sibling [`crate::LimitsSpec::memory`]
16585        // axis. Pin the boundary explicitly so a future off-by-one
16586        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
16587        // surfaces here as a test failure rather than a silent
16588        // contract narrowing.
16589        let mut s = three_member_spec();
16590        s.politicas.retries = Some(POLICY_RETRIES_MAX);
16591        s.validate()
16592            .expect("retries == POLICY_RETRIES_MAX must validate");
16593    }
16594
16595    #[test]
16596    fn accepts_policy_retries_typical_values() {
16597        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
16598        // every value in the validated set must pass. The
16599        // Envoy / Istio production-playbook recommendation band
16600        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
16601        // (`maxRetries ≤ 10`) both lie within this set.
16602        for r in 1..=POLICY_RETRIES_MAX {
16603            let mut s = three_member_spec();
16604            s.politicas.retries = Some(r);
16605            s.validate()
16606                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
16607        }
16608    }
16609
16610    #[test]
16611    fn policy_retries_zero_takes_precedence_over_cap() {
16612        // The cross-arm ordering pin: `Some(0)` is structurally
16613        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
16614        // (cap), but the zero-floor diagnostic is the more
16615        // self-locating one (it directly names the omit-axis
16616        // remediation), so the validate gate must fire on zero
16617        // first. Pin the order so a future refactor that reorders
16618        // the arms surfaces here as a test failure rather than a
16619        // silent diagnostic regression. Same shape every other
16620        // zero-then-shape ordering on this surface uses
16621        // ([`AplicacaoError::PolicyTimeoutZero`] then
16622        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
16623        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
16624        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
16625        let mut s = three_member_spec();
16626        s.politicas.retries = Some(0);
16627        assert_eq!(
16628            s.validate().unwrap_err(),
16629            AplicacaoError::PolicyRetriesZero,
16630            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
16631        );
16632    }
16633
16634    #[test]
16635    fn policy_retries_cap_diagnostic_carries_offending_value() {
16636        // The diagnostic-shape pin: the offending `u32` is carried
16637        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
16638        // variant so the surfaced error message names the value the
16639        // author wrote (`":politicas :retries (47) exceeds the
16640        // mesh-policy ceiling …"`), not just the cap. Same
16641        // self-locating diagnostic shape every other typed-cap arm
16642        // on this surface carries
16643        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16644        // offending byte count verbatim).
16645        let mut s = three_member_spec();
16646        s.politicas.retries = Some(47);
16647        let err = s.validate().unwrap_err();
16648        assert!(
16649            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
16650            "got {err:?}"
16651        );
16652        let msg = err.to_string();
16653        assert!(
16654            msg.contains("47"),
16655            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
16656        );
16657    }
16658
16659    #[test]
16660    fn policy_retries_cap_is_aws_app_mesh_aligned() {
16661        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
16662        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
16663        // schema cap — the only upstream mesh-policy schema that
16664        // documents an explicit hard cap. Pinning the literal value
16665        // here surfaces a future drift (a relaxation to 20, a
16666        // tightening to 5) as a deliberate test edit, not a silent
16667        // contract narrowing.
16668        assert_eq!(POLICY_RETRIES_MAX, 10);
16669    }
16670
16671    #[test]
16672    fn rejects_circuit_breaker_zero_max_failures() {
16673        let mut s = three_member_spec();
16674        s.politicas.circuit_breaker = Some(CircuitBreaker {
16675            max_failures: 0,
16676            window: Duration::from_secs(60),
16677        });
16678        assert_eq!(
16679            s.validate().unwrap_err(),
16680            AplicacaoError::PolicyBreakerZeroFailures
16681        );
16682    }
16683
16684    #[test]
16685    fn rejects_circuit_breaker_max_failures_above_cap() {
16686        // The fail-before-pass-after pin: `1001` is structurally one
16687        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
16688        // silently passed validate on every pre-gate codebase
16689        // because the typed slot's only check was the zero-floor
16690        // arm. The breaker-no-op vector only surfaced at the runtime
16691        // substrate (Envoy / Cilium L7 outlier-detection overlay)
16692        // far from the source caixa.lisp with no field naming the
16693        // offending policy.
16694        let mut s = three_member_spec();
16695        s.politicas.circuit_breaker = Some(CircuitBreaker {
16696            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16697            window: Duration::from_secs(60),
16698        });
16699        assert_eq!(
16700            s.validate().unwrap_err(),
16701            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16702                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16703            }
16704        );
16705    }
16706
16707    #[test]
16708    fn rejects_circuit_breaker_max_failures_far_above_cap() {
16709        // The `u32::MAX` worst case — the four-billion-failure
16710        // threshold a typo (`(:max-failures 4294967295)`) or a
16711        // struct-literal copy-paste lands in the slot. Pin the cap
16712        // arm's coverage explicitly across the full `u32` overflow
16713        // so a future relaxation that drops the upper bound surfaces
16714        // here.
16715        let mut s = three_member_spec();
16716        s.politicas.circuit_breaker = Some(CircuitBreaker {
16717            max_failures: u32::MAX,
16718            window: Duration::from_secs(60),
16719        });
16720        assert_eq!(
16721            s.validate().unwrap_err(),
16722            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16723                max_failures: u32::MAX,
16724            }
16725        );
16726    }
16727
16728    #[test]
16729    fn accepts_circuit_breaker_max_failures_at_cap() {
16730        // The boundary value — exactly
16731        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
16732        // cap is inclusive on the top edge, matching the
16733        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16734        // discipline on the sibling capped axes. Pin the boundary
16735        // explicitly so a future off-by-one tightening
16736        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
16737        // surfaces here as a test failure rather than a silent
16738        // contract narrowing.
16739        let mut s = three_member_spec();
16740        s.politicas.circuit_breaker = Some(CircuitBreaker {
16741            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
16742            window: Duration::from_secs(60),
16743        });
16744        s.validate()
16745            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
16746    }
16747
16748    #[test]
16749    fn accepts_circuit_breaker_max_failures_typical_values() {
16750        // The documented production-playbook band positive-control
16751        // sweep — every value Hystrix / Istio / Envoy / Polly /
16752        // Resilience4j recommend (5..=50) must pass, plus a sweep
16753        // through the hyperscale band (100, 500, 1000) the cap
16754        // accepts. Pin the inclusive validated set explicitly so a
16755        // future tightening of the ceiling surfaces here.
16756        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
16757            let mut s = three_member_spec();
16758            s.politicas.circuit_breaker = Some(CircuitBreaker {
16759                max_failures: n,
16760                window: Duration::from_secs(60),
16761            });
16762            s.validate()
16763                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
16764        }
16765    }
16766
16767    #[test]
16768    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
16769        // The cross-arm ordering pin: `0` is structurally outside
16770        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
16771        // (cap), but the zero-floor diagnostic is the more
16772        // self-locating one (it directly names the omit-axis
16773        // remediation), so the validate gate must fire on zero
16774        // first. Same shape every other zero-then-shape ordering on
16775        // this surface uses
16776        // ([`AplicacaoError::PolicyRetriesZero`] then
16777        // [`AplicacaoError::PolicyRetriesExceedsCap`];
16778        // [`AplicacaoError::PolicyTimeoutZero`] then
16779        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
16780        let mut s = three_member_spec();
16781        s.politicas.circuit_breaker = Some(CircuitBreaker {
16782            max_failures: 0,
16783            window: Duration::from_secs(60),
16784        });
16785        assert_eq!(
16786            s.validate().unwrap_err(),
16787            AplicacaoError::PolicyBreakerZeroFailures,
16788            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
16789        );
16790    }
16791
16792    #[test]
16793    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
16794        // The cross-arm ordering pin between the cap and the
16795        // sibling `:window` gates (zero-window, canonical-window).
16796        // A breaker carrying both an over-cap `max_failures` AND a
16797        // structurally invalid window (zero, sub-ms) must surface
16798        // the cap diagnostic first — the cap arm is wired
16799        // immediately after the zero-failure arm and strictly
16800        // before the window arms, so the offending value the
16801        // diagnostic names matches the order the author would
16802        // discover the gates by reading top-to-bottom through
16803        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
16804        // future refactor that reorders the arms surfaces here as a
16805        // test failure rather than a silent diagnostic regression.
16806        let mut s = three_member_spec();
16807        s.politicas.circuit_breaker = Some(CircuitBreaker {
16808            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16809            window: Duration::ZERO,
16810        });
16811        assert_eq!(
16812            s.validate().unwrap_err(),
16813            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16814                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
16815            },
16816            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
16817        );
16818    }
16819
16820    #[test]
16821    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
16822        // The diagnostic-shape pin: the offending `u32` is carried
16823        // verbatim into the
16824        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
16825        // variant so the surfaced error message names the value the
16826        // author wrote (`":politicas :circuit-breaker :max-failures
16827        // (50000) exceeds the mesh-policy ceiling …"`), not just
16828        // the cap. Same self-locating diagnostic shape every other
16829        // typed-cap arm on this surface carries
16830        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
16831        // offending retry count verbatim,
16832        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16833        // offending byte count verbatim).
16834        let mut s = three_member_spec();
16835        s.politicas.circuit_breaker = Some(CircuitBreaker {
16836            max_failures: 50_000,
16837            window: Duration::from_secs(60),
16838        });
16839        let err = s.validate().unwrap_err();
16840        assert!(
16841            matches!(
16842                err,
16843                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
16844                    max_failures: 50_000
16845                }
16846            ),
16847            "got {err:?}"
16848        );
16849        let msg = err.to_string();
16850        assert!(
16851            msg.contains("50000"),
16852            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
16853        );
16854    }
16855
16856    #[test]
16857    fn policy_breaker_max_failures_cap_pins_canonical_value() {
16858        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
16859        // value at 1000 — an order of magnitude above every
16860        // documented production-playbook recommendation band
16861        // (Hystrix `requestVolumeThreshold` default 20, Istio
16862        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
16863        // `outlier_detection.consecutive_5xx` default 5, Polly /
16864        // Resilience4j typical 5..=50) and below the
16865        // clearly-pathological "effectively no protection" floor
16866        // (10_000, 100_000, u32::MAX). Pinning the literal value
16867        // here surfaces a future drift (a relaxation to 10_000, a
16868        // tightening to 100) as a deliberate test edit, not a
16869        // silent contract narrowing.
16870        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
16871    }
16872
16873    #[test]
16874    fn rejects_circuit_breaker_zero_window() {
16875        let mut s = three_member_spec();
16876        s.politicas.circuit_breaker = Some(CircuitBreaker {
16877            max_failures: 5,
16878            window: Duration::ZERO,
16879        });
16880        assert_eq!(
16881            s.validate().unwrap_err(),
16882            AplicacaoError::PolicyBreakerZeroWindow
16883        );
16884    }
16885
16886    #[test]
16887    fn rejects_zero_rate_limit() {
16888        let mut s = three_member_spec();
16889        s.politicas.rate_limit = Some(RateLimit {
16890            rate: 0,
16891            window: Duration::from_secs(1),
16892        });
16893        assert_eq!(
16894            s.validate().unwrap_err(),
16895            AplicacaoError::PolicyRateLimitZero
16896        );
16897    }
16898
16899    #[test]
16900    fn rejects_rate_limit_zero_window() {
16901        // `RateLimit { rate: 100, window: Duration::ZERO }` is
16902        // constructible programmatically (the typed `Duration` field
16903        // imposes no nonzero invariant) but renders through
16904        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
16905        // codec's `parse` rejects as `unknown rate-limit window unit
16906        // "0s"`. Until this validate-time gate landed the typed slot
16907        // accepted the value silently and the round-trip break only
16908        // surfaced at deserialize time (potentially in a downstream
16909        // consumer that never re-validates). Pin the rejection at
16910        // `AplicacaoSpec::validate` so the typed slot's valid set
16911        // matches the codec's round-trippable set structurally.
16912        let mut s = three_member_spec();
16913        s.politicas.rate_limit = Some(RateLimit {
16914            rate: 100,
16915            window: Duration::ZERO,
16916        });
16917        assert_eq!(
16918            s.validate().unwrap_err(),
16919            AplicacaoError::PolicyRateLimitWindowNotCanonical {
16920                window: Duration::ZERO
16921            }
16922        );
16923    }
16924
16925    #[test]
16926    fn rejects_rate_limit_arbitrary_seconds_window() {
16927        // 45 seconds is a valid `Duration` but not one of the three
16928        // canonical rate-limit windows the codec round-trips
16929        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
16930        // refuses on round-trip — same round-trip-break shape the
16931        // zero-window arm above pins, with a non-zero magnitude to
16932        // guard against a future "reject only zero" half-measure.
16933        let mut s = three_member_spec();
16934        let window = Duration::from_secs(45);
16935        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
16936        assert_eq!(
16937            s.validate().unwrap_err(),
16938            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16939        );
16940    }
16941
16942    #[test]
16943    fn rejects_rate_limit_two_minute_window() {
16944        // 120 seconds = 2 minutes is a "looks-canonical" but
16945        // not-canonical window: it's a clean integer multiple of the
16946        // minute unit, but the codec only round-trips the
16947        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
16948        // A `Duration::from_secs(120)` window renders as `"100/120s"`
16949        // which the parser rejects. Pinning this case rules out a
16950        // future "accept any clean multiple of s/m/h" relaxation
16951        // that would silently break the codec contract.
16952        let mut s = three_member_spec();
16953        let window = Duration::from_secs(120);
16954        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
16955        assert_eq!(
16956            s.validate().unwrap_err(),
16957            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16958        );
16959    }
16960
16961    #[test]
16962    fn rejects_rate_limit_subsecond_window() {
16963        // A sub-second window (e.g. 500ms) is a valid `Duration` but
16964        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
16965        // Pin the rejection so a future relaxation can't silently
16966        // admit fractional-second windows that the codec can't
16967        // round-trip.
16968        let mut s = three_member_spec();
16969        let window = Duration::from_millis(500);
16970        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
16971        assert_eq!(
16972            s.validate().unwrap_err(),
16973            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
16974        );
16975    }
16976
16977    #[test]
16978    fn rejects_policy_rate_limit_above_cap() {
16979        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
16980        // is structurally one past the cap and silently passed
16981        // validate on every pre-gate codebase because the typed slot's
16982        // only `rate` check was the zero-floor arm. The no-op-limiter
16983        // shape only surfaced at the runtime substrate (Envoy's
16984        // `local_rate_limit.token_bucket.max_tokens`, the future
16985        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
16986        // with no field naming the offending policy.
16987        let mut s = three_member_spec();
16988        s.politicas.rate_limit = Some(RateLimit {
16989            rate: POLICY_RATE_LIMIT_MAX + 1,
16990            window: Duration::from_secs(1),
16991        });
16992        assert_eq!(
16993            s.validate().unwrap_err(),
16994            AplicacaoError::PolicyRateLimitExceedsCap {
16995                rate: POLICY_RATE_LIMIT_MAX + 1
16996            }
16997        );
16998    }
16999
17000    #[test]
17001    fn rejects_policy_rate_limit_far_above_cap() {
17002        // The `u32::MAX` worst case — the four-billion-token rate-limit
17003        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
17004        // copy-paste lands in the slot. Pin the cap arm's coverage
17005        // explicitly across the full `u32` overflow so a future
17006        // relaxation that drops the upper bound surfaces here. Peer to
17007        // `rejects_policy_retries_far_above_cap` on the sibling
17008        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
17009        // on the sibling `:max-failures` axis.
17010        let mut s = three_member_spec();
17011        s.politicas.rate_limit = Some(RateLimit {
17012            rate: u32::MAX,
17013            window: Duration::from_secs(1),
17014        });
17015        assert_eq!(
17016            s.validate().unwrap_err(),
17017            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
17018        );
17019    }
17020
17021    #[test]
17022    fn accepts_policy_rate_limit_at_cap() {
17023        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
17024        // must validate. The cap is inclusive on the top edge, matching
17025        // every other typed upper bound in this crate
17026        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
17027        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
17028        // across all three canonical windows so a future off-by-one
17029        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
17030        // window-conditional cap surfaces here as a test failure rather
17031        // than a silent contract narrowing.
17032        for secs in [1u64, 60, 3600] {
17033            let mut s = three_member_spec();
17034            s.politicas.rate_limit = Some(RateLimit {
17035                rate: POLICY_RATE_LIMIT_MAX,
17036                window: Duration::from_secs(secs),
17037            });
17038            s.validate().unwrap_or_else(|e| {
17039                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
17040            });
17041        }
17042    }
17043
17044    #[test]
17045    fn accepts_policy_rate_limit_typical_values() {
17046        // The documented production-playbook recommendation band —
17047        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
17048        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
17049        // Enterprise ~1M per-hour. Every value in the validated set
17050        // must pass; pin the band explicitly so a future tightening
17051        // surfaces here.
17052        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
17053            for secs in [1u64, 60, 3600] {
17054                let mut s = three_member_spec();
17055                s.politicas.rate_limit = Some(RateLimit {
17056                    rate,
17057                    window: Duration::from_secs(secs),
17058                });
17059                s.validate().unwrap_or_else(|e| {
17060                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
17061                });
17062            }
17063        }
17064    }
17065
17066    #[test]
17067    fn policy_rate_limit_zero_takes_precedence_over_cap() {
17068        // The cross-arm ordering pin: `rate == 0` is structurally
17069        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
17070        // (cap), but the zero-floor diagnostic is the more
17071        // self-locating one (it directly names the omit-axis
17072        // remediation). Pin the order so a future refactor that
17073        // reorders the arms surfaces here as a test failure rather
17074        // than a silent diagnostic regression. Same shape every other
17075        // zero-then-cap ordering on this surface uses
17076        // ([`AplicacaoError::PolicyRetriesZero`] then
17077        // [`AplicacaoError::PolicyRetriesExceedsCap`];
17078        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17079        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17080        let mut s = three_member_spec();
17081        s.politicas.rate_limit = Some(RateLimit {
17082            rate: 0,
17083            window: Duration::from_secs(1),
17084        });
17085        assert_eq!(
17086            s.validate().unwrap_err(),
17087            AplicacaoError::PolicyRateLimitZero,
17088            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
17089        );
17090    }
17091
17092    #[test]
17093    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
17094        // Two-axis-bad pin: rate above cap *and* window non-canonical.
17095        // The validate gate must fire on the rate cap first — the
17096        // amplification-shape (no-op limiter) diagnostic is the more
17097        // fundamental one; the window-canonical diagnostic is the
17098        // narrower codec-round-trip shape. Pin the ordering so a future
17099        // refactor that reorders the rate-then-window check arms
17100        // surfaces here as a test failure rather than a silent
17101        // diagnostic regression.
17102        let mut s = three_member_spec();
17103        s.politicas.rate_limit = Some(RateLimit {
17104            rate: POLICY_RATE_LIMIT_MAX + 1,
17105            window: Duration::from_secs(45),
17106        });
17107        assert_eq!(
17108            s.validate().unwrap_err(),
17109            AplicacaoError::PolicyRateLimitExceedsCap {
17110                rate: POLICY_RATE_LIMIT_MAX + 1
17111            },
17112            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
17113        );
17114    }
17115
17116    #[test]
17117    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
17118        // The diagnostic-shape pin: the offending `u32` is carried
17119        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
17120        // variant so the surfaced error message names the value the
17121        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
17122        // the mesh-policy ceiling …"`), not just the cap. Same
17123        // self-locating diagnostic shape every other typed-cap arm on
17124        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
17125        // carries the offending retries count verbatim,
17126        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
17127        // the offending failure count verbatim).
17128        let mut s = three_member_spec();
17129        s.politicas.rate_limit = Some(RateLimit {
17130            rate: 5_000_000,
17131            window: Duration::from_secs(1),
17132        });
17133        let err = s.validate().unwrap_err();
17134        assert!(
17135            matches!(
17136                err,
17137                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
17138            ),
17139            "got {err:?}"
17140        );
17141        let msg = err.to_string();
17142        assert!(
17143            msg.contains("5000000"),
17144            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
17145        );
17146    }
17147
17148    #[test]
17149    fn policy_rate_limit_cap_pins_canonical_value() {
17150        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
17151        // 1_000_000 — two-to-three orders of magnitude above every
17152        // documented production-playbook recommendation band (Envoy /
17153        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
17154        // Gateway 10_000..=100_000 per-minute) and below the
17155        // clearly-pathological "paste-from-binary blob" floor
17156        // (100_000_000, u32::MAX). Pinning the literal value here
17157        // surfaces a future drift (a relaxation to 10_000_000, a
17158        // tightening to 100_000) as a deliberate test edit, not a
17159        // silent contract narrowing.
17160        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
17161    }
17162
17163    #[test]
17164    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
17165        // Both axes are invalid here: rate == 0 *and* window is
17166        // non-canonical. The validate gate must fire on rate first
17167        // (matching the existing `rejects_zero_rate_limit` ordering),
17168        // so the existing diagnostic continues to lead with the
17169        // simpler "zero rate" framing. Pinning the order of checks
17170        // so a future refactor that reorders the arms surfaces here
17171        // as a test failure rather than a silent diagnostic
17172        // regression.
17173        let mut s = three_member_spec();
17174        s.politicas.rate_limit = Some(RateLimit {
17175            rate: 0,
17176            window: Duration::from_secs(45),
17177        });
17178        assert_eq!(
17179            s.validate().unwrap_err(),
17180            AplicacaoError::PolicyRateLimitZero
17181        );
17182    }
17183
17184    #[test]
17185    fn rate_limit_canonical_windows_validate() {
17186        // The three canonical windows the codec round-trips
17187        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
17188        // unchanged. Pin the full canonical set as a positive case
17189        // (the existing `rate_limit_round_trip_seconds` /
17190        // `rate_limit_round_trip_minutes` tests pin the
17191        // serialize-then-deserialize property at the codec layer; this
17192        // test pins the validate-side complement so a future tightening
17193        // of the canonical set — e.g. dropping `:hour` — surfaces here
17194        // as a test failure rather than a silent contract narrowing).
17195        for secs in [1u64, 60, 3600] {
17196            let mut s = three_member_spec();
17197            s.politicas.rate_limit = Some(RateLimit {
17198                rate: 100,
17199                window: Duration::from_secs(secs),
17200            });
17201            s.validate().expect("canonical window must validate");
17202        }
17203    }
17204
17205    #[test]
17206    fn rate_limit_validated_value_round_trips_through_codec() {
17207        // The structural property the validate gate enforces:
17208        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
17209        // losslessly through the `rate_limit_codec` (serialize → string
17210        // → deserialize → equal value). Pin this end-to-end so a future
17211        // change to either side (the validate gate's accepted window
17212        // set, the codec's parse/render unit set) that breaks the
17213        // alignment surfaces here. The previous-state shape (typed
17214        // slot accepts arbitrary `Duration`, codec only round-trips
17215        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
17216        // window — the validate gate now forecloses that.
17217        for secs in [1u64, 60, 3600] {
17218            let mut s = three_member_spec();
17219            s.politicas.rate_limit = Some(RateLimit {
17220                rate: 250,
17221                window: Duration::from_secs(secs),
17222            });
17223            s.validate().unwrap();
17224            let json = serde_json::to_string(&s.politicas).unwrap();
17225            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17226            assert_eq!(
17227                back.rate_limit, s.politicas.rate_limit,
17228                "every validated :rate-limit must round-trip losslessly through the codec"
17229            );
17230        }
17231    }
17232
17233    #[test]
17234    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
17235        // The hour-window canonical form (`"<n>/h"`) was missing from
17236        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
17237        // pair. Now that the validate gate pins 3600s as part of the
17238        // canonical set, pin its serialize-side render shape too so
17239        // the third leg of the s/m/h tripod is explicitly tested.
17240        let policy = MeshPolicy {
17241            rate_limit: Some(RateLimit {
17242                rate: 10000,
17243                window: Duration::from_secs(3600),
17244            }),
17245            ..Default::default()
17246        };
17247        let json = serde_json::to_string(&policy).unwrap();
17248        assert!(
17249            json.contains("\"10000/h\""),
17250            "hour-window canonical form must render with `h` suffix (got: {json})"
17251        );
17252        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17253        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
17254    }
17255
17256    #[test]
17257    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
17258        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
17259        // typed accessor's accepted-window set against the codec's
17260        // accepted set explicitly. A future addition to the codec
17261        // (e.g. accepting `:day`/`:week` as authoring units) must be
17262        // accompanied by a parallel addition here, and a regression
17263        // that drops one of the three canonical units from either
17264        // side surfaces as a test failure. The accessor is the
17265        // single source of truth for the canonical-window set —
17266        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
17267        // gate and [`rate_limit_codec::render`]'s canonical arm both
17268        // read through it — this test enshrines that its
17269        // `Duration → Option<RateLimitUnit>` projection matches the
17270        // codec's parse / render arms' accepted-window set exactly.
17271        //
17272        // Predecessor: this pin previously read the module-private
17273        // free helper `is_canonical_rate_limit_window` — a delegate
17274        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
17275        // — but the helper had no production consumers left after the
17276        // validate-gate migration onto [`RateLimit::canonical_unit`]
17277        // and was deleted; the closed-set arm-window bijection now
17278        // lives on exactly one typed dispatch on the substrate
17279        // primitive.
17280        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
17281            RateLimit { rate: 1, window }.canonical_unit()
17282        };
17283        assert!(canonical_unit(Duration::from_secs(1)).is_some());
17284        assert!(canonical_unit(Duration::from_secs(60)).is_some());
17285        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
17286        // Non-canonical windows the accessor rejects.
17287        assert!(canonical_unit(Duration::ZERO).is_none());
17288        assert!(canonical_unit(Duration::from_secs(2)).is_none());
17289        assert!(canonical_unit(Duration::from_secs(30)).is_none());
17290        assert!(canonical_unit(Duration::from_secs(120)).is_none());
17291        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
17292        // Sub-second windows: even `Duration::from_millis(1000)` is
17293        // exactly 1s and accepted; `Duration::from_millis(500)` is
17294        // sub-second and rejected.
17295        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
17296        assert!(canonical_unit(Duration::from_millis(500)).is_none());
17297        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
17298    }
17299
17300    #[test]
17301    fn rate_limit_unit_table_projections_are_mutual_inverses() {
17302        // Bidirection pin against the closed-set typed enum
17303        // [`RateLimitUnit`] arm-table (the canonical
17304        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
17305        // of the rate-limit unit surface reads from). The two
17306        // projection directions [`RateLimitUnit::from_suffix`] /
17307        // [`RateLimitUnit::window`] (str → Duration, exposed as one
17308        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
17309        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
17310        // (Duration → str, exposed as one typed dispatch through
17311        // [`RateLimit::canonical_unit`] composed with
17312        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
17313        // codec's parse arm ([`rate_limit_codec::parse`] via
17314        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
17315        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
17316        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
17317        // via [`RateLimit::canonical_unit`]) all key off. A future
17318        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
17319        // sub-second window) is one variant + one arm per method on the
17320        // closed-set enum; the compiler-enforced exhaustiveness on
17321        // every consumer's `match self` arms picks it up by
17322        // construction. This pin enshrines that both projection
17323        // directions agree on every canonical arm row and neither
17324        // leaks a spurious entry the other doesn't recognize.
17325        //
17326        // Predecessor: this test previously read the two vestigial
17327        // module-private free helpers `rate_limit_window_unit` and
17328        // `rate_limit_window_from_unit` on the `Duration → &str` and
17329        // `&str → Duration` axes; the former was deleted after its
17330        // sole production consumer ([`rate_limit_codec::render`])
17331        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
17332        // the latter is folded here into the substrate primitive
17333        // [`RateLimitUnit::window_from_suffix`] so both projection
17334        // directions live on the closed-set enum's arm-table.
17335        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
17336            let window = super::RateLimitUnit::window_from_suffix(unit)
17337                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
17338            assert_eq!(
17339                window,
17340                Duration::from_secs(secs),
17341                "unit {unit:?} must resolve to {secs}s"
17342            );
17343            let projected_suffix = RateLimit { rate: 1, window }
17344                .canonical_unit()
17345                .map(super::RateLimitUnit::as_suffix);
17346            assert_eq!(
17347                projected_suffix,
17348                Some(unit),
17349                "Duration({secs}s) must render as {unit:?} \
17350                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
17351            );
17352        }
17353        // Non-table units yield None on the `unit → Duration`
17354        // projection — a future `"d"` addition to the table would
17355        // flip this arm; today it pins the current three-row table's
17356        // rejection semantics.
17357        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
17358        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
17359        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
17360        // Non-table Durations yield None on the `Duration → unit`
17361        // projection — pins that the two projections agree on the
17362        // "not in the table" semantic too, so a drift where the
17363        // parse-side accepts a value the render-side can't emit is
17364        // a build error at the two-arm pair, not a silent codec
17365        // round-trip break.
17366        let projected_suffix = |window: Duration| -> Option<&'static str> {
17367            RateLimit { rate: 1, window }
17368                .canonical_unit()
17369                .map(super::RateLimitUnit::as_suffix)
17370        };
17371        assert!(projected_suffix(Duration::from_secs(2)).is_none());
17372        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
17373        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
17374    }
17375
17376    #[test]
17377    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
17378        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
17379        // substrate-primitive `&str → Duration` associated method the
17380        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
17381        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
17382        // to the same [`Duration`] the two-step composition
17383        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
17384        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
17385        // `"MIN"`) must project to [`None`] on both paths. A future
17386        // implementation of `window_from_suffix` that took a shortcut
17387        // through a per-suffix `match` table (bypassing the arm-table's
17388        // `Self::from_suffix` scan and the arm-table's `Self::window`
17389        // dispatch) would silently split the accept-set — the parse
17390        // arm would accept a suffix the enum's arm-table doesn't know,
17391        // or reject a suffix the enum's arm-table does; this pin
17392        // surfaces that drift at caixa-core build time rather than at a
17393        // downstream serde round-trip audit on a live `MeshPolicy`.
17394        //
17395        // Same byte-parity discipline the sibling
17396        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
17397        // pin carries on the peer `Duration → RateLimitUnit` axis via
17398        // [`RateLimit::canonical_unit`], and the peer
17399        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17400        // carries on the bidirectional arm-table axis — extended here
17401        // onto the fifth (and last unlifted) projection axis on the
17402        // closed-set enum's arm-table.
17403        let composition = |suffix: &str| -> Option<Duration> {
17404            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
17405        };
17406        for suffix in ["s", "m", "h"] {
17407            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17408            let via_composition = composition(suffix);
17409            assert_eq!(
17410                via_method, via_composition,
17411                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17412                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
17413                 method must delegate to the arm-table's two typed dispatches, \
17414                 not shortcut through a per-suffix match table"
17415            );
17416            assert!(
17417                via_method.is_some(),
17418                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
17419                 RateLimitUnit::window_from_suffix"
17420            );
17421        }
17422        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
17423            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17424            let via_composition = composition(suffix);
17425            assert_eq!(
17426                via_method, via_composition,
17427                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17428                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
17429                 axis too"
17430            );
17431            assert!(
17432                via_method.is_none(),
17433                "non-arm suffix {suffix:?} must project to None via \
17434                 RateLimitUnit::window_from_suffix — a future extension that \
17435                 accepted this suffix without a corresponding arm on the enum \
17436                 would split the codec's parse-accepted set from the enum's \
17437                 arm-table"
17438            );
17439        }
17440        // And the codec's parse arm now reads through this method: a
17441        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
17442        // the same `Duration` the method returns for its unit, closing
17443        // the two-consumer drift surface (the codec's parse arm and the
17444        // enum's arm-table) with one typed dispatch on the substrate
17445        // primitive.
17446        for suffix in ["s", "m", "h"] {
17447            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
17448            let mp: MeshPolicy = serde_json::from_str(&wire)
17449                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
17450            let parsed = mp.rate_limit().expect("rate_limit payload present");
17451            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
17452                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
17453            assert_eq!(
17454                parsed.window(),
17455                via_method,
17456                "codec parse arm on {wire:?} must resolve the window through \
17457                 RateLimitUnit::window_from_suffix, not a divergent path"
17458            );
17459        }
17460    }
17461
17462    #[test]
17463    fn rate_limit_unit_all_enumerates_every_arm_once() {
17464        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
17465        // enumerate every arm of the closed-set enum exactly once, in
17466        // the canonical shortest-to-longest window order (Second before
17467        // Minute before Hour) — the same order the sibling
17468        // [`crate::supervisor::RestartStrategy`] /
17469        // [`crate::supervisor::RestartPolicy`] /
17470        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
17471        // typed enums carry (the arm declared first is the arm listed
17472        // first). A future variant addition that extends the enum
17473        // without appending to [`RateLimitUnit::ALL`] leaves the
17474        // exhaustive iteration surface silently short one arm — the
17475        // codec's parse arm would then reject the new suffix even
17476        // though the enum knows it. This pin closes the drift.
17477        assert_eq!(
17478            super::RateLimitUnit::ALL,
17479            &[
17480                super::RateLimitUnit::Second,
17481                super::RateLimitUnit::Minute,
17482                super::RateLimitUnit::Hour,
17483            ],
17484            "RateLimitUnit::ALL must enumerate every arm exactly once, \
17485             in canonical shortest-to-longest window order"
17486        );
17487    }
17488
17489    #[test]
17490    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
17491        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
17492        // every arm's [`RateLimitUnit::as_suffix`] output must parse
17493        // back through [`RateLimitUnit::from_suffix`] to the same
17494        // variant. A future arm addition that lands `as_suffix` but
17495        // forgets `from_suffix` (`from_suffix` iterates
17496        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
17497        // is the load-bearing carrier of the round-trip; the sibling
17498        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
17499        // the `ALL` half) trips here at caixa-core build time rather
17500        // than surfacing as a codec round-trip miss (a `render` emit
17501        // that lands a suffix the paired `parse` cannot decode).
17502        for unit in super::RateLimitUnit::ALL {
17503            let suffix = unit.as_suffix();
17504            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
17505                panic!(
17506                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
17507                     RateLimitUnit::as_suffix output — got None for {unit:?}"
17508                )
17509            });
17510            assert_eq!(
17511                parsed, *unit,
17512                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
17513                 must return RateLimitUnit::{unit:?}"
17514            );
17515        }
17516    }
17517
17518    #[test]
17519    fn rate_limit_unit_from_window_and_window_round_trip() {
17520        // Total round-trip pin on the `(from_window, window)` pair:
17521        // every arm's [`RateLimitUnit::window`] output must parse back
17522        // through [`RateLimitUnit::from_window`] to the same variant.
17523        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
17524        // on the peer `Duration` axis — the two round-trip pins
17525        // together enshrine that both projections of the typed
17526        // canonical-unit bijection are total on the arm-set.
17527        for unit in super::RateLimitUnit::ALL {
17528            let window = unit.window();
17529            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
17530                panic!(
17531                    "RateLimitUnit::from_window({window:?}) must accept every \
17532                     RateLimitUnit::window output — got None for {unit:?}"
17533                )
17534            });
17535            assert_eq!(
17536                parsed, *unit,
17537                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17538                 must return RateLimitUnit::{unit:?}"
17539            );
17540        }
17541    }
17542
17543    #[test]
17544    fn rate_limit_unit_from_window_accessor_is_const_fn() {
17545        // Fail-before-pass-after pin: witnesses the
17546        // [`RateLimitUnit::from_window`] `const`-eval posture via a
17547        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
17548        // -> Option<RateLimitUnit>` whose body calls
17549        // `RateLimitUnit::from_window(window)`, well-formed only when
17550        // the callee is itself `const fn` (any future downgrade to
17551        // non-`const` fails at caixa-core build time with E0015 `cannot
17552        // call non-const function`, strictly stronger than a runtime
17553        // `assert!`, side-stepping the destructor-in-const restriction
17554        // that blocks direct `const _: Option<RateLimitUnit> =
17555        // RateLimitUnit::from_window(...)` items on `Duration`'s
17556        // carrier). The runtime body sweeps every closed-set
17557        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
17558        // rejection sample (`Duration::from_millis(500)` sub-second
17559        // residue) and asserts the wrapped and direct dispatches agree
17560        // — a violation means the wrapper stopped compiling under a
17561        // future `const`-posture downgrade, or the reverse resolver's
17562        // arm-set silently split from the peer `Self::window` emitter's
17563        // arm-set. Peer of the sibling
17564        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
17565        // (152c868) /
17566        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
17567        // (152c868) /
17568        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
17569        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
17570        // `const`-eval-surface pins on the peer M2 / M3 substrate-
17571        // primitive `Copy`-return accessor axes, extended onto the
17572        // reverse `Duration → RateLimitUnit` projection axis on the
17573        // M3 mesh-slot rate-limit closed-set typed enum.
17574        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
17575            super::RateLimitUnit::from_window(window)
17576        }
17577        for unit in super::RateLimitUnit::ALL {
17578            let window = unit.window();
17579            let via_wrapper = from_window_via_const_fn(window);
17580            let direct = super::RateLimitUnit::from_window(window);
17581            assert_eq!(
17582                via_wrapper, direct,
17583                "RateLimitUnit::from_window({window:?}) via const fn \
17584                 wrapper must agree with direct dispatch for {unit:?}"
17585            );
17586            assert_eq!(
17587                via_wrapper,
17588                Some(*unit),
17589                "RateLimitUnit::from_window({window:?}) via const fn \
17590                 wrapper must return Some({unit:?}) for the peer \
17591                 window() output"
17592            );
17593        }
17594        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
17595        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
17596    }
17597
17598    #[test]
17599    fn rate_limit_unit_from_window_composes_through_window_accessor() {
17600        // Composition-witness pin on the routing-through-peer discipline:
17601        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
17602        // through the peer `pub const fn` [`RateLimitUnit::window`]
17603        // canonical-`Duration` projection rather than a hand-authored
17604        // per-arm second-magnitude literal — a future arm-magnitude edit
17605        // on the sibling `window()` accessor (a `Second → 2s` typo, a
17606        // `Hour → 3599s` off-by-one) must therefore reach this reverse
17607        // resolver by construction. A pin that hard-coded the three
17608        // second-magnitudes here would silently split from the peer
17609        // emitter on any such edit; instead, this pin asserts the
17610        // composition invariant `from_window(u.window()) == Some(u)`
17611        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
17612        // arm — a violation means either the peer `Self::window`
17613        // accessor drifted (breaking every downstream consumer that
17614        // reads through it), or the reverse resolver stopped routing
17615        // through the peer (introducing a hand-authored literal that
17616        // silently disagrees with the emitter). Either failure is a
17617        // caixa-core-build-time surface, not a downstream renderer
17618        // round-trip regression.
17619        //
17620        // Peer of the sibling
17621        // [`crate::render::assert_str_reexport_identity`] discipline on
17622        // the substrate-primitive `&'static str` re-export axis and the
17623        // [`rate_limit_unit_from_window_and_window_round_trip`]
17624        // round-trip pin on the peer projection direction; extends the
17625        // one-canonical-dispatch-per-projection discipline onto the
17626        // reverse-resolver's per-arm probe axis.
17627        for unit in super::RateLimitUnit::ALL {
17628            let window_via_peer = unit.window();
17629            let resolved = super::RateLimitUnit::from_window(window_via_peer);
17630            assert_eq!(
17631                resolved,
17632                Some(*unit),
17633                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17634                 must return Some({unit:?}) — the reverse resolver's per-arm \
17635                 probes must route through the peer `Self::window` accessor \
17636                 so any future arm-magnitude edit reaches both projection \
17637                 directions by construction"
17638            );
17639        }
17640    }
17641
17642    #[test]
17643    fn rate_limit_canonical_unit_accessor_is_const_fn() {
17644        // Fail-before-pass-after pin: witnesses the
17645        // [`RateLimit::canonical_unit`] `const`-eval posture via a
17646        // `const fn` wrapper
17647        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
17648        // whose body calls `rl.canonical_unit()`, well-formed only when
17649        // the callee is itself `const fn` (any future downgrade to
17650        // non-`const` fails at caixa-core build time with E0015 `cannot
17651        // call non-const method`). The runtime body sweeps every
17652        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
17653        // constructs a typed [`RateLimit`] with the peer `Self::window`
17654        // canonical `Duration`, then asserts both the wrapper and the
17655        // direct dispatch agree and both return `Some(unit)`. Composes
17656        // with the sibling
17657        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
17658        // typed [`RateLimit`] projection layer's `const`-posture is
17659        // load-bearing on the reverse resolver's `const`-posture, and
17660        // both must migrate together (a downgrade of either surface
17661        // splits the paired `const`-eval-surface pass on the M3
17662        // mesh-slot rate-limit `Duration ↔ Self` bijection).
17663        const fn canonical_unit_via_const_fn(
17664            rl: &super::RateLimit,
17665        ) -> Option<super::RateLimitUnit> {
17666            rl.canonical_unit()
17667        }
17668        for unit in super::RateLimitUnit::ALL {
17669            let rl = super::RateLimit {
17670                rate: 1,
17671                window: unit.window(),
17672            };
17673            let via_wrapper = canonical_unit_via_const_fn(&rl);
17674            let direct = rl.canonical_unit();
17675            assert_eq!(
17676                via_wrapper, direct,
17677                "RateLimit::canonical_unit() via const fn wrapper must \
17678                 agree with direct dispatch for {unit:?}"
17679            );
17680            assert_eq!(
17681                via_wrapper,
17682                Some(*unit),
17683                "RateLimit::canonical_unit() via const fn wrapper must \
17684                 return Some({unit:?}) for a RateLimit whose window is \
17685                 the peer RateLimitUnit::{unit:?}.window() output"
17686            );
17687        }
17688    }
17689
17690    #[test]
17691    fn rate_limit_unit_projections_are_pairwise_distinct() {
17692        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
17693        // [`RateLimitUnit::window`] outputs must be pairwise distinct
17694        // across every arm — an accidental copy-paste flip that
17695        // reroutes one arm's suffix or window to also match another
17696        // silently collapses two arms onto one, so
17697        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
17698        // (both using `find` on `Self::ALL`) would return whichever
17699        // arm the linear scan lands on first — a match-arm-ordering-
17700        // dependent outcome the closed-set typed-enum shape is meant
17701        // to rule out structurally. Peer of the sibling
17702        // `caixa_kind_wire_consts_are_pairwise_distinct` /
17703        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
17704        // other closed-set typed-enum discriminator axes.
17705        let all = super::RateLimitUnit::ALL;
17706        for (i, a) in all.iter().enumerate() {
17707            for (j, b) in all.iter().enumerate() {
17708                if i != j {
17709                    assert_ne!(
17710                        a.as_suffix(),
17711                        b.as_suffix(),
17712                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
17713                         must be distinct — a collision silently collapses two \
17714                         arms onto one under from_suffix's linear scan"
17715                    );
17716                    assert_ne!(
17717                        a.window(),
17718                        b.window(),
17719                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
17720                         must be distinct — a collision silently collapses two \
17721                         arms onto one under from_window's linear scan"
17722                    );
17723                }
17724            }
17725        }
17726    }
17727
17728    #[test]
17729    fn rate_limit_unit_display_routes_through_as_suffix() {
17730        // Route pin: [`std::fmt::Display`] must byte-equal
17731        // [`RateLimitUnit::as_suffix`] on every arm — the single
17732        // source of truth for the canonical suffix. A future
17733        // reimplementation that hand-rolls the arms instead of
17734        // delegating to [`RateLimitUnit::as_suffix`] would silently
17735        // desynchronize `format!("{u}")` from the codec's parse arm
17736        // (which uses `as_suffix` to compare suffixes). Peer of the
17737        // sibling `caixa_kind_display_routes_through_as_str_helper` /
17738        // `placement_strategy_display_routes_through_as_str_helper`
17739        // pins on the peer closed-set typed-enum Display axes.
17740        for unit in super::RateLimitUnit::ALL {
17741            assert_eq!(
17742                unit.to_string(),
17743                unit.as_suffix(),
17744                "RateLimitUnit::{unit:?} Display must route through \
17745                 as_suffix (single source of truth: the canonical suffix \
17746                 the codec parses and renders)"
17747            );
17748        }
17749    }
17750
17751    #[test]
17752    fn rate_limit_unit_from_window_rejects_non_canonical() {
17753        // Rejection pin on the parser's accept-set: any Duration
17754        // outside the three-arm [`RateLimitUnit::window`] output set
17755        // (sub-second residue, or a second-magnitude outside `{1, 60,
17756        // 3600}`) must return `None`. A future accidental widening of
17757        // the accept-set (rounding down sub-second residue to the
17758        // nearest arm, admitting `Duration::from_secs(30)` as a
17759        // half-minute unit) would silently drift the parser's accept-
17760        // set from the emitter's — a validated slot with a
17761        // non-canonical window would then round-trip through the
17762        // codec to a canonical form the author never wrote.
17763        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
17764        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
17765        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
17766        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
17767        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
17768        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
17769        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
17770    }
17771
17772    #[test]
17773    fn rate_limit_unit_from_suffix_rejects_unknown() {
17774        // Rejection pin on the suffix parser's accept-set: any string
17775        // outside the three-arm [`RateLimitUnit::as_suffix`] output
17776        // set must return `None`. Peer of the sibling
17777        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
17778        // the [`crate::CaixaKind`] `from_wire` accept-set.
17779        for bad in [
17780            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
17781            " s",
17782        ] {
17783            assert!(
17784                super::RateLimitUnit::from_suffix(bad).is_none(),
17785                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
17786                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
17787                 outputs"
17788            );
17789        }
17790    }
17791
17792    #[test]
17793    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
17794        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
17795        // every canonical `:window` magnitude the validate gate
17796        // accepts must map to the paired [`RateLimitUnit`] arm through
17797        // this accessor. A future validate-gate rebrand that widened
17798        // the accepted-window set without extending [`RateLimitUnit`]
17799        // would silently split the accessor's `Some`-return set from
17800        // the validate gate's accept-set — a slot that satisfies
17801        // validate would land at the accessor with `None`, so a
17802        // consumer past validate that pattern-matches on the returned
17803        // `Some` would silently miss the newly-accepted magnitude.
17804        for (window_secs, expected) in [
17805            (1u64, super::RateLimitUnit::Second),
17806            (60, super::RateLimitUnit::Minute),
17807            (3600, super::RateLimitUnit::Hour),
17808        ] {
17809            let rl = RateLimit {
17810                rate: 100,
17811                window: Duration::from_secs(window_secs),
17812            };
17813            assert_eq!(
17814                rl.canonical_unit(),
17815                Some(expected),
17816                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
17817                 must return Some({expected:?})"
17818            );
17819        }
17820        // Non-canonical windows the validate gate rejects also return
17821        // None here — the accessor is the typed-enum projection of
17822        // the sibling `is_canonical_rate_limit_window` predicate.
17823        let bad = RateLimit {
17824            rate: 100,
17825            window: Duration::from_secs(30),
17826        };
17827        assert!(
17828            bad.canonical_unit().is_none(),
17829            "RateLimit with a non-canonical window must return None from \
17830             canonical_unit — the validate gate rejects the same set"
17831        );
17832    }
17833
17834    #[test]
17835    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
17836        // Fail-before-pass-after byte-parity pin: for every canonical
17837        // window the [`rate_limit_codec::render`] arm's emitted string
17838        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
17839        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
17840        // the vestigial free helper [`rate_limit_window_unit`] (a
17841        // `find_map`-walked `Duration → &'static str` delegate) onto the
17842        // substrate primitive [`RateLimit::canonical_unit`] typed method
17843        // (a closed-set `match self.window` arm on
17844        // [`RateLimitUnit::from_window`], projected through
17845        // [`RateLimitUnit::as_suffix`] via the enum's
17846        // [`std::fmt::Display`] impl). A future re-routing of the render
17847        // arm through a differently-computed unit projection would break
17848        // this pin at build time rather than as a silent per-consumer
17849        // codec round-trip drift far from the substrate primitive edit.
17850        //
17851        // Sibling to the peer
17852        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17853        // on the free-helper axis: that pin locks the two projections
17854        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
17855        // on the closed-set arm table; this pin locks the codec's render
17856        // arm reads through the typed accessor rather than the free
17857        // helper. Two production consumers of the canonical-unit axis
17858        // now key off one typed dispatch on the substrate primitive.
17859        for (window_secs, unit) in [
17860            (1u64, super::RateLimitUnit::Second),
17861            (60, super::RateLimitUnit::Minute),
17862            (3600, super::RateLimitUnit::Hour),
17863        ] {
17864            let rl = RateLimit {
17865                rate: 42,
17866                window: Duration::from_secs(window_secs),
17867            };
17868            let policy = MeshPolicy {
17869                rate_limit: Some(rl),
17870                ..Default::default()
17871            };
17872            let json = serde_json::to_string(&policy).unwrap();
17873            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
17874            assert!(
17875                json.contains(&expected),
17876                "rate_limit_codec::render must emit {expected} (via \
17877                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
17878                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
17879            );
17880            // And the accessor route resolves to the same typed unit
17881            // the render arm's Display formatting is asked to produce —
17882            // so a future edit that split the two paths (one through
17883            // the accessor, one through a re-introduced free helper)
17884            // trips this pin.
17885            assert_eq!(
17886                rl.canonical_unit(),
17887                Some(unit),
17888                "RateLimit::canonical_unit must return Some({unit:?}) for a \
17889                 {window_secs}s window; the codec render arm reads the same \
17890                 typed unit through this accessor"
17891            );
17892        }
17893    }
17894
17895    #[test]
17896    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
17897        // Fail-before-pass-after byte-parity pin on the validate gate's
17898        // canonical-window shape probe: every non-canonical `:window`
17899        // the free-helper predicate [`is_canonical_rate_limit_window`]
17900        // rejects is also rejected by the substrate primitive
17901        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
17902        // gate now reads through, and vice versa on the accepted set
17903        // (the three canonical windows). Locks the migration from the
17904        // free helper onto the substrate primitive: a future re-routing
17905        // of one of the two paths through a differently-computed unit
17906        // projection would silently split the codec's accepted set from
17907        // the validate gate's accepted set — a two-consumer drift the
17908        // codec-round-trip pin
17909        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
17910        // above closes on the render arm and this pin closes on the
17911        // validate arm.
17912        for canonical_window_secs in [1u64, 60, 3600] {
17913            let mut s = three_member_spec();
17914            let rl = RateLimit {
17915                rate: 100,
17916                window: Duration::from_secs(canonical_window_secs),
17917            };
17918            s.politicas.rate_limit = Some(rl);
17919            assert!(
17920                s.validate().is_ok(),
17921                "canonical {canonical_window_secs}s window must pass \
17922                 validate_politicas — the validate gate now reads \
17923                 RateLimit::canonical_unit().is_none() and the accessor \
17924                 returns Some on every canonical arm"
17925            );
17926            assert!(
17927                rl.canonical_unit().is_some(),
17928                "canonical {canonical_window_secs}s window must resolve to \
17929                 Some on RateLimit::canonical_unit — the validate gate reads \
17930                 this accessor directly"
17931            );
17932        }
17933        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
17934            let mut s = three_member_spec();
17935            let rl = RateLimit {
17936                rate: 100,
17937                window: Duration::from_secs(non_canonical_window_secs),
17938            };
17939            s.politicas.rate_limit = Some(rl);
17940            assert_eq!(
17941                s.validate().unwrap_err(),
17942                AplicacaoError::PolicyRateLimitWindowNotCanonical {
17943                    window: rl.window(),
17944                },
17945                "non-canonical {non_canonical_window_secs}s window must be \
17946                 rejected by validate_politicas — the validate gate now \
17947                 keys off RateLimit::canonical_unit().is_none()"
17948            );
17949            assert!(
17950                rl.canonical_unit().is_none(),
17951                "non-canonical {non_canonical_window_secs}s window must \
17952                 resolve to None on RateLimit::canonical_unit — the two \
17953                 paths (the free helper the validate gate previously read \
17954                 and the substrate primitive the validate gate now reads) \
17955                 must agree on the same rejected set"
17956            );
17957        }
17958        // And the substrate-primitive [`RateLimit::canonical_unit`]
17959        // accessor's accepted-window set matches the codec's parse arm's
17960        // accepted-suffix set on every canonical / non-canonical shape,
17961        // so a future silent drift between the codec's accepted set and
17962        // the validate gate's accepted set is a build error at test time
17963        // (both consumers key off the same closed-set enum's `match self`
17964        // arms). The predecessor free helper `is_canonical_rate_limit_window`
17965        // — a delegate that composed [`RateLimitUnit::from_window`] with
17966        // `.is_some()` — was deleted after this migration; the
17967        // canonical-window set now lives on exactly one typed dispatch
17968        // on the substrate primitive.
17969        for (secs, expected) in [
17970            (1u64, true),
17971            (60, true),
17972            (3600, true),
17973            (2, false),
17974            (30, false),
17975            (86_400, false),
17976        ] {
17977            let window = Duration::from_secs(secs);
17978            let rl = RateLimit { rate: 1, window };
17979            assert_eq!(
17980                rl.canonical_unit().is_some(),
17981                expected,
17982                "RateLimit::canonical_unit().is_some() must agree with the \
17983                 codec-accepted canonical-window set on {secs}s"
17984            );
17985            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
17986                1 => "s",
17987                60 => "m",
17988                3600 => "h",
17989                _ => return,
17990            })
17991            .is_some_and(|d| d == window);
17992            if expected {
17993                assert!(
17994                    suffix_from_axis,
17995                    "the codec's `&str → Duration` axis \
17996                     ({secs}s) must round-trip to the same Duration the \
17997                     substrate primitive's accessor returns Some on"
17998                );
17999            }
18000        }
18001    }
18002
18003    #[test]
18004    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
18005        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
18006        // derive: for each of the three variants, exactly one of the
18007        // generated `is_second` / `is_minute` / `is_hour` predicates
18008        // returns `true` and the other two return `false`. Peer of
18009        // the sibling
18010        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
18011        // sibling `IsVariant`-derived closed-set typed-enum pins.
18012        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
18013            (super::RateLimitUnit::Second, [true, false, false]),
18014            (super::RateLimitUnit::Minute, [false, true, false]),
18015            (super::RateLimitUnit::Hour, [false, false, true]),
18016        ];
18017        for (variant, expected) in rows {
18018            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
18019            assert_eq!(
18020                observed, expected,
18021                "RateLimitUnit::{variant:?} is_* predicates must partition \
18022                 the arm set (second, minute, hour); got {observed:?}"
18023            );
18024        }
18025    }
18026
18027    #[test]
18028    fn rejects_policy_timeout_sub_millisecond() {
18029        // A purely sub-millisecond `Duration` (`from_micros(500)` =
18030        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
18031        // arm passes — but `as_millis() == 0`, so the shared codec's
18032        // `render` arm returns the literal `"0s"`, which the
18033        // codec's `parse` arm then deserializes as `Duration::ZERO`
18034        // and the `PolicyTimeoutZero` zero-floor gate would reject
18035        // on re-validate. Pin the rejection at the typed slot's
18036        // canonical-floor gate so the round-trip break surfaces at
18037        // validate time, naming the offending `Duration`, rather
18038        // than at the next serialize → deserialize round-trip far
18039        // from the source `caixa.lisp`.
18040        let mut s = three_member_spec();
18041        let timeout = Duration::from_micros(500);
18042        s.politicas.timeout = Some(timeout);
18043        assert_eq!(
18044            s.validate().unwrap_err(),
18045            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
18046        );
18047    }
18048
18049    #[test]
18050    fn rejects_policy_timeout_non_integer_millisecond() {
18051        // A `Duration` with non-integer-millisecond residue
18052        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
18053        // through the shared codec's `render` arm as `"1ms"` (the
18054        // `as_millis()` floor truncates), which the codec's `parse`
18055        // arm then deserializes as `Duration::from_millis(1)` =
18056        // 1_000_000 ns — silently *different* from the original.
18057        // Pin the rejection so this round-trip break surfaces at
18058        // validate time, where the offending `Duration` is named,
18059        // rather than as a silent value-laundered round-trip on the
18060        // next codec round-trip.
18061        let mut s = three_member_spec();
18062        let timeout = Duration::from_micros(1500);
18063        s.politicas.timeout = Some(timeout);
18064        assert_eq!(
18065            s.validate().unwrap_err(),
18066            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
18067        );
18068    }
18069
18070    #[test]
18071    fn accepts_policy_timeout_integer_millisecond_forms() {
18072        // The codec's accepted set — integer multiples of 1ms — is
18073        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
18074        // `1h` all pass the canonical gate. Pin the canonical-forms
18075        // sweep so a future tightening of the codec's grammar (e.g.
18076        // dropping `:ms`) surfaces here as a test failure rather
18077        // than a silent contract narrowing on the typed slot.
18078        for timeout in [
18079            Duration::from_millis(1),
18080            Duration::from_millis(500),
18081            Duration::from_millis(1500),
18082            Duration::from_secs(30),
18083            Duration::from_secs(120),
18084            Duration::from_secs(3600),
18085        ] {
18086            let mut s = three_member_spec();
18087            s.politicas.timeout = Some(timeout);
18088            s.validate()
18089                .expect("integer-millisecond :timeout must validate");
18090        }
18091    }
18092
18093    #[test]
18094    fn policy_timeout_zero_takes_precedence_over_canonical() {
18095        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
18096        // pass the canonical-millisecond gate; the more self-locating
18097        // `PolicyTimeoutZero` arm (which names the omit-axis
18098        // remediation directly) must fire first. Pin the ordering so
18099        // a future refactor that reorders the arms surfaces here as a
18100        // test failure rather than a silent diagnostic regression.
18101        let mut s = three_member_spec();
18102        s.politicas.timeout = Some(Duration::ZERO);
18103        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
18104    }
18105
18106    #[test]
18107    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
18108        // The diagnostic envelope carries the offending `Duration`
18109        // verbatim so the author can grep their `caixa.lisp` for
18110        // `:timeout "<value>"` and fix it in one edit. Same
18111        // diagnostic shape every other typed-slot canonical-form
18112        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
18113        // peer `:rate-limit :window` axis.
18114        let mut s = three_member_spec();
18115        let timeout = Duration::from_nanos(1_000_001);
18116        s.politicas.timeout = Some(timeout);
18117        match s.validate().unwrap_err() {
18118            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
18119                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
18120            }
18121            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
18122        }
18123    }
18124
18125    #[test]
18126    fn rejects_policy_timeout_above_cap() {
18127        // The fail-before-pass-after pin: 3601s = 1h + 1s is
18128        // structurally one canonical-tick past the
18129        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
18130        // integer-millisecond magnitude the canonical-form arm above
18131        // accepts cleanly, that the codec round-trips losslessly as
18132        // `"3601s"`, and that silently passed validate on every
18133        // pre-gate codebase because the typed slot's only checks were
18134        // the zero-floor and canonical-form arms. The mesh-level
18135        // deadline degenerates only at the runtime substrate (Envoy
18136        // / Cilium L7 timeout overlay) far from the source
18137        // `caixa.lisp` with no field naming the offending policy.
18138        let mut s = three_member_spec();
18139        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
18140        s.politicas.timeout = Some(timeout);
18141        assert_eq!(
18142            s.validate().unwrap_err(),
18143            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18144        );
18145    }
18146
18147    #[test]
18148    fn rejects_policy_timeout_one_millisecond_above_cap() {
18149        // Boundary case: exactly 1ms past the cap (the granularity
18150        // the canonical-form gate enforces). Catches a future
18151        // "strictly less than" half-measure and pins the diagnostic
18152        // to name the offending `Duration` verbatim. Peer of
18153        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
18154        // boundary pin on the sibling `:limits :memory` top edge.
18155        let mut s = three_member_spec();
18156        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
18157        s.politicas.timeout = Some(timeout);
18158        assert_eq!(
18159            s.validate().unwrap_err(),
18160            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18161        );
18162    }
18163
18164    #[test]
18165    fn rejects_policy_timeout_far_above_cap() {
18166        // The "obvious authoring footgun" case: a `(:timeout "24h")`
18167        // or `(:timeout "86400s")` — values the canonical-form arm
18168        // accepts as integer-millisecond magnitudes, the codec
18169        // round-trips losslessly through serde, but the mesh-level
18170        // policy cannot honor (a 24-hour synchronous-`:contratos`
18171        // deadline is operationally indistinguishable from
18172        // omit-the-axis). Until this gate landed validate accepted
18173        // it. Pin both common above-cap values (24h, 7d) so a future
18174        // relaxation that drops the upper bound surfaces here.
18175        for timeout in [
18176            Duration::from_secs(86_400),    // 24h
18177            Duration::from_secs(604_800),   // 7d
18178            Duration::from_secs(1_000_000), // ~11.5 days
18179        ] {
18180            let mut s = three_member_spec();
18181            s.politicas.timeout = Some(timeout);
18182            assert_eq!(
18183                s.validate().unwrap_err(),
18184                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18185            );
18186        }
18187    }
18188
18189    #[test]
18190    fn accepts_policy_timeout_at_cap() {
18191        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
18192        // must validate. The cap is inclusive on the top edge,
18193        // matching the [`POLICY_RETRIES_MAX`] /
18194        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
18195        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18196        // sibling capped axes. Pin the boundary explicitly so a
18197        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
18198        // instead of `>`) surfaces here as a test failure rather
18199        // than a silent contract narrowing.
18200        let mut s = three_member_spec();
18201        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
18202        s.validate()
18203            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
18204    }
18205
18206    #[test]
18207    fn accepts_policy_timeout_typical_values() {
18208        // The documented production-playbook band positive-control
18209        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
18210        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
18211        // plus a sweep through the long-running-workflow band
18212        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
18213        // validated set explicitly so a future tightening of the
18214        // ceiling surfaces here as a deliberate test edit, not a
18215        // silent contract narrowing.
18216        for timeout in [
18217            Duration::from_millis(1),
18218            Duration::from_millis(500),
18219            Duration::from_secs(1),
18220            Duration::from_secs(10),
18221            Duration::from_secs(15), // Envoy default
18222            Duration::from_secs(30),
18223            Duration::from_secs(60), // AWS App Mesh typical
18224            Duration::from_secs(300),
18225            Duration::from_secs(900),
18226            Duration::from_secs(1800),
18227            Duration::from_secs(3600), // exactly 1h, the cap
18228        ] {
18229            let mut s = three_member_spec();
18230            s.politicas.timeout = Some(timeout);
18231            s.validate()
18232                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
18233        }
18234    }
18235
18236    #[test]
18237    fn policy_timeout_zero_takes_precedence_over_cap() {
18238        // The cross-arm ordering pin: `Duration::ZERO` is
18239        // structurally outside both `>= 1ms` (zero-floor) and
18240        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
18241        // diagnostic is the more self-locating one (it directly
18242        // names the omit-axis remediation), so the validate gate
18243        // must fire on zero first. Same shape every other
18244        // zero-then-shape ordering on this surface uses
18245        // ([`AplicacaoError::PolicyRetriesZero`] then
18246        // [`AplicacaoError::PolicyRetriesExceedsCap`];
18247        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18248        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18249        let mut s = three_member_spec();
18250        s.politicas.timeout = Some(Duration::ZERO);
18251        assert_eq!(
18252            s.validate().unwrap_err(),
18253            AplicacaoError::PolicyTimeoutZero,
18254            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18255        );
18256    }
18257
18258    #[test]
18259    fn policy_timeout_canonical_takes_precedence_over_cap() {
18260        // The cross-arm ordering pin: a `Duration` that is *both*
18261        // sub-millisecond (non-canonical-form) and structurally
18262        // above the cap surfaces the canonical-form diagnostic
18263        // first, because the round-trip-shape break is the more
18264        // fundamental issue (the value can't even round-trip
18265        // through the codec, so the cap diagnostic naming
18266        // `1ms..=1h` would be misleading — there's no integer-ms
18267        // form of the offending value). Pin the order so a future
18268        // refactor that reorders the arms surfaces here as a test
18269        // failure rather than a silent diagnostic regression.
18270        let mut s = three_member_spec();
18271        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
18272        // *and* total magnitude above the 1h cap.
18273        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
18274        s.politicas.timeout = Some(timeout);
18275        assert_eq!(
18276            s.validate().unwrap_err(),
18277            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
18278            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18279        );
18280    }
18281
18282    #[test]
18283    fn policy_timeout_cap_diagnostic_carries_offending_value() {
18284        // The diagnostic-shape pin: the offending `Duration` is
18285        // carried verbatim into the
18286        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
18287        // surfaced error message names the value the author wrote
18288        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
18289        // exceeds the mesh-policy ceiling …"`), not just the cap.
18290        // Same self-locating diagnostic shape every other typed-cap
18291        // arm on this surface carries
18292        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
18293        // offending retry count verbatim).
18294        let mut s = three_member_spec();
18295        let timeout = Duration::from_secs(7200); // 2h
18296        s.politicas.timeout = Some(timeout);
18297        let err = s.validate().unwrap_err();
18298        assert!(
18299            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
18300            "got {err:?}"
18301        );
18302        let msg = err.to_string();
18303        assert!(
18304            msg.contains("7200"),
18305            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
18306        );
18307    }
18308
18309    #[test]
18310    fn policy_timeout_cap_pins_canonical_value() {
18311        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
18312        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
18313        // the shared duration codec emits as a clean canonical
18314        // string (`"<n>h"`). Pinning the literal value here surfaces
18315        // a future drift (a relaxation to 24h, a tightening to 5m)
18316        // as a deliberate test edit, not a silent contract
18317        // narrowing. Same shape every other typed-cap value pin on
18318        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
18319        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
18320        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
18321    }
18322
18323    #[test]
18324    fn policy_timeout_cap_value_round_trips_through_codec() {
18325        // The codec round-trip property the cap arm preserves: the
18326        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
18327        // the shared duration codec — every value at the cap renders
18328        // to a clean canonical string (`"1h"`) and parses back to
18329        // the same `Duration`. Pin this so a future drift between
18330        // the cap constant and the codec's largest emitted unit
18331        // surfaces here. Same shape every other typed boundary pin
18332        // on this surface uses
18333        // (`wasm32_memory_cap_matches_parsed_4_gib`).
18334        let policy = MeshPolicy {
18335            timeout: Some(POLICY_TIMEOUT_MAX),
18336            ..Default::default()
18337        };
18338        let json = serde_json::to_string(&policy).unwrap();
18339        // The codec emits `"1h"` for the canonical 1-hour magnitude.
18340        assert!(
18341            json.contains("\"1h\""),
18342            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
18343        );
18344        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18345        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
18346    }
18347
18348    #[test]
18349    fn rejects_circuit_breaker_window_sub_millisecond() {
18350        // Peer of the `:timeout` sub-millisecond arm on the second
18351        // typed-`Duration` `:politicas` axis: a purely sub-ms
18352        // `Duration` (`from_micros(500)`) renders through the shared
18353        // codec as `"0s"`, which the codec parses back to
18354        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
18355        // zero-floor gate then rejects on re-validate.
18356        let mut s = three_member_spec();
18357        let window = Duration::from_micros(500);
18358        s.politicas.circuit_breaker = Some(CircuitBreaker {
18359            max_failures: 5,
18360            window,
18361        });
18362        assert_eq!(
18363            s.validate().unwrap_err(),
18364            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18365        );
18366    }
18367
18368    #[test]
18369    fn rejects_circuit_breaker_window_non_integer_millisecond() {
18370        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
18371        // with non-integer-millisecond residue renders through the
18372        // shared codec as the truncated `"<n>ms"` form, parsing back
18373        // to a *different* `Duration` on the next round-trip.
18374        let mut s = three_member_spec();
18375        let window = Duration::from_micros(1500);
18376        s.politicas.circuit_breaker = Some(CircuitBreaker {
18377            max_failures: 5,
18378            window,
18379        });
18380        assert_eq!(
18381            s.validate().unwrap_err(),
18382            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18383        );
18384    }
18385
18386    #[test]
18387    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
18388        // The canonical-forms sweep on the breaker axis: every
18389        // integer-ms multiple the codec round-trips losslessly
18390        // passes the canonical gate.
18391        for window in [
18392            Duration::from_millis(1),
18393            Duration::from_millis(500),
18394            Duration::from_millis(1500),
18395            Duration::from_secs(30),
18396            Duration::from_secs(60),
18397            Duration::from_secs(3600),
18398        ] {
18399            let mut s = three_member_spec();
18400            s.politicas.circuit_breaker = Some(CircuitBreaker {
18401                max_failures: 5,
18402                window,
18403            });
18404            s.validate()
18405                .expect("integer-millisecond :circuit-breaker :window must validate");
18406        }
18407    }
18408
18409    #[test]
18410    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
18411        // `Duration::ZERO` would pass the canonical-ms gate (the
18412        // sub-ns residue is zero) but must surface the narrower
18413        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
18414        // remediation.
18415        let mut s = three_member_spec();
18416        s.politicas.circuit_breaker = Some(CircuitBreaker {
18417            max_failures: 5,
18418            window: Duration::ZERO,
18419        });
18420        assert_eq!(
18421            s.validate().unwrap_err(),
18422            AplicacaoError::PolicyBreakerZeroWindow
18423        );
18424    }
18425
18426    #[test]
18427    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
18428        // Both axes invalid: max_failures == 0 *and* window is
18429        // sub-ms. The validate gate must fire on max_failures first
18430        // (matching the existing ordering pin
18431        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
18432        // the existing diagnostic continues to lead with the simpler
18433        // "zero threshold" framing.
18434        let mut s = three_member_spec();
18435        s.politicas.circuit_breaker = Some(CircuitBreaker {
18436            max_failures: 0,
18437            window: Duration::from_micros(500),
18438        });
18439        assert_eq!(
18440            s.validate().unwrap_err(),
18441            AplicacaoError::PolicyBreakerZeroFailures
18442        );
18443    }
18444
18445    #[test]
18446    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
18447        let mut s = three_member_spec();
18448        let window = Duration::from_nanos(60_000_000_001);
18449        s.politicas.circuit_breaker = Some(CircuitBreaker {
18450            max_failures: 5,
18451            window,
18452        });
18453        match s.validate().unwrap_err() {
18454            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
18455                assert_eq!(w, window, "diagnostic must carry the offending Duration");
18456            }
18457            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
18458        }
18459    }
18460
18461    #[test]
18462    fn rejects_circuit_breaker_window_above_cap() {
18463        // The fail-before-pass-after pin: 3601s = 1h + 1s is
18464        // structurally one canonical-tick past the
18465        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
18466        // integer-millisecond magnitude the canonical-form arm above
18467        // accepts cleanly, that the codec round-trips losslessly as
18468        // `"3601s"`, and that silently passed validate on every
18469        // pre-gate codebase because the typed slot's only checks were
18470        // the zero-floor and canonical-form arms. The
18471        // rolling-window-to-lifetime-counter degeneration surfaces
18472        // only at the runtime substrate (Envoy's outlier_detection
18473        // interval, the future CiliumClusterwideEnvoyConfig overlay)
18474        // far from the source `caixa.lisp` with no field naming the
18475        // offending policy.
18476        let mut s = three_member_spec();
18477        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18478        s.politicas.circuit_breaker = Some(CircuitBreaker {
18479            max_failures: 5,
18480            window,
18481        });
18482        assert_eq!(
18483            s.validate().unwrap_err(),
18484            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18485        );
18486    }
18487
18488    #[test]
18489    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
18490        // Boundary case: exactly 1ms past the cap (the granularity the
18491        // canonical-form gate enforces). Catches a future "strictly
18492        // less than" half-measure and pins the diagnostic to name the
18493        // offending `Duration` verbatim. Peer of
18494        // `rejects_policy_timeout_one_millisecond_above_cap` on the
18495        // sibling duration-typed `:politicas :timeout` top edge.
18496        let mut s = three_member_spec();
18497        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
18498        s.politicas.circuit_breaker = Some(CircuitBreaker {
18499            max_failures: 5,
18500            window,
18501        });
18502        assert_eq!(
18503            s.validate().unwrap_err(),
18504            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18505        );
18506    }
18507
18508    #[test]
18509    fn rejects_circuit_breaker_window_far_above_cap() {
18510        // The "obvious authoring footgun" case: a `(:window "24h")` or
18511        // `(:window "86400s")` — values the canonical-form arm
18512        // accepts as integer-millisecond magnitudes, the codec
18513        // round-trips losslessly through serde, but the
18514        // rolling-window breaker contract cannot honor (a 24-hour
18515        // rolling failure window is operationally a lifetime counter).
18516        // Until this gate landed validate accepted it. Pin both common
18517        // above-cap values (24h, 7d) so a future relaxation that
18518        // drops the upper bound surfaces here.
18519        for window in [
18520            Duration::from_secs(86_400),    // 24h
18521            Duration::from_secs(604_800),   // 7d
18522            Duration::from_secs(1_000_000), // ~11.5 days
18523        ] {
18524            let mut s = three_member_spec();
18525            s.politicas.circuit_breaker = Some(CircuitBreaker {
18526                max_failures: 5,
18527                window,
18528            });
18529            assert_eq!(
18530                s.validate().unwrap_err(),
18531                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18532            );
18533        }
18534    }
18535
18536    #[test]
18537    fn accepts_circuit_breaker_window_at_cap() {
18538        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
18539        // (1h) — must validate. The cap is inclusive on the top edge,
18540        // matching the [`POLICY_TIMEOUT_MAX`] /
18541        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
18542        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18543        // sibling capped axes. Pin the boundary explicitly so a
18544        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
18545        // instead of `>`) surfaces here as a test failure rather than
18546        // a silent contract narrowing.
18547        let mut s = three_member_spec();
18548        s.politicas.circuit_breaker = Some(CircuitBreaker {
18549            max_failures: 5,
18550            window: POLICY_BREAKER_WINDOW_MAX,
18551        });
18552        s.validate()
18553            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
18554    }
18555
18556    #[test]
18557    fn accepts_circuit_breaker_window_typical_values() {
18558        // The documented production-playbook band positive-control
18559        // sweep — every value Hystrix / resilience4j / Istio / Envoy
18560        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
18561        // through the long-tail failure-detection band (15m, 30m, 1h)
18562        // the cap accepts. Pin the inclusive validated set explicitly
18563        // so a future tightening of the ceiling surfaces here as a
18564        // deliberate test edit, not a silent contract narrowing.
18565        for window in [
18566            Duration::from_millis(1),
18567            Duration::from_millis(500),
18568            Duration::from_secs(1),
18569            Duration::from_secs(10), // Hystrix / Istio / Envoy default
18570            Duration::from_secs(30),
18571            Duration::from_secs(60),  // resilience4j typical
18572            Duration::from_secs(300), // AWS App Mesh typical
18573            Duration::from_secs(900),
18574            Duration::from_secs(1800),
18575            Duration::from_secs(3600), // exactly 1h, the cap
18576        ] {
18577            let mut s = three_member_spec();
18578            s.politicas.circuit_breaker = Some(CircuitBreaker {
18579                max_failures: 5,
18580                window,
18581            });
18582            s.validate()
18583                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
18584        }
18585    }
18586
18587    #[test]
18588    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
18589        // The cross-arm ordering pin: `Duration::ZERO` is structurally
18590        // outside both `>= 1ms` (zero-floor) and
18591        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
18592        // diagnostic is the more self-locating one (it directly names
18593        // the omit-axis remediation), so the validate gate must fire
18594        // on zero first. Same shape every other zero-then-cap
18595        // ordering on this surface uses
18596        // ([`AplicacaoError::PolicyTimeoutZero`] then
18597        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
18598        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18599        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18600        let mut s = three_member_spec();
18601        s.politicas.circuit_breaker = Some(CircuitBreaker {
18602            max_failures: 5,
18603            window: Duration::ZERO,
18604        });
18605        assert_eq!(
18606            s.validate().unwrap_err(),
18607            AplicacaoError::PolicyBreakerZeroWindow,
18608            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18609        );
18610    }
18611
18612    #[test]
18613    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
18614        // The cross-arm ordering pin: a `Duration` that is *both*
18615        // sub-millisecond (non-canonical-form) and structurally above
18616        // the cap surfaces the canonical-form diagnostic first,
18617        // because the round-trip-shape break is the more fundamental
18618        // issue (the value can't even round-trip through the codec, so
18619        // the cap diagnostic naming `1ms..=1h` would be misleading —
18620        // there's no integer-ms form of the offending value). Pin the
18621        // order so a future refactor that reorders the arms surfaces
18622        // here as a test failure rather than a silent diagnostic
18623        // regression. Peer of
18624        // `policy_timeout_canonical_takes_precedence_over_cap` on the
18625        // sibling duration-typed `:politicas :timeout` axis.
18626        let mut s = three_member_spec();
18627        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
18628        s.politicas.circuit_breaker = Some(CircuitBreaker {
18629            max_failures: 5,
18630            window,
18631        });
18632        assert_eq!(
18633            s.validate().unwrap_err(),
18634            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
18635            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18636        );
18637    }
18638
18639    #[test]
18640    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
18641        // The cross-arm ordering pin between the two breaker axes: a
18642        // `CircuitBreaker` whose *both* `max_failures` is above its
18643        // cap *and* `window` is above its cap surfaces the
18644        // max-failures cap diagnostic first, because the validate
18645        // gate visits the failures arm before the window arm. Pin the
18646        // order so a future refactor that reorders the breaker arms
18647        // surfaces here.
18648        let mut s = three_member_spec();
18649        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18650        s.politicas.circuit_breaker = Some(CircuitBreaker {
18651            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
18652            window,
18653        });
18654        assert_eq!(
18655            s.validate().unwrap_err(),
18656            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
18657                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
18658            },
18659            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
18660        );
18661    }
18662
18663    #[test]
18664    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
18665        // The diagnostic-shape pin: the offending `Duration` is
18666        // carried verbatim into the
18667        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
18668        // the surfaced error message names the value the author wrote
18669        // (`":politicas :circuit-breaker :window (Duration { secs:
18670        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
18671        // just the cap. Same self-locating diagnostic shape every
18672        // other typed-cap arm on this surface carries
18673        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
18674        // offending `Duration` verbatim).
18675        let mut s = three_member_spec();
18676        let window = Duration::from_secs(7200); // 2h
18677        s.politicas.circuit_breaker = Some(CircuitBreaker {
18678            max_failures: 5,
18679            window,
18680        });
18681        let err = s.validate().unwrap_err();
18682        assert!(
18683            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
18684            "got {err:?}"
18685        );
18686        let msg = err.to_string();
18687        assert!(
18688            msg.contains("7200"),
18689            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
18690        );
18691    }
18692
18693    #[test]
18694    fn circuit_breaker_window_cap_pins_canonical_value() {
18695        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
18696        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
18697        // shared duration codec emits as a clean canonical string
18698        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
18699        // the sibling duration-typed `:politicas :timeout` axis (the
18700        // two duration-typed `:politicas` axes share a uniform top
18701        // edge). Pinning the literal value here surfaces a future
18702        // drift (a relaxation to 24h, a tightening to 5m) as a
18703        // deliberate test edit, not a silent contract narrowing. Same
18704        // shape every other typed-cap value pin on this surface uses
18705        // (`policy_timeout_cap_pins_canonical_value`).
18706        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
18707        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
18708        assert_eq!(
18709            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
18710            "the two duration-typed `:politicas` caps share the same top edge"
18711        );
18712    }
18713
18714    #[test]
18715    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
18716        // The codec round-trip property the cap arm preserves: the
18717        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
18718        // through the shared duration codec — every value at the cap
18719        // renders to a clean canonical string (`"1h"`) and parses back
18720        // to the same `Duration`. Pin this so a future drift between
18721        // the cap constant and the codec's largest emitted unit
18722        // surfaces here. Same shape every other typed boundary pin on
18723        // this surface uses
18724        // (`policy_timeout_cap_value_round_trips_through_codec`).
18725        let policy = MeshPolicy {
18726            circuit_breaker: Some(CircuitBreaker {
18727                max_failures: 5,
18728                window: POLICY_BREAKER_WINDOW_MAX,
18729            }),
18730            ..Default::default()
18731        };
18732        let json = serde_json::to_string(&policy).unwrap();
18733        // The codec emits `"1h"` for the canonical 1-hour magnitude.
18734        assert!(
18735            json.contains("\"1h\""),
18736            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
18737        );
18738        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18739        assert_eq!(
18740            back.circuit_breaker.unwrap().window,
18741            POLICY_BREAKER_WINDOW_MAX
18742        );
18743    }
18744
18745    #[test]
18746    fn is_integer_millisecond_duration_predicate_tracks_codec() {
18747        // Pin the predicate's accepted set against the codec's
18748        // accepted set explicitly. The codec parses
18749        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
18750        // accepted value is an integer-millisecond multiple — so the
18751        // predicate must accept exactly that set. Same shape every
18752        // other predicate-on-the-typed-slot helper carries
18753        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
18754        // Read directly from the codec-owned predicate — the crate's
18755        // single source of truth every typed-`Duration` axis now routes
18756        // through via
18757        // [`crate::render::require_positive_canonical_bounded_duration`].
18758        use super::supervisor::duration_codec::is_integer_millisecond_duration;
18759        assert!(is_integer_millisecond_duration(Duration::ZERO));
18760        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
18761        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
18762        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
18763        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
18764        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
18765        // Non-integer-millisecond residue: rejected.
18766        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
18767        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
18768        assert!(!is_integer_millisecond_duration(Duration::from_micros(
18769            1500
18770        )));
18771        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
18772        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
18773            999_999
18774        )));
18775        // The 1-ns-past-1ms boundary: rejected (no longer a clean
18776        // integer-millisecond multiple).
18777        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
18778            1_000_001
18779        )));
18780    }
18781
18782    #[test]
18783    fn policy_timeout_validated_value_round_trips_through_codec() {
18784        // The structural property the canonical-ms gate enforces:
18785        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
18786        // round-trips losslessly through the shared `duration_codec`
18787        // (serialize → string → deserialize → equal value). Pin this
18788        // end-to-end so a future change to either side (the validate
18789        // gate's accepted granularity, the codec's parse/render unit
18790        // set) that breaks the alignment surfaces here. The
18791        // previous-state shape (typed slot accepts arbitrary
18792        // `Duration`, codec only round-trips integer-ms) would fail
18793        // this test for any `Duration::from_micros(1500)` timeout —
18794        // the validate gate now forecloses that.
18795        for timeout in [
18796            Duration::from_millis(1),
18797            Duration::from_millis(1500),
18798            Duration::from_secs(30),
18799            Duration::from_secs(3600),
18800        ] {
18801            let mut s = three_member_spec();
18802            s.politicas.timeout = Some(timeout);
18803            s.validate().unwrap();
18804            let json = serde_json::to_string(&s.politicas).unwrap();
18805            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18806            assert_eq!(
18807                back.timeout, s.politicas.timeout,
18808                "every validated :timeout must round-trip losslessly through the codec"
18809            );
18810        }
18811    }
18812
18813    #[test]
18814    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
18815        // Peer of the `:timeout` round-trip property on the breaker
18816        // axis.
18817        for window in [
18818            Duration::from_millis(1),
18819            Duration::from_millis(1500),
18820            Duration::from_secs(30),
18821            Duration::from_secs(3600),
18822        ] {
18823            let mut s = three_member_spec();
18824            s.politicas.circuit_breaker = Some(CircuitBreaker {
18825                max_failures: 5,
18826                window,
18827            });
18828            s.validate().unwrap();
18829            let json = serde_json::to_string(&s.politicas).unwrap();
18830            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18831            assert_eq!(
18832                back.circuit_breaker.unwrap().window,
18833                window,
18834                "every validated :circuit-breaker :window must round-trip losslessly"
18835            );
18836        }
18837    }
18838
18839    #[test]
18840    fn empty_politicas_validates() {
18841        // Omitting every policy axis is fine — defaults express "no
18842        // policy on this axis", not "policy = 0". The fixture's typical
18843        // values continue to validate; this test pins that
18844        // MeshPolicy::default() is a clean pass through validate().
18845        let mut s = three_member_spec();
18846        s.politicas = MeshPolicy::default();
18847        s.validate().unwrap();
18848    }
18849
18850    #[test]
18851    fn typical_politicas_validates_with_every_axis_set() {
18852        // The full §III.1 example block (timeout + retries + breaker +
18853        // mtls + rate-limit) — every axis nonzero — must remain a
18854        // clean pass.
18855        let mut s = three_member_spec();
18856        s.politicas = MeshPolicy {
18857            timeout: Some(Duration::from_secs(30)),
18858            retries: Some(3),
18859            circuit_breaker: Some(CircuitBreaker {
18860                max_failures: 5,
18861                window: Duration::from_secs(60),
18862            }),
18863            mtls_required: Some(true),
18864            rate_limit: Some(RateLimit {
18865                rate: 100,
18866                window: Duration::from_secs(1),
18867            }),
18868        };
18869        s.validate().unwrap();
18870    }
18871
18872    #[test]
18873    fn rejects_empty_cluster_name() {
18874        let mut s = three_member_spec();
18875        s.placement.clusters = vec!["rio".into(), "".into()];
18876        assert_eq!(
18877            s.validate().unwrap_err(),
18878            AplicacaoError::PlacementClusterEmpty
18879        );
18880    }
18881
18882    #[test]
18883    fn rejects_duplicate_cluster_names() {
18884        let mut s = three_member_spec();
18885        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
18886        let err = s.validate().unwrap_err();
18887        assert!(
18888            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
18889            "got {err:?}"
18890        );
18891    }
18892
18893    #[test]
18894    fn rejects_placement_cluster_with_uppercase() {
18895        // The canonical "I copied the cluster's display name verbatim"
18896        // typo — K8s context names are lowercase per DNS-1123 label
18897        // rule, but org docs often round-trip a TitleCase identifier
18898        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
18899        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
18900        // on the peer name axis.
18901        let mut s = three_member_spec();
18902        s.placement.clusters = vec!["Rio".into(), "mar".into()];
18903        let err = s.validate().unwrap_err();
18904        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
18905            panic!("expected PlacementClusterInvalid, got other variant");
18906        };
18907        assert_eq!(cluster, "Rio");
18908        assert!(
18909            reason.contains("uppercase"),
18910            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
18911        );
18912        assert!(
18913            reason.contains("\"rio\""),
18914            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
18915        );
18916    }
18917
18918    #[test]
18919    fn rejects_placement_cluster_with_underscore() {
18920        // The canonical "I'm thinking of an env var / hostname slug"
18921        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
18922        // schema. K8s context filtering on `my_cluster` silently misses
18923        // the cluster the author intended; the gate moves it to caixa-
18924        // build time. Same shape as `rejects_membro_caixa_with_underscore`
18925        // (3f9d7a0).
18926        let mut s = three_member_spec();
18927        s.placement.clusters = vec!["my_cluster".into()];
18928        let err = s.validate().unwrap_err();
18929        assert!(
18930            matches!(
18931                err,
18932                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18933                    if cluster == "my_cluster" && reason.contains('_')
18934            ),
18935            "got {err:?}"
18936        );
18937    }
18938
18939    #[test]
18940    fn rejects_placement_cluster_with_dot() {
18941        // A `:placement :clusters` entry is a single DNS-1123 *label*,
18942        // not a subdomain — even though K8s context names sometimes
18943        // carry a dotted form via kubeconfig conventions, the strictest
18944        // floor among the use sites (DNS-1035 cluster.x-k8s.io
18945        // `metadata.name`, Cilium identity label values) wins. The "I
18946        // want to namespace my cluster names with `.`" intent is
18947        // expressed via `-` (`mar-east`).
18948        let mut s = three_member_spec();
18949        s.placement.clusters = vec!["team.rio".into()];
18950        let err = s.validate().unwrap_err();
18951        assert!(
18952            matches!(
18953                err,
18954                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18955                    if cluster == "team.rio" && reason.contains('.')
18956            ),
18957            "got {err:?}"
18958        );
18959    }
18960
18961    #[test]
18962    fn rejects_placement_cluster_with_leading_hyphen() {
18963        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
18964        // with an alphanumeric. The K8s apiserver rejects `-rio`
18965        // outright; the rendered fan-out would emit a `metadata.name:
18966        // "-rio"` that fails admission far from the source caixa.lisp.
18967        let mut s = three_member_spec();
18968        s.placement.clusters = vec!["-rio".into()];
18969        let err = s.validate().unwrap_err();
18970        assert!(
18971            matches!(
18972                err,
18973                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
18974                    if cluster == "-rio" && reason.contains("start and end")
18975            ),
18976            "got {err:?}"
18977        );
18978    }
18979
18980    #[test]
18981    fn rejects_placement_cluster_with_trailing_hyphen() {
18982        // The symmetric arm of the boundary rule. Pin separately so
18983        // both ends are covered against a future relaxation that only
18984        // checks one boundary (parallel to
18985        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
18986        let mut s = three_member_spec();
18987        s.placement.clusters = vec!["rio-".into()];
18988        let err = s.validate().unwrap_err();
18989        assert!(
18990            matches!(
18991                err,
18992                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
18993                    if cluster == "rio-"
18994            ),
18995            "got {err:?}"
18996        );
18997    }
18998
18999    #[test]
19000    fn rejects_placement_cluster_with_unicode() {
19001        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19002        // before it reaches K8s. The byte-by-byte ASCII validity check
19003        // rejects multi-byte UTF-8 sequences by the first byte that
19004        // fails `[a-z0-9-]`.
19005        let mut s = three_member_spec();
19006        s.placement.clusters = vec!["rió".into()];
19007        let err = s.validate().unwrap_err();
19008        assert!(
19009            matches!(
19010                err,
19011                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19012                    if cluster == "rió"
19013            ),
19014            "got {err:?}"
19015        );
19016    }
19017
19018    #[test]
19019    fn rejects_placement_cluster_with_whitespace() {
19020        // Whitespace is the canonical "I pasted from a sketch / doc"
19021        // footgun. The apiserver rejects every cluster `metadata.name`
19022        // value carrying whitespace.
19023        let mut s = three_member_spec();
19024        s.placement.clusters = vec!["rio cluster".into()];
19025        let err = s.validate().unwrap_err();
19026        assert!(
19027            matches!(
19028                err,
19029                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19030                    if cluster == "rio cluster"
19031            ),
19032            "got {err:?}"
19033        );
19034    }
19035
19036    #[test]
19037    fn rejects_placement_cluster_too_long() {
19038        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
19039        // pin. The diagnostic names both the cap (63) and the actual
19040        // length so the author can shorten in one edit. Mirrors
19041        // `rejects_membro_caixa_too_long` (3f9d7a0).
19042        let mut s = three_member_spec();
19043        let too_long = "a".repeat(64);
19044        s.placement.clusters = vec![too_long.clone()];
19045        let err = s.validate().unwrap_err();
19046        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19047            panic!("expected PlacementClusterInvalid");
19048        };
19049        assert_eq!(cluster, too_long);
19050        assert!(
19051            reason.contains("63") && reason.contains("64"),
19052            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19053        );
19054    }
19055
19056    #[test]
19057    fn placement_cluster_max_length_validates() {
19058        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
19059        // future tightening (e.g. dropping to 62) surfaces here as a
19060        // regression, mirroring `membro_caixa_max_length_validates`
19061        // (3f9d7a0).
19062        let mut s = three_member_spec();
19063        s.placement.clusters = vec!["a".repeat(63)];
19064        s.validate().unwrap();
19065    }
19066
19067    #[test]
19068    fn accepts_canonical_placement_cluster_forms() {
19069        // The DNS-1123 label shapes a caixa author is realistically
19070        // going to write for cluster names: single-word lowercase
19071        // (`rio`), regional hyphen-joined (`mar-east`), single
19072        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
19073        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
19074        // Pin every leg so a future tightening that bans (e.g.) digit-
19075        // start identifiers surfaces here.
19076        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
19077            let mut s = three_member_spec();
19078            s.placement.clusters = vec![form.into()];
19079            s.validate().unwrap_or_else(|e| {
19080                panic!("canonical cluster form {form:?} must validate, got {e:?}")
19081            });
19082        }
19083    }
19084
19085    #[test]
19086    fn placement_cluster_empty_takes_precedence_over_invalid() {
19087        // Order pin: the existing `PlacementClusterEmpty` diagnostic
19088        // (which doesn't try to parse) fires before the new
19089        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
19090        // `:clusters` entry keeps its narrower error message — the new
19091        // gate would also reject `""`, but the empty-string arm is the
19092        // more self-locating diagnostic. Mirrors the
19093        // `membro_caixa_empty_takes_precedence_over_invalid` pin
19094        // (3f9d7a0).
19095        let mut s = three_member_spec();
19096        s.placement.clusters = vec!["rio".into(), "".into()];
19097        let err = s.validate().unwrap_err();
19098        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
19099    }
19100
19101    #[test]
19102    fn placement_cluster_invalid_fires_before_duplicate_check() {
19103        // Order pin: a malformed-shape `:clusters` entry surfaces *its
19104        // own* diagnostic, even when a later entry would otherwise
19105        // collapse onto a duplicate name. The per-entry shape gate runs
19106        // inline before the duplicate-key insert, parallel to
19107        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
19108        let mut s = three_member_spec();
19109        s.placement.clusters = vec!["Rio".into(), "rio".into()];
19110        let err = s.validate().unwrap_err();
19111        assert!(
19112            matches!(
19113                err,
19114                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
19115            ),
19116            "got {err:?}"
19117        );
19118    }
19119
19120    #[test]
19121    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
19122        // The diagnostic-shape pin: the error names the offending
19123        // `:clusters` value verbatim so the author can grep their
19124        // caixa.lisp without re-running the build, and carries a
19125        // non-empty `reason` naming the specific violation. Same shape
19126        // every typed-shape gate enshrines
19127        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
19128        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
19129        let mut s = three_member_spec();
19130        s.placement.clusters = vec!["BAD_CLUSTER".into()];
19131        let err = s.validate().unwrap_err();
19132        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19133            panic!("expected PlacementClusterInvalid");
19134        };
19135        assert_eq!(cluster, "BAD_CLUSTER");
19136        assert!(
19137            !reason.is_empty(),
19138            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
19139        );
19140    }
19141
19142    #[test]
19143    fn rejects_sharded_with_empty_clusters() {
19144        // §III.1: Sharded uses :clusters as the shard pool. An empty
19145        // pool means "shard across no clusters" — meaningless, same as
19146        // Replicated with no hosts.
19147        let mut s = three_member_spec();
19148        s.placement.estrategia = PlacementStrategy::Sharded;
19149        s.placement.shard_key = Some("$tenantId".into());
19150        s.placement.clusters = vec![];
19151        assert!(matches!(
19152            s.validate().unwrap_err(),
19153            AplicacaoError::PlacementWithoutClusters {
19154                estrategia: PlacementStrategy::Sharded
19155            }
19156        ));
19157    }
19158
19159    #[test]
19160    fn rejects_sharded_with_empty_shard_key() {
19161        let mut s = three_member_spec();
19162        s.placement.estrategia = PlacementStrategy::Sharded;
19163        s.placement.shard_key = Some("".into());
19164        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
19165    }
19166
19167    #[test]
19168    fn rejects_shard_key_under_replicated_strategy() {
19169        // The fail-before-pass-after pin: a `:placement (:estrategia
19170        // Replicated :shard-key "tenantId")` manifest carries the
19171        // hash-keyed-distribution slot on a strategy that never consumes
19172        // it. Before the gate the typed slot's value silently vanished
19173        // at the renderer layer (caixa-mesh emits `placement.shardKey`
19174        // verbatim regardless of strategy; the Akka-style cluster-
19175        // sharding reconciler keys off `estrategia == Sharded` and
19176        // ignores the slot otherwise), with no diagnostic. Lifting the
19177        // rejection to a build-time gate makes the
19178        // `shard_key.is_some() == matches!(estrategia, Sharded)`
19179        // partition a structural property of every validated
19180        // [`Placement`].
19181        let mut s = three_member_spec();
19182        // The fixture already uses Replicated; just add a shard-key.
19183        s.placement.shard_key = Some("$tenantId".into());
19184        let err = s.validate().unwrap_err();
19185        let AplicacaoError::ShardKeyOnNonSharded {
19186            estrategia,
19187            shard_key,
19188        } = err
19189        else {
19190            panic!("expected ShardKeyOnNonSharded, got {err:?}");
19191        };
19192        assert_eq!(estrategia, PlacementStrategy::Replicated);
19193        assert_eq!(shard_key, "$tenantId");
19194    }
19195
19196    #[test]
19197    fn rejects_shard_key_under_singlenode_strategy() {
19198        // Peer of the Replicated case above on the SingleNode arm: OTP
19199        // distributed-app takeover (one cluster runs at a time) has no
19200        // hash-keyed routing axis to consume `:shard-key` either, so
19201        // the rejection fires on both non-Sharded arms uniformly.
19202        let mut s = three_member_spec();
19203        s.placement.estrategia = PlacementStrategy::SingleNode;
19204        s.placement.shard_key = Some("$tenantId".into());
19205        let err = s.validate().unwrap_err();
19206        let AplicacaoError::ShardKeyOnNonSharded {
19207            estrategia,
19208            shard_key,
19209        } = err
19210        else {
19211            panic!("expected ShardKeyOnNonSharded, got {err:?}");
19212        };
19213        assert_eq!(estrategia, PlacementStrategy::SingleNode);
19214        assert_eq!(shard_key, "$tenantId");
19215    }
19216
19217    #[test]
19218    fn rejects_empty_shard_key_under_replicated_strategy() {
19219        // The `Some("")` case under non-Sharded is rejected by
19220        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
19221        // fires before the empty-value gate), not
19222        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
19223        // the `Sharded` arm). Pin the partition so a future reorder of
19224        // the validate_placement match arms doesn't silently swap which
19225        // diagnostic the author sees — both are author errors, but
19226        // ShardKeyOnNonSharded names which strategy is the actual fix
19227        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
19228        // only says "pick a non-empty key".
19229        let mut s = three_member_spec();
19230        s.placement.shard_key = Some(String::new());
19231        let err = s.validate().unwrap_err();
19232        assert!(
19233            matches!(
19234                err,
19235                AplicacaoError::ShardKeyOnNonSharded {
19236                    estrategia: PlacementStrategy::Replicated,
19237                    ref shard_key,
19238                } if shard_key.is_empty()
19239            ),
19240            "got {err:?}"
19241        );
19242    }
19243
19244    #[test]
19245    fn replicated_without_shard_key_validates() {
19246        // The complement of the rejection: `:placement :estrategia
19247        // Replicated` with `:shard-key None` is the canonical happy
19248        // path on every existing fixture. Pin the no-shard-key case so
19249        // the new gate doesn't accidentally fire on `None`.
19250        let mut s = three_member_spec();
19251        assert!(matches!(
19252            s.placement.estrategia,
19253            PlacementStrategy::Replicated
19254        ));
19255        s.placement.shard_key = None;
19256        s.validate().unwrap();
19257    }
19258
19259    #[test]
19260    fn singlenode_without_shard_key_validates() {
19261        // Peer of the Replicated no-shard-key case on the SingleNode
19262        // arm — both non-Sharded strategies must validate cleanly when
19263        // the slot is omitted.
19264        let mut s = three_member_spec();
19265        s.placement.estrategia = PlacementStrategy::SingleNode;
19266        s.placement.shard_key = None;
19267        s.validate().unwrap();
19268    }
19269
19270    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
19271        // Fixture builder for the `:placement :shard-key` shape gate
19272        // tests: a three-member Aplicacao on the `Sharded` strategy
19273        // with the supplied `:shard-key` slot. Co-locates the
19274        // arm-construction so every test below carries one line of
19275        // setup (the offending `:shard-key` value) and the assertion.
19276        let mut s = three_member_spec();
19277        s.placement.estrategia = PlacementStrategy::Sharded;
19278        s.placement.shard_key = Some(key.into());
19279        s
19280    }
19281
19282    #[test]
19283    fn rejects_shard_key_with_embedded_space() {
19284        // The canonical paste-from-aligned-doc footgun:
19285        // `:shard-key "$tenant Id"` — the Akka-style entity-id
19286        // extractor reads the slot as a single-token reference, and an
19287        // embedded space breaks the token boundary at the runtime
19288        // hash-extractor pass with no diagnostic naming the offending
19289        // entry.
19290        let s = sharded_spec_with_key("$tenant Id");
19291        let err = s.validate().unwrap_err();
19292        assert!(
19293            matches!(
19294                err,
19295                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19296                    if shard_key == "$tenant Id" && reason.contains("space")
19297            ),
19298            "got {err:?}"
19299        );
19300    }
19301
19302    #[test]
19303    fn rejects_shard_key_with_leading_space() {
19304        // Leading-space arm of the embedded-whitespace footgun — the
19305        // paste-from-aligned-doc / paste-from-CSV-cell variant where
19306        // the leading column-padding leaked into the slot.
19307        let s = sharded_spec_with_key(" $tenantId");
19308        let err = s.validate().unwrap_err();
19309        assert!(
19310            matches!(
19311                err,
19312                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
19313                    if shard_key == " $tenantId"
19314            ),
19315            "got {err:?}"
19316        );
19317    }
19318
19319    #[test]
19320    fn rejects_shard_key_with_trailing_newline() {
19321        // The canonical paste-from-shell-heredoc footgun — every
19322        // `<<EOF` heredoc terminator paste leaves a trailing newline
19323        // the YAML emitter then folds away inconsistently across
19324        // emitter implementations.
19325        let s = sharded_spec_with_key("$tenantId\n");
19326        let err = s.validate().unwrap_err();
19327        assert!(
19328            matches!(
19329                err,
19330                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19331                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
19332            ),
19333            "got {err:?}"
19334        );
19335    }
19336
19337    #[test]
19338    fn rejects_shard_key_with_embedded_tab() {
19339        // The paste-from-aligned-doc tab-stop variant — tabs land
19340        // alongside spaces in copy-paste from formatted columns.
19341        let s = sharded_spec_with_key("$tenant\tId");
19342        let err = s.validate().unwrap_err();
19343        assert!(
19344            matches!(
19345                err,
19346                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19347                    if shard_key == "$tenant\tId" && reason.contains("tab")
19348            ),
19349            "got {err:?}"
19350        );
19351    }
19352
19353    #[test]
19354    fn rejects_shard_key_with_control_character() {
19355        // The paste-from-binary / paste-from-screen-cleared-terminal
19356        // footgun — an embedded `\x01` (SOH) byte that some YAML
19357        // emitters silently strip and others escape as ``,
19358        // breaking round-trip across emitter implementations.
19359        let s = sharded_spec_with_key("$tenant\u{0001}Id");
19360        let err = s.validate().unwrap_err();
19361        assert!(
19362            matches!(
19363                err,
19364                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19365                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
19366            ),
19367            "got {err:?}"
19368        );
19369    }
19370
19371    #[test]
19372    fn rejects_shard_key_with_non_ascii() {
19373        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
19374        // footgun — non-ASCII bytes normalize differently between the
19375        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
19376        // YAML parser, the same entity ID can silently map to two
19377        // distinct shards on a re-render.
19378        let s = sharded_spec_with_key("$tenàntId");
19379        let err = s.validate().unwrap_err();
19380        assert!(
19381            matches!(
19382                err,
19383                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19384                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
19385            ),
19386            "got {err:?}"
19387        );
19388    }
19389
19390    #[test]
19391    fn rejects_shard_key_too_long() {
19392        // Length cap pin: 64 bytes — one byte over the
19393        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
19394        // here is a paste-from-doc multi-line blob landing in
19395        // `:shard-key` instead of a single-token extractor expression.
19396        let too_long = "a".repeat(64);
19397        let s = sharded_spec_with_key(&too_long);
19398        let err = s.validate().unwrap_err();
19399        let AplicacaoError::ShardKeyInvalid {
19400            ref shard_key,
19401            ref reason,
19402        } = err
19403        else {
19404            panic!("expected ShardKeyInvalid, got {err:?}");
19405        };
19406        assert_eq!(shard_key, &too_long);
19407        assert!(
19408            reason.contains("63") && reason.contains("64"),
19409            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19410        );
19411    }
19412
19413    #[test]
19414    fn shard_key_max_length_validates() {
19415        // Boundary pin: 63 bytes exactly — the
19416        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
19417        // dropping to 62) surfaces here as a regression, mirroring
19418        // `placement_cluster_max_length_validates` /
19419        // `placement_affinity_max_length_validates` on the peer
19420        // identifier-shaped slots.
19421        let s = sharded_spec_with_key(&"a".repeat(63));
19422        s.validate().unwrap();
19423    }
19424
19425    #[test]
19426    fn accepts_canonical_shard_key_forms() {
19427        // The Akka-style entity-id extractor shapes a caixa author is
19428        // realistically going to write — pin every leg so a future
19429        // tightening that bans (e.g.) the `${...}` interpolation
19430        // variant or the `metadata.<field>` JSONPath form surfaces
19431        // here as a regression. The canonical forms span:
19432        //
19433        //   - bare property name (`tenantId`, `customerId`)
19434        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
19435        //   - JSONPath-style nested reference (`metadata.tenantId`,
19436        //     `$.user.id`)
19437        //   - interpolation-style template (`${tenant}`)
19438        //   - snake_case property name (`customer_id`)
19439        //   - kebab-case property name (`customer-id` — accepted
19440        //     because the slot is a printable-ASCII single-token
19441        //     reference, not a DNS-1123 label like
19442        //     `:placement :affinity` / `:clusters`)
19443        //   - single character (`a`, `$` — boundary)
19444        for form in [
19445            "tenantId",
19446            "customerId",
19447            "$tenantId",
19448            "metadata.tenantId",
19449            "$.user.id",
19450            "${tenant}",
19451            "customer_id",
19452            "customer-id",
19453            "a",
19454            "$",
19455        ] {
19456            let s = sharded_spec_with_key(form);
19457            s.validate().unwrap_or_else(|e| {
19458                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
19459            });
19460        }
19461    }
19462
19463    #[test]
19464    fn shard_key_empty_takes_precedence_over_invalid() {
19465        // Order pin: the existing `ShardedKeyEmpty` diagnostic
19466        // (reserved for the `Sharded` `Some("")` arm) fires before the
19467        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
19468        // `:shard-key` keeps its narrower error message — the new gate
19469        // would also reject `""` defensively, but the empty-string arm
19470        // is the more self-locating diagnostic. Mirrors the
19471        // `placement_cluster_empty_takes_precedence_over_invalid` pin
19472        // on the peer identifier-shaped slot.
19473        let s = sharded_spec_with_key("");
19474        let err = s.validate().unwrap_err();
19475        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
19476    }
19477
19478    #[test]
19479    fn shard_key_invalid_diagnostic_carries_offending_value() {
19480        // The diagnostic-shape pin: the error names the offending
19481        // `:shard-key` value verbatim so the author can grep their
19482        // caixa.lisp without re-running the build, and carries a
19483        // parser-shaped `reason:` naming the specific violation —
19484        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19485        // on the peer identifier-shaped slot.
19486        let s = sharded_spec_with_key("$tenant Id");
19487        let err = s.validate().unwrap_err();
19488        let AplicacaoError::ShardKeyInvalid {
19489            ref shard_key,
19490            ref reason,
19491        } = err
19492        else {
19493            panic!("expected ShardKeyInvalid, got {err:?}");
19494        };
19495        assert_eq!(shard_key, "$tenant Id");
19496        assert!(
19497            !reason.is_empty(),
19498            "reason must name the specific violation, got empty string"
19499        );
19500    }
19501
19502    #[test]
19503    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
19504        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
19505        // `:shard-key` carried on non-Sharded strategies) fires before
19506        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
19507        // a `Replicated` strategy surfaces the more self-locating
19508        // strategy-mismatch diagnostic (naming the actual fix — drop
19509        // the slot, or switch to Sharded) rather than the shape
19510        // diagnostic. The strategy-mismatch arm is the more actionable
19511        // diagnostic: a malformed shard-key on Replicated is "you
19512        // shouldn't have a :shard-key here at all", not "your
19513        // :shard-key value is malformed".
19514        let mut s = three_member_spec();
19515        // Replicated is the default fixture strategy.
19516        s.placement.shard_key = Some("$tenant Id".into());
19517        let err = s.validate().unwrap_err();
19518        assert!(
19519            matches!(
19520                err,
19521                AplicacaoError::ShardKeyOnNonSharded {
19522                    estrategia: PlacementStrategy::Replicated,
19523                    ..
19524                }
19525            ),
19526            "got {err:?}"
19527        );
19528    }
19529
19530    #[test]
19531    fn rejects_empty_affinity_hint() {
19532        let mut s = three_member_spec();
19533        s.placement.affinity = Some("".into());
19534        assert_eq!(
19535            s.validate().unwrap_err(),
19536            AplicacaoError::PlacementAffinityEmpty
19537        );
19538    }
19539
19540    #[test]
19541    fn placement_without_affinity_validates() {
19542        // Omitting :affinity is fine — the placement engine falls back
19543        // to the default heuristic. Pin the no-hint case so the
19544        // affinity-empty rejection doesn't accidentally fire on `None`.
19545        let mut s = three_member_spec();
19546        s.placement.affinity = None;
19547        s.validate().unwrap();
19548    }
19549
19550    #[test]
19551    fn rejects_placement_affinity_with_uppercase() {
19552        // The canonical "I copied the ADR's display name verbatim" typo
19553        // — placement hints land verbatim in K8s label-selector
19554        // territory, where the apiserver enforces the DNS-1123 label
19555        // rule (lowercase-only) on every identity-keyed admission axis.
19556        // Mirrors `rejects_placement_cluster_with_uppercase` on the
19557        // sibling slot.
19558        let mut s = three_member_spec();
19559        s.placement.affinity = Some("DataLocality".into());
19560        let err = s.validate().unwrap_err();
19561        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19562            panic!("expected PlacementAffinityInvalid, got other variant");
19563        };
19564        assert_eq!(affinity, "DataLocality");
19565        assert!(
19566            reason.contains("uppercase"),
19567            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19568        );
19569        assert!(
19570            reason.contains("\"datalocality\""),
19571            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19572        );
19573    }
19574
19575    #[test]
19576    fn rejects_placement_affinity_with_underscore() {
19577        // The canonical "I'm thinking of an env var / Python identifier"
19578        // leak — `_` is forbidden by every DNS-1123 label schema. Same
19579        // shape as `rejects_placement_cluster_with_underscore` on the
19580        // sibling slot.
19581        let mut s = three_member_spec();
19582        s.placement.affinity = Some("data_locality".into());
19583        let err = s.validate().unwrap_err();
19584        assert!(
19585            matches!(
19586                err,
19587                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19588                    if affinity == "data_locality" && reason.contains('_')
19589            ),
19590            "got {err:?}"
19591        );
19592    }
19593
19594    #[test]
19595    fn rejects_placement_affinity_with_dot() {
19596        // A `:placement :affinity` value is a single DNS-1123 *label*
19597        // (it lands as a K8s label value selector key), not a subdomain.
19598        // The "I want to namespace my hint with `.`" intent is expressed
19599        // via `-` (`data-locality-east`).
19600        let mut s = three_member_spec();
19601        s.placement.affinity = Some("data.locality".into());
19602        let err = s.validate().unwrap_err();
19603        assert!(
19604            matches!(
19605                err,
19606                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19607                    if affinity == "data.locality" && reason.contains('.')
19608            ),
19609            "got {err:?}"
19610        );
19611    }
19612
19613    #[test]
19614    fn rejects_placement_affinity_with_unicode() {
19615        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19616        // before it reaches K8s. The byte-by-byte ASCII validity check
19617        // rejects multi-byte UTF-8 sequences by the first byte that
19618        // fails `[a-z0-9-]`.
19619        let mut s = three_member_spec();
19620        s.placement.affinity = Some("data-localité".into());
19621        let err = s.validate().unwrap_err();
19622        assert!(
19623            matches!(
19624                err,
19625                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19626                    if affinity == "data-localité"
19627            ),
19628            "got {err:?}"
19629        );
19630    }
19631
19632    #[test]
19633    fn rejects_placement_affinity_with_leading_hyphen() {
19634        // DNS-1123 boundary rule: labels must start with an
19635        // alphanumeric. Pin separately from the trailing-hyphen arm so
19636        // a future relaxation that only checks one boundary surfaces
19637        // here as a regression (parallel to
19638        // `rejects_placement_cluster_with_leading_hyphen`).
19639        let mut s = three_member_spec();
19640        s.placement.affinity = Some("-data-locality".into());
19641        let err = s.validate().unwrap_err();
19642        assert!(
19643            matches!(
19644                err,
19645                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19646                    if affinity == "-data-locality" && reason.contains("start and end")
19647            ),
19648            "got {err:?}"
19649        );
19650    }
19651
19652    #[test]
19653    fn rejects_placement_affinity_with_trailing_hyphen() {
19654        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
19655        // ends are covered against a future relaxation.
19656        let mut s = three_member_spec();
19657        s.placement.affinity = Some("data-locality-".into());
19658        let err = s.validate().unwrap_err();
19659        assert!(
19660            matches!(
19661                err,
19662                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19663                    if affinity == "data-locality-"
19664            ),
19665            "got {err:?}"
19666        );
19667    }
19668
19669    #[test]
19670    fn rejects_placement_affinity_with_whitespace() {
19671        // Whitespace is the canonical "I pasted from a sketch / doc"
19672        // footgun. The apiserver rejects every label-selector value
19673        // carrying whitespace.
19674        let mut s = three_member_spec();
19675        s.placement.affinity = Some("data locality".into());
19676        let err = s.validate().unwrap_err();
19677        assert!(
19678            matches!(
19679                err,
19680                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19681                    if affinity == "data locality"
19682            ),
19683            "got {err:?}"
19684        );
19685    }
19686
19687    #[test]
19688    fn rejects_placement_affinity_too_long() {
19689        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
19690        // pin. The diagnostic names both the cap (63) and the actual
19691        // length so the author can shorten in one edit. Mirrors
19692        // `rejects_placement_cluster_too_long`.
19693        let mut s = three_member_spec();
19694        let too_long = "a".repeat(64);
19695        s.placement.affinity = Some(too_long.clone());
19696        let err = s.validate().unwrap_err();
19697        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19698            panic!("expected PlacementAffinityInvalid");
19699        };
19700        assert_eq!(affinity, too_long);
19701        assert!(
19702            reason.contains("63") && reason.contains("64"),
19703            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19704        );
19705    }
19706
19707    #[test]
19708    fn placement_affinity_max_length_validates() {
19709        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
19710        // future tightening (e.g. dropping to 62) surfaces here as a
19711        // regression, mirroring `placement_cluster_max_length_validates`.
19712        let mut s = three_member_spec();
19713        s.placement.affinity = Some("a".repeat(63));
19714        s.validate().unwrap();
19715    }
19716
19717    #[test]
19718    fn accepts_canonical_placement_affinity_forms() {
19719        // The DNS-1123 label shapes a caixa author is realistically
19720        // going to write for placement hints: the M3 canonical examples
19721        // (`data-locality`, `low-latency`, `anti-affinity`), the
19722        // single-token form (`affinity`), the single-character boundary
19723        // (`a`), the digit-start (DNS-1123 allows this, unlike
19724        // DNS-1035), and a regional-suffixed form. Pin every leg so a
19725        // future tightening that bans (e.g.) digit-start identifiers
19726        // surfaces here.
19727        for form in [
19728            "data-locality",
19729            "low-latency",
19730            "anti-affinity",
19731            "affinity",
19732            "a",
19733            "3-tier",
19734            "locality-east",
19735        ] {
19736            let mut s = three_member_spec();
19737            s.placement.affinity = Some(form.into());
19738            s.validate().unwrap_or_else(|e| {
19739                panic!("canonical affinity form {form:?} must validate, got {e:?}")
19740            });
19741        }
19742    }
19743
19744    #[test]
19745    fn placement_affinity_empty_takes_precedence_over_invalid() {
19746        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
19747        // (which doesn't try to parse) fires before the new
19748        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
19749        // `:affinity` keeps its narrower error message — the new gate
19750        // would also reject `""`, but the empty-string arm is the more
19751        // self-locating diagnostic. Mirrors the
19752        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
19753        let mut s = three_member_spec();
19754        s.placement.affinity = Some(String::new());
19755        let err = s.validate().unwrap_err();
19756        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
19757    }
19758
19759    #[test]
19760    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
19761        // The diagnostic shape pin: every rejection carries the offending
19762        // `affinity:` verbatim plus a parser-shaped `reason:` so the
19763        // author can grep their caixa.lisp for `:affinity "<hint>"` and
19764        // fix it in one edit. Mirrors the
19765        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19766        // pin on the sibling slot.
19767        let mut s = three_member_spec();
19768        s.placement.affinity = Some("Data_Locality".into());
19769        let err = s.validate().unwrap_err();
19770        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19771            panic!("expected PlacementAffinityInvalid");
19772        };
19773        assert_eq!(affinity, "Data_Locality");
19774        assert!(
19775            !reason.is_empty(),
19776            "diagnostic reason must not be empty (got: {reason:?})"
19777        );
19778    }
19779
19780    #[test]
19781    fn singlenode_with_takeover_candidates_validates() {
19782        // OTP distributed-application convention (MESH-COMPOSITION
19783        // §II.1): SingleNode runs on one cluster at a time but the
19784        // :clusters list enumerates the takeover candidates. Multiple
19785        // entries are not a contradiction — they are the failover pool.
19786        let mut s = three_member_spec();
19787        s.placement.estrategia = PlacementStrategy::SingleNode;
19788        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
19789        s.validate().unwrap();
19790    }
19791
19792    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
19793
19794    #[test]
19795    fn mesh_policy_default_is_empty() {
19796        // The Default impl carries None on every axis — the typed
19797        // analog of an unset `:politicas (())` slot. Renderers that
19798        // overlay the policy onto a cluster artifact key off this
19799        // predicate to skip the slot entirely; pinning so a future
19800        // axis added to MeshPolicy can't silently break the contract
19801        // (a new field whose Default is non-None would flip is_empty
19802        // to false on every existing caixa, surfacing here).
19803        assert!(MeshPolicy::default().is_empty());
19804    }
19805
19806    #[test]
19807    fn mesh_policy_with_only_timeout_is_not_empty() {
19808        let p = MeshPolicy {
19809            timeout: Some(Duration::from_secs(30)),
19810            ..Default::default()
19811        };
19812        assert!(!p.is_empty());
19813    }
19814
19815    #[test]
19816    fn mesh_policy_with_only_retries_is_not_empty() {
19817        let p = MeshPolicy {
19818            retries: Some(3),
19819            ..Default::default()
19820        };
19821        assert!(!p.is_empty());
19822    }
19823
19824    #[test]
19825    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
19826        let p = MeshPolicy {
19827            circuit_breaker: Some(CircuitBreaker {
19828                max_failures: 5,
19829                window: Duration::from_secs(60),
19830            }),
19831            ..Default::default()
19832        };
19833        assert!(!p.is_empty());
19834    }
19835
19836    #[test]
19837    fn mesh_policy_with_only_mtls_required_is_not_empty() {
19838        // Even `mtls_required: Some(false)` (an explicit opt-out) is
19839        // not empty — the author *named* the axis, the renderer needs
19840        // to honor that vs. fall back to the cluster default.
19841        let p = MeshPolicy {
19842            mtls_required: Some(false),
19843            ..Default::default()
19844        };
19845        assert!(!p.is_empty());
19846    }
19847
19848    #[test]
19849    fn mesh_policy_with_only_rate_limit_is_not_empty() {
19850        let p = MeshPolicy {
19851            rate_limit: Some(RateLimit {
19852                rate: 100,
19853                window: Duration::from_secs(1),
19854            }),
19855            ..Default::default()
19856        };
19857        assert!(!p.is_empty());
19858    }
19859
19860    #[test]
19861    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
19862        // The three-member happy-path fixture sets timeout + retries +
19863        // mtls_required — every populated axis must read non-empty.
19864        // Pin the round-trip so the M3.x per-:politicas emitter (the
19865        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
19866        // on is_empty() to decide whether to emit at all without
19867        // re-deriving the contract from inline field probes.
19868        assert!(!three_member_spec().politicas.is_empty());
19869    }
19870
19871    // ── shared duration codec: cross-slot integer-magnitude gate ──
19872    //
19873    // The integer-magnitude discipline applied to
19874    // `supervisor::duration_codec::parse` lifts onto every typed slot
19875    // that routes through the shared codec — `MeshPolicy::timeout`
19876    // (`:politicas :timeout`) and `CircuitBreaker::window`
19877    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
19878    // These cross-slot tests pin that the gate fires at the serde
19879    // layer for both typed slots, not just for the supervisor side.
19880
19881    #[test]
19882    fn policy_timeout_serde_rejects_fractional_seconds() {
19883        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
19884        // so the shared codec's integer-magnitude gate applies on
19885        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
19886        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
19887        // deserialize with the canonical-form diagnostic naming the
19888        // offending `"1.5"` and the remediation `"1500ms"`.
19889        let payload = r#"{"timeout":"1.5s"}"#;
19890        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19891        let msg = err.to_string();
19892        assert!(
19893            msg.contains("not a non-negative integer"),
19894            "expected integer-magnitude diagnostic in {msg:?}"
19895        );
19896        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
19897        assert!(
19898            msg.contains("\"1500ms\""),
19899            "missing canonical-form remediation in {msg:?}"
19900        );
19901    }
19902
19903    #[test]
19904    fn policy_timeout_serde_rejects_leading_plus_sign() {
19905        // Pin the leading-`+` arm cross-slot — the prior f64 parser
19906        // accepted `"+30s"` silently and round-tripped to `"30s"`.
19907        let payload = r#"{"timeout":"+30s"}"#;
19908        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19909        let msg = err.to_string();
19910        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
19911    }
19912
19913    #[test]
19914    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
19915        // `CircuitBreaker::window` uses `with =
19916        // "supervisor::duration_codec_required"` (the required-Duration
19917        // variant that delegates to the same shared parser). `"0.5m"`
19918        // parsed to 30s and round-tripped to `"30s"` on next emit —
19919        // DRIFT closed.
19920        let payload = format!(
19921            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
19922            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
19923            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
19924        );
19925        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
19926        let msg = err.to_string();
19927        assert!(
19928            msg.contains("not a non-negative integer"),
19929            "expected integer-magnitude diagnostic in {msg:?}"
19930        );
19931        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
19932        assert!(
19933            msg.contains("\"30s\""),
19934            "missing canonical-form remediation in {msg:?}"
19935        );
19936    }
19937
19938    #[test]
19939    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
19940        // Pin the happy-path on the cross-slot side: every canonical
19941        // author shape `render` ever emits parses cleanly through the
19942        // shared codec on the `CircuitBreaker` slot. The
19943        // codec's accepted set (post-gate) is exactly its emitted set
19944        // for the integer-magnitude class.
19945        for window_lit in ["30s", "500ms", "2m", "1h"] {
19946            let payload = format!(
19947                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
19948                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
19949                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
19950            );
19951            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
19952                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
19953            });
19954            assert_eq!(cb.max_failures, 5);
19955        }
19956    }
19957
19958    // ── rate_limit_codec: integer-magnitude gate ──
19959    //
19960    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
19961    // / 737a676 / d53c922 trajectory landed on every typed-duration /
19962    // typed-byte-size codec in caixa-core lifts onto the fifth typed
19963    // codec — `rate_limit_codec` — through the digit-only magnitude
19964    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
19965    // These tests pin the gate at the serde layer for `:politicas
19966    // :rate-limit` (the only typed slot the codec backs), and at the
19967    // codec-internal `parse` layer for the canonical positive cases.
19968
19969    #[test]
19970    fn rate_limit_serde_rejects_fractional_rate() {
19971        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
19972        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
19973        // wording, which didn't name the canonical-form remediation or
19974        // the round-trip drift the next emit would produce. Now refused
19975        // at deserialize with the canonical-form diagnostic naming the
19976        // offending `"1.5"` magnitude and the round-trip drift wording.
19977        let payload = r#"{"rateLimit":"1.5/s"}"#;
19978        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
19979        let msg = err.to_string();
19980        assert!(
19981            msg.contains("not a non-negative integer"),
19982            "expected integer-magnitude diagnostic in {msg:?}"
19983        );
19984        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
19985        assert!(
19986            msg.contains("THEORY.md"),
19987            "missing render-determinism contract citation in {msg:?}"
19988        );
19989    }
19990
19991    #[test]
19992    fn rate_limit_serde_rejects_leading_plus_sign() {
19993        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
19994        // permissive-`+` parse), so `"+100/s"` silently parsed to
19995        // `RateLimit { 100, 1s }` and round-tripped through `render` to
19996        // `"100/s"` — a *different* canonical string on the next emit,
19997        // breaking the THEORY.md Part V render-determinism contract
19998        // exactly the way the peer duration codecs' `"+30s"` case did.
19999        // This is the load-bearing class the digit-only gate closes
20000        // beyond what `u32::from_str`'s strictness covers on its own.
20001        let payload = r#"{"rateLimit":"+100/s"}"#;
20002        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20003        let msg = err.to_string();
20004        assert!(
20005            msg.contains("not a non-negative integer"),
20006            "expected integer-magnitude diagnostic in {msg:?}"
20007        );
20008        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
20009    }
20010
20011    #[test]
20012    fn rate_limit_serde_rejects_leading_minus_sign() {
20013        // The signed-negative arm: `"-1/s"` lands on the
20014        // non-canonical-but-numeric branch via the `i64` fallback (the
20015        // `f64` parse also succeeds), surfacing the canonical-form
20016        // diagnostic. Replaces the prior value-laundered "not a u32"
20017        // wording with the unified diagnostic across signs.
20018        let payload = r#"{"rateLimit":"-1/s"}"#;
20019        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20020        let msg = err.to_string();
20021        assert!(
20022            msg.contains("not a non-negative integer"),
20023            "expected integer-magnitude diagnostic in {msg:?}"
20024        );
20025        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
20026    }
20027
20028    #[test]
20029    fn rate_limit_serde_rejects_decimal_shaped_integer() {
20030        // `"100.0/s"` is integer-valued numerically but not in the
20031        // codec's accepted set — `render` emits `"100/s"`, so the
20032        // round-trip would drift. Lifted to the canonical-form
20033        // diagnostic peer with the duration codec's `"1.0s"` case
20034        // (1c55a2a).
20035        let payload = r#"{"rateLimit":"100.0/s"}"#;
20036        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20037        let msg = err.to_string();
20038        assert!(
20039            msg.contains("not a non-negative integer"),
20040            "expected integer-magnitude diagnostic in {msg:?}"
20041        );
20042        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
20043    }
20044
20045    #[test]
20046    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
20047        // Non-numeric, non-digit-only input lands on the existing
20048        // narrower `"not a u32"` arm (preserved for diagnostic-shape
20049        // stability on the parser-shape footgun case). Pin this so a
20050        // future relaxation of the numeric-fallback predicate doesn't
20051        // silently collapse garbage onto the canonical-form arm — same
20052        // partition the peer duration codecs draw between
20053        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
20054        let payload = r#"{"rateLimit":"abc/s"}"#;
20055        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20056        let msg = err.to_string();
20057        assert!(
20058            msg.contains("not a u32"),
20059            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
20060        );
20061        assert!(
20062            !msg.contains("not a non-negative integer"),
20063            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
20064        );
20065    }
20066
20067    #[test]
20068    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
20069        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
20070        // u32's range. The digit-only gate passes; `u32::from_str`
20071        // fails on overflow. Surface that with the overflow-shaped
20072        // diagnostic naming the offending magnitude verbatim, peer
20073        // with `supervisor::duration_codec`'s overflow arm. Pinning
20074        // the wording so a future refactor doesn't silently collapse
20075        // overflow onto the canonical-form arm.
20076        let payload = r#"{"rateLimit":"4294967296/s"}"#;
20077        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20078        let msg = err.to_string();
20079        assert!(
20080            msg.contains("overflows u32"),
20081            "expected overflow diagnostic in {msg:?}"
20082        );
20083        assert!(
20084            msg.contains("\"4294967296\""),
20085            "missing offending magnitude in {msg:?}"
20086        );
20087    }
20088
20089    #[test]
20090    fn rate_limit_serde_rejects_leading_zero_magnitude() {
20091        // `"0100/s"` is digit-only, so the existing
20092        // non-digit-only / sign / fractional arm doesn't catch it —
20093        // `u32::from_str("0100")` returns `Ok(100)`, so before this
20094        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
20095        // round-tripped through `render` to `"100/s"` — a *different*
20096        // canonical string on the next emit, breaking the THEORY.md
20097        // Part V render-determinism contract exactly the way the
20098        // peer `"+100/s"` case did before the leading-`+` arm landed.
20099        // This is the load-bearing class the leading-zero gate closes
20100        // beyond what the existing digit-only / sign / fractional
20101        // gates cover, and the peer arm to the leading-`+` test
20102        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
20103        // canonical-form-drift axis.
20104        let payload = r#"{"rateLimit":"0100/s"}"#;
20105        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20106        let msg = err.to_string();
20107        assert!(
20108            msg.contains("non-canonical leading zero"),
20109            "expected leading-zero diagnostic in {msg:?}"
20110        );
20111        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
20112        assert!(
20113            msg.contains("THEORY.md"),
20114            "missing render-determinism contract citation in {msg:?}"
20115        );
20116    }
20117
20118    #[test]
20119    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
20120        // `"00/s"` is the degenerate leading-zero case — every byte
20121        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
20122        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
20123        // a *different* canonical string, same render-determinism
20124        // violation. The single-byte `"0/s"` itself is in the
20125        // accepted set (round-trips losslessly through `render`,
20126        // refused downstream by `PolicyRateLimitZero`); the
20127        // multi-byte `"00/s"` is not. Pins the boundary between the
20128        // accepted single-`0` and the rejected leading-zero class.
20129        let payload = r#"{"rateLimit":"00/s"}"#;
20130        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20131        let msg = err.to_string();
20132        assert!(
20133            msg.contains("non-canonical leading zero"),
20134            "expected leading-zero diagnostic in {msg:?}"
20135        );
20136        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
20137    }
20138
20139    #[test]
20140    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
20141        // Cross-window pin — the gate is window-agnostic; the
20142        // leading-zero class is a property of the magnitude, not the
20143        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
20144        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
20145        // single-window coverage extended across the three canonical
20146        // windows the codec accepts.
20147        let payload = r#"{"rateLimit":"007/h"}"#;
20148        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20149        let msg = err.to_string();
20150        assert!(
20151            msg.contains("non-canonical leading zero"),
20152            "expected leading-zero diagnostic in {msg:?}"
20153        );
20154        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
20155    }
20156
20157    #[test]
20158    fn rate_limit_serde_rejects_leading_whitespace() {
20159        // `" 100/s"` — the canonical paste-from-aligned-doc /
20160        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
20161        // the top-level `s.trim()` silently ate the leading space and
20162        // parsed the value to `RateLimit { 100, 1s }`, which then
20163        // round-tripped through `render` to `"100/s"` (a *different*
20164        // canonical string on the next emit) — the exact
20165        // canonical-form-drift class the leading-`+` / leading-zero
20166        // arms already close, extended to the whitespace byte class.
20167        let payload = r#"{"rateLimit":" 100/s"}"#;
20168        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20169        let msg = err.to_string();
20170        assert!(
20171            msg.contains("contains whitespace byte"),
20172            "expected whitespace diagnostic in {msg:?}"
20173        );
20174        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20175        assert!(
20176            msg.contains("THEORY.md"),
20177            "missing render-determinism contract citation in {msg:?}"
20178        );
20179    }
20180
20181    #[test]
20182    fn rate_limit_serde_rejects_trailing_whitespace() {
20183        // `"100/s "` — the canonical shell-history / trailing-space
20184        // paste footgun. Before this gate the top-level `s.trim()`
20185        // silently ate the trailing space and parsed to
20186        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
20187        // next emit — same canonical-form drift as the leading-space
20188        // sibling, closed on the same whitespace-byte arm.
20189        let payload = r#"{"rateLimit":"100/s "}"#;
20190        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20191        let msg = err.to_string();
20192        assert!(
20193            msg.contains("contains whitespace byte"),
20194            "expected whitespace diagnostic in {msg:?}"
20195        );
20196        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20197    }
20198
20199    #[test]
20200    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
20201        // `"100 / s"` — the canonical typographically-spaced author
20202        // shape (the same idiom every prose reference to a rate limit
20203        // renders as, mistakenly retained when the value is pasted
20204        // into a codec-shaped slot). Before this gate the per-part
20205        // `rate_str.trim()` / `unit.trim()` calls silently ate both
20206        // spaces on either side of `/` and parsed to
20207        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
20208        // codec's *internal* whitespace-tolerance vector, orthogonal
20209        // to the leading / trailing surface but the same canonical-
20210        // form-drift class. Pins the arm as strictly stronger than the
20211        // pre-existing top-level `s.trim()` behavior: it fires on
20212        // whitespace anywhere in the value, not just at the string
20213        // boundary.
20214        let payload = r#"{"rateLimit":"100 / s"}"#;
20215        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20216        let msg = err.to_string();
20217        assert!(
20218            msg.contains("contains whitespace byte"),
20219            "expected whitespace diagnostic in {msg:?}"
20220        );
20221        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20222    }
20223
20224    #[test]
20225    fn rate_limit_serde_rejects_tab_byte() {
20226        // `"\t100/s"` — the canonical paste-from-indented-doc /
20227        // paste-from-YAML-block-scalar footgun where a tab byte leads
20228        // the magnitude. Pins that the gate covers tab (`0x09`) as
20229        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
20230        // members and both would be silently swallowed by `s.trim()`
20231        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
20232        // space alone to the full ASCII-whitespace set (space `0x20`,
20233        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
20234        // the tab arm as a representative of the non-space members.
20235        let payload = r#"{"rateLimit":"\t100/s"}"#;
20236        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20237        let msg = err.to_string();
20238        assert!(
20239            msg.contains("contains whitespace byte"),
20240            "expected whitespace diagnostic in {msg:?}"
20241        );
20242        assert!(
20243            msg.contains("0x09"),
20244            "missing offending tab byte in {msg:?}"
20245        );
20246    }
20247
20248    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
20249    //
20250    // Successor to the ASCII-whitespace arm (1ad7755) on
20251    // `rate_limit_codec` — closes the strictly-complementary class the
20252    // byte-scan cannot see, through the lifted
20253    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
20254
20255    #[test]
20256    fn rate_limit_serde_rejects_leading_nbsp() {
20257        // NBSP prefix — paste-from-typography footgun. Byte-scan
20258        // misses, `str::trim` silently strips it, value drifts to
20259        // `"100/s"` on next serialize.
20260        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
20261        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20262        let msg = err.to_string();
20263        assert!(
20264            msg.contains("non-ASCII Unicode whitespace character"),
20265            "expected non-ASCII whitespace diagnostic in {msg:?}"
20266        );
20267        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
20268    }
20269
20270    #[test]
20271    fn rate_limit_serde_rejects_internal_em_space() {
20272        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
20273        // paste-from-typography footgun on the `<integer>/<unit>`
20274        // shape.
20275        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
20276        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20277        let msg = err.to_string();
20278        assert!(
20279            msg.contains("non-ASCII Unicode whitespace character"),
20280            "expected non-ASCII whitespace diagnostic in {msg:?}"
20281        );
20282        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
20283    }
20284
20285    #[test]
20286    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
20287        // Positive-control pin: every ASCII-only canonical form the
20288        // renderer emits stays accepted through the new arm.
20289        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
20290            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
20291            let p: MeshPolicy = serde_json::from_str(&payload)
20292                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
20293            assert!(p.rate_limit.is_some());
20294        }
20295    }
20296
20297    #[test]
20298    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
20299        // The boundary case — `"0/s"` is the canonical form
20300        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
20301        // it at the parse layer; the downstream
20302        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
20303        // `rate == 0` at the typed-validate layer above. Pins the
20304        // partition: the leading-zero gate at the codec layer does
20305        // not poach the rate-zero semantic-validation arm at the
20306        // typed-validate layer above (a future stricter codec must
20307        // not reject `"0/s"` here, or it'd collapse the diagnostic
20308        // partitioning that lets `PolicyRateLimitZero` name the
20309        // offending typed slot).
20310        let payload = r#"{"rateLimit":"0/s"}"#;
20311        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
20312            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
20313        });
20314        let rl = policy.rate_limit.expect("rate_limit must be Some");
20315        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
20316        assert_eq!(
20317            rl.window,
20318            Duration::from_secs(1),
20319            "single-`0` magnitude with `s` unit must parse to window=1s"
20320        );
20321    }
20322
20323    #[test]
20324    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
20325        // The complementary boundary pin — every magnitude
20326        // `render` emits starts with `[1-9]` (or is the single byte
20327        // `"0"`), so the canonical-form predicate is `(len == 1) ||
20328        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
20329        // '1'` case explicitly so a future tightening of the gate
20330        // (e.g. an over-eager "no leading digit < 5" rule, or a
20331        // mistakenly anchored start-of-magnitude byte check) lands
20332        // here before the canonical-forms-iterating test would catch
20333        // it.
20334        let payload = r#"{"rateLimit":"100/s"}"#;
20335        let policy: MeshPolicy = serde_json::from_str(payload)
20336            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
20337        let rl = policy.rate_limit.expect("rate_limit must be Some");
20338        assert_eq!(
20339            rl.rate, 100,
20340            "canonical-100 magnitude must parse to rate=100"
20341        );
20342    }
20343
20344    #[test]
20345    fn rate_limit_serde_accepts_integer_canonical_forms() {
20346        // Pin the happy-path: every canonical author shape `render`
20347        // ever emits parses cleanly through the codec post-gate. The
20348        // codec's accepted set (post-gate) is exactly its emitted set
20349        // for the integer-magnitude class — same property
20350        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
20351        // gates guarantee on the peer codecs. Iterating across rate
20352        // magnitudes (including `"0"`, which the codec accepts even
20353        // though `validate_politicas` rejects `rate == 0` at the typed
20354        // layer above) closes the codec contract at the parse layer
20355        // independently of the validate layer.
20356        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
20357            for unit_lit in ["s", "m", "h"] {
20358                let lit = format!("{rate_lit}/{unit_lit}");
20359                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
20360                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
20361                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
20362                });
20363                let rl = policy.rate_limit.expect("rate_limit must be Some");
20364                assert_eq!(
20365                    rl.rate,
20366                    rate_lit.parse::<u32>().unwrap(),
20367                    "rate mismatch for {lit:?}"
20368                );
20369            }
20370        }
20371    }
20372
20373    #[test]
20374    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
20375        // The structural property the gate enforces: serialize ∘
20376        // deserialize is the identity on every canonical author shape.
20377        // Peer of `parse_byte_size`'s and `parse_duration`'s
20378        // `_round_trips_through_render_for_every_canonical_form` tests
20379        // on the rate-limit axis. Before the gate, `"+100/s"` violated
20380        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
20381        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
20382        for rate in [1u32, 100, 5000, 1_000_000] {
20383            for (window, unit) in [
20384                (Duration::from_secs(1), "s"),
20385                (Duration::from_secs(60), "m"),
20386                (Duration::from_secs(3600), "h"),
20387            ] {
20388                let policy = MeshPolicy {
20389                    rate_limit: Some(RateLimit { rate, window }),
20390                    ..Default::default()
20391                };
20392                let json = serde_json::to_string(&policy).unwrap();
20393                let expected = format!("\"{rate}/{unit}\"");
20394                assert!(
20395                    json.contains(&expected),
20396                    "expected {expected:?} in {json:?}"
20397                );
20398                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20399                assert_eq!(
20400                    back.rate_limit, policy.rate_limit,
20401                    "round-trip for {json:?}"
20402                );
20403            }
20404        }
20405    }
20406
20407    // ── self-membership cross-slot gate ──────────────────────────────
20408
20409    #[test]
20410    fn validate_no_self_membership_rejects_self_named_membro() {
20411        // An Aplicacao whose `:membros` lists its own `:nome` is a
20412        // one-node lacre-closure recursion — rejected, naming the parent.
20413        let membros = vec![
20414            membro("catalog", "^0.1"),
20415            membro("checkout", "^0.1"),
20416            membro("cart", "^0.1"),
20417        ];
20418        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
20419        assert!(
20420            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
20421            "got {err:?}"
20422        );
20423    }
20424
20425    #[test]
20426    fn validate_no_self_membership_accepts_distinct_membros() {
20427        // Positive control: distinct member names (including a member
20428        // that is itself an Aplicacao — recursive composition is valid,
20429        // MESH-COMPOSITION §V) pass the gate.
20430        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
20431        validate_no_self_membership(&membros, "checkout").unwrap();
20432    }
20433
20434    #[test]
20435    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
20436        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
20437        // `NoMembros` arm (the more-fundamental "graph must have nodes"
20438        // gate), not by this cross-slot self-edge gate. Keeping the
20439        // self-membership predicate vacuously-ok on the empty input
20440        // matches its supervisor-axis peer
20441        // (`validate_no_self_supervision_empty_children_is_ok`) and
20442        // makes the gate composable from any future call site (an M4
20443        // CR materializer's per-membros validator) without re-checking
20444        // emptiness.
20445        validate_no_self_membership(&[], "checkout").unwrap();
20446    }
20447
20448    #[test]
20449    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
20450        // Pinning the Display: the self-membership diagnostic must name
20451        // the offending caixa verbatim + the "lists itself" framing the
20452        // author can grep for, so the cluster-far failure surfaces at
20453        // build time with one-line remediation. Same diagnostic shape
20454        // as the supervisor-axis `ChildSupervisesSelf` peer.
20455        let membros = vec![membro("orquestra", "^0.1")];
20456        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
20457        let msg = err.to_string();
20458        assert!(
20459            msg.contains("orquestra"),
20460            "diagnostic must name the offending caixa nome (got: {msg:?})"
20461        );
20462        assert!(
20463            msg.contains("lists itself"),
20464            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
20465        );
20466    }
20467
20468    #[test]
20469    fn default_servico_port_constant_pins_canonical_8080_literal() {
20470        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
20471        // at the verbatim `8080` literal both consumers (the
20472        // `Entrada::port` serde default via [`default_port`] and the
20473        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
20474        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
20475        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
20476        // discipline (a085b26) on the per-renderer canonical-K8s-axis
20477        // string-constant axis: a future refactor that drifts the
20478        // constant out from under either consumer surfaces here ahead
20479        // of every per-renderer's first emission. The literal value
20480        // matches the well-known HTTP-alt port the `pleme-computeunit`
20481        // library chart already emits as its `trigger.service.port`
20482        // default — by construction the same value the substrate
20483        // assumes about every Servico's in-cluster L4 listener.
20484        assert_eq!(
20485            DEFAULT_SERVICO_PORT, 8080,
20486            "canonical Servico port literal must remain `8080` verbatim — \
20487             this is the value both the `Entrada::port` serde default and the \
20488             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
20489        );
20490    }
20491
20492    #[test]
20493    fn default_port_helper_returns_canonical_servico_port_constant() {
20494        // The bridge-arm — pins that the [`default_port`] helper
20495        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
20496        // attribute hooks routes through the lifted
20497        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
20498        // literal. A future refactor that re-introduces the `8080`
20499        // literal at the helper's return site (silently re-opening
20500        // the drift footgun this lift closed) surfaces here ahead of
20501        // every author-side `(:entrada (:host … :para …))` slot
20502        // without an explicit `:port`. Peer with the
20503        // `default_namespace_re_export_points_at_caixa_core_canonical`
20504        // pin on the caixa-mesh-side re-export axis.
20505        assert_eq!(
20506            default_port(),
20507            DEFAULT_SERVICO_PORT,
20508            "the serde-default helper must route through the lifted constant"
20509        );
20510    }
20511
20512    #[test]
20513    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
20514        // The end-to-end pin — an author-surface `(:entrada (:host …
20515        // :para …))` without an explicit `:port` slot deserializes to
20516        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
20517        // verbatim. Routes the canonical lifted constant through both
20518        // the serde-default machinery (the `#[serde(default =
20519        // "default_port")]` attribute) and the typed-value-shape
20520        // contract (the resulting [`Entrada::port`] value). A future
20521        // refactor that drifts either axis — replacing the serde
20522        // hook's helper, changing the typed slot's wire shape — would
20523        // surface here before any per-renderer's CNP / Gateway /
20524        // HTTPRoute emission consumed the drifted default.
20525        let entrada: Entrada =
20526            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
20527        assert_eq!(
20528            entrada.port, DEFAULT_SERVICO_PORT,
20529            "the serde default must materialize as the lifted canonical Servico port"
20530        );
20531    }
20532
20533    #[test]
20534    fn servico_port_min_pins_canonical_accept_set_floor() {
20535        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
20536        // verbatim `1` literal every typed `:entrada :port` acceptance
20537        // gate keys off. Peer with the
20538        // [`default_servico_port_constant_pins_canonical_8080_literal`]
20539        // discipline on the canonical-Servico-port-constant axis: a
20540        // future refactor that drifts the accept-set floor out from
20541        // under the sole consumer at [`AplicacaoSpec::validate`]'s
20542        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
20543        // every per-`:entrada` `EntradaPortZero` diagnostic. The
20544        // literal value matches the IANA-registered TCP/UDP port
20545        // space floor (`1..=65535` — port `0` is the "any ephemeral"
20546        // sentinel, not a well-defined destination the substrate's
20547        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
20548        // axis can honor).
20549        assert_eq!(
20550            SERVICO_PORT_MIN, 1,
20551            "canonical Servico port accept-set floor must remain `1` verbatim — \
20552             this is the value the `AplicacaoSpec::validate` gate at \
20553             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
20554        );
20555    }
20556
20557    #[test]
20558    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
20559        // The cross-const invariant pin — the substrate's canonical
20560        // default port must satisfy its own accept-set floor by
20561        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
20562        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
20563        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
20564        // override the operator pins through a future
20565        // `:placement :default-port` slot that lands out-of-range, a
20566        // per-edition Servico-port migration that lifted the floor
20567        // above the previous default without coordinating the pair —
20568        // would silently invalidate the serde-default emission at
20569        // every author-side `(:entrada (:host … :para …))` slot
20570        // without an explicit `:port`: the default port would fall
20571        // below the accept-set floor, the `AplicacaoSpec::validate`
20572        // gate would reject every default-carrying Aplicacao as
20573        // `EntradaPortZero`, and the substrate's typed
20574        // `(defcaixa … :kind Aplicacao)` surface would fail validate
20575        // on every Aplicacao whose author omitted `:entrada :port`
20576        // for the substrate's chosen default — a class of authoring-
20577        // surface footguns the compile-time pin structurally closes.
20578        // Peer with the
20579        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
20580        // (27f9b34) cross-const invariant pin discipline on the peer
20581        // canonical-Helm-per-values-block child-chart-enablement-toggle
20582        // axis pair.
20583        assert!(
20584            SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
20585            "the substrate's canonical default port ({DEFAULT_SERVICO_PORT}) must \
20586             satisfy its own accept-set floor (SERVICO_PORT_MIN = {SERVICO_PORT_MIN}) — \
20587             every default-carrying `(:entrada (:host … :para …))` slot without an \
20588             explicit `:port` inherits `DEFAULT_SERVICO_PORT` through the serde default \
20589             hook and must pass the `AplicacaoSpec::validate` floor gate by construction"
20590        );
20591    }
20592
20593    #[test]
20594    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
20595        // The gate-site pin — asserts the `AplicacaoSpec::validate`
20596        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
20597        // `EntradaPortZero` diagnostic on the below-floor input
20598        // `port: 0` (the only below-floor value the `u16` field can
20599        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
20600        // is the singleton `{0}`). A future refactor that drifts the
20601        // gate off the lifted const (silently re-introducing an
20602        // inline `if e.port == 0` byte-check) surfaces here — the
20603        // pin cannot distinguish `< 1` from `== 0` on the current
20604        // floor, but it *does* pin that the diagnostic fires on `0`
20605        // through whichever gate is wired, so any future accept-set
20606        // floor migration (a hypothetical unprivileged-only
20607        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
20608        // update this test alongside the const declaration —
20609        // structurally guaranteeing the gate + accept-set + pin
20610        // trio move together. Peer with the
20611        // [`rejects_zero_entrada_port`] behavioral pin on the same
20612        // per-`:entrada :port` axis — that pin asserts the pre-lift
20613        // behavioral contract (`port: 0` → `EntradaPortZero`); this
20614        // pin adds the structural link to the lifted floor const.
20615        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
20616        let mut s = three_member_spec();
20617        s.entrada.as_mut().unwrap().port = 0;
20618        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
20619    }
20620
20621    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
20622
20623    #[test]
20624    fn membro_serde_keys_match_lifted_membro_key_consts() {
20625        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
20626        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
20627        // name the exact camelCase JSON keys the
20628        // `#[serde(rename_all = "camelCase")]` attribute on
20629        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
20630        // that each canonical byte-sequence appears verbatim in the
20631        // JSON — a future accidental `rename_all = "snake_case"` /
20632        // `"kebab-case"` / verbatim-field-name flip at the derive
20633        // attribute (any of which would silently break every downstream
20634        // JSON consumer that reaches for one of the two consts via
20635        // `Value::get(...)`) surfaces here as a build-time test failure
20636        // at `aplicacao.rs`, not as an apply-time
20637        // `.get(<stale-canonical-const>)` returning `None` far from the
20638        // derive-attr drift's commit. Peer with the sibling
20639        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
20640        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
20641        // same discipline the SupervisorSpec top-level lift established,
20642        // extended here to the M3 [`Membro`] per-`:membros` axis.
20643        let m = Membro {
20644            caixa: "catalog".into(),
20645            versao: "^0.1".into(),
20646        };
20647        let json = serde_json::to_string(&m).unwrap();
20648        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
20649            let quoted = format!("\"{key}\"");
20650            assert!(
20651                json.contains(&quoted),
20652                "serialized Membro must carry the lifted MEMBRO_KEY_* \
20653                 byte-sequence {quoted} verbatim in the JSON emission \
20654                 (got: {json})",
20655            );
20656        }
20657    }
20658
20659    #[test]
20660    fn membro_key_consts_are_pairwise_distinct() {
20661        // Cross-axis drift-detection pin: a future collapse of the two
20662        // canonical [`Membro`] per-entry byte-strings onto the same
20663        // value (e.g. an accidental copy-paste flip of
20664        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
20665        // silently reroute every downstream probe on one axis onto the
20666        // sibling axis's overlay entry and pass every propagation-probe
20667        // test that expected only the stale axis's value. Peer of the
20668        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
20669        // (40cc4e5).
20670        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
20671        for (i, a) in all.iter().enumerate() {
20672            for b in all.iter().skip(i + 1) {
20673                assert_ne!(
20674                    a, b,
20675                    "MEMBRO_KEY_* consts must be pairwise-distinct \
20676                     canonical byte-sequences — got `{a}` == `{b}`",
20677                );
20678            }
20679        }
20680    }
20681
20682    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
20683    //    URL-path fallback resolver every HTTPRoute-aware renderer
20684    //    reaching for a per-rule path-list resolution routes through.
20685    //    The four pin tests below fix the four-way accept-set the
20686    //    resolver must always honor: (:paths-non-empty-verbatim,
20687    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
20688    //    :paths-preserves-order-across-multiple-entries) — drift on any
20689    //    arm surfaces at caixa-core build time rather than at cluster-
20690    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
20691    //    sibling `:politicas` typed-primitive dispatch axis.
20692
20693    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
20694        Entrada {
20695            host: "example.com".into(),
20696            para: "cart".into(),
20697            paths: paths.into_iter().map(String::from).collect(),
20698            port: DEFAULT_SERVICO_PORT,
20699        }
20700    }
20701
20702    #[test]
20703    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
20704        // The typed `:entrada :paths` slot carries an author-declared
20705        // list — the resolver returns each entry verbatim, no
20706        // catch-all substitution. The canonical "author declared
20707        // paths, honor them verbatim" arm of the path-list dispatch.
20708        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
20709        assert_eq!(
20710            e.resolved_paths(),
20711            vec!["/api/cart", "/api/products"],
20712            "resolved_paths must return each `:entrada :paths` entry \
20713             verbatim when the typed slot is non-empty (got {:?})",
20714            e.resolved_paths(),
20715        );
20716    }
20717
20718    #[test]
20719    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
20720        // Empty `:entrada :paths` slot — the resolver substitutes the
20721        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
20722        // catch-all fallback verbatim. Pins the empty-arm of the
20723        // resolver's four-way accept-set against a future silent
20724        // detour that returned an empty Vec (which would emit an
20725        // HTTPRoute with zero rules — silently dropping every
20726        // external `:entrada` flow at admission time), routed to a
20727        // different fallback shape, or dropped the catch-all
20728        // altogether.
20729        let e = entrada_with_paths(vec![]);
20730        assert_eq!(
20731            e.resolved_paths(),
20732            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
20733            "resolved_paths on empty `:entrada :paths` must fall back \
20734             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
20735             all — got {:?}",
20736            e.resolved_paths(),
20737        );
20738    }
20739
20740    #[test]
20741    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
20742        // Single-entry `:entrada :paths` — the resolver returns the
20743        // single declared path verbatim, NOT the catch-all fallback
20744        // (author declared a path, honor it — the empty-arm and the
20745        // len-1 arm are semantically distinct axes of the resolver's
20746        // accept-set). Pins that the resolver treats "author declared
20747        // one path" as authored input, not as the empty case.
20748        let e = entrada_with_paths(vec!["/api/only"]);
20749        assert_eq!(
20750            e.resolved_paths(),
20751            vec!["/api/only"],
20752            "resolved_paths on single-entry `:entrada :paths` must \
20753             return the declared path verbatim, NOT the catch-all \
20754             fallback (got {:?})",
20755            e.resolved_paths(),
20756        );
20757    }
20758
20759    #[test]
20760    fn resolved_paths_preserves_author_declared_order() {
20761        // The `:entrada :paths` list is author-ordered — the resolver
20762        // preserves the author's declaration order verbatim, since
20763        // per-rule dispatch order at the K8s Gateway API HTTPRoute
20764        // consumer is significant (first-match-wins under the
20765        // path-prefix matcher). Pins against a future silent
20766        // re-sort / dedup / normalize detour that reordered author
20767        // input.
20768        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
20769        assert_eq!(
20770            e.resolved_paths(),
20771            vec!["/z/last", "/a/first", "/m/mid"],
20772            "resolved_paths must preserve author-declared `:entrada \
20773             :paths` order verbatim — got {:?}",
20774            e.resolved_paths(),
20775        );
20776    }
20777
20778    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
20779    //    slot `&[String]` slice accessor every per-`:entrada` consumer
20780    //    that must see the author's declaration verbatim (not the
20781    //    fallback-applied projection the sibling `resolved_paths`
20782    //    returns) routes through. The three pin tests below fix the
20783    //    accept-set the accessor must honor: (:non-empty-byte-equal,
20784    //    :empty-projects-empty-slice, :preserves-author-declared-order)
20785    //    — drift on any arm surfaces at caixa-core build time rather
20786    //    than at cluster-apply time. Peer discipline with the sibling
20787    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
20788    //    peer M3 mesh-slot `Vec<String>`-carry axis.
20789
20790    #[test]
20791    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
20792        // Byte-equal pin: [`Entrada::paths`] must project the raw
20793        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
20794        // slice borrowed from the typed slot's own [`Vec<String>`]
20795        // storage — no re-ordering, no dedup, no per-entry normalization,
20796        // no fallback substitution (the fallback-applying projection is
20797        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
20798        // a future silent detour that re-normalized the list, dropped
20799        // duplicates the [`AplicacaoSpec::validate`]
20800        // `EntradaPathDuplicate` refusal already rejects at build time,
20801        // or (most severe) accidentally routed through the fallback-
20802        // applying sibling and returned the substrate catch-all when
20803        // the author declared an empty list — collapsing the raw-slot
20804        // and fallback-applied axes into one and breaking the
20805        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
20806        //
20807        // Peer of the sibling
20808        // [`Placement::clusters`]-shape byte-equal pin
20809        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
20810        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
20811        let fixtures: Vec<Vec<String>> = vec![
20812            Vec::new(),
20813            vec!["/api/cart".into()],
20814            vec!["/api/cart".into(), "/api/products".into()],
20815            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
20816        ];
20817        for paths in fixtures {
20818            let e = Entrada {
20819                host: "example.com".into(),
20820                para: "cart".into(),
20821                paths: paths.clone(),
20822                port: DEFAULT_SERVICO_PORT,
20823            };
20824            assert_eq!(
20825                e.paths(),
20826                paths.as_slice(),
20827                "Entrada::paths must return :entrada :paths verbatim \
20828                 (got {:?}, expected {:?})",
20829                e.paths(),
20830                paths.as_slice(),
20831            );
20832            assert_eq!(
20833                e.paths(),
20834                e.paths.as_slice(),
20835                "Entrada::paths accessor and .paths.as_slice() field \
20836                 access must byte-equal — the accessor is the substrate-\
20837                 primitive typed dispatch every downstream per-`:entrada` \
20838                 raw-slot path-list consumer must route through",
20839            );
20840            assert_eq!(
20841                e.paths().len(),
20842                e.paths.len(),
20843                "Entrada::paths().len() must byte-equal self.paths.len() \
20844                 — a length drift would silently split the paired \
20845                 pre-flight cascade-head `.is_empty()` probe input in \
20846                 the sibling [`Entrada::resolved_paths`] resolver from \
20847                 the per-entry validate loop's traversal input in \
20848                 [`AplicacaoSpec::validate`]",
20849            );
20850        }
20851    }
20852
20853    #[test]
20854    fn resolved_paths_reads_through_lifted_paths_accessor() {
20855        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
20856        // pre-flight `.paths().is_empty()` cascade-head probe (which
20857        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
20858        // catch-all fallback arm when the accessor projects the empty
20859        // slice) and the per-entry `.paths().iter().map(String::as_str)`
20860        // projection (which must reach every entry in the same order
20861        // the accessor projects, so the sibling
20862        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
20863        // per-entry projection stay in lockstep by construction) must
20864        // both key off the lifted accessor. Pins the two-site coherence
20865        // by exercising each production consumer end-to-end: (1) the
20866        // catch-all-fallback arm under the empty slice, (2) the
20867        // author-declared-verbatim arm under a two-entry cohort whose
20868        // per-entry projection must byte-equal the input's per-entry
20869        // author-declared paths in the author's declared order.
20870        //
20871        // Peer of the sibling M3
20872        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
20873        // `validate_placement_reads_through_lifted_clusters_accessor`
20874        // on the sibling `Placement::clusters` reader-site convergence.
20875        let empty = entrada_with_paths(vec![]);
20876        assert_eq!(
20877            empty.resolved_paths(),
20878            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
20879            "resolved_paths on empty :entrada :paths must trip the \
20880             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
20881             catch-all fallback — routing through the lifted paths() \
20882             accessor must not silently drop the fallback arm",
20883        );
20884
20885        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
20886        assert_eq!(
20887            declared.resolved_paths(),
20888            vec!["/api/cart", "/api/products"],
20889            "resolved_paths on non-empty :entrada :paths must return each \
20890             entry verbatim in the author's declared order — routing \
20891             through the lifted paths() accessor must not silently \
20892             reorder or drop entries",
20893        );
20894        // Byte-equal pin against the raw-slot accessor to keep the
20895        // fallback-applying resolver's per-entry projection input in
20896        // lockstep with the raw-slot accessor's projection.
20897        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
20898        assert_eq!(
20899            declared.resolved_paths(),
20900            raw_projected,
20901            "resolved_paths non-empty projection must byte-equal the \
20902             lifted paths() accessor's per-entry String::as_str projection \
20903             — the two projections share the same input slice by \
20904             construction, so any drift here would surface a silent \
20905             re-ordering / dedup / normalization detour in the resolver",
20906        );
20907    }
20908
20909    #[test]
20910    fn validate_reads_through_lifted_entrada_paths_accessor() {
20911        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
20912        // per-entry value-shape gate's `for p in e.paths()` traversal
20913        // (which must reach every entry in the same order the accessor
20914        // projects, so both the per-entry `EntradaPathEmpty` /
20915        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
20916        // the duplicate-detection HashSet insert that trips
20917        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
20918        // projection) must route through the lifted accessor. Pins the
20919        // coherence by exercising each production consumer end-to-end:
20920        // (1) the `EntradaPathEmpty` refusal fires on the second entry
20921        // of a two-entry cohort whose head is valid but tail is empty
20922        // (which requires the loop to reach the second entry through
20923        // the accessor), and (2) the `EntradaPathDuplicate` refusal
20924        // fires on the second entry of a two-entry cohort that shares
20925        // a path (which requires the loop to reach both entries — a
20926        // first-entry-only projection would silently pass since the
20927        // dedup HashSet has room for the first insert).
20928        //
20929        // Peer of the sibling
20930        // `validate_placement_reads_through_lifted_clusters_accessor`
20931        // on the sibling `Placement::clusters` reader-site convergence.
20932        let base = crate::AplicacaoSpec {
20933            membros: vec![crate::Membro {
20934                caixa: "cart".into(),
20935                versao: "^0.1".into(),
20936            }],
20937            contratos: Vec::new(),
20938            politicas: crate::MeshPolicy::default(),
20939            placement: crate::Placement {
20940                estrategia: crate::PlacementStrategy::SingleNode,
20941                clusters: vec!["rio".into()],
20942                shard_key: None,
20943                affinity: None,
20944            },
20945            entrada: Some(Entrada {
20946                host: "example.com".into(),
20947                para: "cart".into(),
20948                paths: vec!["/api/cart".into(), String::new()],
20949                port: DEFAULT_SERVICO_PORT,
20950            }),
20951        };
20952        assert_eq!(
20953            base.validate(),
20954            Err(crate::AplicacaoError::EntradaPathEmpty),
20955            "validate must trip EntradaPathEmpty on the second entry of \
20956             a two-entry cohort — routing through the lifted paths() \
20957             accessor must not silently short-circuit the loop at the \
20958             valid head entry",
20959        );
20960
20961        let mut dup = base;
20962        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
20963        assert_eq!(
20964            dup.validate(),
20965            Err(crate::AplicacaoError::EntradaPathDuplicate {
20966                path: "/api/cart".into(),
20967            }),
20968            "validate must trip EntradaPathDuplicate on the second entry \
20969             of a two-entry cohort that shares a path — routing through \
20970             the lifted paths() accessor must not silently short-circuit \
20971             the dedup HashSet insert at the first entry",
20972        );
20973    }
20974
20975    // ── Entrada::hostname / Entrada::hostnames — the substrate-
20976    //    canonical per-`:entrada` DNS-hostname resolver pair every
20977    //    Gateway-API-aware renderer reaching for a per-listener
20978    //    singular `hostname:` filter (Gateway) or a per-route plural
20979    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
20980    //    The three pin tests below fix the two-way accept-set the pair
20981    //    must always honor: (:singular-byte-equal-to-host,
20982    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
20983    //    on any arm surfaces at caixa-core build time rather than at
20984    //    cluster-apply time when the API server refuses the HTTPRoute
20985    //    for non-intersecting hostname filters. Peer discipline with
20986    //    the sibling `resolved_paths` accept-set pin block above on the
20987    //    per-`:entrada` path-list resolver axis.
20988
20989    fn entrada_with_host(host: &str) -> Entrada {
20990        Entrada {
20991            host: host.into(),
20992            para: "cart".into(),
20993            paths: Vec::new(),
20994            port: DEFAULT_SERVICO_PORT,
20995        }
20996    }
20997
20998    #[test]
20999    fn hostname_returns_entrada_host_byte_equal() {
21000        // The canonical singular-axis pin: [`Entrada::hostname`] must
21001        // return the `:entrada :host` field byte-for-byte, borrowed
21002        // from the typed slot's own [`String`] storage. Pins against a
21003        // future silent detour that re-normalized the host (an
21004        // accidental `.to_lowercase()` — validate_entrada_host already
21005        // enforces lowercase, so any re-normalization is redundant + a
21006        // drift surface between the validator and the accessor), a
21007        // trailing-`.` fully-qualified DNS shape substitution, or a
21008        // Punycode round-trip that lowered a Unicode host through IDNA.
21009        let e = entrada_with_host("checkout.quero.cloud");
21010        assert_eq!(
21011            e.hostname(),
21012            "checkout.quero.cloud",
21013            "Entrada::hostname must return :entrada :host verbatim \
21014             (got {:?})",
21015            e.hostname(),
21016        );
21017        assert_eq!(
21018            e.hostname(),
21019            e.host.as_str(),
21020            "Entrada::hostname must byte-equal the .host field access",
21021        );
21022    }
21023
21024    #[test]
21025    fn hostnames_returns_singleton_of_hostname_accessor() {
21026        // The pair-invariant pin: [`Entrada::hostnames`] must always
21027        // return exactly `vec![hostname()]` — the singleton list whose
21028        // sole entry is the substrate's canonical per-`:entrada`
21029        // singular hostname. Pins the two-consumer coherence axis: the
21030        // Gateway listener's singular `hostname:` filter and the
21031        // HTTPRoute's plural `spec.hostnames[]` filter list must
21032        // agree, else the Gateway API v1.x conformance layer rejects
21033        // the HTTPRoute at attach time with
21034        // `Accepted:False/NoMatchingParent` (the parent Gateway's
21035        // listener hostname doesn't intersect the route's hostname
21036        // filter list) — a divergence whose apply-time symptom is far
21037        // from any single-site commit and never surfaces in the
21038        // emitted YAML. Pinning the pair-invariant here makes any
21039        // future accidental split (an accidental `.to_string() + "."`
21040        // trailing-`.` on the plural side that didn't land on the
21041        // singular side, an accidental prefix stripping on one axis,
21042        // an accidental wildcard prepend the SNI fan-out overlay
21043        // authors on the plural side without a paired singular
21044        // migration) trip at caixa-core build time.
21045        let e = entrada_with_host("checkout.quero.cloud");
21046        assert_eq!(
21047            e.hostnames(),
21048            vec![e.hostname()],
21049            "Entrada::hostnames must return `vec![hostname()]` under \
21050             the pair-invariant — got {:?} vs. singleton {:?}",
21051            e.hostnames(),
21052            vec![e.hostname()],
21053        );
21054    }
21055
21056    #[test]
21057    fn hostnames_is_singleton_under_single_host_author_surface() {
21058        // The singleton-shape pin: under today's single-hostname-per-
21059        // `:entrada` author surface (the `:host` slot is a single
21060        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
21061        // must always return a list of length exactly one. Pins
21062        // against a future silent detour that returned an empty list
21063        // (which would emit an HTTPRoute with `spec.hostnames: []` —
21064        // matching every incoming Host header regardless of the
21065        // Aplicacao's declared ingress apex, silently over-matching
21066        // every foreign VirtualHost the parent Gateway also fronts) or
21067        // a duplicated entry (which the Gateway API v1.x parser
21068        // accepts as a `[]-length-2 list of equal hostnames]` but
21069        // whose semantics differ from the intended singleton). The
21070        // author-surface extension point ("a future `:entrada
21071        // :alt-hosts` list overlay" the docstring names) is the sole
21072        // future axis that flips this pin — that migration will re-
21073        // author this test to pin the new plural cardinality.
21074        let e = entrada_with_host("checkout.quero.cloud");
21075        assert_eq!(
21076            e.hostnames().len(),
21077            1,
21078            "Entrada::hostnames must be a singleton under today's \
21079             single-hostname-per-`:entrada` author surface — got \
21080             length {}: {:?}",
21081            e.hostnames().len(),
21082            e.hostnames(),
21083        );
21084    }
21085
21086    // ── Entrada::destination — the substrate-canonical per-`:entrada`
21087    //    destination-Servico scalar accessor every Gateway-API
21088    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
21089    //    discriminator arg (HTTPRoute name composer) or a per-rule
21090    //    `backendRefs[0].name` axis routes through. The two pin tests
21091    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
21092    //    either arm surfaces at caixa-core build time rather than at
21093    //    cluster-apply time when an HTTPRoute's `metadata.name` and
21094    //    `backendRefs[]` silently disagree on which destination Servico
21095    //    the ingress fronts. Peer discipline with the sibling
21096    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
21097    //    blocks above on the per-`:entrada` path-list / DNS-hostname
21098    //    resolver axes.
21099
21100    #[test]
21101    fn destination_returns_entrada_para_byte_equal() {
21102        // The canonical destination-scalar pin: [`Entrada::destination`]
21103        // must return the `:entrada :para` field byte-for-byte, borrowed
21104        // from the typed slot's own [`String`] storage. Pins against a
21105        // future silent detour that re-normalized the destination (an
21106        // accidental `.to_lowercase()` — the destination Servico is
21107        // already validated as a DNS-1123 label upstream, so any
21108        // re-normalization is redundant + a drift surface between the
21109        // validator and the accessor), a namespace-prefix rewrite (an
21110        // accidental `format!("{namespace}/{para}")` per-CR fully-
21111        // qualified rewrite that didn't land on the peer axis), or a
21112        // per-cluster suffix stamp the operator authors on one
21113        // consumer without the other.
21114        for para in ["cart", "checkout", "catalog", "orders-v2"] {
21115            let e = Entrada {
21116                host: "checkout.quero.cloud".into(),
21117                para: para.into(),
21118                paths: Vec::new(),
21119                port: DEFAULT_SERVICO_PORT,
21120            };
21121            assert_eq!(
21122                e.destination(),
21123                para,
21124                "Entrada::destination must return :entrada :para verbatim \
21125                 (got {:?}, expected {para:?})",
21126                e.destination(),
21127            );
21128            assert_eq!(
21129                e.destination(),
21130                e.para.as_str(),
21131                "Entrada::destination must byte-equal the .para field access",
21132            );
21133        }
21134    }
21135
21136    #[test]
21137    fn destination_borrows_from_entrada_para_storage() {
21138        // The borrow-not-copy pin: [`Entrada::destination`] must
21139        // return a `&str` slice that borrows from the typed slot's
21140        // own [`String`] storage — same-address invariant with
21141        // `entrada.para.as_str()`. Pins against a future silent detour
21142        // that allocated a fresh `String` (`self.para.clone()` in the
21143        // body would type-check but silently drop the borrow, and
21144        // every downstream consumer that assumed the returned slice
21145        // outlives `&self` would break on a stale-reference use-after-
21146        // free). Peer with the sibling `hostname_returns_entrada_
21147        // host_byte_equal` on the singular-DNS-hostname axis.
21148        let e = entrada_with_host("checkout.quero.cloud");
21149        let dest = e.destination();
21150        let para_slice = e.para.as_str();
21151        assert_eq!(
21152            dest.as_ptr(),
21153            para_slice.as_ptr(),
21154            "Entrada::destination must borrow from the .para String's \
21155             backing storage — a fresh allocation here means the \
21156             accessor no longer names the substrate-primitive typed \
21157             dispatch and every downstream consumer would silently \
21158             carry a detached copy",
21159        );
21160        assert_eq!(
21161            dest.len(),
21162            para_slice.len(),
21163            "Entrada::destination and .para.as_str() must byte-equal in \
21164             length as well as in address",
21165        );
21166    }
21167
21168    #[test]
21169    fn port_returns_entrada_port_verbatim_across_permutations() {
21170        // The canonical L4-port-scalar pin: [`Entrada::port`] must
21171        // return the `:entrada :port` field verbatim as a `u16` across
21172        // every author-declared value in the validated accept-set
21173        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
21174        // silent detour that clamped the port (an accidental
21175        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
21176        // land on the peer [`AplicacaoSpec::port_for_destination`]
21177        // resolver), rewrote it through a per-cluster port-remap table
21178        // the operator authors on one consumer without the other, or
21179        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
21180        // serde-default value (which would silently collapse the
21181        // distinction between "author explicitly declared `:port 8080`"
21182        // and "author omitted the slot and inherited the default" the
21183        // future per-cluster override slot depends on). Peer with the
21184        // sibling `destination_returns_entrada_para_byte_equal` +
21185        // `hostname_returns_entrada_host_byte_equal` pins on the
21186        // per-`:entrada` `&str` scalar axes.
21187        for port in [
21188            SERVICO_PORT_MIN,
21189            DEFAULT_SERVICO_PORT,
21190            8443u16,
21191            9090u16,
21192            u16::MAX,
21193        ] {
21194            let e = Entrada {
21195                host: "checkout.quero.cloud".into(),
21196                para: "cart".into(),
21197                paths: Vec::new(),
21198                port,
21199            };
21200            assert_eq!(
21201                e.port(),
21202                port,
21203                "Entrada::port must return :entrada :port verbatim \
21204                 (got {}, expected {port})",
21205                e.port(),
21206            );
21207            assert_eq!(
21208                e.port(),
21209                e.port,
21210                "Entrada::port accessor and .port field access must \
21211                 byte-equal — the accessor is the substrate-primitive \
21212                 typed dispatch every downstream L4-port consumer must \
21213                 route through",
21214            );
21215        }
21216    }
21217
21218    #[test]
21219    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
21220        // Two-consumer coherence pin: the
21221        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
21222        // (which reads through [`Entrada::port`] to compare against
21223        // [`SERVICO_PORT_MIN`]) and the
21224        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
21225        // through [`Entrada::port`] to emit the per-destination
21226        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
21227        // lifted accessor, so any future rebrand on the typed slot's
21228        // reader shape lands at exactly one place. Pins the two-site
21229        // coherence by exercising a below-floor port through validate
21230        // (which must reject) and a validated in-accept-set port through
21231        // port_for_destination (which must emit the same value the
21232        // accessor returns).
21233        let mut spec = three_member_spec();
21234        if let Some(e) = spec.entrada.as_mut() {
21235            e.port = 0;
21236        }
21237        assert_eq!(
21238            spec.validate().unwrap_err(),
21239            AplicacaoError::EntradaPortZero,
21240            "validate must reject `:entrada :port 0` through the lifted \
21241             Entrada::port accessor — port zero lies below \
21242             SERVICO_PORT_MIN and the validator routes through port() \
21243             to name the floor",
21244        );
21245
21246        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
21247            let mut spec = three_member_spec();
21248            if let Some(e) = spec.entrada.as_mut() {
21249                e.port = port;
21250            }
21251            spec.validate().expect(
21252                "entrada with in-accept-set :port must validate — the \
21253                 structural-floor gate reads through Entrada::port",
21254            );
21255            let entrada_ref = spec.entrada().expect(":entrada present");
21256            assert_eq!(
21257                spec.port_for_destination(entrada_ref.destination()),
21258                entrada_ref.port(),
21259                "port_for_destination(entrada.destination()) must equal \
21260                 entrada.port() — the two consumers of the per-:entrada \
21261                 L4-port axis (validator, per-destination resolver) both \
21262                 route through Entrada::port",
21263            );
21264        }
21265    }
21266
21267    #[test]
21268    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
21269        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
21270        // must return the `:contratos :de` field byte-for-byte, borrowed
21271        // from the typed slot's own [`String`] storage. Peer of the
21272        // sibling `destination_returns_entrada_para_byte_equal` pin on
21273        // the per-`:entrada` axis — same "the substrate-primitive
21274        // accessor must byte-equal the raw field access verbatim across
21275        // every author-declared value" discipline extended to the
21276        // per-`:contratos` caller arm. Pins against a future silent
21277        // detour that re-normalized the caller (an accidental
21278        // `.to_lowercase()` — every `:contratos :de` is validated as a
21279        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
21280        // re-normalization is redundant + a drift surface between the
21281        // validator and the accessor), a namespace-prefix rewrite (an
21282        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
21283        // rewrite that didn't land on the peer axis), or a per-cluster
21284        // suffix stamp the operator authors on one consumer without the
21285        // other.
21286        for de in ["cart", "checkout", "catalog", "orders-v2"] {
21287            let c = WitContract {
21288                de: de.into(),
21289                para: "downstream".into(),
21290                wit: "wasi:http/proxy".into(),
21291                endpoint: Some("/lookup".into()),
21292                subject: None,
21293                slot: None,
21294            };
21295            assert_eq!(
21296                c.source(),
21297                de,
21298                "WitContract::source must return :contratos :de verbatim \
21299                 (got {:?}, expected {de:?})",
21300                c.source(),
21301            );
21302            assert_eq!(
21303                c.source(),
21304                c.de.as_str(),
21305                "WitContract::source must byte-equal the .de field access",
21306            );
21307        }
21308    }
21309
21310    #[test]
21311    fn wit_contract_source_borrows_from_de_storage() {
21312        // The borrow-not-copy pin: [`WitContract::source`] must return a
21313        // `&str` slice that borrows from the typed slot's own [`String`]
21314        // storage — same-address invariant with `c.de.as_str()`. Pins
21315        // against a future silent detour that allocated a fresh `String`
21316        // (`self.de.clone()` in the body would type-check but silently
21317        // drop the borrow, and every downstream consumer that assumed
21318        // the returned slice outlives `&self` would break on a stale-
21319        // reference use-after-free). Peer of the sibling
21320        // `destination_borrows_from_entrada_para_storage` on the
21321        // per-`:entrada` axis.
21322        let c = WitContract {
21323            de: "cart".into(),
21324            para: "catalog".into(),
21325            wit: "wasi:http/proxy".into(),
21326            endpoint: Some("/lookup".into()),
21327            subject: None,
21328            slot: None,
21329        };
21330        let src = c.source();
21331        let de_slice = c.de.as_str();
21332        assert_eq!(
21333            src.as_ptr(),
21334            de_slice.as_ptr(),
21335            "WitContract::source must borrow from the .de String's \
21336             backing storage — a fresh allocation here means the \
21337             accessor no longer names the substrate-primitive typed \
21338             dispatch and every downstream consumer would silently \
21339             carry a detached copy",
21340        );
21341        assert_eq!(
21342            src.len(),
21343            de_slice.len(),
21344            "WitContract::source and .de.as_str() must byte-equal in \
21345             length as well as in address",
21346        );
21347    }
21348
21349    #[test]
21350    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
21351        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
21352        // must return the `:contratos :para` field byte-for-byte,
21353        // borrowed from the typed slot's own [`String`] storage. Peer of
21354        // the sibling `destination_returns_entrada_para_byte_equal` on
21355        // the per-`:entrada` axis — both accessors name "the destination-
21356        // Servico byte-string" concept on their respective mesh-slot
21357        // atoms (per-ingress apex vs. per-typed-edge callee) and both
21358        // must project the underlying `.para` field verbatim so every
21359        // downstream renderer that composes them with peer accessors
21360        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
21361        // per-edge L4 port emit site) reads the same byte-string the
21362        // author declared.
21363        for para in ["catalog", "payment", "orders", "inventory-v3"] {
21364            let c = WitContract {
21365                de: "cart".into(),
21366                para: para.into(),
21367                wit: "wasi:http/proxy".into(),
21368                endpoint: Some("/lookup".into()),
21369                subject: None,
21370                slot: None,
21371            };
21372            assert_eq!(
21373                c.destination(),
21374                para,
21375                "WitContract::destination must return :contratos :para \
21376                 verbatim (got {:?}, expected {para:?})",
21377                c.destination(),
21378            );
21379            assert_eq!(
21380                c.destination(),
21381                c.para.as_str(),
21382                "WitContract::destination must byte-equal the .para \
21383                 field access",
21384            );
21385        }
21386    }
21387
21388    #[test]
21389    fn wit_contract_destination_borrows_from_para_storage() {
21390        // The borrow-not-copy pin: [`WitContract::destination`] must
21391        // return a `&str` slice that borrows from the typed slot's own
21392        // [`String`] storage — same-address invariant with
21393        // `c.para.as_str()`. Peer of the sibling
21394        // `destination_borrows_from_entrada_para_storage` on the
21395        // per-`:entrada` axis.
21396        let c = WitContract {
21397            de: "cart".into(),
21398            para: "catalog".into(),
21399            wit: "wasi:http/proxy".into(),
21400            endpoint: Some("/lookup".into()),
21401            subject: None,
21402            slot: None,
21403        };
21404        let dest = c.destination();
21405        let para_slice = c.para.as_str();
21406        assert_eq!(
21407            dest.as_ptr(),
21408            para_slice.as_ptr(),
21409            "WitContract::destination must borrow from the .para \
21410             String's backing storage — a fresh allocation here means \
21411             the accessor no longer names the substrate-primitive typed \
21412             dispatch and every downstream consumer would silently \
21413             carry a detached copy",
21414        );
21415        assert_eq!(
21416            dest.len(),
21417            para_slice.len(),
21418            "WitContract::destination and .para.as_str() must byte-equal \
21419             in length as well as in address",
21420        );
21421    }
21422
21423    #[test]
21424    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
21425        // The canonical per-`:contratos` WIT-world-reference scalar pin:
21426        // [`WitContract::world_ref`] must return the `:contratos :wit`
21427        // field byte-for-byte, borrowed from the typed slot's own
21428        // [`String`] storage. Sibling of the peer per-`:contratos`
21429        // [`WitContract::source`] / [`WitContract::destination`]
21430        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
21431        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
21432        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
21433        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
21434        // "the substrate-primitive accessor must byte-equal the raw
21435        // field access verbatim across every author-declared value"
21436        // discipline extended to the per-`:contratos` WIT-world arm.
21437        // Pins against a future silent detour that re-canonicalized the
21438        // WIT world reference (an accidental `.to_lowercase()` pass that
21439        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
21440        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
21441        // gate is already lowercase-prefixed so any re-normalization is
21442        // redundant + a drift surface between the validator and the
21443        // accessor), an M4-promotion-shape rewrite that formatted a
21444        // typed WIT-world enum through [`Display`] and silently drifted
21445        // the printer output from the source `caixa.lisp`, or a per-
21446        // cluster WIT-alias rewrite that didn't land on the peer field-
21447        // access sites. Five values sweep the shape-dispatch accept-set
21448        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
21449        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
21450        // `wasi:keyvalue/`).
21451        for (wit, endpoint, subject, slot) in [
21452            ("wasi:http/proxy", Some("/lookup"), None, None),
21453            ("http:proxy", Some("/health"), None, None),
21454            ("nats:pub-sub", None, Some("orders.paid"), None),
21455            ("kafka:events", None, Some("checkout-events"), None),
21456            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
21457        ] {
21458            let c = WitContract {
21459                de: "cart".into(),
21460                para: "downstream".into(),
21461                wit: wit.into(),
21462                endpoint: endpoint.map(str::to_string),
21463                subject: subject.map(str::to_string),
21464                slot: slot.map(str::to_string),
21465            };
21466            assert_eq!(
21467                c.world_ref(),
21468                wit,
21469                "WitContract::world_ref must return :contratos :wit \
21470                 verbatim (got {:?}, expected {wit:?})",
21471                c.world_ref(),
21472            );
21473            assert_eq!(
21474                c.world_ref(),
21475                c.wit.as_str(),
21476                "WitContract::world_ref must byte-equal the .wit field \
21477                 access",
21478            );
21479        }
21480    }
21481
21482    #[test]
21483    fn wit_contract_world_ref_borrows_from_wit_storage() {
21484        // The borrow-not-copy pin: [`WitContract::world_ref`] must
21485        // return a `&str` slice that borrows from the typed slot's own
21486        // [`String`] storage — same-address invariant with
21487        // `c.wit.as_str()`. Pins against a future silent detour that
21488        // allocated a fresh `String` (`self.wit.clone()` in the body
21489        // would type-check but silently drop the borrow, and every
21490        // downstream consumer that assumed the returned slice outlives
21491        // `&self` would break on a stale-reference use-after-free — the
21492        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
21493        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
21494        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
21495        // / [`is_pubsub`][WitContract::is_pubsub] /
21496        // [`is_store`][WitContract::is_store] methods route through —
21497        // each borrow from the WitContract's own storage and each would
21498        // silently misbehave if this accessor produced a detached copy).
21499        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
21500        // [`WitContract::destination`] and per-`:entrada`
21501        // [`Entrada::destination`] / [`Entrada::hostname`] and
21502        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
21503        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
21504        let c = WitContract {
21505            de: "cart".into(),
21506            para: "catalog".into(),
21507            wit: "wasi:http/proxy".into(),
21508            endpoint: Some("/lookup".into()),
21509            subject: None,
21510            slot: None,
21511        };
21512        let world = c.world_ref();
21513        let wit_slice = c.wit.as_str();
21514        assert_eq!(
21515            world.as_ptr(),
21516            wit_slice.as_ptr(),
21517            "WitContract::world_ref must borrow from the .wit String's \
21518             backing storage — a fresh allocation here means the \
21519             accessor no longer names the substrate-primitive typed \
21520             dispatch and every downstream consumer would silently carry \
21521             a detached copy",
21522        );
21523        assert_eq!(
21524            world.len(),
21525            wit_slice.len(),
21526            "WitContract::world_ref and .wit.as_str() must byte-equal in \
21527             length as well as in address",
21528        );
21529    }
21530
21531    #[test]
21532    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
21533        // Sibling-triple invariant pin composing all three per-`:contratos`
21534        // substrate-primitive typed dispatches — [`WitContract::source`]
21535        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
21536        // [`WitContract::world_ref`] — at the joint
21537        // `(source(), destination(), world_ref())` call shape every
21538        // renderer that fans on per-edge caller-callee-shape identity
21539        // keys off. The invariant, evaluated per-contract:
21540        //
21541        //   (c.source(), c.destination(), c.world_ref())
21542        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
21543        //
21544        // Closes the last unlifted per-`:contratos` scalar axis — every
21545        // downstream consumer that reads the triple now routes through
21546        // exactly three typed dispatches on the substrate primitive,
21547        // not two typed + one open-coded field access. A future refactor
21548        // that silently split any one accessor's projection (an
21549        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
21550        // canonicalization that didn't reach the peer `source`/
21551        // `destination` arms, an accidental `source()` per-cluster
21552        // caller-alias rewrite that didn't land on the `world_ref` peer)
21553        // surfaces at caixa-core build time. Peer of the sibling per-
21554        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
21555        // per-`:entrada` `(hostname(), destination())` (6db982c /
21556        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
21557        // axes, extended to the per-`:contratos` triple.
21558        for (de, para, wit, endpoint, subject, slot) in [
21559            (
21560                "cart",
21561                "catalog",
21562                "wasi:http/proxy",
21563                Some("/lookup"),
21564                None,
21565                None,
21566            ),
21567            (
21568                "checkout",
21569                "orders",
21570                "nats:pub-sub",
21571                None,
21572                Some("orders.paid"),
21573                None,
21574            ),
21575            (
21576                "cart",
21577                "kv",
21578                "wasi:keyvalue/store",
21579                None,
21580                None,
21581                Some("carts/{cart_id}"),
21582            ),
21583            (
21584                "orders-v2",
21585                "inventory-v3",
21586                "http:proxy",
21587                Some("/reserve"),
21588                None,
21589                None,
21590            ),
21591        ] {
21592            let c = WitContract {
21593                de: de.into(),
21594                para: para.into(),
21595                wit: wit.into(),
21596                endpoint: endpoint.map(str::to_string),
21597                subject: subject.map(str::to_string),
21598                slot: slot.map(str::to_string),
21599            };
21600            assert_eq!(
21601                (c.source(), c.destination(), c.world_ref()),
21602                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
21603                "(WitContract::source, ::destination, ::world_ref) must \
21604                 project (.de, .para, .wit) verbatim across every author-\
21605                 declared triple (got ({:?}, {:?}, {:?}), expected \
21606                 ({de:?}, {para:?}, {wit:?}))",
21607                c.source(),
21608                c.destination(),
21609                c.world_ref(),
21610            );
21611        }
21612    }
21613
21614    #[test]
21615    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
21616        // The canonical per-`:contratos` owned-form caller-callee-pair
21617        // pin: [`WitContract::edge_pair`] must return the
21618        // `(source(), destination())` tuple in owned form byte-for-byte,
21619        // projected through the lifted [`WitContract::source`] /
21620        // [`WitContract::destination`] scalar accessors. Pins the
21621        // composite-projection invariant on the per-`:contratos`
21622        // mesh-slot atom — every author-declared `(de, para)` pair must
21623        // round-trip verbatim through the substrate primitive's typed
21624        // dispatch, so the nine [`AplicacaoError`] diagnostic-
21625        // construction sites the accessor now feeds
21626        // ([`AplicacaoError::EmptyWit`],
21627        // [`AplicacaoError::ContratoEndpointEmpty`],
21628        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
21629        // [`AplicacaoError::ContratoEndpointInvalid`],
21630        // [`AplicacaoError::ContratoSubjectEmpty`],
21631        // [`AplicacaoError::ContratoSubjectInvalid`],
21632        // [`AplicacaoError::ContratoSlotEmpty`],
21633        // [`AplicacaoError::ContratoSlotInvalid`],
21634        // [`AplicacaoError::ContratoDuplicate`]) all read the same
21635        // `(de, para)` label pair every author sees at the source
21636        // `caixa.lisp`. Pins against a future silent detour that swapped
21637        // the `.0` / `.1` arms (an accidental `(destination(),
21638        // source())` re-order in the body would silently invert every
21639        // downstream diagnostic's `de:` / `para:` label pair, silently
21640        // reversing the direction of every operator-facing typed error
21641        // arrow), a fresh-allocation shape drift (an accidental
21642        // `.to_string()` on one arm but not the other would leave the
21643        // owned/borrowed pair mismatched vs. the sibling `source()` /
21644        // `destination()` returns), or an M4 per-cluster caller/callee-
21645        // alias rewrite that landed on `source()` without reaching
21646        // `destination()` (or vice versa). Peer of the sibling per-
21647        // `:contratos` `(source, destination, world_ref)` triple
21648        // pin above on the mesh-slot-atom scalar-value axes, extended
21649        // to the owned-form pair-projection axis.
21650        for (de, para, wit, endpoint, subject, slot) in [
21651            (
21652                "cart",
21653                "catalog",
21654                "wasi:http/proxy",
21655                Some("/lookup"),
21656                None,
21657                None,
21658            ),
21659            (
21660                "checkout",
21661                "orders",
21662                "nats:pub-sub",
21663                None,
21664                Some("orders.paid"),
21665                None,
21666            ),
21667            (
21668                "cart",
21669                "kv",
21670                "wasi:keyvalue/store",
21671                None,
21672                None,
21673                Some("carts/{cart_id}"),
21674            ),
21675            (
21676                "orders-v2",
21677                "inventory-v3",
21678                "http:proxy",
21679                Some("/reserve"),
21680                None,
21681                None,
21682            ),
21683        ] {
21684            let c = WitContract {
21685                de: de.into(),
21686                para: para.into(),
21687                wit: wit.into(),
21688                endpoint: endpoint.map(str::to_string),
21689                subject: subject.map(str::to_string),
21690                slot: slot.map(str::to_string),
21691            };
21692            assert_eq!(
21693                c.edge_pair(),
21694                (de.to_string(), para.to_string()),
21695                "WitContract::edge_pair must return (:contratos :de, \
21696                 :contratos :para) as an owned tuple verbatim (got {:?}, \
21697                 expected ({de:?}, {para:?}))",
21698                c.edge_pair(),
21699            );
21700        }
21701    }
21702
21703    #[test]
21704    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
21705        // The composition pin: [`WitContract::edge_pair`] must return
21706        // exactly `(source().to_string(), destination().to_string())` —
21707        // the owned form of the sibling accessor pair — so any future
21708        // refactor that silently re-authored the caller-arm / callee-arm
21709        // projection to bypass the lifted scalar accessors (an accidental
21710        // `(self.de.clone(), self.para.clone())` regression back to the
21711        // raw field-access shape, an M4-typed-caller-enum `Display`
21712        // re-canonicalization on `source()` that didn't reach
21713        // `edge_pair()`, a per-cluster alias rewrite the operator lands
21714        // on `destination()` without reaching this composite projection)
21715        // trips at caixa-core build time. Pins the "typed dispatch
21716        // composes with typed dispatch, not with raw field access"
21717        // discipline every downstream diagnostic-construction site now
21718        // routes through — a `de:` / `para:` label pair whose
21719        // projection silently drifted off the substrate primitive's
21720        // scalar accessors would silently split the diagnostic's self-
21721        // locating signal from the source `caixa.lisp` author's view.
21722        // Peer of the sibling per-`:politicas` `is_empty` /
21723        // `validate_politicas` accessor-routing-pin family on the M3
21724        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
21725        let c = WitContract {
21726            de: "cart".into(),
21727            para: "catalog".into(),
21728            wit: "wasi:http/proxy".into(),
21729            endpoint: Some("/lookup".into()),
21730            subject: None,
21731            slot: None,
21732        };
21733        assert_eq!(
21734            c.edge_pair(),
21735            (c.source().to_string(), c.destination().to_string()),
21736            "WitContract::edge_pair must compose exactly \
21737             (source().to_string(), destination().to_string()) — a \
21738             bypass of either sibling accessor here would silently \
21739             decouple the composite-projection axis from the \
21740             substrate-primitive scalar accessors every downstream \
21741             consumer routes through",
21742        );
21743    }
21744
21745    #[test]
21746    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
21747     {
21748        // The canonical per-`:contratos` owned-form
21749        // caller-callee-world-ref-triple pin:
21750        // [`WitContract::edge_triple`] must return the
21751        // `(source(), destination(), world_ref())` tuple in owned form
21752        // byte-for-byte, projected through the lifted
21753        // [`WitContract::source`] / [`WitContract::destination`] /
21754        // [`WitContract::world_ref`] scalar accessors. Pins the
21755        // composite-projection invariant on the per-`:contratos`
21756        // mesh-slot atom — every author-declared `(de, para, wit)`
21757        // triple must round-trip verbatim through the substrate
21758        // primitive's typed dispatch, so the nine
21759        // [`AplicacaoError`] diagnostic-construction sites the
21760        // accessor now feeds (the [`WitTarget`]-dispatch's eight
21761        // wrong-target / missing-target / invalid-wit / capability-
21762        // with-payload arms in [`WitContract::target`], plus the
21763        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
21764        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
21765        // read the same `(de, para, wit)` triple every author sees at
21766        // the source `caixa.lisp`. Pins against a future silent
21767        // detour that swapped any two arms (an accidental `(destination(),
21768        // source(), world_ref())` re-order in the body would silently
21769        // invert every downstream diagnostic's `de:` / `para:` label
21770        // pair, silently reversing the direction of every operator-
21771        // facing typed error arrow), a fresh-allocation shape drift
21772        // (an accidental `.to_string()` skipped on one arm would leave
21773        // the owned/borrowed triple mismatched vs. the sibling
21774        // `source()` / `destination()` / `world_ref()` returns), or an
21775        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
21776        // canonicalization pass that landed on one accessor without
21777        // reaching the peers. Peer of the sibling per-`:contratos`
21778        // caller-callee-pair
21779        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
21780        // pin on the mesh-slot-atom composite-projection axis,
21781        // extended to the triple-projection axis.
21782        for (de, para, wit, endpoint, subject, slot) in [
21783            (
21784                "cart",
21785                "catalog",
21786                "wasi:http/proxy",
21787                Some("/lookup"),
21788                None,
21789                None,
21790            ),
21791            (
21792                "checkout",
21793                "orders",
21794                "nats:pub-sub",
21795                None,
21796                Some("orders.paid"),
21797                None,
21798            ),
21799            (
21800                "cart",
21801                "kv",
21802                "wasi:keyvalue/store",
21803                None,
21804                None,
21805                Some("carts/{cart_id}"),
21806            ),
21807            (
21808                "orders-v2",
21809                "inventory-v3",
21810                "http:proxy",
21811                Some("/reserve"),
21812                None,
21813                None,
21814            ),
21815        ] {
21816            let c = WitContract {
21817                de: de.into(),
21818                para: para.into(),
21819                wit: wit.into(),
21820                endpoint: endpoint.map(str::to_string),
21821                subject: subject.map(str::to_string),
21822                slot: slot.map(str::to_string),
21823            };
21824            assert_eq!(
21825                c.edge_triple(),
21826                (de.to_string(), para.to_string(), wit.to_string()),
21827                "WitContract::edge_triple must return (:contratos :de, \
21828                 :contratos :para, :contratos :wit) as an owned triple \
21829                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
21830                c.edge_triple(),
21831            );
21832        }
21833    }
21834
21835    #[test]
21836    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
21837        // The composition pin: [`WitContract::edge_triple`] must return
21838        // exactly `(source().to_string(), destination().to_string(),
21839        // world_ref().to_string())` — the owned form of the sibling
21840        // scalar-accessor triple — so any future refactor that silently
21841        // re-authored one arm's projection to bypass the lifted scalar
21842        // accessors (an accidental `(self.de.clone(), self.para.clone(),
21843        // self.wit.clone())` regression back to the raw field-access
21844        // shape the internal `edge` closure and the ContratoDuplicate
21845        // diagnostic both carried before this lift landed, an
21846        // M4-typed-caller-enum `Display` re-canonicalization on
21847        // `source()` that didn't reach `edge_triple()`, a per-cluster
21848        // alias rewrite the operator lands on `destination()` /
21849        // `world_ref()` without reaching this composite projection)
21850        // trips at caixa-core build time. Pins the "typed dispatch
21851        // composes with typed dispatch, not with raw field access"
21852        // discipline every downstream diagnostic-construction site now
21853        // routes through — a `de:` / `para:` / `wit:` triple whose
21854        // projection silently drifted off the substrate primitive's
21855        // scalar accessors would silently split the diagnostic's self-
21856        // locating signal from the source `caixa.lisp` author's view.
21857        // Peer of the sibling per-`:contratos` edge_pair composition-
21858        // pin above on the mesh-slot-atom composite-projection axis.
21859        let c = WitContract {
21860            de: "cart".into(),
21861            para: "catalog".into(),
21862            wit: "wasi:http/proxy".into(),
21863            endpoint: Some("/lookup".into()),
21864            subject: None,
21865            slot: None,
21866        };
21867        assert_eq!(
21868            c.edge_triple(),
21869            (
21870                c.source().to_string(),
21871                c.destination().to_string(),
21872                c.world_ref().to_string(),
21873            ),
21874            "WitContract::edge_triple must compose exactly \
21875             (source().to_string(), destination().to_string(), \
21876             world_ref().to_string()) — a bypass of any sibling accessor \
21877             here would silently decouple the composite-projection axis \
21878             from the substrate-primitive scalar accessors every \
21879             downstream consumer routes through",
21880        );
21881    }
21882
21883    #[test]
21884    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
21885        // The canonical semantics-pin: [`WitContract::edge_triple`] must
21886        // project the full `(de, para, wit)` identity of a `:contratos`
21887        // edge — the sub-triple every triple-carrying
21888        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
21889        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
21890        // missing-target, capability-with-payload, invalid-wit, and the
21891        // duplicate-gate). Rejects a drift in shape (an accidental
21892        // silent detour that returned a `(de, para)` pair or added an
21893        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
21894        // would trip here because the return type would no longer
21895        // pattern-match the eight `let (de, para, wit) = edge();`
21896        // destructures the [`WitContract::target`] dispatch feeds off
21897        // + the paired duplicate-gate `let (de, para, wit) =
21898        // c.edge_triple();` destructure in
21899        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
21900        // `:contratos` caller-callee-pair pin above extended to the
21901        // triple projection surface: closes the "one composite
21902        // accessor per typed diagnostic-construction sub-tuple"
21903        // discipline on the per-`:contratos` mesh-slot-atom axis.
21904        let c = WitContract {
21905            de: "checkout".into(),
21906            para: "orders".into(),
21907            wit: "nats:pub-sub".into(),
21908            endpoint: None,
21909            subject: Some("orders.paid".into()),
21910            slot: None,
21911        };
21912        let (de, para, wit) = c.edge_triple();
21913        assert_eq!(de, "checkout");
21914        assert_eq!(para, "orders");
21915        assert_eq!(wit, "nats:pub-sub");
21916    }
21917
21918    #[test]
21919    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
21920     {
21921        // The composition pin: [`WitContract::identity`] must return
21922        // exactly `(source(), destination(), world_ref(), endpoint(),
21923        // subject(), slot())` — the borrowed form of the six-scalar-
21924        // accessor identity axis. Any future refactor that silently
21925        // re-authored one arm's projection to bypass a scalar accessor
21926        // (a `self.de.as_str()` regression back to raw field access on
21927        // any of the three required arms, a `self.endpoint.as_deref()`
21928        // regression on any of the three optional arms, an M4 per-
21929        // cluster caller/callee-alias rewrite the operator lands on
21930        // `source()` / `destination()` without reaching this composite
21931        // projection) trips at caixa-core build time. Sweeps four
21932        // permutations of the WIT-shape × payload lattice — HTTP with
21933        // endpoint, pub-sub with subject, store with slot, payload-less
21934        // capability — so every payload arm is exercised. Peer of the
21935        // sibling per-`:contratos`
21936        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
21937        // composition pin on the mesh-slot-atom composite-projection
21938        // axis; extends the discipline from the (de, para, wit) prefix
21939        // onto the full-identity axis carrying the three payload arms.
21940        for (de, para, wit, endpoint, subject, slot) in [
21941            (
21942                "cart",
21943                "catalog",
21944                "wasi:http/proxy",
21945                Some("/lookup"),
21946                None,
21947                None,
21948            ),
21949            (
21950                "checkout",
21951                "orders",
21952                "nats:pub-sub",
21953                None,
21954                Some("orders.paid"),
21955                None,
21956            ),
21957            (
21958                "cart",
21959                "kv",
21960                "wasi:keyvalue/store",
21961                None,
21962                None,
21963                Some("carts/{cart_id}"),
21964            ),
21965            ("audit", "sink", "wasi:logging", None, None, None),
21966        ] {
21967            let c = WitContract {
21968                de: de.into(),
21969                para: para.into(),
21970                wit: wit.into(),
21971                endpoint: endpoint.map(str::to_owned),
21972                subject: subject.map(str::to_owned),
21973                slot: slot.map(str::to_owned),
21974            };
21975            assert_eq!(
21976                c.identity(),
21977                (
21978                    c.source(),
21979                    c.destination(),
21980                    c.world_ref(),
21981                    c.endpoint(),
21982                    c.subject(),
21983                    c.slot(),
21984                ),
21985                "WitContract::identity must compose exactly \
21986                 (source(), destination(), world_ref(), endpoint(), \
21987                 subject(), slot()) — a bypass of any sibling accessor \
21988                 here would silently decouple the identity-projection \
21989                 axis from the substrate-primitive scalar accessors \
21990                 every dedup-key consumer routes through",
21991            );
21992        }
21993    }
21994
21995    #[test]
21996    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
21997        // The canonical semantics-pin: [`WitContract::identity`] must
21998        // project the six-axis (de, para, wit, endpoint, subject, slot)
21999        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22000        // gate keys off — two `WitContract`s that agree on all six axes
22001        // are the same typed edge declared twice, the graph-edge
22002        // analogue of duplicate `:membros` / `:placement :clusters` /
22003        // `:entrada :paths` entries. Rejects a shape drift (an
22004        // accidental silent detour that returned a prefix tuple or
22005        // added an extra field) by pattern-matching the six-arm shape.
22006        // Peer of the sibling per-`:contratos`
22007        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
22008        // pin extended from the (de, para, wit) prefix onto the full
22009        // six-axis identity that the dedup key rides.
22010        let c = WitContract {
22011            de: "cart".into(),
22012            para: "catalog".into(),
22013            wit: "wasi:http/proxy".into(),
22014            endpoint: Some("/products/:id".into()),
22015            subject: None,
22016            slot: None,
22017        };
22018        let (de, para, wit, endpoint, subject, slot) = c.identity();
22019        assert_eq!(de, "cart");
22020        assert_eq!(para, "catalog");
22021        assert_eq!(wit, "wasi:http/proxy");
22022        assert_eq!(endpoint, Some("/products/:id"));
22023        assert_eq!(subject, None);
22024        assert_eq!(slot, None);
22025
22026        // Two byte-identical contracts must produce equal identities —
22027        // the dedup key's foundational invariant.
22028        let c2 = c.clone();
22029        assert_eq!(c.identity(), c2.identity());
22030
22031        // Any change on any of the six axes must break the identity —
22032        // sweeps by mutating one axis at a time.
22033        let mut mutated = c.clone();
22034        mutated.de = "search".into();
22035        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
22036        let mut mutated = c.clone();
22037        mutated.para = "warehouse".into();
22038        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
22039        let mut mutated = c.clone();
22040        mutated.wit = "http:legacy".into();
22041        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
22042        let mut mutated = c.clone();
22043        mutated.endpoint = Some("/search".into());
22044        assert_ne!(
22045            c.identity(),
22046            mutated.identity(),
22047            "endpoint axis must partition"
22048        );
22049        let mut mutated = c.clone();
22050        mutated.subject = Some("orders.paid".into());
22051        assert_ne!(
22052            c.identity(),
22053            mutated.identity(),
22054            "subject axis must partition"
22055        );
22056        let mut mutated = c;
22057        mutated.slot = Some("carts/{id}".into());
22058        assert_ne!(mutated.identity().5, None, "slot axis must partition");
22059    }
22060
22061    #[test]
22062    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
22063        // The canonical per-`:contratos` structural-self-edge pin:
22064        // [`WitContract::is_self_loop`] must return `true` when the
22065        // `:de` and `:para` fields agree byte-for-byte, across every
22066        // WIT-shape variant the per-edge shape family carries. Pins
22067        // the shape-agnostic identity-space partition the
22068        // [`AplicacaoSpec::validate`] self-edge gate at
22069        // caixa-core/src/aplicacao.rs:5559 fires against — all four
22070        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
22071        // under the same one predicate. Four permutations sweep the
22072        // accept-set: HTTP with endpoint, pub-sub with subject, KV
22073        // store with slot, and payload-less capability.
22074        for (nome, wit, endpoint, subject, slot) in [
22075            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
22076            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
22077            (
22078                "kv",
22079                "wasi:keyvalue/store",
22080                None,
22081                None,
22082                Some("carts/{cart_id}"),
22083            ),
22084            ("audit", "wasi:logging", None, None, None),
22085        ] {
22086            let c = WitContract {
22087                de: nome.into(),
22088                para: nome.into(),
22089                wit: wit.into(),
22090                endpoint: endpoint.map(str::to_string),
22091                subject: subject.map(str::to_string),
22092                slot: slot.map(str::to_string),
22093            };
22094            assert!(
22095                c.is_self_loop(),
22096                "WitContract::is_self_loop must return true when \
22097                 :contratos :de == :contratos :para (got false on \
22098                 {nome:?} under {wit:?})",
22099            );
22100        }
22101    }
22102
22103    #[test]
22104    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
22105        // The complement pin: [`WitContract::is_self_loop`] must return
22106        // `false` on every well-shaped inter-Servico contract (the
22107        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
22108        // names — "Servico A calls Servico B" between two distinct
22109        // graph nodes). Pins against a future silent detour that
22110        // inverted the predicate (an accidental `!= ` swap for `==`
22111        // would silently reject every legitimate inter-Servico edge
22112        // and admit every self-edge — the exact inversion of the
22113        // author-intended shape). Four permutations sweep the same
22114        // WIT-shape accept-set the sibling positive-arm test carries.
22115        for (de, para, wit, endpoint, subject, slot) in [
22116            (
22117                "cart",
22118                "catalog",
22119                "wasi:http/proxy",
22120                Some("/lookup"),
22121                None,
22122                None,
22123            ),
22124            (
22125                "checkout",
22126                "orders",
22127                "nats:pub-sub",
22128                None,
22129                Some("orders.paid"),
22130                None,
22131            ),
22132            (
22133                "cart",
22134                "kv",
22135                "wasi:keyvalue/store",
22136                None,
22137                None,
22138                Some("carts/{cart_id}"),
22139            ),
22140            ("audit", "sink", "wasi:logging", None, None, None),
22141        ] {
22142            let c = WitContract {
22143                de: de.into(),
22144                para: para.into(),
22145                wit: wit.into(),
22146                endpoint: endpoint.map(str::to_string),
22147                subject: subject.map(str::to_string),
22148                slot: slot.map(str::to_string),
22149            };
22150            assert!(
22151                !c.is_self_loop(),
22152                "WitContract::is_self_loop must return false when \
22153                 :contratos :de differs from :contratos :para (got true \
22154                 on {de:?} → {para:?} under {wit:?})",
22155            );
22156        }
22157    }
22158
22159    #[test]
22160    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
22161        // The composition pin: [`WitContract::is_self_loop`] must
22162        // resolve to exactly `self.source() == self.destination()` —
22163        // the equality probe of the sibling scalar-accessor pair — so
22164        // any future refactor that silently re-authored the predicate
22165        // to bypass the lifted scalar accessors (an accidental
22166        // `self.de == self.para` regression back to the raw field-
22167        // access shape, an M4-typed-caller-enum identity-comparison
22168        // rule that landed on `source()` without reaching
22169        // `destination()`, a per-cluster alias rewrite the operator
22170        // pins on `destination()` without reaching this predicate)
22171        // trips at caixa-core build time. Pins the "typed dispatch
22172        // composes with typed dispatch, not with raw field access"
22173        // discipline the sibling [`WitContract::edge_pair`] /
22174        // [`WitContract::edge_triple`] composite-projection accessors
22175        // already carry, extended onto the per-edge endpoint-equality
22176        // predicate axis. Positive and complement arms both fire.
22177        let self_edge = WitContract {
22178            de: "cart".into(),
22179            para: "cart".into(),
22180            wit: "wasi:http/proxy".into(),
22181            endpoint: Some("/lookup".into()),
22182            subject: None,
22183            slot: None,
22184        };
22185        assert_eq!(
22186            self_edge.is_self_loop(),
22187            self_edge.source() == self_edge.destination(),
22188            "WitContract::is_self_loop must compose exactly \
22189             `source() == destination()` — a bypass of either sibling \
22190             accessor here would silently decouple the endpoint-\
22191             equality predicate from the substrate-primitive scalar \
22192             accessors every downstream consumer routes through",
22193        );
22194        let inter_edge = WitContract {
22195            de: "cart".into(),
22196            para: "catalog".into(),
22197            wit: "wasi:http/proxy".into(),
22198            endpoint: Some("/lookup".into()),
22199            subject: None,
22200            slot: None,
22201        };
22202        assert_eq!(
22203            inter_edge.is_self_loop(),
22204            inter_edge.source() == inter_edge.destination(),
22205            "WitContract::is_self_loop must compose exactly \
22206             `source() == destination()` on the complement arm too",
22207        );
22208    }
22209
22210    #[test]
22211    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
22212        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
22213        // pin: [`WitContract::endpoint`] must return the `:contratos
22214        // :endpoint` field byte-for-byte, borrowed from the typed slot's
22215        // own `Option<String>` storage. Peer of the sibling
22216        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
22217        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
22218        // mesh-slot `Option<String>` optional-scalar axes — same "the
22219        // substrate-primitive accessor must byte-equal the raw field
22220        // access verbatim across every author-declared value" discipline
22221        // extended to the per-`:contratos` HTTP-payload-carrier arm.
22222        // Pins against a future silent detour that re-canonicalized the
22223        // endpoint (an accidental percent-encoding pass that didn't
22224        // reach the peer field-access site at the dedup key, a per-CR
22225        // fully-qualified prefix rewrite the operator authors on one
22226        // consumer without the other, or an M4 typed-path-template
22227        // `Display` re-canonicalization that silently drifted the
22228        // printer output from the source `caixa.lisp`). Four values
22229        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
22230        // gate upstream admits (short root-path, dashed, param-shaped,
22231        // deep-hierarchy).
22232        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
22233            let c = WitContract {
22234                de: "cart".into(),
22235                para: "catalog".into(),
22236                wit: "wasi:http/proxy".into(),
22237                endpoint: Some(endpoint.into()),
22238                subject: None,
22239                slot: None,
22240            };
22241            assert_eq!(
22242                c.endpoint(),
22243                Some(endpoint),
22244                "WitContract::endpoint must return :contratos :endpoint \
22245                 verbatim (got {:?}, expected Some({endpoint:?}))",
22246                c.endpoint(),
22247            );
22248            assert_eq!(
22249                c.endpoint(),
22250                c.endpoint.as_deref(),
22251                "WitContract::endpoint must byte-equal the .endpoint \
22252                 field's `.as_deref()` projection",
22253            );
22254        }
22255    }
22256
22257    #[test]
22258    fn wit_contract_endpoint_none_when_field_is_none() {
22259        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
22260        // payload-carrier accessor pin: when the typed slot is absent —
22261        // the canonical shape under a non-HTTP `:wit` world per the
22262        // [`WitContract::target`]-enforced shape ↔ target partition
22263        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
22264        // carries `:slot`, [`WitTarget::Capability`] carries none) —
22265        // [`WitContract::endpoint`] must return `None`. Pins against a
22266        // future silent detour that projected the absent slot to a
22267        // `Some("")` empty-string default (the canonical `Option<String>`
22268        // → `String` collapse footgun the sibling M2
22269        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22270        // emptiness predicates already guard on the peer M2 typed-slot
22271        // surfaces), a `Some("None")` stringified-None round-trip, or a
22272        // `Some` arm whose contents were derived from a sibling slot (an
22273        // accidental fallback to the `:subject` / `:slot` payload that
22274        // read the pub-sub / store payload into the endpoint axis).
22275        // Three contracts sweep the accept-set every non-HTTP `:wit`
22276        // world lands on — pub-sub NATS, key/value, and payload-less
22277        // capability.
22278        for (wit, subject, slot) in [
22279            ("nats:pub-sub", Some("orders.paid"), None),
22280            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22281            ("wasi:cli/environment", None, None),
22282        ] {
22283            let c = WitContract {
22284                de: "cart".into(),
22285                para: "downstream".into(),
22286                wit: wit.into(),
22287                endpoint: None,
22288                subject: subject.map(str::to_string),
22289                slot: slot.map(str::to_string),
22290            };
22291            assert!(
22292                c.endpoint().is_none(),
22293                "WitContract::endpoint must return None when the typed \
22294                 slot is absent under :wit {wit:?} (got {:?})",
22295                c.endpoint(),
22296            );
22297            assert_eq!(
22298                c.endpoint(),
22299                c.endpoint.as_deref(),
22300                "WitContract::endpoint must byte-equal the .endpoint \
22301                 field's `.as_deref()` projection in the absent arm",
22302            );
22303        }
22304    }
22305
22306    #[test]
22307    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
22308        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
22309        // an `Option<&str>` whose `Some` arm borrows from the typed
22310        // slot's own [`String`] storage — same-address invariant with
22311        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
22312        // detour that allocated a fresh `String`
22313        // (`self.endpoint.clone().map(...)` in the body would type-check
22314        // but silently drop the borrow, and every downstream consumer
22315        // that assumed the returned slice outlives `&self` would break
22316        // on a stale-reference use-after-free — the [`WitContract::target`]
22317        // Http-arm payload extraction rebinds the returned `Option<&str>`
22318        // through `.ok_or_else(...)` and threads the `&str` payload into
22319        // [`WitTarget::Http { endpoint: &'a str }`], the
22320        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
22321        // [`ContratoIdentity`] dedup key threads the returned
22322        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
22323        // from the WitContract's own storage and each would silently
22324        // misbehave if this accessor produced a detached copy). Peer of
22325        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
22326        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22327        // shaped optional-scalar axes — first extension of the
22328        // `Option<&str>` borrow-not-copy discipline onto the
22329        // per-`:contratos` HTTP-shaped payload-carrier axis.
22330        let c = WitContract {
22331            de: "cart".into(),
22332            para: "catalog".into(),
22333            wit: "wasi:http/proxy".into(),
22334            endpoint: Some("/lookup".into()),
22335            subject: None,
22336            slot: None,
22337        };
22338        let ep = c.endpoint().expect("Some arm");
22339        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
22340        assert_eq!(
22341            ep.as_ptr(),
22342            storage_slice.as_ptr(),
22343            "WitContract::endpoint must borrow from the .endpoint \
22344             String's backing storage — a fresh allocation here means \
22345             the accessor no longer names the substrate-primitive typed \
22346             dispatch and every downstream consumer would silently \
22347             carry a detached copy",
22348        );
22349        assert_eq!(
22350            ep.len(),
22351            storage_slice.len(),
22352            "WitContract::endpoint and .endpoint.as_deref() must byte-\
22353             equal in length as well as in address",
22354        );
22355    }
22356
22357    #[test]
22358    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
22359        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
22360        // pin: [`WitContract::subject`] must return the `:contratos
22361        // :subject` field byte-for-byte, borrowed from the typed slot's
22362        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
22363        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
22364        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22365        // optional-scalar axis — same "the substrate-primitive accessor
22366        // must byte-equal the raw field access verbatim across every
22367        // author-declared value" discipline extended to the pub-sub arm.
22368        // Pins against a future silent detour that re-canonicalized the
22369        // subject (an accidental `.to_lowercase()` normalization that
22370        // didn't reach the peer field-access site at the dedup key, a
22371        // per-CR fully-qualified prefix rewrite the operator authors on
22372        // one consumer without the other, or an M4 typed-subject-template
22373        // `Display` re-canonicalization that silently drifted the printer
22374        // output from the source `caixa.lisp`). Four values sweep the
22375        // NATS accept-set every pub-sub author-declared subject lands on
22376        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
22377        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
22378            let c = WitContract {
22379                de: "cart".into(),
22380                para: "notifier".into(),
22381                wit: "nats:pub-sub".into(),
22382                endpoint: None,
22383                subject: Some(subject.into()),
22384                slot: None,
22385            };
22386            assert_eq!(
22387                c.subject(),
22388                Some(subject),
22389                "WitContract::subject must return :contratos :subject \
22390                 verbatim (got {:?}, expected Some({subject:?}))",
22391                c.subject(),
22392            );
22393            assert_eq!(
22394                c.subject(),
22395                c.subject.as_deref(),
22396                "WitContract::subject must byte-equal the .subject \
22397                 field's `.as_deref()` projection",
22398            );
22399        }
22400    }
22401
22402    #[test]
22403    fn wit_contract_subject_none_when_field_is_none() {
22404        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
22405        // shaped payload-carrier accessor pin: when the typed slot is
22406        // absent — the canonical shape under a non-pub-sub `:wit` world
22407        // per the [`WitContract::target`]-enforced shape ↔ target
22408        // partition ([`WitTarget::Http`] carries `:endpoint`,
22409        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
22410        // carries none) — [`WitContract::subject`] must return `None`.
22411        // Pins against a future silent detour that projected the absent
22412        // slot to a `Some("")` empty-string default (the canonical
22413        // `Option<String>` → `String` collapse footgun the sibling M2
22414        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22415        // emptiness predicates already guard on the peer M2 typed-slot
22416        // surfaces), a `Some("None")` stringified-None round-trip, or a
22417        // `Some` arm whose contents were derived from a sibling slot (an
22418        // accidental fallback to the `:endpoint` / `:slot` payload that
22419        // read the HTTP / store payload into the subject axis). Three
22420        // contracts sweep the accept-set every non-pub-sub `:wit` world
22421        // lands on — HTTP proxy, key/value store, and payload-less
22422        // capability.
22423        for (wit, endpoint, slot) in [
22424            ("wasi:http/proxy", Some("/lookup"), None),
22425            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22426            ("wasi:cli/environment", None, None),
22427        ] {
22428            let c = WitContract {
22429                de: "cart".into(),
22430                para: "downstream".into(),
22431                wit: wit.into(),
22432                endpoint: endpoint.map(str::to_string),
22433                subject: None,
22434                slot: slot.map(str::to_string),
22435            };
22436            assert!(
22437                c.subject().is_none(),
22438                "WitContract::subject must return None when the typed \
22439                 slot is absent under :wit {wit:?} (got {:?})",
22440                c.subject(),
22441            );
22442            assert_eq!(
22443                c.subject(),
22444                c.subject.as_deref(),
22445                "WitContract::subject must byte-equal the .subject \
22446                 field's `.as_deref()` projection in the absent arm",
22447            );
22448        }
22449    }
22450
22451    #[test]
22452    fn wit_contract_subject_borrows_from_subject_storage() {
22453        // The borrow-not-copy pin: [`WitContract::subject`] must return
22454        // an `Option<&str>` whose `Some` arm borrows from the typed
22455        // slot's own [`String`] storage — same-address invariant with
22456        // `c.subject.as_deref().unwrap()`. Pins against a future silent
22457        // detour that allocated a fresh `String`
22458        // (`self.subject.clone().map(...)` in the body would type-check
22459        // but silently drop the borrow, and every downstream consumer
22460        // that assumed the returned slice outlives `&self` would break
22461        // on a stale-reference use-after-free — the [`WitContract::target`]
22462        // PubSub-arm payload extraction rebinds the returned
22463        // `Option<&str>` through `.ok_or_else(...)` and threads the
22464        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
22465        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22466        // [`ContratoIdentity`] dedup key threads the returned
22467        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
22468        // from the WitContract's own storage and each would silently
22469        // misbehave if this accessor produced a detached copy). Peer of
22470        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
22471        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22472        // shaped optional-scalar axis — second extension of the
22473        // `Option<&str>` borrow-not-copy discipline onto the
22474        // per-`:contratos` payload-carrier family, this time on the
22475        // pub-sub arm.
22476        let c = WitContract {
22477            de: "cart".into(),
22478            para: "notifier".into(),
22479            wit: "nats:pub-sub".into(),
22480            endpoint: None,
22481            subject: Some("orders.paid".into()),
22482            slot: None,
22483        };
22484        let sub = c.subject().expect("Some arm");
22485        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
22486        assert_eq!(
22487            sub.as_ptr(),
22488            storage_slice.as_ptr(),
22489            "WitContract::subject must borrow from the .subject \
22490             String's backing storage — a fresh allocation here means \
22491             the accessor no longer names the substrate-primitive typed \
22492             dispatch and every downstream consumer would silently \
22493             carry a detached copy",
22494        );
22495        assert_eq!(
22496            sub.len(),
22497            storage_slice.len(),
22498            "WitContract::subject and .subject.as_deref() must byte-\
22499             equal in length as well as in address",
22500        );
22501    }
22502
22503    #[test]
22504    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
22505        // The canonical per-`:contratos` key/value-store-shaped
22506        // `:slot`-scalar pin: [`WitContract::slot`] must return the
22507        // `:contratos :slot` field byte-for-byte, borrowed from the
22508        // typed slot's own `Option<String>` storage. Peer of the
22509        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
22510        // [`WitContract::subject`] (90de675) accessor pins on the M3
22511        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22512        // optional-scalar axis — same "the substrate-primitive
22513        // accessor must byte-equal the raw field access verbatim
22514        // across every author-declared value" discipline extended to
22515        // the store arm. Pins against a future silent detour that
22516        // re-canonicalized the slot template (an accidental
22517        // `.to_lowercase()` bucket-prefix normalization that didn't
22518        // reach the peer field-access site at the dedup key, a per-CR
22519        // fully-qualified prefix rewrite the operator authors on one
22520        // consumer without the other, or an M4 typed-key-template
22521        // `Display` re-canonicalization that silently drifted the
22522        // printer output from the source `caixa.lisp`). Four values
22523        // sweep the wasi:keyvalue accept-set every store-shaped
22524        // author-declared slot lands on (flat bucket, single-param
22525        // template, multi-param template, nested-hierarchy template).
22526        for slot in [
22527            "sessions",
22528            "carts/{cart_id}",
22529            "orders/{tenant}/{order_id}",
22530            "cache/tenant-a/orders/{id}",
22531        ] {
22532            let c = WitContract {
22533                de: "cart".into(),
22534                para: "kv".into(),
22535                wit: "wasi:keyvalue/store".into(),
22536                endpoint: None,
22537                subject: None,
22538                slot: Some(slot.into()),
22539            };
22540            assert_eq!(
22541                c.slot(),
22542                Some(slot),
22543                "WitContract::slot must return :contratos :slot \
22544                 verbatim (got {:?}, expected Some({slot:?}))",
22545                c.slot(),
22546            );
22547            assert_eq!(
22548                c.slot(),
22549                c.slot.as_deref(),
22550                "WitContract::slot must byte-equal the .slot field's \
22551                 `.as_deref()` projection",
22552            );
22553        }
22554    }
22555
22556    #[test]
22557    fn wit_contract_slot_none_when_field_is_none() {
22558        // The absent-`:slot` arm of the per-`:contratos` store-shaped
22559        // payload-carrier accessor pin: when the typed slot is absent —
22560        // the canonical shape under a non-store `:wit` world per the
22561        // [`WitContract::target`]-enforced shape ↔ target partition
22562        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
22563        // carries `:subject`, [`WitTarget::Capability`] carries none) —
22564        // [`WitContract::slot`] must return `None`. Pins against a
22565        // future silent detour that projected the absent slot to a
22566        // `Some("")` empty-string default (the canonical
22567        // `Option<String>` → `String` collapse footgun the sibling M2
22568        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22569        // emptiness predicates already guard on the peer M2 typed-slot
22570        // surfaces), a `Some("None")` stringified-None round-trip, or
22571        // a `Some` arm whose contents were derived from a sibling
22572        // slot (an accidental fallback to the `:endpoint` / `:subject`
22573        // payload that read the HTTP / pub-sub payload into the store
22574        // axis). Three contracts sweep the accept-set every non-store
22575        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
22576        // payload-less capability.
22577        for (wit, endpoint, subject) in [
22578            ("wasi:http/proxy", Some("/lookup"), None),
22579            ("nats:pub-sub", None, Some("orders.paid")),
22580            ("wasi:cli/environment", None, None),
22581        ] {
22582            let c = WitContract {
22583                de: "cart".into(),
22584                para: "downstream".into(),
22585                wit: wit.into(),
22586                endpoint: endpoint.map(str::to_string),
22587                subject: subject.map(str::to_string),
22588                slot: None,
22589            };
22590            assert!(
22591                c.slot().is_none(),
22592                "WitContract::slot must return None when the typed \
22593                 slot is absent under :wit {wit:?} (got {:?})",
22594                c.slot(),
22595            );
22596            assert_eq!(
22597                c.slot(),
22598                c.slot.as_deref(),
22599                "WitContract::slot must byte-equal the .slot field's \
22600                 `.as_deref()` projection in the absent arm",
22601            );
22602        }
22603    }
22604
22605    #[test]
22606    fn wit_contract_slot_borrows_from_slot_storage() {
22607        // The borrow-not-copy pin: [`WitContract::slot`] must return
22608        // an `Option<&str>` whose `Some` arm borrows from the typed
22609        // slot's own [`String`] storage — same-address invariant with
22610        // `c.slot.as_deref().unwrap()`. Pins against a future silent
22611        // detour that allocated a fresh `String`
22612        // (`self.slot.clone().map(...)` in the body would type-check
22613        // but silently drop the borrow, and every downstream consumer
22614        // that assumed the returned slice outlives `&self` would
22615        // break on a stale-reference use-after-free — the
22616        // [`WitContract::target`] Store-arm payload extraction rebinds
22617        // the returned `Option<&str>` through `.ok_or_else(...)` and
22618        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
22619        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22620        // [`ContratoIdentity`] dedup key threads the returned
22621        // `Option<&str>` into the six-tuple's store arm — each borrow
22622        // from the WitContract's own storage and each would silently
22623        // misbehave if this accessor produced a detached copy). Peer
22624        // of the sibling per-`:contratos` [`WitContract::endpoint`]
22625        // (7020470) / [`WitContract::subject`] (90de675)
22626        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
22627        // shaped optional-scalar axis — third and final extension of
22628        // the `Option<&str>` borrow-not-copy discipline onto the
22629        // per-`:contratos` payload-carrier family, this time on the
22630        // store arm.
22631        let c = WitContract {
22632            de: "cart".into(),
22633            para: "kv".into(),
22634            wit: "wasi:keyvalue/store".into(),
22635            endpoint: None,
22636            subject: None,
22637            slot: Some("carts/{cart_id}".into()),
22638        };
22639        let slot = c.slot().expect("Some arm");
22640        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
22641        assert_eq!(
22642            slot.as_ptr(),
22643            storage_slice.as_ptr(),
22644            "WitContract::slot must borrow from the .slot String's \
22645             backing storage — a fresh allocation here means the \
22646             accessor no longer names the substrate-primitive typed \
22647             dispatch and every downstream consumer would silently \
22648             carry a detached copy",
22649        );
22650        assert_eq!(
22651            slot.len(),
22652            storage_slice.len(),
22653            "WitContract::slot and .slot.as_deref() must byte-equal \
22654             in length as well as in address",
22655        );
22656    }
22657
22658    #[test]
22659    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
22660        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
22661        // [`Membro::nome`] must return the `:membros :caixa` field
22662        // byte-for-byte, borrowed from the typed slot's own [`String`]
22663        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
22664        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22665        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
22666        // slot-atom scalar-value axes — same "the substrate-primitive
22667        // accessor must byte-equal the raw field access verbatim across
22668        // every author-declared value" discipline extended to the
22669        // per-`:membros` member-identity arm. Pins against a future
22670        // silent detour that re-normalized the member identity (an
22671        // accidental `.to_lowercase()` — every `:membros :caixa` is
22672        // validated as a DNS-1123 label upstream via
22673        // [`validate_membro_caixa`], so any re-normalization is
22674        // redundant + a drift surface between the validator and the
22675        // accessor), a namespace-prefix rewrite (an accidental
22676        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
22677        // rewrite that didn't land on the peer axes), or a per-cluster
22678        // alias stamp the operator authors on one consumer without the
22679        // other. Four values sweep the accept-set the DNS-1123 gate
22680        // upstream admits (short single-word / dashed / v-suffixed
22681        // member names).
22682        for name in ["cart", "checkout", "catalog", "orders-v2"] {
22683            let m = Membro {
22684                caixa: name.into(),
22685                versao: "^0.1".into(),
22686            };
22687            assert_eq!(
22688                m.nome(),
22689                name,
22690                "Membro::nome must return :membros :caixa verbatim \
22691                 (got {:?}, expected {name:?})",
22692                m.nome(),
22693            );
22694            assert_eq!(
22695                m.nome(),
22696                m.caixa.as_str(),
22697                "Membro::nome must byte-equal the .caixa field access",
22698            );
22699        }
22700    }
22701
22702    #[test]
22703    fn membro_nome_borrows_from_caixa_storage() {
22704        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
22705        // slice that borrows from the typed slot's own [`String`]
22706        // storage — same-address invariant with `m.caixa.as_str()`. Pins
22707        // against a future silent detour that allocated a fresh `String`
22708        // (`self.caixa.clone()` in the body would type-check but
22709        // silently drop the borrow, and every downstream consumer that
22710        // assumed the returned slice outlives `&self` would break on a
22711        // stale-reference use-after-free — the `HashSet<&str>` collector
22712        // at [`AplicacaoSpec::validate`]'s `names` seed, the
22713        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
22714        // [`AplicacaoSpec::detect_sync_cycles`], the
22715        // [`crate::render::insert_first_seen`] dedup key at
22716        // [`AplicacaoSpec::validate_membros`] — each borrow from the
22717        // Membro's own storage and each would silently misbehave if
22718        // this accessor produced a detached copy). Peer of the sibling
22719        // per-`:contratos` [`WitContract::source`] /
22720        // [`WitContract::destination`] and per-`:entrada`
22721        // [`Entrada::destination`] borrow-invariant pins on the mesh-
22722        // slot-atom scalar-value axes.
22723        let m = Membro {
22724            caixa: "checkout".into(),
22725            versao: "^0.1".into(),
22726        };
22727        let name = m.nome();
22728        let caixa_slice = m.caixa.as_str();
22729        assert_eq!(
22730            name.as_ptr(),
22731            caixa_slice.as_ptr(),
22732            "Membro::nome must borrow from the .caixa String's backing \
22733             storage — a fresh allocation here means the accessor no \
22734             longer names the substrate-primitive typed dispatch and \
22735             every downstream consumer would silently carry a detached \
22736             copy",
22737        );
22738        assert_eq!(
22739            name.len(),
22740            caixa_slice.len(),
22741            "Membro::nome and .caixa.as_str() must byte-equal in length \
22742             as well as in address",
22743        );
22744    }
22745
22746    #[test]
22747    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
22748        // The canonical per-`:membros` member-`:versao`-scalar pin:
22749        // [`Membro::versao_requirement`] must return the
22750        // `:membros :versao` field byte-for-byte, borrowed from the typed
22751        // slot's own [`String`] storage. Sibling of the peer
22752        // `membro_nome_returns_caixa_byte_equal_across_permutations`
22753        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
22754        // — same "the substrate-primitive accessor must byte-equal the
22755        // raw field access verbatim across every author-declared value"
22756        // discipline extended to the per-`:membros` member-`:versao`
22757        // requirement-string arm. Pins against a future silent detour
22758        // that re-canonicalized the requirement (an accidental
22759        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
22760        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
22761        // drifted the printer output away from the source `caixa.lisp`,
22762        // an accidental whitespace trim on `"^ 0.1"` that no consumer
22763        // ever produced from the field-access side, an accidental
22764        // per-cluster lacre-projected concrete-version rewrite that
22765        // didn't land on the peer field-access sites). Five values sweep
22766        // the accept-set the shared
22767        // [`crate::render::require_valid_versao_requirement`] gate
22768        // admits (caret / tilde / exact / wildcard / bare-major).
22769        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
22770            let m = Membro {
22771                caixa: "cart".into(),
22772                versao: req.into(),
22773            };
22774            assert_eq!(
22775                m.versao_requirement(),
22776                req,
22777                "Membro::versao_requirement must return :membros :versao \
22778                 verbatim (got {:?}, expected {req:?})",
22779                m.versao_requirement(),
22780            );
22781            assert_eq!(
22782                m.versao_requirement(),
22783                m.versao.as_str(),
22784                "Membro::versao_requirement must byte-equal the .versao \
22785                 field access",
22786            );
22787        }
22788    }
22789
22790    #[test]
22791    fn membro_versao_requirement_borrows_from_versao_storage() {
22792        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
22793        // return a `&str` slice that borrows from the typed slot's own
22794        // [`String`] storage — same-address invariant with
22795        // `m.versao.as_str()`. Pins against a future silent detour that
22796        // allocated a fresh `String` (`self.versao.clone()` in the body
22797        // would type-check but silently drop the borrow, and every
22798        // downstream consumer that assumed the returned slice outlives
22799        // `&self` would break on a stale-reference use-after-free). Peer
22800        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
22801        // per-`:contratos` [`WitContract::source`] /
22802        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22803        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
22804        // the mesh-slot-atom scalar-value axes.
22805        let m = Membro {
22806            caixa: "checkout".into(),
22807            versao: "^0.1".into(),
22808        };
22809        let req = m.versao_requirement();
22810        let versao_slice = m.versao.as_str();
22811        assert_eq!(
22812            req.as_ptr(),
22813            versao_slice.as_ptr(),
22814            "Membro::versao_requirement must borrow from the .versao \
22815             String's backing storage — a fresh allocation here means \
22816             the accessor no longer names the substrate-primitive typed \
22817             dispatch and every downstream consumer would silently carry \
22818             a detached copy",
22819        );
22820        assert_eq!(
22821            req.len(),
22822            versao_slice.len(),
22823            "Membro::versao_requirement and .versao.as_str() must byte-\
22824             equal in length as well as in address",
22825        );
22826    }
22827
22828    #[test]
22829    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
22830        // Sibling-pair invariant pin composing both per-`:membros`
22831        // substrate-primitive typed dispatches — [`Membro::nome`]
22832        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
22833        // `(nome(), versao_requirement())` call shape every renderer
22834        // that fans on per-member identity + version pin keys off. The
22835        // invariant, evaluated per-member:
22836        //
22837        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
22838        //
22839        // Closes the last unlifted per-`:membros` scalar axis — every
22840        // downstream consumer that reads the pair now routes through
22841        // exactly two typed dispatches on the substrate primitive, not
22842        // one typed + one open-coded field access. A future refactor
22843        // that silently split either accessor's projection (an
22844        // accidental `nome()` namespace-prefix rewrite that didn't
22845        // reach the peer, an accidental `versao_requirement()` lacre-
22846        // projected concrete-version rewrite that didn't land on the
22847        // `nome()` peer) surfaces at caixa-core build time. Peer of the
22848        // sibling per-`:entrada` `(hostname(), destination())` and
22849        // per-`:contratos` `(source(), destination())` pair invariants
22850        // on the mesh-slot-atom scalar-value axes.
22851        for (caixa, versao) in [
22852            ("cart", "^0.1"),
22853            ("checkout", "~0.1.2"),
22854            ("catalog", "0.1.0"),
22855            ("orders-v2", "*"),
22856        ] {
22857            let m = Membro {
22858                caixa: caixa.into(),
22859                versao: versao.into(),
22860            };
22861            assert_eq!(
22862                (m.nome(), m.versao_requirement()),
22863                (m.caixa.as_str(), m.versao.as_str()),
22864                "(Membro::nome, Membro::versao_requirement) must project \
22865                 (.caixa, .versao) verbatim across every author-declared \
22866                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
22867                m.nome(),
22868                m.versao_requirement(),
22869            );
22870        }
22871    }
22872
22873    #[test]
22874    fn validate_membros_empty_gate_routes_through_nome_accessor() {
22875        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
22876        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
22877        // not the raw `.caixa` field access. Structurally: setting
22878        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
22879        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
22880        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
22881        // (i.e. the empty string) — so the emptiness predicate the
22882        // refusal arm reaches under is the accessor-projected value,
22883        // not a peer field that would silently drift under a future
22884        // accessor-side rewrite.
22885        //
22886        // Pins against a future silent detour that (a) re-derived the
22887        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
22888        // instead of `self.nome().is_empty()`, silently disagreeing with
22889        // every peer consumer (the `validate_membro_caixa(m.nome())`
22890        // call one line below, the dedup-key `insert_first_seen(&mut
22891        // seen, m.nome(), …)` two lines below, the emit-side per-
22892        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
22893        // (b) accessor-side introduced a per-tenant alias arm the
22894        // caller was unaware of, silently rewriting an author-declared
22895        // `:caixa "checkout"` to `""` — the raw-field-access gate
22896        // would fail-open while the accessor-routed peer consumers
22897        // would fail-closed, splitting the diagnostic from the actual
22898        // failure surface.
22899        //
22900        // Peer of the sibling
22901        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
22902        // (c0110f1) composition pin — same "the shape-gate predicate
22903        // must route through the substrate-primitive typed dispatch"
22904        // discipline extended onto the per-`:membros` empty-`:caixa`
22905        // refusal-arm axis. Closes the last unlifted `.caixa` production-
22906        // code read site on `Membro` — after this converge every
22907        // caixa-core `.caixa` field access outside the accessor's own
22908        // body is either a test-side field-setter (in-module tests
22909        // constructing invalid-shape inputs) or a doc-comment reference.
22910        let mut s = three_member_spec();
22911        s.membros[1].caixa = String::new();
22912        assert!(
22913            s.membros[1].nome().is_empty(),
22914            "Membro::nome must byte-equal the .caixa field access — an \
22915             accessor-side detour that no longer projects the raw field \
22916             would silently split this drift-detection test from the \
22917             validate() refusal arm",
22918        );
22919        assert_eq!(
22920            s.membros[1].nome(),
22921            s.membros[1].caixa.as_str(),
22922            "Membro::nome and .caixa.as_str() must byte-equal on an \
22923             empty-`:caixa` entry — the emptiness gate keys off the \
22924             accessor by construction",
22925        );
22926        assert_eq!(
22927            s.validate().unwrap_err(),
22928            AplicacaoError::MembroCaixaEmpty,
22929            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
22930             on an entry whose accessor-projected `nome()` is empty",
22931        );
22932    }
22933
22934    #[test]
22935    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
22936        // The canonical per-`:placement` Akka-cluster-sharding
22937        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
22938        // the `:placement :shard-key` field byte-for-byte, borrowed
22939        // from the typed slot's own `Option<String>` storage. Peer of
22940        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
22941        // per-`:contratos` [`WitContract::source`] /
22942        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
22943        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
22944        // slot-atom scalar-value axes — same "the substrate-primitive
22945        // accessor must byte-equal the raw field access verbatim across
22946        // every author-declared value" discipline extended to the
22947        // per-`:placement` Akka-cluster-sharding key extractor arm.
22948        // Pins against a future silent detour that re-normalized the
22949        // key (an accidental `.to_lowercase()` — every non-empty
22950        // `:shard-key` is validated as a printable-ASCII single-token
22951        // reference upstream via [`validate_placement_shard_key`], so
22952        // any re-normalization is redundant + a drift surface between
22953        // the validator and the accessor), a per-cluster alias rewrite
22954        // the operator authors on one consumer without the other, or an
22955        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
22956        // that didn't land on the peer field-access sites. Four values
22957        // sweep the accept-set the shape gate admits — bare identifier,
22958        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
22959        // the four canonical Akka-style entity-id extractor shapes the
22960        // future M4 cluster-sharding reconciler hashes.
22961        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
22962            let p = Placement {
22963                estrategia: PlacementStrategy::Sharded,
22964                clusters: vec!["rio".into()],
22965                affinity: None,
22966                shard_key: Some(key.into()),
22967            };
22968            assert_eq!(
22969                p.shard_key(),
22970                Some(key),
22971                "Placement::shard_key must return :placement :shard-key \
22972                 verbatim (got {:?}, expected Some({key:?}))",
22973                p.shard_key(),
22974            );
22975            assert_eq!(
22976                p.shard_key(),
22977                p.shard_key.as_deref(),
22978                "Placement::shard_key must byte-equal the .shard_key \
22979                 field's `.as_deref()` projection",
22980            );
22981        }
22982    }
22983
22984    #[test]
22985    fn placement_shard_key_none_when_field_is_none() {
22986        // The absent-`:shard-key` arm of the per-`:placement`
22987        // Akka-cluster-sharding accessor pin: when the typed slot is
22988        // absent — the canonical shape under `:estrategia Replicated` /
22989        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
22990        // enforced `shard_key.is_some() == matches!(estrategia,
22991        // Sharded)` partition — [`Placement::shard_key`] must return
22992        // `None`. Pins against a future silent detour that projected
22993        // the absent slot to a `Some("")` empty-string default (the
22994        // canonical `Option<String>` → `String` collapse footgun the
22995        // sibling M2 [`crate::LimitsSpec::is_empty`] /
22996        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
22997        // already guard on the peer M2 typed-slot surfaces), a
22998        // `Some("None")` stringified-None round-trip, or a `Some` arm
22999        // whose contents were derived from a sibling slot (an
23000        // accidental fallback to `estrategia.as_str()` that read the
23001        // strategy discriminator into the key axis). Two placements
23002        // sweep the accept-set every `validate`-passing non-`Sharded`
23003        // shape lands on — `Replicated` (Erlang/OTP distributed-app
23004        // takeover) and `SingleNode` (single-node hosting).
23005        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
23006            let p = Placement {
23007                estrategia,
23008                clusters: vec!["rio".into()],
23009                affinity: None,
23010                shard_key: None,
23011            };
23012            assert!(
23013                p.shard_key().is_none(),
23014                "Placement::shard_key must return None when the typed \
23015                 slot is absent under :estrategia {estrategia:?} (got {:?})",
23016                p.shard_key(),
23017            );
23018            assert_eq!(
23019                p.shard_key(),
23020                p.shard_key.as_deref(),
23021                "Placement::shard_key must byte-equal the .shard_key \
23022                 field's `.as_deref()` projection in the absent arm",
23023            );
23024        }
23025    }
23026
23027    #[test]
23028    fn placement_shard_key_borrows_from_shard_key_storage() {
23029        // The borrow-not-copy pin: [`Placement::shard_key`] must return
23030        // an `Option<&str>` whose `Some` arm borrows from the typed
23031        // slot's own [`String`] storage — same-address invariant with
23032        // `p.shard_key.as_deref().unwrap()`. Pins against a future
23033        // silent detour that allocated a fresh `String`
23034        // (`self.shard_key.clone().map(...)` in the body would type-
23035        // check but silently drop the borrow, and every downstream
23036        // consumer that assumed the returned slice outlives `&self`
23037        // would break on a stale-reference use-after-free — the
23038        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
23039        // gate's `Some(k)`-bound match arm reads `k: &str` under the
23040        // accessor's return type and would silently misbehave if this
23041        // accessor produced a detached copy). Peer of the sibling
23042        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
23043        // [`WitContract::source`] / [`WitContract::destination`]
23044        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
23045        // (6db982c) borrow-invariant pins on the mesh-slot-atom
23046        // scalar-value axes — first extension of the discipline onto
23047        // an `Option<String>`-shaped optional-scalar axis.
23048        let p = Placement {
23049            estrategia: PlacementStrategy::Sharded,
23050            clusters: vec!["rio".into()],
23051            affinity: None,
23052            shard_key: Some("tenantId".into()),
23053        };
23054        let key = p.shard_key().expect("Some arm");
23055        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
23056        assert_eq!(
23057            key.as_ptr(),
23058            storage_slice.as_ptr(),
23059            "Placement::shard_key must borrow from the .shard_key \
23060             String's backing storage — a fresh allocation here means \
23061             the accessor no longer names the substrate-primitive typed \
23062             dispatch and every downstream consumer would silently \
23063             carry a detached copy",
23064        );
23065        assert_eq!(
23066            key.len(),
23067            storage_slice.len(),
23068            "Placement::shard_key and .shard_key.as_deref() must byte-\
23069             equal in length as well as in address",
23070        );
23071    }
23072
23073    #[test]
23074    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
23075        // The canonical per-`:placement` M3-Adaptive-compression-hint
23076        // scalar pin: [`Placement::affinity`] must return the
23077        // `:placement :affinity` field byte-for-byte, borrowed from the
23078        // typed slot's own `Option<String>` storage. Peer of the sibling
23079        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
23080        // pin on the sibling `Option<&str>` optional-scalar axis — same
23081        // "the substrate-primitive accessor must byte-equal the raw
23082        // field access verbatim across every author-declared value"
23083        // discipline extended to the peer per-`:placement` M3-Adaptive-
23084        // compression-hint arm. Pins against a future silent detour
23085        // that re-normalized the hint (an accidental `.to_lowercase()`
23086        // — every `:affinity` is already validated as a DNS-1123 label
23087        // upstream via [`validate_placement_affinity`], so any re-
23088        // normalization is redundant + a drift surface between the
23089        // validator and the accessor), a per-cluster alias rewrite the
23090        // operator authors on one consumer without the other, or an
23091        // accidental hint-family collapse (`low-latency` → `latency`
23092        // that dropped the qualifier prefix). Four values sweep the
23093        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
23094        // canonical adaptive-compression-weight biases the future M4
23095        // placement engine reads.
23096        for hint in [
23097            "data-locality",
23098            "low-latency",
23099            "high-throughput",
23100            "cost-optimized",
23101        ] {
23102            let p = Placement {
23103                estrategia: PlacementStrategy::Replicated,
23104                clusters: vec!["rio".into()],
23105                affinity: Some(hint.into()),
23106                shard_key: None,
23107            };
23108            assert_eq!(
23109                p.affinity(),
23110                Some(hint),
23111                "Placement::affinity must return :placement :affinity \
23112                 verbatim (got {:?}, expected Some({hint:?}))",
23113                p.affinity(),
23114            );
23115            assert_eq!(
23116                p.affinity(),
23117                p.affinity.as_deref(),
23118                "Placement::affinity must byte-equal the .affinity \
23119                 field's `.as_deref()` projection",
23120            );
23121        }
23122    }
23123
23124    #[test]
23125    fn placement_affinity_none_when_field_is_none() {
23126        // The absent-`:affinity` arm of the per-`:placement`
23127        // M3-Adaptive-compression-hint accessor pin: when the typed
23128        // slot is absent — the canonical shape of an Aplicacao that
23129        // leaves the compression weighting up to the placement engine's
23130        // cluster-default arm — [`Placement::affinity`] must return
23131        // `None`. Pins against a future silent detour that projected
23132        // the absent slot to a `Some("")` empty-string default (the
23133        // canonical `Option<String>` → `String` collapse footgun the
23134        // sibling M2 [`crate::LimitsSpec::is_empty`] /
23135        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
23136        // already guard on the peer M2 typed-slot surfaces), a
23137        // `Some("None")` stringified-None round-trip, a `Some` arm
23138        // whose contents were derived from a sibling slot (an
23139        // accidental fallback to `estrategia.as_str()` that read the
23140        // strategy discriminator into the hint axis), or a
23141        // `Some("default")` implicit-default that would silently biases
23142        // the routing without the author having written one. Three
23143        // placements sweep the accept-set every `validate`-passing
23144        // `:affinity None` shape lands on — one per PlacementStrategy
23145        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
23146        // with a shard-key), since `:affinity` is orthogonal to
23147        // `:estrategia` in the typed grammar.
23148        for (estrategia, shard_key) in [
23149            (PlacementStrategy::SingleNode, None),
23150            (PlacementStrategy::Replicated, None),
23151            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
23152        ] {
23153            let p = Placement {
23154                estrategia,
23155                clusters: vec!["rio".into()],
23156                affinity: None,
23157                shard_key,
23158            };
23159            assert!(
23160                p.affinity().is_none(),
23161                "Placement::affinity must return None when the typed \
23162                 slot is absent under :estrategia {estrategia:?} (got {:?})",
23163                p.affinity(),
23164            );
23165            assert_eq!(
23166                p.affinity(),
23167                p.affinity.as_deref(),
23168                "Placement::affinity must byte-equal the .affinity \
23169                 field's `.as_deref()` projection in the absent arm",
23170            );
23171        }
23172    }
23173
23174    #[test]
23175    fn placement_affinity_borrows_from_affinity_storage() {
23176        // The borrow-not-copy pin: [`Placement::affinity`] must return
23177        // an `Option<&str>` whose `Some` arm borrows from the typed
23178        // slot's own [`String`] storage — same-address invariant with
23179        // `p.affinity.as_deref().unwrap()`. Pins against a future
23180        // silent detour that allocated a fresh `String`
23181        // (`self.affinity.clone().map(...)` in the body would type-
23182        // check but silently drop the borrow, and every downstream
23183        // consumer that assumed the returned slice outlives `&self`
23184        // would break on a stale-reference use-after-free — the
23185        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
23186        // gate reads the accessor's `&str` return through the
23187        // [`validate_placement_affinity`] `&str` parameter and would
23188        // silently misbehave if this accessor produced a detached
23189        // copy). Peer of the sibling per-`:placement`
23190        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
23191        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
23192        // extends the discipline onto the sibling per-`:placement`
23193        // M3-Adaptive-compression-hint arm.
23194        let p = Placement {
23195            estrategia: PlacementStrategy::Replicated,
23196            clusters: vec!["rio".into()],
23197            affinity: Some("data-locality".into()),
23198            shard_key: None,
23199        };
23200        let hint = p.affinity().expect("Some arm");
23201        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
23202        assert_eq!(
23203            hint.as_ptr(),
23204            storage_slice.as_ptr(),
23205            "Placement::affinity must borrow from the .affinity \
23206             String's backing storage — a fresh allocation here means \
23207             the accessor no longer names the substrate-primitive typed \
23208             dispatch and every downstream consumer would silently \
23209             carry a detached copy",
23210        );
23211        assert_eq!(
23212            hint.len(),
23213            storage_slice.len(),
23214            "Placement::affinity and .affinity.as_deref() must byte-\
23215             equal in length as well as in address",
23216        );
23217    }
23218
23219    #[test]
23220    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
23221        // The canonical per-`:placement` distribution-strategy-scalar
23222        // pin: [`Placement::estrategia`] must return the `:placement
23223        // :estrategia` field verbatim as a [`PlacementStrategy`],
23224        // `Copy`-projected from the typed slot's own `PlacementStrategy`
23225        // storage across every variant in the closed accept-set
23226        // (`SingleNode` — Erlang/OTP distributed-app takeover;
23227        // `Replicated` — active-active across every named cluster;
23228        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
23229        // against a future silent detour that re-derived the strategy
23230        // from a peer axis (an accidental fallback to
23231        // `if shard_key.is_some() { Sharded } else { Replicated }`
23232        // collapse that read the shard-key axis into the strategy
23233        // discriminator), a variant remap the operator authors on one
23234        // consumer without the other, or a stale-derive detour that
23235        // substituted [`PlacementStrategy::default`] when the field
23236        // held any explicit variant (which would silently collapse the
23237        // distinction between "author explicitly declared `:estrategia
23238        // Replicated`" and "author omitted the slot and inherited the
23239        // default" the future per-cluster override slot depends on).
23240        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
23241        // pin on the `Copy`-return `u16` scalar axis — same "the
23242        // substrate-primitive accessor must byte-equal the raw field
23243        // access verbatim across every author-declared value" discipline
23244        // extended onto the per-`:placement` distribution-strategy
23245        // `Copy`-composite-enum scalar axis.
23246        for estrategia in [
23247            PlacementStrategy::SingleNode,
23248            PlacementStrategy::Replicated,
23249            PlacementStrategy::Sharded,
23250        ] {
23251            // Route the paired `:shard-key` fixture-builder through the
23252            // typed cross-slot invariant predicate
23253            // [`PlacementStrategy::requires_shard_key`] rather than the
23254            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
23255            // arm-identity predicate — same discipline the sibling
23256            // `placement_strategy_variants_round_trip` fixture builder now
23257            // reads through.
23258            let shard_key = estrategia
23259                .requires_shard_key()
23260                .then(|| "tenantId".to_string());
23261            let p = Placement {
23262                estrategia,
23263                clusters: vec!["rio".into()],
23264                affinity: None,
23265                shard_key,
23266            };
23267            assert_eq!(
23268                p.estrategia(),
23269                estrategia,
23270                "Placement::estrategia must return :placement :estrategia \
23271                 verbatim (got {:?}, expected {estrategia:?})",
23272                p.estrategia(),
23273            );
23274            assert_eq!(
23275                p.estrategia(),
23276                p.estrategia,
23277                "Placement::estrategia accessor and .estrategia field \
23278                 access must byte-equal — the accessor is the substrate-\
23279                 primitive typed dispatch every downstream distribution-\
23280                 strategy consumer must route through",
23281            );
23282        }
23283    }
23284
23285    #[test]
23286    fn validate_placement_reads_through_lifted_estrategia_accessor() {
23287        // Three-consumer coherence pin: the
23288        // [`AplicacaoSpec::validate_placement`]
23289        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
23290        // `estrategia:` field (which reads through
23291        // [`Placement::estrategia`] to name the strategy the empty
23292        // `:clusters` list was declared against), the same method's
23293        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
23294        // reads through [`Placement::estrategia`] to fan across the
23295        // shape-gate cascades), and the non-`Sharded`-arm
23296        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
23297        // `estrategia:` field (which reads through
23298        // [`Placement::estrategia`] to name the strategy the declared-
23299        // but-inert `:shard-key` was authored under) must all key off
23300        // the lifted accessor, so any future rebrand on the typed
23301        // slot's reader shape lands at exactly one place. Pins the
23302        // three-site coherence by exercising each error surface end-
23303        // to-end and asserting the surfaced `estrategia:` field byte-
23304        // equals the accessor's return. Peer of the sibling per-
23305        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
23306        // pin on the M3 mesh-slot `Copy`-return scalar axis.
23307
23308        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
23309        // whose `estrategia:` field must byte-equal the accessor's return
23310        // for every variant in the closed accept-set.
23311        for estrategia in [
23312            PlacementStrategy::SingleNode,
23313            PlacementStrategy::Replicated,
23314            PlacementStrategy::Sharded,
23315        ] {
23316            let mut spec = three_member_spec();
23317            spec.placement.estrategia = estrategia;
23318            spec.placement.clusters = Vec::new();
23319            // Route the paired `:shard-key` spec-mutator through the typed
23320            // cross-slot invariant predicate
23321            // [`PlacementStrategy::requires_shard_key`] rather than the
23322            // [`gen_platform::IsVariant`]-derived
23323            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
23324            // same discipline the sibling
23325            // `placement_strategy_variants_round_trip` and
23326            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
23327            // fixture builders now read through.
23328            spec.placement.shard_key = estrategia
23329                .requires_shard_key()
23330                .then(|| "tenantId".to_string());
23331            let err = spec.validate().unwrap_err();
23332            match err {
23333                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
23334                    assert_eq!(
23335                        e,
23336                        spec.placement.estrategia(),
23337                        "PlacementWithoutClusters.estrategia must byte-equal \
23338                         Placement::estrategia() — the error carrier reads \
23339                         through the lifted accessor",
23340                    );
23341                }
23342                other => panic!(
23343                    "expected PlacementWithoutClusters, got {other:?} for \
23344                     estrategia={estrategia:?}"
23345                ),
23346            }
23347        }
23348
23349        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
23350        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
23351        // must byte-equal the accessor's return for both non-`Sharded`
23352        // strategies.
23353        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
23354            let mut spec = three_member_spec();
23355            spec.placement.estrategia = estrategia;
23356            spec.placement.shard_key = Some("tenantId".into());
23357            let err = spec.validate().unwrap_err();
23358            match err {
23359                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
23360                    assert_eq!(
23361                        e,
23362                        spec.placement.estrategia(),
23363                        "ShardKeyOnNonSharded.estrategia must byte-equal \
23364                         Placement::estrategia() — the non-Sharded-arm \
23365                         refusal reads through the lifted accessor",
23366                    );
23367                }
23368                other => panic!(
23369                    "expected ShardKeyOnNonSharded, got {other:?} for \
23370                     estrategia={estrategia:?}"
23371                ),
23372            }
23373        }
23374    }
23375
23376    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
23377    //
23378    // The [`Placement::clusters`] accessor lift is the second slice-return
23379    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
23380    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
23381    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
23382    // below cover (1) the accessor's byte-equal projection against the raw
23383    // field access across the empty / singleton / cohort fixtures the
23384    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
23385    // and the per-cluster validate loop fan between, and (2) the two-
23386    // consumer coherence of the paired pre-flight refusal probe and the
23387    // per-cluster validate loop routing through the accessor on both arms.
23388
23389    #[test]
23390    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
23391        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
23392        // [`Placement::clusters`] must return the `:placement :clusters`
23393        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
23394        // the same backing buffer the raw `self.clusters.as_slice()`
23395        // field access borrows from, byte-equal across every
23396        // representative fixture in the accept-set — the empty slice
23397        // (the pre-validation sentinel every
23398        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
23399        // the singleton slice (the minimal `SingleNode`-shape cohort),
23400        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
23401        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
23402        //
23403        // Pins against a future silent detour that returned
23404        // `&Vec<String>` (which would type-check but leak the storage-
23405        // side `Vec`'s grow/push/reserve surface no consumer of the
23406        // typed view reaches for), a fresh-allocated `Vec<String>` copy
23407        // (which would type-check via a coercion but silently break
23408        // every downstream caller that relied on the slice sharing the
23409        // backing buffer's identity), or an out-of-order or length-
23410        // drifted projection (which would silently split the paired
23411        // pre-flight `.is_empty()` refusal probe's input from the per-
23412        // cluster validate loop's traversal input).
23413        //
23414        // Peer of the sibling M2
23415        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23416        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23417        // `:supervisor` static-child-list axis, extended onto the M3
23418        // per-`:placement` distribution-target-list `Vec`-carry axis.
23419        let fixtures: Vec<Vec<String>> = vec![
23420            Vec::new(),
23421            vec!["rio".into()],
23422            vec!["rio".into(), "mar".into()],
23423            vec!["rio".into(), "mar".into(), "plo".into()],
23424        ];
23425        for clusters in fixtures {
23426            let p = Placement {
23427                clusters: clusters.clone(),
23428                ..Placement::default()
23429            };
23430            assert_eq!(
23431                p.clusters(),
23432                clusters.as_slice(),
23433                "Placement::clusters must return :placement :clusters \
23434                 verbatim (got {:?}, expected {:?})",
23435                p.clusters(),
23436                clusters.as_slice(),
23437            );
23438            assert_eq!(
23439                p.clusters(),
23440                p.clusters.as_slice(),
23441                "Placement::clusters accessor and .clusters.as_slice() \
23442                 field access must byte-equal — the accessor is the \
23443                 substrate-primitive typed dispatch every downstream \
23444                 cluster-pool consumer must route through",
23445            );
23446            assert_eq!(
23447                p.clusters().len(),
23448                p.clusters.len(),
23449                "Placement::clusters().len() must byte-equal \
23450                 self.clusters.len() — a length-drift would silently \
23451                 split the paired pre-flight `.is_empty()` refusal \
23452                 probe input from the per-cluster validate loop's \
23453                 traversal input",
23454            );
23455        }
23456    }
23457
23458    #[test]
23459    fn validate_placement_reads_through_lifted_clusters_accessor() {
23460        // Two-consumer coherence pin: the
23461        // [`AplicacaoSpec::validate_placement`] pre-flight
23462        // `self.placement.clusters().is_empty()` refusal probe (which
23463        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
23464        // the accessor projects the empty slice) and the per-cluster
23465        // validate loop's `for c in self.placement.clusters()`
23466        // traversal (which must reach every entry in the same order
23467        // the accessor projects, so both the per-entry value-shape
23468        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
23469        // and the duplicate-detection HashSet insert that trips
23470        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
23471        // accessor's projection) must both key off the lifted
23472        // accessor, so any future rebrand on the typed slot's reader
23473        // shape lands at exactly one place. Pins the two-site
23474        // coherence by exercising each production consumer end-to-end:
23475        // (1) the `PlacementWithoutClusters` refusal under the empty
23476        // slice, (2) the `PlacementClusterInvalid` refusal fires on
23477        // the second entry of a two-cluster cohort whose head is
23478        // valid but tail is not (which requires the loop to reach the
23479        // second entry through the accessor), and (3) the
23480        // `PlacementClusterDuplicate` refusal fires on the second
23481        // entry of a two-cluster cohort that shares a name (which
23482        // requires the loop to reach both entries — a first-entry-only
23483        // projection would silently pass since the dedup HashSet has
23484        // room for the first insert).
23485        //
23486        // Peer of the sibling M2
23487        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23488        // (bc92bce) coherence pin on the per-`:supervisor` static-
23489        // child-list axis, extended onto the M3 per-`:placement`
23490        // distribution-target-list `Vec`-carry axis.
23491
23492        // (1) Pre-flight `.is_empty()` probe: the empty slice must
23493        // trip `PlacementWithoutClusters`.
23494        let mut spec = three_member_spec();
23495        spec.placement.clusters = Vec::new();
23496        match spec.validate().unwrap_err() {
23497            AplicacaoError::PlacementWithoutClusters { .. } => {}
23498            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
23499        }
23500        assert!(
23501            spec.placement.clusters().is_empty(),
23502            "the pre-flight refusal input must be the empty slice per \
23503             the accessor's projection",
23504        );
23505
23506        // (2) Per-cluster validate loop: a two-cluster cohort with an
23507        // invalid tail entry must trip `PlacementClusterInvalid` on
23508        // the tail — the loop must reach the second entry through
23509        // the accessor.
23510        let mut spec = three_member_spec();
23511        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
23512        match spec.validate().unwrap_err() {
23513            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
23514                assert_eq!(
23515                    cluster, "BAD_CLUSTER",
23516                    "PlacementClusterInvalid.cluster must carry the \
23517                     tail entry the loop reached through the accessor",
23518                );
23519            }
23520            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
23521        }
23522        assert_eq!(
23523            spec.placement.clusters().len(),
23524            2,
23525            "the per-cluster validate loop's traversal input must be \
23526             a two-element slice per the accessor's projection",
23527        );
23528
23529        // (3) Per-cluster validate loop: a two-cluster cohort that
23530        // shares a name must trip `PlacementClusterDuplicate` on the
23531        // second entry — the loop must reach both entries through the
23532        // accessor for the dedup HashSet's second insert to collide.
23533        let mut spec = three_member_spec();
23534        spec.placement.clusters = vec!["rio".into(), "rio".into()];
23535        match spec.validate().unwrap_err() {
23536            AplicacaoError::PlacementClusterDuplicate { cluster } => {
23537                assert_eq!(
23538                    cluster, "rio",
23539                    "PlacementClusterDuplicate.cluster must carry the \
23540                     shared cluster name verbatim",
23541                );
23542            }
23543            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
23544        }
23545        assert_eq!(
23546            spec.placement.clusters().len(),
23547            2,
23548            "the per-cluster validate loop's traversal input must be \
23549             a two-element slice per the accessor's projection",
23550        );
23551    }
23552
23553    #[test]
23554    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
23555        // The canonical per-`:membros` member-list-slice-shape pin:
23556        // [`AplicacaoSpec::membros`] must return the `:membros` typed
23557        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
23558        // same backing buffer the raw `self.membros.as_slice()` field
23559        // access borrows from, byte-equal across every representative
23560        // fixture in the accept-set — the empty slice (the pre-
23561        // validation sentinel every [`AplicacaoError::NoMembros`]
23562        // refusal keys off), the singleton slice (the minimal one-
23563        // Servico Aplicacao shape), and multi-entry cohorts (the peer
23564        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
23565        // load-bearing identity of the application graph).
23566        //
23567        // Pins against a future silent detour that returned
23568        // `&Vec<Membro>` (which would type-check but leak the storage-
23569        // side `Vec`'s grow/push/reserve surface no consumer of the
23570        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
23571        // (which would type-check via a coercion but silently break
23572        // every downstream caller that relied on the slice sharing the
23573        // backing buffer's identity), or an out-of-order or length-
23574        // drifted projection (which would silently split the paired
23575        // `HashSet<&str>` name-set seed's collect input from the
23576        // pre-flight `.is_empty()` refusal probe's input from the per-
23577        // member validate loop's traversal input from the
23578        // programs.yaml emitter's per-entry fan-out loop's input from
23579        // the `feira app graph` per-member print traversal's input).
23580        //
23581        // Peer of the sibling M2
23582        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23583        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23584        // `:supervisor` static-child-list axis and the sibling M3
23585        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
23586        // (a6e18d7) `&[String]` byte-equal pin on the per-
23587        // `:placement` distribution-target-list axis — extends the
23588        // slice-return-accessor byte-equal-projection discipline onto
23589        // the outermost M3 mesh-slot type's per-Aplicacao member-list
23590        // `Vec`-carry axis.
23591        let fixtures: Vec<Vec<Membro>> = vec![
23592            Vec::new(),
23593            vec![membro("catalog", "^0.1")],
23594            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
23595            vec![
23596                membro("catalog", "^0.1"),
23597                membro("cart", "^0.1"),
23598                membro("payment", "^0.2"),
23599            ],
23600        ];
23601        for membros in fixtures {
23602            let s = AplicacaoSpec {
23603                membros: membros.clone(),
23604                contratos: Vec::new(),
23605                politicas: MeshPolicy::default(),
23606                placement: Placement::default(),
23607                entrada: None,
23608            };
23609            assert_eq!(
23610                s.membros(),
23611                membros.as_slice(),
23612                "AplicacaoSpec::membros must return :membros verbatim \
23613                 (got {:?}, expected {:?})",
23614                s.membros(),
23615                membros.as_slice(),
23616            );
23617            assert_eq!(
23618                s.membros(),
23619                s.membros.as_slice(),
23620                "AplicacaoSpec::membros accessor and .membros.as_slice() \
23621                 field access must byte-equal — the accessor is the \
23622                 substrate-primitive typed dispatch every downstream \
23623                 member-list consumer must route through",
23624            );
23625            assert_eq!(
23626                s.membros().len(),
23627                s.membros.len(),
23628                "AplicacaoSpec::membros().len() must byte-equal \
23629                 self.membros.len() — a length-drift would silently \
23630                 split the paired `HashSet<&str>` name-set seed's \
23631                 collect input from the pre-flight `.is_empty()` \
23632                 refusal probe input from the per-member validate \
23633                 loop's traversal input",
23634            );
23635        }
23636    }
23637
23638    #[test]
23639    fn validate_reads_through_lifted_membros_accessor() {
23640        // Three-consumer coherence pin: the
23641        // [`AplicacaoSpec::validate_membros`] pre-flight
23642        // `self.membros().is_empty()` refusal probe (which must trip
23643        // [`AplicacaoError::NoMembros`] when the accessor projects the
23644        // empty slice), the same method's per-member validate loop's
23645        // `for m in self.membros()` traversal (which must reach every
23646        // entry in the same order the accessor projects, so both the
23647        // per-entry empty-`:caixa` gate that trips
23648        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
23649        // detection `insert_first_seen` that trips
23650        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
23651        // projection), and the peer [`AplicacaoSpec::validate`]'s
23652        // `HashSet<&str>` name-set seed's
23653        // `self.membros().iter().map(Membro::nome).collect()` collect
23654        // input (which every `:contratos` `:de` / `:para` membership
23655        // lookup rejects an unknown name against) must all three key
23656        // off the lifted accessor, so any future rebrand on the typed
23657        // slot's reader shape lands at exactly one place. Pins the
23658        // three-site coherence by exercising each production consumer
23659        // end-to-end: (1) the `NoMembros` refusal under the empty
23660        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
23661        // second entry of a two-member cohort whose head is valid but
23662        // tail has an empty `:caixa` (which requires the loop to
23663        // reach the second entry through the accessor), and (3) the
23664        // `MembroDuplicate` refusal fires on the second entry of a
23665        // two-member cohort that shares a `:caixa` name (which
23666        // requires the loop to reach both entries through the
23667        // accessor for the dedup HashSet's second insert to collide).
23668        //
23669        // Peer of the sibling M2
23670        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
23671        // (bc92bce) coherence pin on the per-`:supervisor` static-
23672        // child-list axis and the sibling M3
23673        // `validate_placement_reads_through_lifted_clusters_accessor`
23674        // (a6e18d7) coherence pin on the per-`:placement` distribution-
23675        // target-list axis — extends the slice-return-accessor
23676        // multi-consumer coherence discipline onto the outermost M3
23677        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
23678
23679        // (1) Pre-flight `.is_empty()` probe: the empty slice must
23680        // trip `NoMembros`.
23681        let mut spec = three_member_spec();
23682        spec.membros = Vec::new();
23683        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
23684        assert!(
23685            spec.membros().is_empty(),
23686            "the pre-flight refusal input must be the empty slice per \
23687             the accessor's projection",
23688        );
23689
23690        // (2) Per-member validate loop: a two-member cohort with an
23691        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
23692        // the tail — the loop must reach the second entry through
23693        // the accessor.
23694        let mut spec = three_member_spec();
23695        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
23696        assert_eq!(
23697            spec.validate().unwrap_err(),
23698            AplicacaoError::MembroCaixaEmpty,
23699        );
23700        assert_eq!(
23701            spec.membros().len(),
23702            2,
23703            "the per-member validate loop's traversal input must be \
23704             a two-element slice per the accessor's projection",
23705        );
23706
23707        // (3) Per-member validate loop: a two-member cohort that
23708        // shares a `:caixa` name must trip `MembroDuplicate` on the
23709        // second entry — the loop must reach both entries through the
23710        // accessor for the dedup HashSet's second insert to collide.
23711        let mut spec = three_member_spec();
23712        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
23713        match spec.validate().unwrap_err() {
23714            AplicacaoError::MembroDuplicate { caixa } => {
23715                assert_eq!(
23716                    caixa, "catalog",
23717                    "MembroDuplicate.caixa must carry the shared \
23718                     member name verbatim",
23719                );
23720            }
23721            other => panic!("expected MembroDuplicate, got {other:?}"),
23722        }
23723        assert_eq!(
23724            spec.membros().len(),
23725            2,
23726            "the per-member validate loop's traversal input must be \
23727             a two-element slice per the accessor's projection",
23728        );
23729    }
23730
23731    #[test]
23732    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
23733        // The canonical per-`:contratos` contract-list-slice-shape pin:
23734        // [`AplicacaoSpec::contratos`] must return the `:contratos`
23735        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
23736        // slice-view over the same backing buffer the raw
23737        // `self.contratos.as_slice()` field access borrows from, byte-
23738        // equal across every representative fixture in the accept-set —
23739        // the empty slice (the pre-validation "internal-only mesh" shape
23740        // an Aplicacao whose members exchange no typed edges renders
23741        // through), the singleton slice (the minimal one-edge Aplicacao
23742        // shape), and multi-entry cohorts (the peer multi-edge shapes
23743        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
23744        // of the application graph).
23745        //
23746        // Pins against a future silent detour that returned
23747        // `&Vec<WitContract>` (which would type-check but leak the
23748        // storage-side `Vec`'s grow/push/reserve surface no consumer of
23749        // the typed view reaches for), a fresh-allocated
23750        // `Vec<WitContract>` copy (which would type-check via a coercion
23751        // but silently break every downstream caller that relied on the
23752        // slice sharing the backing buffer's identity), or an out-of-
23753        // order or length-drifted projection (which would silently split
23754        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
23755        // seed's traversal input from the `detect_sync_cycles` per-edge
23756        // adjacency-list seed's traversal input from the
23757        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
23758        // BTreeMap grouping loop's traversal input from the
23759        // `feira app graph` per-contract print traversal's input).
23760        //
23761        // Peer of the immediately-adjacent sibling M3
23762        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
23763        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
23764        // node-list axis, the sibling M3
23765        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
23766        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
23767        // distribution-target-list axis, and the sibling M2
23768        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23769        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23770        // `:supervisor` static-child-list axis — extends the slice-
23771        // return-accessor byte-equal-projection discipline onto the
23772        // outermost M3 mesh-slot type's per-Aplicacao contract-list
23773        // `Vec`-carry axis, closing the last unlifted per-
23774        // `AplicacaoSpec` `Vec`-carry axis.
23775        let fixtures: Vec<Vec<WitContract>> = vec![
23776            Vec::new(),
23777            vec![contract_http("cart", "catalog", "/products/:id")],
23778            vec![
23779                contract_http("cart", "catalog", "/products/:id"),
23780                contract_http("cart", "payment", "/charge"),
23781            ],
23782            vec![
23783                contract_http("cart", "catalog", "/products/:id"),
23784                contract_http("cart", "payment", "/charge"),
23785                contract_http("payment", "catalog", "/audit"),
23786            ],
23787        ];
23788        for contratos in fixtures {
23789            let s = AplicacaoSpec {
23790                membros: vec![
23791                    membro("catalog", "^0.1"),
23792                    membro("cart", "^0.1"),
23793                    membro("payment", "^0.2"),
23794                ],
23795                contratos: contratos.clone(),
23796                politicas: MeshPolicy::default(),
23797                placement: Placement::default(),
23798                entrada: None,
23799            };
23800            assert_eq!(
23801                s.contratos(),
23802                contratos.as_slice(),
23803                "AplicacaoSpec::contratos must return :contratos verbatim \
23804                 (got {:?}, expected {:?})",
23805                s.contratos(),
23806                contratos.as_slice(),
23807            );
23808            assert_eq!(
23809                s.contratos(),
23810                s.contratos.as_slice(),
23811                "AplicacaoSpec::contratos accessor and \
23812                 .contratos.as_slice() field access must byte-equal — \
23813                 the accessor is the substrate-primitive typed dispatch \
23814                 every downstream contract-list consumer must route \
23815                 through",
23816            );
23817            assert_eq!(
23818                s.contratos().len(),
23819                s.contratos.len(),
23820                "AplicacaoSpec::contratos().len() must byte-equal \
23821                 self.contratos.len() — a length-drift would silently \
23822                 split the paired per-edge validate-loop's traversal \
23823                 input from the sync-cycle adjacency-list seed's \
23824                 traversal input from the cilium_network_policies \
23825                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
23826                 input from the `feira app graph` per-contract print \
23827                 traversal's input",
23828            );
23829        }
23830    }
23831
23832    #[test]
23833    fn validate_reads_through_lifted_contratos_accessor() {
23834        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
23835        // per-`:contratos` validate-loop's `for c in self.contratos()`
23836        // traversal (which must reach every entry in the same order the
23837        // accessor projects, so both the per-entry
23838        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
23839        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
23840        // dedup `HashSet` insert key off the accessor's projection),
23841        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
23842        // `for c in self.contratos()` adjacency-list seed (which drives
23843        // the sync-subgraph deadlock-detection gate via
23844        // [`AplicacaoError::SyncCycle`]), and the peer
23845        // [`caixa_mesh::cilium_network_policies`]'s
23846        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
23847        // grouping loop (which drives the per-CNP fan-out) must all
23848        // three key off the lifted accessor, so any future rebrand on
23849        // the typed slot's reader shape lands at exactly one place. Pins
23850        // the three-site coherence by exercising the two caixa-core
23851        // production consumers end-to-end: (1) the empty-`:contratos`
23852        // slice must validate without a per-edge diagnostic (the
23853        // per-edge loop is a no-op under the empty projection), (2) the
23854        // `ContratoMemberMissing` refusal fires on the second entry of a
23855        // two-edge cohort whose head references a valid member but tail
23856        // references a phantom name (which requires the loop to reach
23857        // the second entry through the accessor), and (3) the
23858        // `SyncCycle` refusal fires on a self-referential two-edge
23859        // cohort through the sync-cycle detector's peer projection
23860        // (which requires the detector to iterate the accessor's
23861        // projection to add the back-edge to its adjacency list).
23862        //
23863        // Peer of the sibling M3
23864        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
23865        // three-consumer coherence pin on the per-`:membros` node-list
23866        // axis and the sibling M3
23867        // `validate_placement_reads_through_lifted_clusters_accessor`
23868        // (a6e18d7) coherence pin on the per-`:placement` distribution-
23869        // target-list axis — extends the slice-return-accessor multi-
23870        // consumer coherence discipline onto the outermost M3 mesh-slot
23871        // type's per-Aplicacao contract-list `Vec`-carry axis.
23872
23873        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
23874        // and no per-edge diagnostic surfaces. Validate succeeds on
23875        // the well-formed `:membros` head.
23876        let mut spec = three_member_spec();
23877        spec.contratos = Vec::new();
23878        assert!(
23879            spec.validate().is_ok(),
23880            "empty :contratos must validate — the per-edge loop is a \
23881             no-op under the accessor's empty projection",
23882        );
23883        assert!(
23884            spec.contratos().is_empty(),
23885            "the per-edge validate loop's traversal input must be the \
23886             empty slice per the accessor's projection",
23887        );
23888
23889        // (2) Per-edge validate loop: a two-edge cohort whose tail
23890        // references a phantom `:para` member must trip
23891        // `ContratoMemberMissing` on the tail — the loop must reach
23892        // the second entry through the accessor for the membership
23893        // lookup to fail on the phantom name.
23894        let mut spec = three_member_spec();
23895        spec.contratos = vec![
23896            contract_http("cart", "catalog", "/products/:id"),
23897            contract_http("cart", "phantom", "/x"),
23898        ];
23899        let err = spec.validate().unwrap_err();
23900        assert!(
23901            matches!(
23902                err,
23903                AplicacaoError::ContratoMemberMissing { ref caixa }
23904                    if caixa == "phantom"
23905            ),
23906            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
23907        );
23908        assert_eq!(
23909            spec.contratos().len(),
23910            2,
23911            "the per-edge validate loop's traversal input must be \
23912             a two-element slice per the accessor's projection",
23913        );
23914
23915        // (3) Sync-cycle detector: a two-edge synchronous cohort
23916        // whose second edge closes the sync-subgraph back onto the
23917        // first must trip [`AplicacaoError::ContratoCycle`] — the
23918        // detector must iterate the accessor's projection to add
23919        // both edges to its adjacency list, so a length-drift on
23920        // the accessor's projection would silently disagree with
23921        // the sync-cycle detector on which edge closes the loop.
23922        // Peer projection to the `validate` per-edge loop above:
23923        // the sync-cycle detector routes through the same lifted
23924        // accessor, so a rebrand of the reader shape lands at one
23925        // place. Uses a two-edge cohort (cart → catalog → cart)
23926        // because the per-edge `ContratoSelfLoop` gate fires before
23927        // the sync-cycle detector on a single self-referential edge
23928        // (`cart → cart`) — the cycle-detector's input must be a
23929        // multi-edge cohort for its per-edge traversal input to be
23930        // observably wider than the per-edge validate loop's input.
23931        let mut spec = three_member_spec();
23932        spec.contratos = vec![
23933            contract_http("cart", "catalog", "/products/:id"),
23934            contract_http("catalog", "cart", "/callback"),
23935        ];
23936        let err = spec.validate().unwrap_err();
23937        assert!(
23938            matches!(err, AplicacaoError::ContratoCycle { .. }),
23939            "expected ContratoCycle from the sync-cycle detector on a \
23940             two-edge back-edge cohort, got {err:?}",
23941        );
23942        assert_eq!(
23943            spec.contratos().len(),
23944            2,
23945            "the sync-cycle detector's traversal input must be a \
23946             two-element slice per the accessor's projection",
23947        );
23948    }
23949
23950    #[test]
23951    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
23952        // The canonical per-`:politicas` outer-composite-reference-shape
23953        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
23954        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
23955        // the same backing storage the raw `&self.politicas` field
23956        // access borrows from, byte-equal across every representative
23957        // fixture in the accept-set — the default `MeshPolicy` (the
23958        // author-empty "no policy on any axis" shape whose
23959        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
23960        // shapes carrying one axis at a time
23961        // (`{mtls_required, timeout, retries, circuit_breaker,
23962        // rate_limit}` — the minimal five-axis fan-out over the
23963        // per-axis lifted accessor family every downstream mesh-artifact
23964        // emitter dispatches on), and the multi-axis composite (the
23965        // canonical `three_member_spec` fixture's `{timeout, retries,
23966        // mtls_required}` triple — the load-bearing shape every
23967        // Aplicacao-scoped fixture in this suite constructs).
23968        //
23969        // Pins against a future silent detour that returned a fresh-
23970        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
23971        // impl but silently break every downstream caller that relied
23972        // on the reference sharing the composite's backing identity), a
23973        // reference to an operator-resolved overlay (the future
23974        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
23975        // acknowledges — its resolution must land at exactly this
23976        // accessor body, not silently divert the raw slot away from a
23977        // second consumer), or an axis-shuffled projection (a future
23978        // detour that swapped `timeout` and `retries` through the
23979        // accessor would silently split the paired `validate_politicas`
23980        // per-axis bracket-dispatch's traversal input from the peer
23981        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
23982        // emitter's fan-out input from the peer
23983        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
23984        // overlay emitter's fan-out input).
23985        //
23986        // Peer of the sibling M3
23987        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
23988        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
23989        // node-list `Vec`-carry axis and the sibling M3
23990        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
23991        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
23992        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
23993        // accessor byte-equal-projection discipline onto the outermost
23994        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
23995        // reference axis, the first `&Composite`-return accessor on the
23996        // outer [`AplicacaoSpec`] type.
23997        let fixtures: Vec<MeshPolicy> = vec![
23998            MeshPolicy::default(),
23999            MeshPolicy {
24000                mtls_required: Some(true),
24001                ..MeshPolicy::default()
24002            },
24003            MeshPolicy {
24004                mtls_required: Some(false),
24005                ..MeshPolicy::default()
24006            },
24007            MeshPolicy {
24008                timeout: Some(Duration::from_secs(30)),
24009                ..MeshPolicy::default()
24010            },
24011            MeshPolicy {
24012                retries: Some(3),
24013                ..MeshPolicy::default()
24014            },
24015            MeshPolicy {
24016                circuit_breaker: Some(CircuitBreaker {
24017                    max_failures: 5,
24018                    window: Duration::from_secs(30),
24019                }),
24020                ..MeshPolicy::default()
24021            },
24022            MeshPolicy {
24023                rate_limit: Some(RateLimit {
24024                    rate: 100,
24025                    window: Duration::from_secs(1),
24026                }),
24027                ..MeshPolicy::default()
24028            },
24029            MeshPolicy {
24030                timeout: Some(Duration::from_secs(30)),
24031                retries: Some(3),
24032                mtls_required: Some(true),
24033                ..MeshPolicy::default()
24034            },
24035        ];
24036        for politicas in fixtures {
24037            let s = AplicacaoSpec {
24038                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24039                contratos: Vec::new(),
24040                politicas: politicas.clone(),
24041                placement: Placement::default(),
24042                entrada: None,
24043            };
24044            assert_eq!(
24045                *s.politicas(),
24046                politicas,
24047                "AplicacaoSpec::politicas must return :politicas verbatim \
24048                 (got {:?}, expected {:?})",
24049                s.politicas(),
24050                politicas,
24051            );
24052            assert!(
24053                std::ptr::eq(s.politicas(), &s.politicas),
24054                "AplicacaoSpec::politicas accessor and &self.politicas \
24055                 field access must borrow the same backing storage — \
24056                 the accessor is the substrate-primitive typed dispatch \
24057                 every downstream mesh-policy composite consumer must \
24058                 route through, and a reference-identity split would \
24059                 silently break every consumer that relied on the \
24060                 borrow sharing the composite's storage",
24061            );
24062            assert_eq!(
24063                s.politicas().is_empty(),
24064                s.politicas.is_empty(),
24065                "AplicacaoSpec::politicas().is_empty() must byte-equal \
24066                 self.politicas.is_empty() — an emptiness-drift would \
24067                 silently split the paired `validate_politicas` \
24068                 per-axis bracket-dispatch's seed from the peer \
24069                 caixa-mesh CNP mTLS-overlay emitter's key from the \
24070                 peer caixa-mesh HTTPRoute timeout+retry overlay \
24071                 emitter's key",
24072            );
24073        }
24074    }
24075
24076    #[test]
24077    fn validate_politicas_reads_through_lifted_politicas_accessor() {
24078        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
24079        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
24080        // followed by the per-axis fan-out `p.timeout()` /
24081        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
24082        // the lifted axis-level accessor family) must key off the
24083        // lifted outer accessor, so any future rebrand on the typed
24084        // slot's outer-composite reader shape lands at exactly one
24085        // place. Pins the multi-axis coherence by exercising each
24086        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
24087        // a `Some(Duration::ZERO)` timeout under the outer accessor's
24088        // reference projection, (2) `PolicyRetriesZero` fires on a
24089        // `Some(0)` retries under the same projection, and (3) an
24090        // empty [`MeshPolicy::default`] passes `validate_politicas` —
24091        // the outer accessor's reference-projection reaches every
24092        // per-axis branch without silently short-circuiting any.
24093        //
24094        // Peer of the sibling M3
24095        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24096        // three-consumer coherence pin on the per-`:membros` node-list
24097        // axis and the sibling M3
24098        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24099        // three-consumer coherence pin on the per-`:contratos`
24100        // edge-list axis — extends the multi-consumer coherence
24101        // discipline onto the outermost M3 mesh-slot type's per-
24102        // Aplicacao mesh-policy composite-reference axis, the first
24103        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
24104        // type.
24105
24106        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
24107        // reference projection: a `Some(Duration::ZERO)` timeout must
24108        // trip the zero-floor gate. The bracket-dispatch's first arm
24109        // reads `p.timeout()` on the reference returned by the outer
24110        // accessor.
24111        let mut spec = three_member_spec();
24112        spec.politicas.timeout = Some(Duration::ZERO);
24113        spec.politicas.retries = None;
24114        spec.politicas.circuit_breaker = None;
24115        spec.politicas.rate_limit = None;
24116        assert_eq!(
24117            spec.validate().unwrap_err(),
24118            AplicacaoError::PolicyTimeoutZero,
24119        );
24120        assert!(
24121            std::ptr::eq(spec.politicas(), &spec.politicas),
24122            "the `validate_politicas` per-axis bracket-dispatch's \
24123             traversal input must be the same backing composite the \
24124             accessor's reference projection borrows from",
24125        );
24126
24127        // (2) `PolicyRetriesZero` refusal under the outer accessor's
24128        // reference projection: a `Some(0)` retries must trip the
24129        // zero-floor gate. The bracket-dispatch's second arm reads
24130        // `p.retries()` on the reference returned by the outer accessor.
24131        let mut spec = three_member_spec();
24132        spec.politicas.timeout = None;
24133        spec.politicas.retries = Some(0);
24134        spec.politicas.circuit_breaker = None;
24135        spec.politicas.rate_limit = None;
24136        assert_eq!(
24137            spec.validate().unwrap_err(),
24138            AplicacaoError::PolicyRetriesZero,
24139        );
24140
24141        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
24142        // — every per-axis arm short-circuits on `None`, so the outer
24143        // accessor's reference projection reaches the fall-through
24144        // `Ok(())` without any per-axis refusal firing.
24145        let mut spec = three_member_spec();
24146        spec.politicas = MeshPolicy::default();
24147        assert!(
24148            spec.validate().is_ok(),
24149            "an empty `MeshPolicy` must pass `validate_politicas` — \
24150             every per-axis arm short-circuits on `None` under the \
24151             outer accessor's reference projection",
24152        );
24153        assert!(
24154            spec.politicas().is_empty(),
24155            "the outer accessor's reference projection must be the \
24156             empty composite per the `MeshPolicy::default()` fixture",
24157        );
24158    }
24159
24160    #[test]
24161    #[allow(clippy::too_many_lines)]
24162    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
24163        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
24164        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
24165        // must both key off the lifted axis-level accessors
24166        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
24167        // the peer `:circuit-breaker` / `:rate-limit` arms already
24168        // routing through [`MeshPolicy::circuit_breaker`] /
24169        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
24170        // per axis on the substrate primitive" shape at the fan-out
24171        // (four axes, four accessors, no raw-field-access site
24172        // anywhere on the bracket-dispatch). Pins the per-axis
24173        // coherence at the accept-set boundaries the bracket carves:
24174        //   1. accessor byte-equal to raw field on every representative
24175        //      accept-set value (`None`, sub-cap, at-cap, past-cap
24176        //      sentinel) — a future accessor drift that no longer
24177        //      shipped the raw slot verbatim would surface here,
24178        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
24179        //      routed through the accessor's projection, proving the
24180        //      first arm reads through the accessor rather than a
24181        //      silent-detour peer-axis field access,
24182        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
24183        //      through the accessor's projection, proving the second
24184        //      arm reads through the accessor,
24185        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
24186        //      passes validate under the accessor projection (paired
24187        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
24188        //      sibling axis), pinning the upper-boundary accept-arm
24189        //      also routes through the accessor.
24190        //
24191        // Peer of the sibling M3
24192        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24193        // outer-composite-reference coherence pin (which asserts the
24194        // `let p = self.politicas()` seed); extends the discipline onto
24195        // the per-axis fan-out layer that consumes the seed's
24196        // reference. Same shape as
24197        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24198        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24199        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
24200        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
24201
24202        // (1) Accessor byte-equal to raw field on the `:timeout` axis
24203        // across the accept-set boundaries the bracket dispatch's
24204        // three-arm gate carves out
24205        // ([`crate::render::require_positive_canonical_bounded_duration`]
24206        // — zero-floor + canonical-form + upper-cap).
24207        for timeout in [
24208            None,
24209            Some(Duration::ZERO),
24210            Some(Duration::from_millis(1)),
24211            Some(POLICY_TIMEOUT_MAX),
24212        ] {
24213            let p = MeshPolicy {
24214                timeout,
24215                ..MeshPolicy::default()
24216            };
24217            assert_eq!(
24218                p.timeout(),
24219                p.timeout,
24220                "MeshPolicy::timeout accessor must byte-equal the raw \
24221                 .timeout field across every accept-set boundary the \
24222                 validate_politicas :timeout arm carves out — a drift \
24223                 here would silently split the validate bracket's arm \
24224                 from the peer caixa-mesh HTTPRoute timeout-overlay \
24225                 emitter's read",
24226            );
24227        }
24228
24229        // (2) Accessor byte-equal to raw field on the `:retries` axis
24230        // across the accept-set boundaries the bracket dispatch's
24231        // two-arm gate carves out
24232        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
24233        // + upper-cap).
24234        for retries in [
24235            None,
24236            Some(0u32),
24237            Some(1u32),
24238            Some(POLICY_RETRIES_MAX),
24239            Some(POLICY_RETRIES_MAX + 1),
24240            Some(u32::MAX),
24241        ] {
24242            let p = MeshPolicy {
24243                retries,
24244                ..MeshPolicy::default()
24245            };
24246            assert_eq!(
24247                p.retries(),
24248                p.retries,
24249                "MeshPolicy::retries accessor must byte-equal the raw \
24250                 .retries field across every accept-set boundary the \
24251                 validate_politicas :retries arm carves out — a drift \
24252                 here would silently split the validate bracket's arm \
24253                 from the peer caixa-mesh HTTPRoute retry-overlay \
24254                 emitter's read",
24255            );
24256        }
24257
24258        // (3) `PolicyTimeoutZero` fires on the accessor-projected
24259        // zero-floor boundary. A silent detour that no longer read
24260        // through `p.timeout()` (a peer-axis field read, an accidental
24261        // Option::and-then chain that collapsed the None arm to Some,
24262        // an accessor rebrand that clamped the return through the
24263        // upper cap) would fail to refuse here.
24264        let mut spec = three_member_spec();
24265        spec.politicas.timeout = Some(Duration::ZERO);
24266        spec.politicas.retries = None;
24267        spec.politicas.circuit_breaker = None;
24268        spec.politicas.rate_limit = None;
24269        assert_eq!(
24270            spec.politicas().timeout(),
24271            Some(Duration::ZERO),
24272            "the accessor projection must reflect the fixture's \
24273             `Some(Duration::ZERO)` :timeout verbatim",
24274        );
24275        assert_eq!(
24276            spec.validate().unwrap_err(),
24277            AplicacaoError::PolicyTimeoutZero,
24278            "the validate_politicas :timeout zero-floor arm must fire \
24279             through the lifted accessor's projection — a silent \
24280             detour to a peer-axis field would fail to refuse",
24281        );
24282
24283        // (4) `PolicyRetriesZero` fires on the accessor-projected
24284        // zero-floor boundary on the sibling `:retries` axis.
24285        let mut spec = three_member_spec();
24286        spec.politicas.timeout = None;
24287        spec.politicas.retries = Some(0);
24288        spec.politicas.circuit_breaker = None;
24289        spec.politicas.rate_limit = None;
24290        assert_eq!(
24291            spec.politicas().retries(),
24292            Some(0),
24293            "the accessor projection must reflect the fixture's \
24294             `Some(0)` :retries verbatim",
24295        );
24296        assert_eq!(
24297            spec.validate().unwrap_err(),
24298            AplicacaoError::PolicyRetriesZero,
24299            "the validate_politicas :retries zero-floor arm must fire \
24300             through the lifted accessor's projection — a silent \
24301             detour to a peer-axis field would fail to refuse",
24302        );
24303
24304        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
24305        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
24306        // must pass validate under the accessor projection — pins the
24307        // upper-boundary accept-arm also routes through the lifted
24308        // accessor (a drift that clamped or short-circuited at the
24309        // upper boundary would fail the whole-spec validate here).
24310        let mut spec = three_member_spec();
24311        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
24312        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
24313        spec.politicas.circuit_breaker = None;
24314        spec.politicas.rate_limit = None;
24315        assert_eq!(
24316            spec.politicas().timeout(),
24317            Some(POLICY_TIMEOUT_MAX),
24318            "the accessor projection must reflect the fixture's \
24319             at-cap :timeout verbatim",
24320        );
24321        assert_eq!(
24322            spec.politicas().retries(),
24323            Some(POLICY_RETRIES_MAX),
24324            "the accessor projection must reflect the fixture's \
24325             at-cap :retries verbatim",
24326        );
24327        assert!(
24328            spec.validate().is_ok(),
24329            "at-cap :timeout + :retries must pass validate under the \
24330             accessor projection — the upper-boundary accept-arm on \
24331             both axes routes through the lifted accessor",
24332        );
24333    }
24334
24335    #[test]
24336    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
24337        // The canonical per-`:placement` outer-composite-reference-shape
24338        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
24339        // typed `Placement` verbatim as a `&Placement` reference over the
24340        // same backing storage the raw `&self.placement` field access
24341        // borrows from, byte-equal across every representative fixture in
24342        // the accept-set — the default `Placement` (the substrate seed
24343        // shape whose [`PlacementStrategy::default`] evaluates to
24344        // `SingleNode` with an empty `:clusters` pool and both
24345        // optional-scalar axes `None`), and every canonical strategy /
24346        // cluster-pool / optional-scalar combination the
24347        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
24348        // three [`PlacementStrategy`] variants — `SingleNode`,
24349        // `Replicated`, `Sharded` — cross-projected with a non-empty
24350        // `:clusters` pool and, on the `Sharded` arm, a non-empty
24351        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
24352        // canonical `three_member_spec` `Replicated` fixture's
24353        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
24354        //
24355        // Pins against a future silent detour that returned a fresh-
24356        // cloned `Placement` copy (which would type-check via a `Clone`
24357        // impl but silently break every downstream caller that relied on
24358        // the reference sharing the composite's backing identity), a
24359        // reference to an operator-resolved overlay (the future per-
24360        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
24361        // acknowledges — its resolution must land at exactly this
24362        // accessor body, not silently divert the raw slot away from a
24363        // second consumer), or an axis-shuffled projection (a future
24364        // detour that swapped `clusters` and `affinity` through the
24365        // accessor would silently split the paired `validate_placement`
24366        // per-axis bracket-dispatch's traversal input from the peer
24367        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
24368        // programs.yaml distribution-annotation emitter's fan-out input
24369        // from the peer `feira app graph` per-Aplicacao print line's
24370        // input).
24371        //
24372        // Peer of the sibling M3
24373        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24374        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
24375        // outer mesh-policy composite-reference axis, and of the sibling
24376        // slice-return `aplicacao_spec_membros_returns_membros_slice_
24377        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
24378        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
24379        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
24380        // the outer-accessor byte-equal-projection discipline onto the
24381        // outermost M3 mesh-slot type's per-Aplicacao distribution
24382        // composite-reference axis, the second `&Composite`-return
24383        // accessor on the outer [`AplicacaoSpec`] type.
24384        let fixtures: Vec<Placement> = vec![
24385            Placement::default(),
24386            Placement {
24387                estrategia: PlacementStrategy::SingleNode,
24388                clusters: vec!["rio".into()],
24389                affinity: None,
24390                shard_key: None,
24391            },
24392            Placement {
24393                estrategia: PlacementStrategy::Replicated,
24394                clusters: vec!["rio".into(), "mar".into()],
24395                affinity: None,
24396                shard_key: None,
24397            },
24398            Placement {
24399                estrategia: PlacementStrategy::Replicated,
24400                clusters: vec!["rio".into(), "mar".into()],
24401                affinity: Some("data-locality".into()),
24402                shard_key: None,
24403            },
24404            Placement {
24405                estrategia: PlacementStrategy::Sharded,
24406                clusters: vec!["rio".into(), "mar".into()],
24407                affinity: None,
24408                shard_key: Some("tenantId".into()),
24409            },
24410            Placement {
24411                estrategia: PlacementStrategy::Sharded,
24412                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
24413                affinity: Some("low-latency".into()),
24414                shard_key: Some("metadata.tenantId".into()),
24415            },
24416        ];
24417        for placement in fixtures {
24418            let s = AplicacaoSpec {
24419                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24420                contratos: Vec::new(),
24421                politicas: MeshPolicy::default(),
24422                placement: placement.clone(),
24423                entrada: None,
24424            };
24425            assert_eq!(
24426                *s.placement(),
24427                placement,
24428                "AplicacaoSpec::placement must return :placement verbatim \
24429                 (got {:?}, expected {:?})",
24430                s.placement(),
24431                placement,
24432            );
24433            assert!(
24434                std::ptr::eq(s.placement(), &s.placement),
24435                "AplicacaoSpec::placement accessor and &self.placement \
24436                 field access must borrow the same backing storage — the \
24437                 accessor is the substrate-primitive typed dispatch every \
24438                 downstream distribution-composite consumer must route \
24439                 through, and a reference-identity split would silently \
24440                 break every consumer that relied on the borrow sharing \
24441                 the composite's storage",
24442            );
24443            assert_eq!(
24444                s.placement().estrategia(),
24445                s.placement.estrategia,
24446                "AplicacaoSpec::placement().estrategia() must byte-equal \
24447                 self.placement.estrategia — a strategy-drift would \
24448                 silently split the paired `validate_placement` \
24449                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
24450                 peer caixa-mesh programs.yaml `placement.estrategia` \
24451                 emitter's key from the peer `feira app graph` printer's \
24452                 strategy label",
24453            );
24454            assert_eq!(
24455                s.placement().clusters(),
24456                s.placement.clusters.as_slice(),
24457                "AplicacaoSpec::placement().clusters() must byte-equal \
24458                 self.placement.clusters — a cluster-pool drift would \
24459                 silently split the paired `validate_placement` \
24460                 pre-flight `.is_empty()` refusal probe's traversal from \
24461                 the peer caixa-mesh programs.yaml `placement.clusters` \
24462                 emitter's fan-out from the peer `feira app graph` \
24463                 printer's cluster list",
24464            );
24465        }
24466    }
24467
24468    #[test]
24469    fn validate_placement_reads_through_lifted_placement_accessor() {
24470        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
24471        // per-axis bracket-dispatch seed (`let p = self.placement();`,
24472        // followed by the per-axis fan-out `p.clusters()` /
24473        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
24474        // lifted axis-level accessor family) must key off the lifted
24475        // outer accessor, so any future rebrand on the typed slot's
24476        // outer-composite reader shape lands at exactly one place. Pins
24477        // the multi-axis coherence by exercising each per-axis refusal
24478        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
24479        // `:clusters` pool under the outer accessor's reference
24480        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
24481        // strategy with a `None` `:shard-key` under the same projection,
24482        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
24483        // with a `Some` `:shard-key` under the same projection, and
24484        // (4) the canonical `three_member_spec` `Replicated` fixture
24485        // passes `validate_placement` under the outer accessor's
24486        // reference projection — the accessor's reference-projection
24487        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
24488        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
24489        // without silently short-circuiting any.
24490        //
24491        // Peer of the sibling M3
24492        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24493        // (534dc21) multi-axis coherence pin on the per-`:politicas`
24494        // outer mesh-policy composite-reference axis — extends the
24495        // multi-consumer coherence discipline onto the outermost M3
24496        // mesh-slot type's per-Aplicacao distribution composite-
24497        // reference axis, the second `&Composite`-return accessor on
24498        // the outer [`AplicacaoSpec`] type.
24499
24500        // (1) `PlacementWithoutClusters` refusal under the outer
24501        // accessor's reference projection: an empty `:clusters` pool
24502        // must trip the pre-flight refusal probe. The bracket-dispatch's
24503        // first arm reads `p.clusters()` on the reference returned by
24504        // the outer accessor.
24505        let mut spec = three_member_spec();
24506        spec.placement.clusters = Vec::new();
24507        assert_eq!(
24508            spec.validate().unwrap_err(),
24509            AplicacaoError::PlacementWithoutClusters {
24510                estrategia: PlacementStrategy::Replicated,
24511            },
24512        );
24513        assert!(
24514            std::ptr::eq(spec.placement(), &spec.placement),
24515            "the `validate_placement` per-axis bracket-dispatch's \
24516             traversal input must be the same backing composite the \
24517             accessor's reference projection borrows from",
24518        );
24519
24520        // (2) `ShardedWithoutKey` refusal under the outer accessor's
24521        // reference projection: a `Sharded` strategy with a `None`
24522        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
24523        // The bracket-dispatch's third arm reads `p.estrategia()` for
24524        // the match scrutinee then `p.shard_key()` for the cascade
24525        // scrutinee, both on the reference returned by the outer
24526        // accessor.
24527        let mut spec = three_member_spec();
24528        spec.placement.estrategia = PlacementStrategy::Sharded;
24529        spec.placement.shard_key = None;
24530        assert_eq!(
24531            spec.validate().unwrap_err(),
24532            AplicacaoError::ShardedWithoutKey,
24533        );
24534
24535        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
24536        // reference projection: a non-`Sharded` strategy with a `Some`
24537        // `:shard-key` must trip the declared-but-inert refusal. The
24538        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
24539        // + `p.estrategia()` for the diagnostic on the reference
24540        // returned by the outer accessor.
24541        let mut spec = three_member_spec();
24542        spec.placement.estrategia = PlacementStrategy::Replicated;
24543        spec.placement.shard_key = Some("tenantId".into());
24544        assert_eq!(
24545            spec.validate().unwrap_err(),
24546            AplicacaoError::ShardKeyOnNonSharded {
24547                estrategia: PlacementStrategy::Replicated,
24548                shard_key: "tenantId".into(),
24549            },
24550        );
24551
24552        // (4) Canonical `three_member_spec` `Replicated` fixture passes
24553        // `validate_placement` — every per-axis arm reaches the fall-
24554        // through `Ok(())` without any per-axis refusal firing under the
24555        // outer accessor's reference projection.
24556        let spec = three_member_spec();
24557        assert!(
24558            spec.validate().is_ok(),
24559            "the canonical Replicated placement fixture must pass \
24560             `validate_placement` — every per-axis arm short-circuits on \
24561             valid input under the outer accessor's reference projection",
24562        );
24563        assert_eq!(
24564            spec.placement().estrategia(),
24565            PlacementStrategy::Replicated,
24566            "the outer accessor's reference projection must be the \
24567             canonical Replicated fixture's strategy",
24568        );
24569        assert_eq!(
24570            spec.placement().clusters(),
24571            &["rio", "mar"],
24572            "the outer accessor's reference projection must be the \
24573             canonical Replicated fixture's cluster pool",
24574        );
24575    }
24576
24577    #[test]
24578    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
24579        // The canonical per-`:entrada` outer-composite-optional-
24580        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
24581        // the `:entrada` typed `Option<Entrada>` verbatim as an
24582        // `Option<&Entrada>` reference over the same backing storage
24583        // the raw `self.entrada.as_ref()` field access borrows from,
24584        // byte-equal across every representative fixture in the
24585        // accept-set — the author-omitted `None` shape (the
24586        // "internal-only mesh" partition every downstream external-
24587        // gateway emitter treats as "emit nothing"), the minimal
24588        // singleton `:entrada` composite (host + destination + empty
24589        // paths + default port), the paths-carrying composite (the
24590        // canonical `three_member_spec` fixture's ["/api" "/health"]
24591        // path-list shape every HTTPRoute per-rule fan-out emitter
24592        // reads), and the non-default port composite (the canonical
24593        // custom-port shape the port-fallback resolver reads).
24594        //
24595        // Pins against a future silent detour that returned a fresh-
24596        // cloned `Entrada` copy (which would type-check via a `Clone`
24597        // impl but silently break every downstream caller that
24598        // relied on the reference sharing the composite's backing
24599        // identity), a reference to an operator-resolved overlay
24600        // (the future per-cluster `:entrada-overrides` slot the
24601        // MESH-COMPOSITION §V federation roadmap acknowledges — its
24602        // resolution must land at exactly this accessor body, not
24603        // silently divert the raw slot away from a second consumer),
24604        // a `None` → `Some(Entrada::default)` cluster-default
24605        // projection (which would collapse the load-bearing
24606        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
24607        // the peer `gateway_routes` early-return + `feira app graph`
24608        // internal-only-mesh partition both read), or an axis-
24609        // shuffled projection (a future detour that swapped
24610        // `host` and `para` through the accessor would silently
24611        // split the paired `validate` per-`:entrada` shape-and-
24612        // membership gate's traversal input from the peer
24613        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
24614        // fan-out input from the peer `feira app graph` external-
24615        // gateway summary line).
24616        //
24617        // Peer of the sibling M3
24618        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24619        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
24620        // `:politicas` outer mesh-policy composite-reference axis
24621        // and of the sibling M3
24622        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
24623        // (9abb8f0) `&Placement` byte-equal pin on the per-
24624        // `:placement` outer distribution-composite composite-
24625        // reference axis — extends the outer-accessor byte-equal-
24626        // projection discipline onto the last unlifted outermost M3
24627        // mesh-slot type's per-Aplicacao external-gateway composite-
24628        // reference axis, the third and final `&Composite`-return
24629        // accessor on the outer [`AplicacaoSpec`] type.
24630        let fixtures: Vec<Option<Entrada>> = vec![
24631            None,
24632            Some(Entrada {
24633                host: "checkout.quero.cloud".into(),
24634                para: "cart".into(),
24635                paths: Vec::new(),
24636                port: DEFAULT_SERVICO_PORT,
24637            }),
24638            Some(Entrada {
24639                host: "checkout.quero.cloud".into(),
24640                para: "cart".into(),
24641                paths: vec!["/api".into(), "/health".into()],
24642                port: DEFAULT_SERVICO_PORT,
24643            }),
24644            Some(Entrada {
24645                host: "checkout.quero.cloud".into(),
24646                para: "cart".into(),
24647                paths: vec!["/api".into()],
24648                port: 9443,
24649            }),
24650        ];
24651        for entrada in fixtures {
24652            let s = AplicacaoSpec {
24653                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24654                contratos: Vec::new(),
24655                politicas: MeshPolicy::default(),
24656                placement: Placement::default(),
24657                entrada: entrada.clone(),
24658            };
24659            assert_eq!(
24660                s.entrada(),
24661                entrada.as_ref(),
24662                "AplicacaoSpec::entrada must return :entrada verbatim \
24663                 (got {:?}, expected {:?})",
24664                s.entrada(),
24665                entrada.as_ref(),
24666            );
24667            match (s.entrada(), s.entrada.as_ref()) {
24668                (Some(a), Some(b)) => assert!(
24669                    std::ptr::eq(a, b),
24670                    "AplicacaoSpec::entrada accessor and \
24671                     self.entrada.as_ref() field access must borrow \
24672                     the same backing storage — the accessor is the \
24673                     substrate-primitive typed dispatch every \
24674                     downstream external-gateway composite consumer \
24675                     must route through, and a reference-identity \
24676                     split would silently break every consumer that \
24677                     relied on the borrow sharing the composite's \
24678                     storage",
24679                ),
24680                (None, None) => {}
24681                _ => panic!(
24682                    "AplicacaoSpec::entrada presence bit must byte-\
24683                     equal self.entrada.is_some() — a presence-bit \
24684                     drift would silently split the paired `validate` \
24685                     per-`:entrada` shape-and-membership gate's \
24686                     traversal head from the peer \
24687                     caixa-mesh gateway_routes early-return partition \
24688                     from the peer `feira app graph` internal-only-\
24689                     mesh partition",
24690                ),
24691            }
24692            assert_eq!(
24693                s.entrada().is_some(),
24694                s.entrada.is_some(),
24695                "AplicacaoSpec::entrada().is_some() must byte-equal \
24696                 self.entrada.is_some() — a presence-bit drift would \
24697                 silently split every downstream `Option<&Entrada>` \
24698                 consumer's partition on the internal-only-mesh arm",
24699            );
24700        }
24701    }
24702
24703    #[test]
24704    fn validate_reads_through_lifted_entrada_accessor() {
24705        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
24706        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
24707        // self.entrada() { … }`, followed by the per-axis fan-out
24708        // `validate_entrada_para(&e.para)` /
24709        // `EntradaMemberMissing` membership lookup /
24710        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
24711        // per-`e.paths` `validate_entrada_path` traversal) must key
24712        // off the lifted outer accessor, so any future rebrand on
24713        // the typed slot's outer-composite reader shape lands at
24714        // exactly one place. Pins the multi-axis coherence by
24715        // exercising each per-axis refusal end-to-end: (1) the
24716        // author-omitted `None` shape short-circuits past every
24717        // per-`:entrada` refusal (the internal-only mesh partition
24718        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
24719        // fires on a well-shaped but phantom `:para` under the outer
24720        // accessor's reference projection, and (3) the canonical
24721        // `three_member_spec` `:entrada` fixture passes `validate`
24722        // under the outer accessor's reference projection.
24723        //
24724        // Peer of the sibling M3
24725        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24726        // (534dc21) multi-axis coherence pin on the per-`:politicas`
24727        // outer mesh-policy composite-reference axis and the sibling
24728        // M3
24729        // [`validate_placement_reads_through_lifted_placement_accessor`]
24730        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
24731        // outer distribution-composite composite-reference axis —
24732        // extends the multi-consumer coherence discipline onto the
24733        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
24734        // external-gateway composite-reference axis, the third and
24735        // final `&Composite`-return accessor on the outer
24736        // [`AplicacaoSpec`] type.
24737
24738        // (1) `None` :entrada — the internal-only-mesh partition
24739        // short-circuits past every per-`:entrada` refusal. The outer
24740        // accessor's reference projection reaches the fall-through
24741        // `Ok(())` on the `None` arm without any per-axis refusal
24742        // firing.
24743        let mut spec = three_member_spec();
24744        spec.entrada = None;
24745        assert!(
24746            spec.validate().is_ok(),
24747            "an author-omitted `:entrada` must pass `validate` — the \
24748             internal-only-mesh partition short-circuits past every \
24749             per-`:entrada` refusal under the outer accessor's \
24750             reference projection",
24751        );
24752        assert!(
24753            spec.entrada().is_none(),
24754            "the outer accessor's reference projection must name the \
24755             internal-only-mesh partition per the `None` fixture",
24756        );
24757
24758        // (2) `EntradaMemberMissing` refusal under the outer accessor's
24759        // reference projection: a well-shaped but phantom `:para` must
24760        // trip the membership-lookup refusal. The gate's second arm
24761        // reads `e.para` on the reference returned by the outer
24762        // accessor.
24763        let mut spec = three_member_spec();
24764        if let Some(e) = spec.entrada.as_mut() {
24765            e.para = "phantom".into();
24766        }
24767        assert_eq!(
24768            spec.validate().unwrap_err(),
24769            AplicacaoError::EntradaMemberMissing {
24770                para: "phantom".into(),
24771            },
24772        );
24773        match (spec.entrada(), spec.entrada.as_ref()) {
24774            (Some(a), Some(b)) => assert!(
24775                std::ptr::eq(a, b),
24776                "the `validate` per-`:entrada` gate's traversal head \
24777                 must be the same backing composite the accessor's \
24778                 reference projection borrows from",
24779            ),
24780            _ => panic!("fixture must carry Some(:entrada)"),
24781        }
24782
24783        // (3) Canonical `three_member_spec` `:entrada` fixture passes
24784        // `validate` — every per-axis arm reaches the fall-through
24785        // `Ok(())` without any per-axis refusal firing under the
24786        // outer accessor's reference projection.
24787        let spec = three_member_spec();
24788        assert!(
24789            spec.validate().is_ok(),
24790            "the canonical `:entrada` fixture must pass `validate` — \
24791             every per-axis arm short-circuits on valid input under \
24792             the outer accessor's reference projection",
24793        );
24794        assert!(
24795            spec.entrada().is_some(),
24796            "the outer accessor's reference projection must be the \
24797             canonical `:entrada` fixture's composite",
24798        );
24799    }
24800
24801    #[test]
24802    fn port_for_destination_reads_through_lifted_entrada_accessor() {
24803        // Peer coherence pin: the
24804        // [`AplicacaoSpec::port_for_destination`] per-destination
24805        // L4-port fallback resolver's composite-projection seed
24806        // (`self.entrada().filter(…).map_or(…)`) must key off the
24807        // lifted outer accessor. Pins the coherence by exercising
24808        // the resolver end-to-end: (1) the `None` `:entrada` shape
24809        // falls through to `DEFAULT_SERVICO_PORT` under the outer
24810        // accessor's reference projection, (2) a non-matching
24811        // destination falls through to `DEFAULT_SERVICO_PORT` under
24812        // the outer accessor's reference projection, and (3) the
24813        // matching destination resolves to the `:entrada :port`
24814        // value under the outer accessor's reference projection.
24815        //
24816        // Peer of the sibling
24817        // [`validate_reads_through_lifted_entrada_accessor`] multi-
24818        // consumer coherence pin on the same per-`:entrada` outer-
24819        // composite axis — extends the multi-consumer coherence
24820        // discipline onto the second per-`:entrada` production
24821        // consumer, the L4-port fallback resolver.
24822
24823        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
24824        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
24825        // arm under the outer accessor's reference projection.
24826        let mut spec = three_member_spec();
24827        spec.entrada = None;
24828        assert_eq!(
24829            spec.port_for_destination("cart"),
24830            DEFAULT_SERVICO_PORT,
24831            "the port-fallback resolver must fall through to \
24832             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
24833             under the outer accessor's reference projection",
24834        );
24835
24836        // (2) Non-matching destination — the resolver's `filter(…)`
24837        // arm rejects a mismatched destination and falls through
24838        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
24839        // reference projection.
24840        let mut spec = three_member_spec();
24841        if let Some(e) = spec.entrada.as_mut() {
24842            e.para = "cart".into();
24843            e.port = 9443;
24844        }
24845        assert_eq!(
24846            spec.port_for_destination("catalog"),
24847            DEFAULT_SERVICO_PORT,
24848            "the port-fallback resolver must fall through to \
24849             DEFAULT_SERVICO_PORT on a non-matching destination \
24850             under the outer accessor's reference projection",
24851        );
24852
24853        // (3) Matching destination — the resolver's `map_or(…)` arm
24854        // returns the `:entrada :port` value under the outer
24855        // accessor's reference projection.
24856        let mut spec = three_member_spec();
24857        if let Some(e) = spec.entrada.as_mut() {
24858            e.para = "cart".into();
24859            e.port = 9443;
24860        }
24861        assert_eq!(
24862            spec.port_for_destination("cart"),
24863            9443,
24864            "the port-fallback resolver must return the \
24865             `:entrada :port` value on a matching destination \
24866             under the outer accessor's reference projection",
24867        );
24868    }
24869
24870    #[test]
24871    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
24872        // The canonical per-`:politicas` `:mtls-required` mTLS-
24873        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
24874        // must return the `:politicas :mtls-required` typed bool
24875        // verbatim as an `Option<bool>`, byte-equal to the raw field
24876        // access across every value in the three-way accept-set —
24877        // `None` (cluster default applies), `Some(true)` (mTLS
24878        // handshake enforced — the sandboxing-by-default arm the
24879        // MeshPolicy's docstring names), `Some(false)` (handshake
24880        // skipped — the explicit debug-edge opt-out).
24881        //
24882        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
24883        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
24884        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
24885        // shape — first `Option<Copy-T>`-return accessor on the M3
24886        // mesh-slot family. Pins against a future silent detour that
24887        // re-derived the toggle from a peer axis (an accidental
24888        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
24889        // whenever a breaker is set), a `None` → `Some(false)` cluster-
24890        // default projection (the canonical `Option<bool>` → `bool`
24891        // collapse footgun the surrounding `is_empty()` predicate
24892        // guards on the peer emptiness axis), or a `Some(true)` /
24893        // `Some(false)` variant swap that landed on one consumer
24894        // without the other.
24895        for required in [None, Some(true), Some(false)] {
24896            let p = MeshPolicy {
24897                mtls_required: required,
24898                ..MeshPolicy::default()
24899            };
24900            assert_eq!(
24901                p.mtls_required(),
24902                required,
24903                "MeshPolicy::mtls_required must return :politicas \
24904                 :mtls-required verbatim (got {:?}, expected {required:?})",
24905                p.mtls_required(),
24906            );
24907            assert_eq!(
24908                p.mtls_required(),
24909                p.mtls_required,
24910                "MeshPolicy::mtls_required must byte-equal the raw \
24911                 .mtls_required field access across every value in the \
24912                 three-way accept-set",
24913            );
24914        }
24915    }
24916
24917    #[test]
24918    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
24919        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
24920        // arm must key off [`MeshPolicy::mtls_required`], not the raw
24921        // `.mtls_required` field access. Structurally: toggling ONLY
24922        // the `mtls_required` slot on an otherwise-default MeshPolicy
24923        // must flip `is_empty()` from `true` (all-`None`) to `false`
24924        // (one axis carries a value); the flip must be observed for
24925        // both `Some(true)` and `Some(false)` since the emptiness
24926        // semantic reads "any axis carries a value" — not "any axis
24927        // carries a truthy value" — the same non-collapsing shape the
24928        // sibling M2 [`crate::LimitsSpec::is_empty`] /
24929        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
24930        // peer `Option<T>`-typed slot surfaces.
24931        //
24932        // Pins against a future silent detour that re-derived the
24933        // emptiness predicate off a peer axis (an accidental
24934        // `.rate_limit.is_none()`-only chain that dropped the
24935        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
24936        // collapse to a truthy-only check (which would silently
24937        // classify `Some(false)` as empty), or an accessor-side
24938        // detour that no longer names the substrate-primitive typed
24939        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
24940        // == false` fallback in the accessor that would silently
24941        // classify both `None` and `Some(false)` as the same value).
24942        //
24943        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
24944        // (7cd2a28) accessor-composition pin on the sibling optional-
24945        // scalar axis — same "the emptiness / shape-gate predicate
24946        // must route through the substrate-primitive typed dispatch"
24947        // discipline extended onto the peer per-`:politicas` emptiness
24948        // predicate.
24949        let empty = MeshPolicy::default();
24950        assert!(
24951            empty.is_empty(),
24952            "MeshPolicy::default() must be is_empty() — every axis \
24953             defaults to None",
24954        );
24955        for required in [Some(true), Some(false)] {
24956            let p = MeshPolicy {
24957                mtls_required: required,
24958                ..MeshPolicy::default()
24959            };
24960            assert!(
24961                !p.is_empty(),
24962                "MeshPolicy::is_empty must return false when \
24963                 :mtls-required is {required:?} — the emptiness \
24964                 predicate reads \"any axis carries a value\", not \
24965                 \"any axis carries a truthy value\"",
24966            );
24967            assert_eq!(
24968                p.mtls_required().is_none(),
24969                p.is_empty(),
24970                "when :mtls-required is the only set axis, \
24971                 is_empty() must equal mtls_required().is_none() — \
24972                 the accessor and the emptiness predicate must \
24973                 route through the same substrate-primitive typed \
24974                 dispatch on the :mtls-required arm",
24975            );
24976        }
24977    }
24978
24979    #[test]
24980    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
24981        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
24982        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
24983        // accessor must return by value, not by reference. Peer of the
24984        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
24985        // borrow-invariant pin on the sibling `Option<String>` slot,
24986        // but extended onto the peer `Option<bool>` copy-invariant
24987        // shape — the accessor's returned `Option<bool>` must outlive
24988        // `&self` (multiple calls must return equal values from a
24989        // dropped-`&self` copy, since the returned Option carries no
24990        // borrow), and calling the accessor twice on the same
24991        // MeshPolicy must yield the same `Option<bool>` verbatim
24992        // (idempotent, no side effects on `&self`).
24993        //
24994        // Pins against a future silent detour that returned
24995        // `Option<&bool>` (which would type-check but silently break
24996        // every downstream caller — [`single_field_overlay`]'s first
24997        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
24998        // detached copy at the call site), an accidental
24999        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
25000        // would also type-check but return `Option<&bool>`), or a
25001        // one-arm-only accessor that reads `Some(*b)` in the Some arm
25002        // but reads a fresh Default::default() in the None arm.
25003        for required in [None, Some(true), Some(false)] {
25004            let p = MeshPolicy {
25005                mtls_required: required,
25006                ..MeshPolicy::default()
25007            };
25008            let first = p.mtls_required();
25009            let second = p.mtls_required();
25010            assert_eq!(
25011                first, second,
25012                "MeshPolicy::mtls_required must be idempotent — two \
25013                 successive calls on the same &self must return the \
25014                 same Option<bool>",
25015            );
25016            assert_eq!(
25017                first, required,
25018                "MeshPolicy::mtls_required must return :politicas \
25019                 :mtls-required verbatim by copy — got {first:?}, \
25020                 expected {required:?}",
25021            );
25022        }
25023    }
25024
25025    #[test]
25026    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
25027        // The canonical per-`:politicas` `:retries` transient-failure-
25028        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
25029        // the `:politicas :retries` typed `u32` verbatim as an
25030        // `Option<u32>`, byte-equal to the raw field access across every
25031        // representative value in the accept-set — `None` (cluster
25032        // default applies — typically "no retries beyond a single
25033        // dispatch attempt" the caixa-mesh `retry_overlay` builder
25034        // documents), `Some(1)` (the lower boundary of the
25035        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
25036        // `AplicacaoSpec::validate_politicas` gate carves out on the
25037        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
25038        // (the upper boundary the same gate carves out on the sibling
25039        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
25040        // past-the-guard sentinel that pins the accessor doesn't perform
25041        // a silent bounds-collapse at the return path).
25042        //
25043        // Sibling of the peer per-`:politicas`
25044        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
25045        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
25046        // peer per-`:politicas` `Option<u32>` shape — second
25047        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
25048        // Pins against a future silent detour that re-derived the retry
25049        // cap from a peer axis (an accidental `.circuit_breaker
25050        // .as_ref().map(|b| b.max_failures)` collapse that read the
25051        // breaker's max-failure count as a retry budget), a
25052        // `None → Some(0)` cluster-default projection (which would
25053        // silently re-introduce the `PolicyRetriesZero` refusal case at
25054        // the emit boundary), or a bounds-collapsing accessor that
25055        // clamped the return through `POLICY_RETRIES_MAX` (the
25056        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25057        // must ship the raw slot verbatim so a validate-time gate
25058        // regression surfaces at the emit boundary rather than being
25059        // silently absorbed).
25060        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
25061            let p = MeshPolicy {
25062                retries,
25063                ..MeshPolicy::default()
25064            };
25065            assert_eq!(
25066                p.retries(),
25067                retries,
25068                "MeshPolicy::retries must return :politicas :retries \
25069                 verbatim (got {:?}, expected {retries:?})",
25070                p.retries(),
25071            );
25072            assert_eq!(
25073                p.retries(),
25074                p.retries,
25075                "MeshPolicy::retries must byte-equal the raw .retries \
25076                 field access across every value in the accept-set",
25077            );
25078        }
25079    }
25080
25081    #[test]
25082    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
25083        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
25084        // must key off [`MeshPolicy::retries`], not the raw `.retries`
25085        // field access. Structurally: toggling ONLY the `retries` slot
25086        // on an otherwise-default MeshPolicy must flip `is_empty()`
25087        // from `true` (all-`None`) to `false` (one axis carries a
25088        // value); the flip must be observed for every value in the
25089        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25090        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
25091        // the emptiness semantic reads "any axis carries a value" —
25092        // not "any axis carries a value the validate gate accepts" —
25093        // the same non-collapsing shape the peer M2
25094        // [`crate::LimitsSpec::is_empty`] /
25095        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25096        //
25097        // Pins against a future silent detour that re-derived the
25098        // emptiness predicate off a peer axis (an accidental
25099        // `.rate_limit.is_none()`-only chain that dropped the
25100        // `retries` arm entirely), a `retries == Some(_)` collapse
25101        // that key-off a validate-gate-clamped bounds check (which
25102        // would silently classify a past-the-guard `Some(u32::MAX)`
25103        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
25104        // check), or an accessor-side detour that no longer names the
25105        // substrate-primitive typed dispatch.
25106        //
25107        // Sibling of the peer per-`:politicas`
25108        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
25109        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
25110        // same "the emptiness predicate must route through the
25111        // substrate-primitive typed dispatch" discipline extended onto
25112        // the peer per-`:politicas` `Option<u32>` axis.
25113        let empty = MeshPolicy::default();
25114        assert!(
25115            empty.is_empty(),
25116            "MeshPolicy::default() must be is_empty() — every axis \
25117             defaults to None",
25118        );
25119        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
25120            let p = MeshPolicy {
25121                retries,
25122                ..MeshPolicy::default()
25123            };
25124            assert!(
25125                !p.is_empty(),
25126                "MeshPolicy::is_empty must return false when \
25127                 :retries is {retries:?} — the emptiness \
25128                 predicate reads \"any axis carries a value\", not \
25129                 \"any axis carries a value the validate gate \
25130                 accepts\"",
25131            );
25132            assert_eq!(
25133                p.retries().is_none(),
25134                p.is_empty(),
25135                "when :retries is the only set axis, is_empty() \
25136                 must equal retries().is_none() — the accessor and \
25137                 the emptiness predicate must route through the same \
25138                 substrate-primitive typed dispatch on the :retries \
25139                 arm",
25140            );
25141        }
25142    }
25143
25144    #[test]
25145    fn mesh_policy_retries_projects_option_u32_by_copy() {
25146        // The by-copy pin: [`MeshPolicy::retries`] returns
25147        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
25148        // accessor must return by value, not by reference. Sibling of
25149        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
25150        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
25151        // extended onto the sibling `Option<u32>` copy-invariant
25152        // shape — the accessor's returned `Option<u32>` must outlive
25153        // `&self` (multiple calls must return equal values from a
25154        // dropped-`&self` copy, since the returned Option carries no
25155        // borrow), and calling the accessor twice on the same
25156        // MeshPolicy must yield the same `Option<u32>` verbatim
25157        // (idempotent, no side effects on `&self`).
25158        //
25159        // Pins against a future silent detour that returned
25160        // `Option<&u32>` (which would type-check but silently break
25161        // every downstream caller — [`crate::render::single_field_overlay`]'s
25162        // first parameter is `Option<T: Clone>`, and `&u32` would
25163        // fold to a detached copy at the call site), an accidental
25164        // `Option::as_ref()` projection (`self.retries.as_ref()` would
25165        // also type-check but return `Option<&u32>`), or a one-arm-
25166        // only accessor that reads `Some(*n)` in the Some arm but
25167        // reads a fresh `Default::default()` (`0_u32`) in the None
25168        // arm.
25169        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
25170            let p = MeshPolicy {
25171                retries,
25172                ..MeshPolicy::default()
25173            };
25174            let first = p.retries();
25175            let second = p.retries();
25176            assert_eq!(
25177                first, second,
25178                "MeshPolicy::retries must be idempotent — two \
25179                 successive calls on the same &self must return the \
25180                 same Option<u32>",
25181            );
25182            assert_eq!(
25183                first, retries,
25184                "MeshPolicy::retries must return :politicas :retries \
25185                 verbatim by copy — got {first:?}, expected {retries:?}",
25186            );
25187        }
25188    }
25189
25190    #[test]
25191    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
25192        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
25193        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
25194        // return the `:politicas :timeout` typed [`Duration`] verbatim
25195        // as an `Option<Duration>`, byte-equal to the raw field access
25196        // across every representative value in the accept-set — `None`
25197        // (cluster default applies — typically the gateway class's
25198        // implementation-side per-request wall-clock cap the caixa-mesh
25199        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
25200        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
25201        // set the surrounding `AplicacaoSpec::validate_politicas` gate
25202        // carves out on the sibling `PolicyTimeoutZero` /
25203        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
25204        // (the upper boundary the same gate carves out on the sibling
25205        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
25206        // (a past-the-guard sentinel that pins the accessor doesn't
25207        // perform a silent bounds-collapse into `None` on the zero-
25208        // Duration arm — validate rejects zero but the accessor must
25209        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
25210        // past-the-guard sentinel that pins the accessor doesn't
25211        // perform a silent bounds-collapse at the return path).
25212        //
25213        // Sibling of the peer per-`:politicas`
25214        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
25215        // `Option<u32>` optional-scalar axis and the peer per-
25216        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
25217        // pin on the sibling `Option<bool>` optional-scalar axis,
25218        // extended onto the peer per-`:politicas` `Option<Duration>`
25219        // shape — third `Option<Copy-T>`-return accessor on the M3
25220        // mesh-slot family. Pins against a future silent detour that
25221        // re-derived the per-call cap from a peer axis (an accidental
25222        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
25223        // read the breaker's rolling-window duration as a per-call
25224        // deadline), a `None → Some(Duration::MAX)` cluster-default
25225        // projection (which would silently re-introduce the
25226        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
25227        // blocking" arm at the emit boundary), or a bounds-collapsing
25228        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
25229        // (the `AplicacaoSpec::validate` gate owns the bounds; the
25230        // accessor must ship the raw slot verbatim so a validate-time
25231        // gate regression surfaces at the emit boundary rather than
25232        // being silently absorbed).
25233        for timeout in [
25234            None,
25235            Some(Duration::from_millis(1)),
25236            Some(POLICY_TIMEOUT_MAX),
25237            Some(Duration::ZERO),
25238            Some(Duration::MAX),
25239        ] {
25240            let p = MeshPolicy {
25241                timeout,
25242                ..MeshPolicy::default()
25243            };
25244            assert_eq!(
25245                p.timeout(),
25246                timeout,
25247                "MeshPolicy::timeout must return :politicas :timeout \
25248                 verbatim (got {:?}, expected {timeout:?})",
25249                p.timeout(),
25250            );
25251            assert_eq!(
25252                p.timeout(),
25253                p.timeout,
25254                "MeshPolicy::timeout must byte-equal the raw .timeout \
25255                 field access across every value in the accept-set",
25256            );
25257        }
25258    }
25259
25260    #[test]
25261    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
25262        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
25263        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
25264        // field access. Structurally: toggling ONLY the `timeout` slot
25265        // on an otherwise-default MeshPolicy must flip `is_empty()`
25266        // from `true` (all-`None`) to `false` (one axis carries a
25267        // value); the flip must be observed for every value in the
25268        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25269        // gate accepts (`Some(Duration::from_millis(1))`,
25270        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
25271        // reads "any axis carries a value" — not "any axis carries a
25272        // value the validate gate accepts" — the same non-collapsing
25273        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
25274        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25275        //
25276        // Pins against a future silent detour that re-derived the
25277        // emptiness predicate off a peer axis (an accidental
25278        // `.rate_limit.is_none()`-only chain that dropped the
25279        // `timeout` arm entirely), a `timeout == Some(_)` collapse
25280        // that key-off a validate-gate-clamped bounds check (which
25281        // would silently classify a past-the-guard `Some(Duration::MAX)`
25282        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
25283        // check), or an accessor-side detour that no longer names the
25284        // substrate-primitive typed dispatch.
25285        //
25286        // Sibling of the peer per-`:politicas`
25287        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
25288        // the sibling `Option<u32>` optional-scalar axis and the peer
25289        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25290        // accessor-composition pin on the sibling `Option<bool>`
25291        // optional-scalar axis — same "the emptiness predicate must
25292        // route through the substrate-primitive typed dispatch"
25293        // discipline extended onto the peer per-`:politicas`
25294        // `Option<Duration>` axis.
25295        let empty = MeshPolicy::default();
25296        assert!(
25297            empty.is_empty(),
25298            "MeshPolicy::default() must be is_empty() — every axis \
25299             defaults to None",
25300        );
25301        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
25302            let p = MeshPolicy {
25303                timeout,
25304                ..MeshPolicy::default()
25305            };
25306            assert!(
25307                !p.is_empty(),
25308                "MeshPolicy::is_empty must return false when \
25309                 :timeout is {timeout:?} — the emptiness \
25310                 predicate reads \"any axis carries a value\", not \
25311                 \"any axis carries a value the validate gate \
25312                 accepts\"",
25313            );
25314            assert_eq!(
25315                p.timeout().is_none(),
25316                p.is_empty(),
25317                "when :timeout is the only set axis, is_empty() \
25318                 must equal timeout().is_none() — the accessor and \
25319                 the emptiness predicate must route through the same \
25320                 substrate-primitive typed dispatch on the :timeout \
25321                 arm",
25322            );
25323        }
25324    }
25325
25326    #[test]
25327    fn mesh_policy_timeout_projects_option_duration_by_copy() {
25328        // The by-copy pin: [`MeshPolicy::timeout`] returns
25329        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
25330        // and the accessor must return by value, not by reference.
25331        // Sibling of the peer per-`:politicas`
25332        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
25333        // sibling `Option<u32>` optional-scalar axis and the peer
25334        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25335        // by-copy pin on the sibling `Option<bool>` optional-scalar
25336        // axis, extended onto the peer per-`:politicas`
25337        // `Option<Duration>` copy-invariant shape — the accessor's
25338        // returned `Option<Duration>` must outlive `&self` (multiple
25339        // calls must return equal values from a dropped-`&self`
25340        // copy, since the returned Option carries no borrow), and
25341        // calling the accessor twice on the same MeshPolicy must
25342        // yield the same `Option<Duration>` verbatim (idempotent, no
25343        // side effects on `&self`).
25344        //
25345        // Pins against a future silent detour that returned
25346        // `Option<&Duration>` (which would type-check but silently
25347        // break every downstream caller — [`crate::render::single_field_overlay`]'s
25348        // first parameter is `Option<T: Clone>`, and `&Duration`
25349        // would fold to a detached copy at the call site), an
25350        // accidental `Option::as_ref()` projection
25351        // (`self.timeout.as_ref()` would also type-check but return
25352        // `Option<&Duration>`), or a one-arm-only accessor that
25353        // reads `Some(*d)` in the Some arm but reads a fresh
25354        // `Default::default()` (`Duration::ZERO`) in the None arm
25355        // (which would silently re-classify every unset `:timeout`
25356        // as the `PolicyTimeoutZero`-refused zero-Duration value at
25357        // the accessor boundary).
25358        for timeout in [
25359            None,
25360            Some(Duration::from_millis(1)),
25361            Some(POLICY_TIMEOUT_MAX),
25362            Some(Duration::ZERO),
25363            Some(Duration::MAX),
25364        ] {
25365            let p = MeshPolicy {
25366                timeout,
25367                ..MeshPolicy::default()
25368            };
25369            let first = p.timeout();
25370            let second = p.timeout();
25371            assert_eq!(
25372                first, second,
25373                "MeshPolicy::timeout must be idempotent — two \
25374                 successive calls on the same &self must return the \
25375                 same Option<Duration>",
25376            );
25377            assert_eq!(
25378                first, timeout,
25379                "MeshPolicy::timeout must return :politicas :timeout \
25380                 verbatim by copy — got {first:?}, expected {timeout:?}",
25381            );
25382        }
25383    }
25384
25385    #[test]
25386    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
25387        // The canonical per-`:politicas` `:rate-limit` Envoy-
25388        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
25389        // [`MeshPolicy::rate_limit`] must return the `:politicas
25390        // :rate-limit` typed [`RateLimit`] verbatim as an
25391        // `Option<RateLimit>`, byte-equal to the raw field access
25392        // across every representative value in the accept-set — `None`
25393        // (cluster default applies — no per-Aplicacao rate declaration,
25394        // the gateway-class per-listener default arm the future caixa-
25395        // mesh `local_rate_limit_overlay` emitter documents),
25396        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
25397        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
25398        // accept-set the surrounding
25399        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25400        // sibling `PolicyRateLimitZero` refusal, paired with the
25401        // canonical-window "1 second" arm of the three-unit
25402        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
25403        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
25404        // (the upper boundary the same gate carves out on the sibling
25405        // `PolicyRateLimitExceedsCap` refusal, paired with the
25406        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
25407        // (a past-the-guard sentinel that pins the accessor doesn't
25408        // perform a silent bounds-collapse into `None` on the
25409        // zero-rate/zero-window arm — validate rejects zero but the
25410        // accessor must ship the raw slot verbatim so a validate-time
25411        // gate regression surfaces at the emit boundary rather than
25412        // being silently absorbed), and
25413        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
25414        // (a past-the-guard sentinel that pins the accessor doesn't
25415        // perform a silent bounds-collapse at the return path).
25416        //
25417        // First `Option<Copy-composite-T>`-return accessor pin on the
25418        // M3 mesh-slot family (peer of the sibling per-`:politicas`
25419        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
25420        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
25421        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
25422        // Copy accessor pins, extended onto the peer per-`:politicas`
25423        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
25424        // and the accessor returns by value). Pins against a future
25425        // silent detour that re-derived the rate declaration from a
25426        // peer axis (an accidental
25427        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
25428        // collapse that read the breaker's trip threshold + rolling
25429        // window as a rate declaration), a `None → Some(default())`
25430        // cluster-default projection (which would silently re-
25431        // introduce a "cluster default is 0/s" arm the emit boundary
25432        // would take as "declared but inert" — the canonical
25433        // declared-but-inert footgun the sibling
25434        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
25435        // amplification-shape axis), a bounds-collapsing accessor
25436        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
25437        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
25438        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
25439        // accessor must ship the raw slot verbatim), or a
25440        // by-reference detour (`Option<&RateLimit>`) that broke every
25441        // downstream consumer keying off `Option<RateLimit>` by-copy.
25442        for rl in [
25443            None,
25444            Some(RateLimit {
25445                rate: 1,
25446                window: Duration::from_secs(1),
25447            }),
25448            Some(RateLimit {
25449                rate: POLICY_RATE_LIMIT_MAX,
25450                window: Duration::from_secs(3600),
25451            }),
25452            Some(RateLimit {
25453                rate: 0,
25454                window: Duration::ZERO,
25455            }),
25456            Some(RateLimit {
25457                rate: u32::MAX,
25458                window: Duration::MAX,
25459            }),
25460        ] {
25461            let p = MeshPolicy {
25462                rate_limit: rl,
25463                ..MeshPolicy::default()
25464            };
25465            assert_eq!(
25466                p.rate_limit(),
25467                rl,
25468                "MeshPolicy::rate_limit must return :politicas :rate-limit \
25469                 verbatim (got {:?}, expected {rl:?})",
25470                p.rate_limit(),
25471            );
25472            assert_eq!(
25473                p.rate_limit(),
25474                p.rate_limit,
25475                "MeshPolicy::rate_limit must byte-equal the raw \
25476                 .rate_limit field access across every value in the \
25477                 accept-set",
25478            );
25479        }
25480    }
25481
25482    #[test]
25483    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
25484        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
25485        // must key off [`MeshPolicy::rate_limit`], not the raw
25486        // `.rate_limit` field access. Structurally: toggling ONLY the
25487        // `rate_limit` slot on an otherwise-default MeshPolicy must
25488        // flip `is_empty()` from `true` (all-`None`) to `false` (one
25489        // axis carries a value); the flip must be observed for every
25490        // representative value in the accept-set the surrounding
25491        // [`AplicacaoSpec::validate_politicas`] gate accepts
25492        // (`Some(RateLimit { rate: 1, window: 1s })`,
25493        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
25494        // since the emptiness semantic reads "any axis carries a
25495        // value" — not "any axis carries a value the validate gate
25496        // accepts" — the same non-collapsing shape the peer M2
25497        // [`crate::LimitsSpec::is_empty`] /
25498        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25499        //
25500        // Pins against a future silent detour that re-derived the
25501        // emptiness predicate off a peer axis (an accidental
25502        // `.timeout.is_none()`-only chain that dropped the
25503        // `rate_limit` arm entirely — the last unlifted inline field
25504        // access on `is_empty` before this lift), a `rate_limit ==
25505        // Some(_)` collapse that key-off a validate-gate-clamped
25506        // bounds check (which would silently classify a past-the-
25507        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
25508        // because it fails the value-shape gate), or an accessor-
25509        // side detour that no longer names the substrate-primitive
25510        // typed dispatch.
25511        //
25512        // Fourth "the emptiness predicate must route through the
25513        // substrate-primitive typed dispatch" composition pin on the
25514        // M3 mesh-slot family — closes the last unlifted composition
25515        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
25516        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
25517        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
25518        // 7073d0f is_empty-composition pins on the sibling primitive-
25519        // Copy axes, extended onto the peer per-`:politicas`
25520        // composite-Copy `Option<RateLimit>` axis).
25521        let empty = MeshPolicy::default();
25522        assert!(
25523            empty.is_empty(),
25524            "MeshPolicy::default() must be is_empty() — every axis \
25525             defaults to None",
25526        );
25527        for rl in [
25528            RateLimit {
25529                rate: 1,
25530                window: Duration::from_secs(1),
25531            },
25532            RateLimit {
25533                rate: POLICY_RATE_LIMIT_MAX,
25534                window: Duration::from_secs(3600),
25535            },
25536        ] {
25537            let p = MeshPolicy {
25538                rate_limit: Some(rl),
25539                ..MeshPolicy::default()
25540            };
25541            assert!(
25542                !p.is_empty(),
25543                "MeshPolicy::is_empty must return false when \
25544                 :rate-limit is {rl:?} — the emptiness predicate \
25545                 reads \"any axis carries a value\", not \"any axis \
25546                 carries a value the validate gate accepts\"",
25547            );
25548            assert_eq!(
25549                p.rate_limit().is_none(),
25550                p.is_empty(),
25551                "when :rate-limit is the only set axis, is_empty() \
25552                 must equal rate_limit().is_none() — the accessor \
25553                 and the emptiness predicate must route through the \
25554                 same substrate-primitive typed dispatch on the \
25555                 :rate-limit arm",
25556            );
25557        }
25558    }
25559
25560    #[test]
25561    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
25562        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25563        // `:rate-limit` value-shape gate must key off
25564        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
25565        // field bind. Structurally: a `MeshPolicy` whose only set
25566        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
25567        // the `PolicyRateLimitZero` refusal exactly, and the same
25568        // MeshPolicy with the rate at the canonical lower boundary
25569        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
25570        // The pair jointly pins the accessor + validate-gate
25571        // composition: any future silent detour that had the accessor
25572        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
25573        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
25574        // silently absorb the `PolicyRateLimitZero` refusal at the
25575        // accessor boundary — the composition pin catches that at
25576        // caixa-core build time.
25577        //
25578        // Sibling of the peer [`validate_politicas`]
25579        // `:mtls-required` / `:retries` / `:timeout` composition pins
25580        // on the sibling primitive-Copy optional-scalar axes — same
25581        // "the validate / shape-gate predicate must route through the
25582        // substrate-primitive typed dispatch" discipline extended
25583        // onto the peer per-`:politicas` composite-Copy
25584        // `Option<RateLimit>` axis. Second composition-with-accessor
25585        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
25586        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
25587        let mut spec = three_member_spec();
25588        spec.politicas = MeshPolicy {
25589            rate_limit: Some(RateLimit {
25590                rate: 0,
25591                window: Duration::from_secs(1),
25592            }),
25593            ..MeshPolicy::default()
25594        };
25595        assert!(
25596            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
25597            "validate_politicas must reject rate == 0 with \
25598             PolicyRateLimitZero — the accessor and the validate gate \
25599             must route through the same substrate-primitive typed \
25600             dispatch on the :rate-limit zero-floor arm",
25601        );
25602        spec.politicas = MeshPolicy {
25603            rate_limit: Some(RateLimit {
25604                rate: 1,
25605                window: Duration::from_secs(1),
25606            }),
25607            ..MeshPolicy::default()
25608        };
25609        assert!(
25610            spec.validate().is_ok(),
25611            "validate_politicas must accept rate == 1 (the canonical \
25612             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
25613             set) with a canonical 1s window",
25614        );
25615    }
25616
25617    #[test]
25618    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
25619        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
25620        // `outlier_detection`-mesh consecutive-failure-ejection scalar
25621        // pin: [`MeshPolicy::circuit_breaker`] must return the
25622        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
25623        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
25624        // raw field access across every representative value in the
25625        // accept-set — `None` (cluster default applies — no
25626        // per-Aplicacao breaker declaration, the gateway-class per-
25627        // listener default arm the future caixa-mesh
25628        // `outlier_detection_overlay` emitter documents),
25629        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
25630        // (the lower boundary of the accept-set the surrounding
25631        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25632        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
25633        // refusals),
25634        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
25635        // (the upper boundary the same gate carves out on the sibling
25636        // `PolicyBreakerMaxFailuresExceedsCap` /
25637        // `PolicyBreakerWindowExceedsCap` refusals),
25638        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
25639        // (a past-the-guard sentinel that pins the accessor doesn't
25640        // perform a silent bounds-collapse into `None` on the
25641        // zero-failures/zero-window arm — validate rejects zero but
25642        // the accessor must ship the raw slot verbatim so a validate-
25643        // time gate regression surfaces at the emit boundary rather
25644        // than being silently absorbed), and
25645        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
25646        // (a past-the-guard sentinel that pins the accessor doesn't
25647        // perform a silent bounds-collapse at the return path).
25648        //
25649        // Second `Option<Copy-composite-T>`-return accessor pin on the
25650        // M3 mesh-slot family (peer of the sibling per-`:politicas`
25651        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
25652        // composite-Copy accessor pin, and of the sibling per-
25653        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
25654        // [`MeshPolicy::retries`] bdfb399 /
25655        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
25656        // accessor pins). Pins against a future silent detour that
25657        // re-derived the breaker declaration from a peer axis (an
25658        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
25659        // collapse that read the rate-limit's bucket capacity + refill
25660        // period as a breaker declaration), a `None → Some(default())`
25661        // cluster-default projection (which would silently re-
25662        // introduce the `PolicyBreakerZeroFailures` /
25663        // `PolicyBreakerZeroWindow` refusal cases at the emit
25664        // boundary), a bounds-collapsing accessor that clamped
25665        // `cb.max_failures` through
25666        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
25667        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
25668        // [`AplicacaoSpec::validate`] gate owns the bounds; the
25669        // accessor must ship the raw slot verbatim), or a
25670        // by-reference detour (`Option<&CircuitBreaker>`) that broke
25671        // every downstream consumer keying off `Option<CircuitBreaker>`
25672        // by-copy.
25673        for cb in [
25674            None,
25675            Some(CircuitBreaker {
25676                max_failures: 1,
25677                window: Duration::from_millis(1),
25678            }),
25679            Some(CircuitBreaker {
25680                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25681                window: POLICY_BREAKER_WINDOW_MAX,
25682            }),
25683            Some(CircuitBreaker {
25684                max_failures: 0,
25685                window: Duration::ZERO,
25686            }),
25687            Some(CircuitBreaker {
25688                max_failures: u32::MAX,
25689                window: Duration::MAX,
25690            }),
25691        ] {
25692            let p = MeshPolicy {
25693                circuit_breaker: cb,
25694                ..MeshPolicy::default()
25695            };
25696            assert_eq!(
25697                p.circuit_breaker(),
25698                cb,
25699                "MeshPolicy::circuit_breaker must return :politicas \
25700                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
25701                p.circuit_breaker(),
25702            );
25703            assert_eq!(
25704                p.circuit_breaker(),
25705                p.circuit_breaker,
25706                "MeshPolicy::circuit_breaker must byte-equal the raw \
25707                 .circuit_breaker field access across every value in \
25708                 the accept-set",
25709            );
25710        }
25711    }
25712
25713    #[test]
25714    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
25715        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
25716        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
25717        // `.circuit_breaker` field access. Structurally: toggling ONLY
25718        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
25719        // must flip `is_empty()` from `true` (all-`None`) to `false`
25720        // (one axis carries a value); the flip must be observed for
25721        // every representative value in the accept-set the surrounding
25722        // [`AplicacaoSpec::validate_politicas`] gate accepts
25723        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
25724        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
25725        // since the emptiness semantic reads "any axis carries a
25726        // value" — not "any axis carries a value the validate gate
25727        // accepts" — the same non-collapsing shape the peer M2
25728        // [`crate::LimitsSpec::is_empty`] /
25729        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25730        //
25731        // Pins against a future silent detour that re-derived the
25732        // emptiness predicate off a peer axis (an accidental
25733        // `.rate_limit.is_none()`-only chain that dropped the
25734        // `circuit_breaker` arm entirely — the last unlifted inline
25735        // field access on `is_empty` before this lift), a
25736        // `circuit_breaker == Some(_)` collapse that key-off a
25737        // validate-gate-clamped bounds check (which would silently
25738        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
25739        // 0, window: 0s })` as empty because it fails the value-shape
25740        // gate), or an accessor-side detour that no longer names the
25741        // substrate-primitive typed dispatch.
25742        //
25743        // Fifth "the emptiness predicate must route through the
25744        // substrate-primitive typed dispatch" composition pin on the
25745        // M3 mesh-slot family — closes the last unlifted composition
25746        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
25747        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
25748        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
25749        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
25750        // composition pins on the sibling primitive-Copy + composite-
25751        // Copy axes, extended onto the peer per-`:politicas`
25752        // composite-Copy `Option<CircuitBreaker>` axis).
25753        let empty = MeshPolicy::default();
25754        assert!(
25755            empty.is_empty(),
25756            "MeshPolicy::default() must be is_empty() — every axis \
25757             defaults to None",
25758        );
25759        for cb in [
25760            CircuitBreaker {
25761                max_failures: 1,
25762                window: Duration::from_millis(1),
25763            },
25764            CircuitBreaker {
25765                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
25766                window: POLICY_BREAKER_WINDOW_MAX,
25767            },
25768        ] {
25769            let p = MeshPolicy {
25770                circuit_breaker: Some(cb),
25771                ..MeshPolicy::default()
25772            };
25773            assert!(
25774                !p.is_empty(),
25775                "MeshPolicy::is_empty must return false when \
25776                 :circuit-breaker is {cb:?} — the emptiness predicate \
25777                 reads \"any axis carries a value\", not \"any axis \
25778                 carries a value the validate gate accepts\"",
25779            );
25780            assert_eq!(
25781                p.circuit_breaker().is_none(),
25782                p.is_empty(),
25783                "when :circuit-breaker is the only set axis, \
25784                 is_empty() must equal circuit_breaker().is_none() — \
25785                 the accessor and the emptiness predicate must route \
25786                 through the same substrate-primitive typed dispatch \
25787                 on the :circuit-breaker arm",
25788            );
25789        }
25790    }
25791
25792    #[test]
25793    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
25794        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25795        // `:circuit-breaker` value-shape gate must key off
25796        // [`MeshPolicy::circuit_breaker`], not the raw
25797        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
25798        // whose only set axis is a `Some(CircuitBreaker { max_failures:
25799        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
25800        // refusal exactly, and the same MeshPolicy with the breaker at
25801        // the canonical lower boundary
25802        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
25803        // pass validate. The pair jointly pins the accessor +
25804        // validate-gate composition: any future silent detour that had
25805        // the accessor omit the `Some(CircuitBreaker { max_failures:
25806        // 0, .. })` arm (a
25807        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
25808        // collapse) would silently absorb the
25809        // `PolicyBreakerZeroFailures` refusal at the accessor
25810        // boundary — the composition pin catches that at caixa-core
25811        // build time.
25812        //
25813        // Sibling of the peer [`validate_politicas`]
25814        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
25815        // composition pins on the sibling primitive-Copy + composite-
25816        // Copy optional-scalar axes — same "the validate / shape-gate
25817        // predicate must route through the substrate-primitive typed
25818        // dispatch" discipline extended onto the peer per-`:politicas`
25819        // composite-Copy `Option<CircuitBreaker>` axis. Second
25820        // composition-with-accessor pin on the M3 mesh-slot
25821        // `Option<CircuitBreaker>` arm alongside the
25822        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
25823        let mut spec = three_member_spec();
25824        spec.politicas = MeshPolicy {
25825            circuit_breaker: Some(CircuitBreaker {
25826                max_failures: 0,
25827                window: Duration::from_millis(1),
25828            }),
25829            ..MeshPolicy::default()
25830        };
25831        assert!(
25832            matches!(
25833                spec.validate(),
25834                Err(AplicacaoError::PolicyBreakerZeroFailures)
25835            ),
25836            "validate_politicas must reject max_failures == 0 with \
25837             PolicyBreakerZeroFailures — the accessor and the validate \
25838             gate must route through the same substrate-primitive \
25839             typed dispatch on the :circuit-breaker zero-floor arm",
25840        );
25841        spec.politicas = MeshPolicy {
25842            circuit_breaker: Some(CircuitBreaker {
25843                max_failures: 1,
25844                window: Duration::from_millis(1),
25845            }),
25846            ..MeshPolicy::default()
25847        };
25848        assert!(
25849            spec.validate().is_ok(),
25850            "validate_politicas must accept a CircuitBreaker at the \
25851             canonical lower boundary (max_failures = 1, window = \
25852             1ms) — the accessor and the validate gate must route \
25853             through the same substrate-primitive typed dispatch on \
25854             the :circuit-breaker arm",
25855        );
25856    }
25857
25858    #[test]
25859    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
25860        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
25861        // Envoy-outlier-detection trip-threshold scalar pin:
25862        // [`CircuitBreaker::max_failures`] must return the
25863        // `:politicas :circuit-breaker :max-failures` typed `u32`
25864        // verbatim, byte-equal to the raw field access across every
25865        // representative value in the accept-set — `1` (the lower
25866        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
25867        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
25868        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
25869        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
25870        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
25871        // refusal), `0` (a past-the-guard sentinel that pins the accessor
25872        // doesn't perform a silent bounds-collapse into `1` on the zero
25873        // arm — validate rejects zero but the accessor must ship the
25874        // raw slot verbatim so a validate-time gate regression surfaces
25875        // at the emit boundary rather than being silently absorbed),
25876        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
25877        // doesn't perform a silent bounds-collapse through
25878        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
25879        //
25880        // First sub-struct required-scalar accessor pin on the M3
25881        // mesh-slot family — sibling in shape to the peer per-`:membros`
25882        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
25883        // (a40b0e3) required-`String`-carry accessor pins and the peer
25884        // per-`:contratos` [`WitContract::source`] /
25885        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
25886        // accessor pins, extended onto the peer per-`CircuitBreaker`
25887        // required-`u32` scalar-value axis. Pins against a future silent
25888        // detour that re-derived the trip threshold from a peer axis (an
25889        // accidental `self.window.as_secs() as u32` collapse that read
25890        // the breaker's rolling-window duration as a failure count), a
25891        // `0 → 1` cluster-default projection (which would silently absorb
25892        // the `PolicyBreakerZeroFailures` refusal case at the accessor
25893        // boundary), or a bounds-collapsing accessor that clamped the
25894        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
25895        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25896        // must ship the raw slot verbatim).
25897        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
25898            let cb = CircuitBreaker {
25899                max_failures,
25900                window: Duration::from_secs(60),
25901            };
25902            assert_eq!(
25903                cb.max_failures(),
25904                max_failures,
25905                "CircuitBreaker::max_failures must return :politicas \
25906                 :circuit-breaker :max-failures verbatim (got {}, \
25907                 expected {max_failures})",
25908                cb.max_failures(),
25909            );
25910            assert_eq!(
25911                cb.max_failures(),
25912                cb.max_failures,
25913                "CircuitBreaker::max_failures must byte-equal the raw \
25914                 .max_failures field access across every value in the \
25915                 u32 accept-set",
25916            );
25917        }
25918    }
25919
25920    #[test]
25921    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
25922        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
25923        // `:circuit-breaker :max-failures` zero-floor arm must key off
25924        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
25925        // field access. Structurally: a `CircuitBreaker { max_failures:
25926        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
25927        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
25928        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
25929        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
25930        // pass validate. The pair jointly pins the accessor +
25931        // validate-gate composition: any future silent detour that had
25932        // the accessor return a fresh `1` on the zero arm (a
25933        // `.max_failures().max(1)` collapse) would silently absorb the
25934        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
25935        // and the validate gate would accept a struct-literal
25936        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
25937        // catches that at caixa-core build time.
25938        //
25939        // Peer of the sibling per-`:politicas`
25940        // [`MeshPolicy::mtls_required`] (c0110f1) /
25941        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
25942        // (7073d0f) accessor-composition pins on the sibling optional-
25943        // scalar axes — same "the validate / shape-gate predicate must
25944        // route through the substrate-primitive typed dispatch"
25945        // discipline extended onto the peer per-`CircuitBreaker`
25946        // required-scalar composition axis.
25947        let mut spec = three_member_spec();
25948        spec.politicas = MeshPolicy {
25949            circuit_breaker: Some(CircuitBreaker {
25950                max_failures: 0,
25951                window: Duration::from_secs(60),
25952            }),
25953            ..MeshPolicy::default()
25954        };
25955        assert!(
25956            matches!(
25957                spec.validate(),
25958                Err(AplicacaoError::PolicyBreakerZeroFailures)
25959            ),
25960            "validate_politicas must reject max_failures == 0 with \
25961             PolicyBreakerZeroFailures — the accessor and the validate \
25962             gate must route through the same substrate-primitive typed \
25963             dispatch on the :max-failures zero-floor arm",
25964        );
25965        spec.politicas = MeshPolicy {
25966            circuit_breaker: Some(CircuitBreaker {
25967                max_failures: 1,
25968                window: Duration::from_secs(60),
25969            }),
25970            ..MeshPolicy::default()
25971        };
25972        assert!(
25973            spec.validate().is_ok(),
25974            "validate_politicas must accept max_failures == 1 (the \
25975             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
25976             accept-set)",
25977        );
25978    }
25979
25980    #[test]
25981    fn circuit_breaker_max_failures_projects_u32_by_copy() {
25982        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
25983        // `u32` by copy — `u32` is `Copy` and the accessor must return
25984        // by value, not by reference. Peer of the sibling
25985        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
25986        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
25987        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
25988        // optional-scalar axes, extended onto the peer
25989        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
25990        // the accessor's returned `u32` must outlive `&self` (multiple
25991        // calls must return equal values from a dropped-`&self` copy,
25992        // since the returned scalar carries no borrow), and calling
25993        // the accessor twice on the same CircuitBreaker must yield the
25994        // same `u32` verbatim (idempotent, no side effects on `&self`).
25995        //
25996        // Pins against a future silent detour that returned `&u32`
25997        // (which would type-check but silently break every downstream
25998        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
25999        // first parameter is `u32`, and `&u32` would fold to a detached
26000        // copy at the call site with a `*` deref the sibling accessors
26001        // don't need), an accidental `.max_failures.wrapping_add(0)`
26002        // detour that returned a fresh copy through an arithmetic
26003        // no-op (breaking a future `const fn` regression), or a
26004        // one-arm-only accessor that returned a saturating value on
26005        // some sentinel input (breaking the pass-through invariant the
26006        // sibling required-scalar accessors carry).
26007        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
26008            let cb = CircuitBreaker {
26009                max_failures,
26010                window: Duration::from_secs(60),
26011            };
26012            let first = cb.max_failures();
26013            let second = cb.max_failures();
26014            assert_eq!(
26015                first, second,
26016                "CircuitBreaker::max_failures must be idempotent — two \
26017                 successive calls on the same &self must return the \
26018                 same u32",
26019            );
26020            assert_eq!(
26021                first, max_failures,
26022                "CircuitBreaker::max_failures must return :politicas \
26023                 :circuit-breaker :max-failures verbatim by copy — \
26024                 got {first}, expected {max_failures}",
26025            );
26026        }
26027    }
26028
26029    #[test]
26030    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
26031        // The canonical per-`:politicas :circuit-breaker` `:window`
26032        // Envoy-outlier-detection rolling-observation-interval scalar
26033        // pin: [`CircuitBreaker::window`] must return the
26034        // `:politicas :circuit-breaker :window` typed `Duration`
26035        // verbatim, byte-equal to the raw field access across every
26036        // representative value in the accept-set — `Duration::from_millis(1)`
26037        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
26038        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
26039        // gate carves out on the sibling `PolicyBreakerZeroWindow`
26040        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
26041        // same gate carves out on the sibling
26042        // `PolicyBreakerWindowExceedsCap` refusal),
26043        // `Duration::ZERO` (a past-the-guard sentinel that pins the
26044        // accessor doesn't perform a silent bounds-collapse into
26045        // `Duration::from_millis(1)` on the zero arm — validate rejects
26046        // zero but the accessor must ship the raw slot verbatim so a
26047        // validate-time gate regression surfaces at the emit boundary
26048        // rather than being silently absorbed),
26049        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
26050        // far above the 1h cap — that pins the accessor doesn't perform
26051        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
26052        // at the return path).
26053        //
26054        // Second sub-struct required-scalar accessor pin on the M3
26055        // mesh-slot family — sibling in shape to the just-landed
26056        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
26057        // (3a74062) required-`u32` accessor pin on the peer
26058        // per-`CircuitBreaker` required-axis, extended onto the
26059        // per-sub-struct required-`Duration` axis. Pins against a
26060        // future silent detour that re-derived the observation window
26061        // from a peer axis (an accidental
26062        // `Duration::from_secs(self.max_failures as u64)` collapse that
26063        // read the breaker's trip count as an observation-interval
26064        // duration), a `Duration::ZERO → Duration::from_millis(1)`
26065        // cluster-default projection (which would silently absorb the
26066        // `PolicyBreakerZeroWindow` refusal case at the accessor
26067        // boundary), or a bounds-collapsing accessor that clamped the
26068        // return through `POLICY_BREAKER_WINDOW_MAX` (the
26069        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
26070        // must ship the raw slot verbatim).
26071        for window in [
26072            Duration::from_millis(1),
26073            POLICY_BREAKER_WINDOW_MAX,
26074            Duration::ZERO,
26075            Duration::from_secs(86_400),
26076        ] {
26077            let cb = CircuitBreaker {
26078                max_failures: 5,
26079                window,
26080            };
26081            assert_eq!(
26082                cb.window(),
26083                window,
26084                "CircuitBreaker::window must return :politicas \
26085                 :circuit-breaker :window verbatim (got {:?}, \
26086                 expected {window:?})",
26087                cb.window(),
26088            );
26089            assert_eq!(
26090                cb.window(),
26091                cb.window,
26092                "CircuitBreaker::window must byte-equal the raw \
26093                 .window field access across every value in the \
26094                 Duration accept-set",
26095            );
26096        }
26097    }
26098
26099    #[test]
26100    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
26101        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26102        // `:circuit-breaker :window` zero-floor arm must key off
26103        // [`CircuitBreaker::window`], not the raw `.window` field
26104        // access. Structurally: a `CircuitBreaker { window:
26105        // Duration::ZERO, .. }` embedded in a
26106        // `:politicas :circuit-breaker` slot must surface the
26107        // `PolicyBreakerZeroWindow` refusal exactly, and a
26108        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
26109        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
26110        // accept-set) must pass validate. The pair jointly pins the
26111        // accessor + validate-gate composition: any future silent
26112        // detour that had the accessor return a fresh
26113        // `Duration::from_millis(1)` on the zero arm (a
26114        // `.window().max(Duration::from_millis(1))` collapse) would
26115        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
26116        // accessor boundary and the validate gate would accept a
26117        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
26118        // — the composition pin catches that at caixa-core build time.
26119        //
26120        // Peer of the sibling per-`CircuitBreaker`
26121        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
26122        // pin on the peer required-scalar `:max-failures` axis — same
26123        // "the validate / shape-gate predicate must route through the
26124        // substrate-primitive typed dispatch" discipline extended onto
26125        // the peer per-`CircuitBreaker` required-`Duration` composition
26126        // axis.
26127        let mut spec = three_member_spec();
26128        spec.politicas = MeshPolicy {
26129            circuit_breaker: Some(CircuitBreaker {
26130                max_failures: 5,
26131                window: Duration::ZERO,
26132            }),
26133            ..MeshPolicy::default()
26134        };
26135        assert!(
26136            matches!(
26137                spec.validate(),
26138                Err(AplicacaoError::PolicyBreakerZeroWindow)
26139            ),
26140            "validate_politicas must reject window == Duration::ZERO \
26141             with PolicyBreakerZeroWindow — the accessor and the \
26142             validate gate must route through the same substrate-\
26143             primitive typed dispatch on the :window zero-floor arm",
26144        );
26145        spec.politicas = MeshPolicy {
26146            circuit_breaker: Some(CircuitBreaker {
26147                max_failures: 5,
26148                window: Duration::from_millis(1),
26149            }),
26150            ..MeshPolicy::default()
26151        };
26152        assert!(
26153            spec.validate().is_ok(),
26154            "validate_politicas must accept window == \
26155             Duration::from_millis(1) (the lower boundary of the \
26156             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
26157        );
26158    }
26159
26160    #[test]
26161    fn circuit_breaker_window_projects_duration_by_copy() {
26162        // The by-copy pin: [`CircuitBreaker::window`] returns
26163        // `Duration` by copy — `Duration` is `Copy` and the accessor
26164        // must return by value, not by reference. Peer of the sibling
26165        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
26166        // (3a74062) by-copy pin on the peer required-scalar
26167        // `:max-failures` axis, extended onto the peer
26168        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
26169        // — the accessor's returned `Duration` must outlive `&self`
26170        // (multiple calls must return equal values from a
26171        // dropped-`&self` copy, since the returned scalar carries no
26172        // borrow), and calling the accessor twice on the same
26173        // CircuitBreaker must yield the same `Duration` verbatim
26174        // (idempotent, no side effects on `&self`).
26175        //
26176        // Pins against a future silent detour that returned
26177        // `&Duration` (which would type-check but silently break every
26178        // downstream `Duration`-by-value consumer —
26179        // [`crate::render::require_positive_canonical_bounded_duration`]'s
26180        // first parameter is `Duration`, and `&Duration` would fold to
26181        // a detached copy at the call site with a `*` deref the sibling
26182        // accessors don't need), an accidental `.window + Duration::ZERO`
26183        // detour that returned a fresh copy through an arithmetic
26184        // no-op (breaking a future `const fn` regression), or a
26185        // one-arm-only accessor that returned a saturating value on
26186        // some sentinel input (breaking the pass-through invariant the
26187        // sibling required-scalar accessors carry).
26188        for window in [
26189            Duration::from_millis(1),
26190            POLICY_BREAKER_WINDOW_MAX,
26191            Duration::ZERO,
26192            Duration::from_secs(86_400),
26193        ] {
26194            let cb = CircuitBreaker {
26195                max_failures: 5,
26196                window,
26197            };
26198            let first = cb.window();
26199            let second = cb.window();
26200            assert_eq!(
26201                first, second,
26202                "CircuitBreaker::window must be idempotent — two \
26203                 successive calls on the same &self must return the \
26204                 same Duration",
26205            );
26206            assert_eq!(
26207                first, window,
26208                "CircuitBreaker::window must return :politicas \
26209                 :circuit-breaker :window verbatim by copy — \
26210                 got {first:?}, expected {window:?}",
26211            );
26212        }
26213    }
26214
26215    #[test]
26216    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
26217        // Apex-identity pair-invariant pin composing both substrate-
26218        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
26219        // and [`WitContract::destination`] — at the emit-side call shape
26220        // every per-`(:de, :para)` CNP L4 port reader now takes. The
26221        // invariant, evaluated per-edge:
26222        //
26223        //   spec.port_for_destination(c.destination()) == expected_port
26224        //
26225        // where `expected_port` is `entrada.port` when
26226        // `c.destination() == entrada.destination()` and
26227        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
26228        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
26229        // pin on the per-`:entrada` axis — that pin encodes the apex
26230        // ingress L4 identity via `entrada.destination()`; this pin
26231        // encodes the per-edge L4 identity via `c.destination()`, and
26232        // both compose on the same substrate-primitive resolver so a
26233        // future refactor that silently split either accessor's apex
26234        // behavior surfaces at caixa-core build time.
26235        let mut spec = three_member_spec();
26236        if let Some(e) = spec.entrada.as_mut() {
26237            e.para = "cart".into();
26238            e.port = 8443;
26239        }
26240        let apex_contract = WitContract {
26241            de: "checkout".into(),
26242            para: "cart".into(),
26243            wit: "wasi:http/proxy".into(),
26244            endpoint: Some("/hello".into()),
26245            subject: None,
26246            slot: None,
26247        };
26248        assert_eq!(
26249            spec.port_for_destination(apex_contract.destination()),
26250            8443,
26251            "`spec.port_for_destination(c.destination())` must equal \
26252             `entrada.port` when the contract callee names the ingress \
26253             apex — the CNP per-edge L4 port and the HTTPRoute apex \
26254             backendRef port share this substrate-primitive resolver.",
26255        );
26256        let non_apex_contract = WitContract {
26257            de: "cart".into(),
26258            para: "payment".into(),
26259            wit: "wasi:http/proxy".into(),
26260            endpoint: Some("/charge".into()),
26261            subject: None,
26262            slot: None,
26263        };
26264        assert_eq!(
26265            spec.port_for_destination(non_apex_contract.destination()),
26266            DEFAULT_SERVICO_PORT,
26267            "`spec.port_for_destination(c.destination())` must fall back \
26268             to the substrate-canonical port floor when the contract \
26269             callee is not the ingress apex — the resolver's non-apex \
26270             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
26271        );
26272    }
26273
26274    #[test]
26275    fn membro_key_consts_are_lower_camel_case_shape() {
26276        // Shape-pin: every `MEMBRO_KEY_*` const must be a
26277        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26278        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26279        // leading capital, no whitespace / dots) — the canonical shape
26280        // the `#[serde(rename_all = "camelCase")]` derive produces on
26281        // [`Membro`]. A future flip to a non-camelCase attribute at
26282        // the derive surfaces both here (this test fails on the
26283        // stale-constant shape) and at
26284        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
26285        // fails on the mismatch between const and derive). Peer with
26286        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
26287        // on the sibling `SupervisorSpec` top-level axis.
26288        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
26289            assert!(
26290                !key.is_empty(),
26291                "MEMBRO_KEY_* must be non-empty (got {key:?})"
26292            );
26293            let first = key.chars().next().unwrap();
26294            assert!(
26295                first.is_ascii_lowercase(),
26296                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
26297                 (got {key:?}, leads with {first:?})",
26298            );
26299            assert!(
26300                key.chars().all(|c| c.is_ascii_alphanumeric()),
26301                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
26302                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26303            );
26304        }
26305    }
26306
26307    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
26308
26309    #[test]
26310    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
26311        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
26312        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
26313        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
26314        // keys the `#[serde(rename_all = "camelCase")]` attribute on
26315        // [`WitContract`] emits for the required-triad. The three
26316        // sibling payload-arm keys already pin under
26317        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
26318        // `STORE_FIELD_NAME` — pin all six alongside so a future
26319        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26320        // verbatim-field-name flip at the derive attribute (any of which
26321        // would silently break every downstream JSON consumer that
26322        // reaches for one of the six via `Value::get(...)`) surfaces
26323        // here as a build-time test failure at `aplicacao.rs`, not as an
26324        // apply-time `.get(<stale-canonical-const>)` returning `None`
26325        // far from the derive-attr drift's commit. Peer with the sibling
26326        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26327        // pin on the M3 `:membros` per-entry axis — same discipline the
26328        // `Membro` per-entry lift established, extended here to the
26329        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
26330        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
26331        // axis on the Aplicacao surface without a lifted serde-key peer.
26332        let c = WitContract {
26333            de: "cart".into(),
26334            para: "catalog".into(),
26335            wit: "wasi:http/proxy".into(),
26336            endpoint: Some("/lookup".into()),
26337            subject: None,
26338            slot: None,
26339        };
26340        let json = serde_json::to_string(&c).unwrap();
26341        for key in [
26342            crate::CONTRATO_KEY_DE,
26343            crate::CONTRATO_KEY_PARA,
26344            crate::CONTRATO_KEY_WIT,
26345            WitTarget::HTTP_FIELD_NAME,
26346        ] {
26347            let quoted = format!("\"{key}\"");
26348            assert!(
26349                json.contains(&quoted),
26350                "serialized WitContract must carry the lifted \
26351                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
26352                 {quoted} verbatim in the JSON emission (got: {json})",
26353            );
26354        }
26355
26356        // Pin the two remaining payload-arm keys by round-tripping a
26357        // `WitContract` under each payload-shape (pub-sub, store) — the
26358        // required-triad appears on every emission but the payload arms
26359        // only surface when their `Option<String>` field is `Some`.
26360        let pubsub = WitContract {
26361            de: "cart".into(),
26362            para: "events".into(),
26363            wit: "nats:pub-sub".into(),
26364            endpoint: None,
26365            subject: Some("orders.placed".into()),
26366            slot: None,
26367        };
26368        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
26369        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
26370        assert!(
26371            pubsub_json.contains(&pubsub_quoted),
26372            "serialized pub-sub WitContract must carry the lifted \
26373             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
26374             verbatim in the JSON emission (got: {pubsub_json})",
26375        );
26376        let store = WitContract {
26377            de: "cart".into(),
26378            para: "sessions".into(),
26379            wit: "wasi:keyvalue/store".into(),
26380            endpoint: None,
26381            subject: None,
26382            slot: Some("cart/$id".into()),
26383        };
26384        let store_json = serde_json::to_string(&store).unwrap();
26385        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
26386        assert!(
26387            store_json.contains(&store_quoted),
26388            "serialized store WitContract must carry the lifted \
26389             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
26390             verbatim in the JSON emission (got: {store_json})",
26391        );
26392    }
26393
26394    #[test]
26395    fn contrato_key_consts_are_pairwise_distinct() {
26396        // Cross-axis drift-detection pin: a future collapse of the six
26397        // canonical [`WitContract`] per-entry byte-strings onto the same
26398        // value (e.g. an accidental copy-paste flip of
26399        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
26400        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
26401        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
26402        // every downstream probe on one axis onto the sibling axis's
26403        // overlay entry and pass every propagation-probe test that
26404        // expected only the stale axis's value. Peer of the sibling
26405        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
26406        // widened here to the six-way axis the `WitContract`
26407        // required-triad + `WitTarget` payload-triad jointly cover.
26408        let all = [
26409            crate::CONTRATO_KEY_DE,
26410            crate::CONTRATO_KEY_PARA,
26411            crate::CONTRATO_KEY_WIT,
26412            WitTarget::HTTP_FIELD_NAME,
26413            WitTarget::PUBSUB_FIELD_NAME,
26414            WitTarget::STORE_FIELD_NAME,
26415        ];
26416        for (i, a) in all.iter().enumerate() {
26417            for b in all.iter().skip(i + 1) {
26418                assert_ne!(
26419                    a, b,
26420                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
26421                     must be pairwise-distinct canonical byte-sequences \
26422                     — got `{a}` == `{b}`",
26423                );
26424            }
26425        }
26426    }
26427
26428    #[test]
26429    fn contrato_key_consts_are_lower_camel_case_shape() {
26430        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
26431        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
26432        // byte-sequence (no `snake_case` underscores, no `kebab-case`
26433        // hyphens, no leading colon, no `PascalCase` leading capital, no
26434        // whitespace / dots) — the canonical shape the
26435        // `#[serde(rename_all = "camelCase")]` derive produces on
26436        // [`WitContract`]. A future flip to a non-camelCase attribute at
26437        // the derive surfaces both here (this test fails on the
26438        // stale-constant shape) and at
26439        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26440        // (that test fails on the mismatch between const and derive).
26441        // Peer with `membro_key_consts_are_lower_camel_case_shape`
26442        // (ce80ca0) on the sibling `Membro` per-entry axis.
26443        for key in [
26444            crate::CONTRATO_KEY_DE,
26445            crate::CONTRATO_KEY_PARA,
26446            crate::CONTRATO_KEY_WIT,
26447            WitTarget::HTTP_FIELD_NAME,
26448            WitTarget::PUBSUB_FIELD_NAME,
26449            WitTarget::STORE_FIELD_NAME,
26450        ] {
26451            assert!(
26452                !key.is_empty(),
26453                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26454                 non-empty (got {key:?})"
26455            );
26456            let first = key.chars().next().unwrap();
26457            assert!(
26458                first.is_ascii_lowercase(),
26459                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
26460                 with an ASCII-lowercase byte (got {key:?}, leads with \
26461                 {first:?})",
26462            );
26463            assert!(
26464                key.chars().all(|c| c.is_ascii_alphanumeric()),
26465                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26466                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
26467                 whitespace (got {key:?})",
26468            );
26469        }
26470    }
26471
26472    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
26473
26474    #[test]
26475    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
26476        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
26477        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
26478        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
26479        // name the exact camelCase JSON keys the
26480        // `#[serde(rename_all = "camelCase")]` attribute on
26481        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
26482        // pin that each canonical byte-sequence appears verbatim in the
26483        // JSON — a future accidental `rename_all = "snake_case"` /
26484        // `"kebab-case"` / verbatim-field-name flip at the derive
26485        // attribute (any of which would silently break every downstream
26486        // JSON consumer that reaches for one of the four consts via
26487        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
26488        // emitter's per-Aplicacao hostname/paths/port projection, the
26489        // future `app-operator` reconciler's per-Aplicacao ingress
26490        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
26491        // materializer's admission-time cross-check) surfaces here as
26492        // a build-time test failure at `aplicacao.rs`, not as an
26493        // apply-time `.get(<stale-canonical-const>)` returning `None`
26494        // far from the derive-attr drift's commit. Peer with the
26495        // sibling
26496        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26497        // (ca463a4) and
26498        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26499        // pins on the M3 collection-slot atom axes — same discipline
26500        // both collection-slot lifts established, extended here to the
26501        // singleton `:entrada` mesh-slot atom axis, the last M3
26502        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
26503        // axis on the Aplicacao surface without a lifted serde-key
26504        // peer.
26505        let e = Entrada {
26506            host: "checkout.quero.cloud".into(),
26507            para: "cart".into(),
26508            paths: vec!["/cart".into()],
26509            port: 8080,
26510        };
26511        let json = serde_json::to_string(&e).unwrap();
26512        for key in [
26513            crate::ENTRADA_KEY_HOST,
26514            crate::ENTRADA_KEY_PARA,
26515            crate::ENTRADA_KEY_PATHS,
26516            crate::ENTRADA_KEY_PORT,
26517        ] {
26518            let quoted = format!("\"{key}\"");
26519            assert!(
26520                json.contains(&quoted),
26521                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
26522                 byte-sequence {quoted} verbatim in the JSON emission \
26523                 (got: {json})",
26524            );
26525        }
26526    }
26527
26528    #[test]
26529    fn entrada_key_consts_are_pairwise_distinct() {
26530        // Cross-axis drift-detection pin: a future collapse of the four
26531        // canonical [`Entrada`] singleton byte-strings onto the same
26532        // value (e.g. an accidental copy-paste flip of
26533        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
26534        // silently reroute every downstream probe on one axis onto the
26535        // sibling axis's overlay entry and pass every propagation-probe
26536        // test that expected only the stale axis's value — the
26537        // Gateway/HTTPRoute emitter would read the hostname string
26538        // where the destination-Servico name was expected (or vice
26539        // versa), the admission-webhook cross-check would compare the
26540        // wrong pair of values, and the resulting Gateway resource
26541        // would either be admitted with garbage or rejected at the
26542        // controller far from the rebrand commit's source. Peer of the
26543        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
26544        // tetrad (40cc4e5), the two-way distinct pin on the
26545        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
26546        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
26547        // triad (ca463a4).
26548        let all = [
26549            crate::ENTRADA_KEY_HOST,
26550            crate::ENTRADA_KEY_PARA,
26551            crate::ENTRADA_KEY_PATHS,
26552            crate::ENTRADA_KEY_PORT,
26553        ];
26554        for (i, a) in all.iter().enumerate() {
26555            for b in all.iter().skip(i + 1) {
26556                assert_ne!(
26557                    a, b,
26558                    "ENTRADA_KEY_* consts must be pairwise-distinct \
26559                     canonical byte-sequences — got `{a}` == `{b}`",
26560                );
26561            }
26562        }
26563    }
26564
26565    #[test]
26566    fn entrada_key_consts_are_lower_camel_case_shape() {
26567        // Shape-pin: every `ENTRADA_KEY_*` const must be a
26568        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26569        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26570        // leading capital, no whitespace / dots) — the canonical shape
26571        // the `#[serde(rename_all = "camelCase")]` derive produces on
26572        // [`Entrada`]. A future flip to a non-camelCase attribute at
26573        // the derive surfaces both here (this test fails on the
26574        // stale-constant shape) and at
26575        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
26576        // test fails on the mismatch between const and derive). Peer
26577        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
26578        // and `contrato_key_consts_are_lower_camel_case_shape`
26579        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
26580        // entry axes.
26581        for key in [
26582            crate::ENTRADA_KEY_HOST,
26583            crate::ENTRADA_KEY_PARA,
26584            crate::ENTRADA_KEY_PATHS,
26585            crate::ENTRADA_KEY_PORT,
26586        ] {
26587            assert!(
26588                !key.is_empty(),
26589                "ENTRADA_KEY_* must be non-empty (got {key:?})"
26590            );
26591            let first = key.chars().next().unwrap();
26592            assert!(
26593                first.is_ascii_lowercase(),
26594                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
26595                 (got {key:?}, leads with {first:?})",
26596            );
26597            assert!(
26598                key.chars().all(|c| c.is_ascii_alphanumeric()),
26599                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
26600                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26601            );
26602        }
26603    }
26604
26605    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
26606
26607    #[test]
26608    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
26609        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
26610        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
26611        // [`crate::POLITICAS_KEY_RETRIES`] /
26612        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
26613        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
26614        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
26615        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
26616        // on [`MeshPolicy`] emits. Three of the five axes
26617        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
26618        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
26619        // camelCase transforms — the derive-attribute is load-bearing
26620        // on those, unlike the sibling `Entrada` / `Membro` /
26621        // `WitContract` structs whose fields are all lowercase-single-
26622        // word and where the derive is a no-op on every axis.
26623        // Serialize a fully-populated [`MeshPolicy`] (every axis
26624        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
26625        // on none of the five slots) and pin that each canonical
26626        // byte-sequence appears verbatim in the JSON — a future
26627        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26628        // verbatim-field-name flip at the derive attribute (any of
26629        // which would silently break every downstream JSON consumer
26630        // that reaches for one of the five consts via
26631        // `Value::get(...)` — the future M4 per-edge `:politicas`
26632        // overlay projection onto Cilium `L7Rules` and Gateway API
26633        // `HTTPRoute` backend timeouts, the future
26634        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26635        // admission-time mesh-policy cross-check, the future
26636        // `feira lint` per-`:politicas` bound-check gate) surfaces here
26637        // as a build-time test failure at `aplicacao.rs`, not as an
26638        // apply-time `.get(<stale-canonical-const>)` returning `None`
26639        // far from the derive-attr drift's commit. Peer with the
26640        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
26641        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26642        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
26643        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
26644        // atom axes — same discipline every M3 sibling lift
26645        // established, extended here to the singleton `:politicas`
26646        // mesh-slot atom axis, closing the last M3 typed-struct
26647        // top-level `#[serde(rename_all = "camelCase")]` axis on the
26648        // Aplicacao surface without a lifted serde-key peer.
26649        let p = MeshPolicy {
26650            timeout: Some(Duration::from_secs(30)),
26651            retries: Some(3),
26652            circuit_breaker: Some(CircuitBreaker {
26653                max_failures: 5,
26654                window: Duration::from_secs(60),
26655            }),
26656            mtls_required: Some(true),
26657            rate_limit: Some(RateLimit {
26658                rate: 100,
26659                window: Duration::from_secs(1),
26660            }),
26661        };
26662        let json = serde_json::to_string(&p).unwrap();
26663        for key in [
26664            crate::POLITICAS_KEY_TIMEOUT,
26665            crate::POLITICAS_KEY_RETRIES,
26666            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26667            crate::POLITICAS_KEY_MTLS_REQUIRED,
26668            crate::POLITICAS_KEY_RATE_LIMIT,
26669        ] {
26670            let quoted = format!("\"{key}\"");
26671            assert!(
26672                json.contains(&quoted),
26673                "serialized MeshPolicy must carry the lifted \
26674                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
26675                 JSON emission (got: {json})",
26676            );
26677        }
26678    }
26679
26680    #[test]
26681    fn politicas_key_consts_are_pairwise_distinct() {
26682        // Cross-axis drift-detection pin: a future collapse of the five
26683        // canonical [`MeshPolicy`] singleton byte-strings onto the same
26684        // value (e.g. an accidental copy-paste flip of
26685        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
26686        // would silently reroute every downstream probe on one axis
26687        // onto the sibling axis's overlay entry and pass every
26688        // propagation-probe test that expected only the stale axis's
26689        // value — the M4 per-edge `:politicas` overlay projection would
26690        // read the retry-count string where the timeout duration was
26691        // expected (or vice versa), the CR materializer's admission
26692        // cross-check would compare the wrong pair of values, and the
26693        // resulting mesh reconciler would either bind the wrong axis
26694        // or reject the resource at reconcile far from the rebrand
26695        // commit's source. Peer of the sibling four-way distinct pin
26696        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
26697        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
26698        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
26699        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
26700        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26701        let all = [
26702            crate::POLITICAS_KEY_TIMEOUT,
26703            crate::POLITICAS_KEY_RETRIES,
26704            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26705            crate::POLITICAS_KEY_MTLS_REQUIRED,
26706            crate::POLITICAS_KEY_RATE_LIMIT,
26707        ];
26708        for (i, a) in all.iter().enumerate() {
26709            for b in all.iter().skip(i + 1) {
26710                assert_ne!(
26711                    a, b,
26712                    "POLITICAS_KEY_* consts must be pairwise-distinct \
26713                     canonical byte-sequences — got `{a}` == `{b}`",
26714                );
26715            }
26716        }
26717    }
26718
26719    #[test]
26720    fn politicas_key_consts_are_lower_camel_case_shape() {
26721        // Shape-pin: every `POLITICAS_KEY_*` const must be a
26722        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26723        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26724        // leading capital, no whitespace / dots) — the canonical shape
26725        // the `#[serde(rename_all = "camelCase")]` derive produces on
26726        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
26727        // at the derive surfaces both here (this test fails on the
26728        // stale-constant shape) and at
26729        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26730        // (that test fails on the mismatch between const and derive).
26731        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
26732        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26733        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26734        // (ca463a4) on the sibling M3 typed-struct axes.
26735        for key in [
26736            crate::POLITICAS_KEY_TIMEOUT,
26737            crate::POLITICAS_KEY_RETRIES,
26738            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
26739            crate::POLITICAS_KEY_MTLS_REQUIRED,
26740            crate::POLITICAS_KEY_RATE_LIMIT,
26741        ] {
26742            assert!(
26743                !key.is_empty(),
26744                "POLITICAS_KEY_* must be non-empty (got {key:?})"
26745            );
26746            let first = key.chars().next().unwrap();
26747            assert!(
26748                first.is_ascii_lowercase(),
26749                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
26750                 byte (got {key:?}, leads with {first:?})",
26751            );
26752            assert!(
26753                key.chars().all(|c| c.is_ascii_alphanumeric()),
26754                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
26755                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26756            );
26757        }
26758    }
26759
26760    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
26761
26762    #[test]
26763    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
26764        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
26765        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
26766        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
26767        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
26768        // [`CircuitBreaker`] emits inside the
26769        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
26770        // two axes (`max_failures` → `maxFailures`) is a non-trivial
26771        // camelCase transform — the derive-attribute is load-bearing on
26772        // that axis, unlike the sibling `window` field where the derive
26773        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
26774        // pin that each canonical byte-sequence appears verbatim in the
26775        // JSON — a future accidental `rename_all = "snake_case"` /
26776        // `"kebab-case"` / verbatim-field-name flip at the derive
26777        // attribute (any of which would silently break every downstream
26778        // JSON consumer that reaches for one of the two consts via
26779        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
26780        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
26781        // per-edge `:politicas` overlay projection onto the mesh's
26782        // per-backend consecutive-failure-counter tripping threshold, the
26783        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26784        // admission-time breaker cross-check, the future `feira lint`
26785        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
26786        // here as a build-time test failure at `aplicacao.rs`, not as an
26787        // apply-time `.get(<stale-canonical-const>)` returning `None`
26788        // far from the derive-attr drift's commit. Peer with the sibling
26789        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26790        // (b55cca7) parent-axis pin — that test pins the outer
26791        // sub-block key the derive on [`MeshPolicy`] emits, this test
26792        // pins the inner keys the derive on the payload type emits, so
26793        // the two together lock the whole [`MeshPolicy`] breaker-tuning
26794        // shape end-to-end at build time.
26795        let cb = CircuitBreaker {
26796            max_failures: 5,
26797            window: Duration::from_secs(60),
26798        };
26799        let json = serde_json::to_string(&cb).unwrap();
26800        for key in [
26801            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26802            crate::CIRCUIT_BREAKER_KEY_WINDOW,
26803        ] {
26804            let quoted = format!("\"{key}\"");
26805            assert!(
26806                json.contains(&quoted),
26807                "serialized CircuitBreaker must carry the lifted \
26808                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
26809                 in the JSON emission (got: {json})",
26810            );
26811        }
26812    }
26813
26814    #[test]
26815    fn circuit_breaker_key_consts_are_pairwise_distinct() {
26816        // Cross-axis drift-detection pin: a future collapse of the two
26817        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
26818        // same value (e.g. an accidental copy-paste flip of
26819        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
26820        // `"maxFailures"`) would silently reroute every downstream
26821        // probe on one axis onto the sibling axis's overlay entry and
26822        // pass every propagation-probe test that expected only the
26823        // stale axis's value — the M4 per-edge `:politicas` overlay
26824        // projection would read the failure-count where the window
26825        // duration was expected (or vice versa), the CR materializer's
26826        // admission cross-check would compare the wrong pair of values,
26827        // and the resulting mesh reconciler would either bind the wrong
26828        // axis or reject the resource at reconcile far from the rebrand
26829        // commit's source. Peer of the sibling five-way distinct pin on
26830        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
26831        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
26832        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
26833        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
26834        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26835        let all = [
26836            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26837            crate::CIRCUIT_BREAKER_KEY_WINDOW,
26838        ];
26839        for (i, a) in all.iter().enumerate() {
26840            for b in all.iter().skip(i + 1) {
26841                assert_ne!(
26842                    a, b,
26843                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
26844                     canonical byte-sequences — got `{a}` == `{b}`",
26845                );
26846            }
26847        }
26848    }
26849
26850    #[test]
26851    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
26852        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
26853        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26854        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26855        // leading capital, no whitespace / dots) — the canonical shape
26856        // the `#[serde(rename_all = "camelCase")]` derive produces on
26857        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
26858        // at the derive surfaces both here (this test fails on the
26859        // stale-constant shape) and at
26860        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
26861        // (that test fails on the mismatch between const and derive).
26862        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
26863        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
26864        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
26865        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
26866        // (ca463a4) on the sibling M3 typed-struct axes.
26867        for key in [
26868            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
26869            crate::CIRCUIT_BREAKER_KEY_WINDOW,
26870        ] {
26871            assert!(
26872                !key.is_empty(),
26873                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
26874            );
26875            let first = key.chars().next().unwrap();
26876            assert!(
26877                first.is_ascii_lowercase(),
26878                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
26879                 byte (got {key:?}, leads with {first:?})",
26880            );
26881            assert!(
26882                key.chars().all(|c| c.is_ascii_alphanumeric()),
26883                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
26884                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26885            );
26886        }
26887    }
26888
26889    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
26890
26891    #[test]
26892    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
26893        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
26894        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
26895        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
26896        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
26897        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
26898        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
26899        // [`Placement`] emits. One of the four axes (`shard_key` →
26900        // `shardKey`) is a non-trivial camelCase transform — the
26901        // derive-attribute is load-bearing on that axis, unlike the
26902        // sibling `estrategia` / `clusters` / `affinity` axes whose
26903        // source-side field names carry no `_` and where the derive is a
26904        // no-op. Serialize a fully-populated [`Placement`] (both
26905        // `Option`-carrying axes `Some(_)` so
26906        // `skip_serializing_if = "Option::is_none"` fires on neither of
26907        // the two optional slots) and pin that each canonical
26908        // byte-sequence appears verbatim in the JSON — a future
26909        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26910        // verbatim-field-name flip at the derive attribute (any of which
26911        // would silently break every downstream consumer that reaches
26912        // for one of the four consts via
26913        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
26914        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
26915        // aggregator's per-cluster fanout filter keying off
26916        // `placement.clusters`, the M3 shard-pool dispatch materializer
26917        // keying off `placement.shardKey`, the M3 Adaptive compression
26918        // pass weighting off `placement.affinity`, every downstream
26919        // dispatcher branching on `placement.estrategia`, the future
26920        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
26921        // admission-time placement cross-check, the future `feira lint`
26922        // per-`:placement` bound-check gate) surfaces here as a
26923        // build-time test failure at `aplicacao.rs`, not as an
26924        // apply-time `.get(<stale-canonical-const>)` returning `None`
26925        // far from the derive-attr drift's commit. Peer with the sibling
26926        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
26927        // (b55cca7),
26928        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
26929        // (468e959),
26930        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
26931        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26932        // (ca463a4), and
26933        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26934        // pins on the M3 collection-slot / singleton-slot atom axes —
26935        // closes the last M3 typed-struct top-level
26936        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
26937        // surface without a drift-detection pin.
26938        let p = Placement {
26939            estrategia: PlacementStrategy::Sharded,
26940            clusters: vec!["rio".into(), "mar".into()],
26941            affinity: Some("data-locality".into()),
26942            shard_key: Some("$tenantId".into()),
26943        };
26944        let json = serde_json::to_string(&p).unwrap();
26945        for key in [
26946            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26947            crate::M3_PLACEMENT_KEY_CLUSTERS,
26948            crate::M3_PLACEMENT_KEY_AFFINITY,
26949            crate::M3_PLACEMENT_KEY_SHARD_KEY,
26950        ] {
26951            let quoted = format!("\"{key}\"");
26952            assert!(
26953                json.contains(&quoted),
26954                "serialized Placement must carry the lifted \
26955                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
26956                 the JSON emission (got: {json})",
26957            );
26958        }
26959    }
26960
26961    #[test]
26962    fn m3_placement_key_consts_are_pairwise_distinct() {
26963        // Cross-axis drift-detection pin: a future collapse of the four
26964        // canonical [`Placement`] sub-block byte-strings onto the same
26965        // value (e.g. an accidental copy-paste flip of
26966        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
26967        // `"affinity"`) would silently reroute every downstream probe on
26968        // one axis onto the sibling axis's overlay entry and pass every
26969        // propagation-probe test that expected only the stale axis's
26970        // value — the M3 shard-pool dispatch materializer would read the
26971        // affinity placement-hint where the shard-selection template was
26972        // expected (or vice versa), the M3 Adaptive compression pass's
26973        // cross-check would compare the wrong pair of values, and the
26974        // resulting placement engine would either bind the wrong axis or
26975        // reject the resource at reconcile far from the rebrand commit's
26976        // source. Peer of the sibling two-way distinct pin on the
26977        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
26978        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
26979        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
26980        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
26981        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
26982        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
26983        let all = [
26984            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
26985            crate::M3_PLACEMENT_KEY_CLUSTERS,
26986            crate::M3_PLACEMENT_KEY_AFFINITY,
26987            crate::M3_PLACEMENT_KEY_SHARD_KEY,
26988        ];
26989        for (i, a) in all.iter().enumerate() {
26990            for b in all.iter().skip(i + 1) {
26991                assert_ne!(
26992                    a, b,
26993                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
26994                     canonical byte-sequences — got `{a}` == `{b}`",
26995                );
26996            }
26997        }
26998    }
26999
27000    #[test]
27001    fn m3_placement_key_consts_are_lower_camel_case_shape() {
27002        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
27003        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27004        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27005        // leading capital, no whitespace / dots) — the canonical shape
27006        // the `#[serde(rename_all = "camelCase")]` derive produces on
27007        // [`Placement`]. A future flip to a non-camelCase attribute at
27008        // the derive surfaces both here (this test fails on the stale-
27009        // constant shape) and at
27010        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
27011        // (that test fails on the mismatch between const and derive).
27012        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
27013        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
27014        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
27015        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27016        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27017        // (ca463a4) on the sibling M3 typed-struct axes.
27018        for key in [
27019            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27020            crate::M3_PLACEMENT_KEY_CLUSTERS,
27021            crate::M3_PLACEMENT_KEY_AFFINITY,
27022            crate::M3_PLACEMENT_KEY_SHARD_KEY,
27023        ] {
27024            assert!(
27025                !key.is_empty(),
27026                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
27027            );
27028            let first = key.chars().next().unwrap();
27029            assert!(
27030                first.is_ascii_lowercase(),
27031                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
27032                 byte (got {key:?}, leads with {first:?})",
27033            );
27034            assert!(
27035                key.chars().all(|c| c.is_ascii_alphanumeric()),
27036                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
27037                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27038            );
27039        }
27040    }
27041
27042    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
27043    //    destination-facing L4 port resolver every per-Aplicacao renderer
27044    //    reaching for a per-destination Servico TCP port axis routes
27045    //    through. The four pin tests below fix the four-way accept-set
27046    //    the resolver must always honor: (:entrada-para-matches,
27047    //    :entrada-para-mismatches, :entrada-none-so-fallback,
27048    //    :entrada-port-non-default-honored) — drift on any arm surfaces
27049    //    at caixa-core build time rather than at cluster-apply time.
27050
27051    #[test]
27052    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
27053        // The typed `:entrada` block's `:para "cart"` matches the
27054        // queried destination, so the resolver returns the author-
27055        // declared `:port` scalar verbatim — the canonical "the
27056        // destination Servico IS the ingress apex, honor the typed
27057        // listener port" arm of the port-resolution dispatch.
27058        let mut spec = three_member_spec();
27059        if let Some(e) = spec.entrada.as_mut() {
27060            e.para = "cart".into();
27061            e.port = 9090;
27062        }
27063        assert_eq!(
27064            spec.port_for_destination("cart"),
27065            9090,
27066            "port_for_destination(entrada.para) must return entrada.port \
27067             verbatim, not the DEFAULT_SERVICO_PORT fallback"
27068        );
27069    }
27070
27071    #[test]
27072    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
27073        // The typed `:entrada` block names `:para "cart"`, but the
27074        // queried destination is `"payment"` — a Servico that
27075        // participates in the mesh graph but is not the ingress apex.
27076        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
27077        // canonical port floor, closing the "non-apex destination reads
27078        // the substrate default" arm. Same fixture the peer
27079        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
27080        // pin at caixa-mesh exercises through the CNP emit-side path;
27081        // this pin exercises the shared underlying resolver directly.
27082        let spec = three_member_spec();
27083        assert_eq!(
27084            spec.port_for_destination("payment"),
27085            DEFAULT_SERVICO_PORT,
27086            "port_for_destination(non-apex-destination) must route \
27087             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
27088        );
27089    }
27090
27091    #[test]
27092    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
27093        // Internal-only Aplicacao — no `:entrada` block declared. Every
27094        // per-destination port query falls back to the lifted
27095        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
27096        // the Aplicacao surface admits `:entrada None` (internal mesh
27097        // with no external gateway); every downstream renderer's per-
27098        // destination port axis must still resolve to a well-defined
27099        // scalar even without an ingress apex.
27100        let mut spec = three_member_spec();
27101        spec.entrada = None;
27102        assert_eq!(
27103            spec.port_for_destination("cart"),
27104            DEFAULT_SERVICO_PORT,
27105            "port_for_destination on an internal-only Aplicacao must \
27106             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
27107             every destination"
27108        );
27109        assert_eq!(
27110            spec.port_for_destination("payment"),
27111            DEFAULT_SERVICO_PORT,
27112            "port_for_destination on an internal-only Aplicacao must \
27113             fall back uniformly across every destination — the fallback \
27114             is not entrada-shape-conditional"
27115        );
27116    }
27117
27118    #[test]
27119    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
27120        // Structural pin against a hypothetical future refactor that
27121        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
27122        // the resolver (a "normalize to the default when the author's
27123        // port matches the substrate default" collapse) — that would
27124        // break renderer sites that carry meaning on the emitted port
27125        // value beyond bare equality (a future per-cluster listener-
27126        // audit that keys off the author-declared port, not the
27127        // resolved-with-fallback port). Pin that a non-default
27128        // entrada.port is returned verbatim so drift here surfaces at
27129        // caixa-core build time.
27130        let mut spec = three_member_spec();
27131        if let Some(e) = spec.entrada.as_mut() {
27132            e.para = "cart".into();
27133            e.port = 8443;
27134        }
27135        assert_ne!(
27136            8443, DEFAULT_SERVICO_PORT,
27137            "test fixture must probe a port distinct from \
27138             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
27139        );
27140        assert_eq!(
27141            spec.port_for_destination("cart"),
27142            8443,
27143            "port_for_destination(entrada.para) must return entrada.port \
27144             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
27145        );
27146    }
27147
27148    #[test]
27149    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
27150        // Apex-identity pair-invariant pin composing both substrate-
27151        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
27152        // and [`Entrada::destination`] — at the emit-side call shape
27153        // every per-Aplicacao renderer's ingress-apex L4 port reader
27154        // now takes. The invariant:
27155        //
27156        //   spec.port_for_destination(entrada.destination()) == entrada.port
27157        //
27158        // holds by construction under today's single-destination
27159        // `:entrada` slot (`destination()` returns `entrada.para`, and
27160        // the resolver's apex arm matches `para == destination` and
27161        // returns `entrada.port`), and every downstream consumer that
27162        // composes the two accessors at the ingress apex — the
27163        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
27164        // `backendRefs[0].port` emit-site path, the peer future M4 CR
27165        // materializer's admission-webhook that promotes the scalar to
27166        // a per-CR override overlay, every future per-Aplicacao snapshot
27167        // renderer's apex-facing L4 port reader — reaches through the
27168        // same composition. Pin the identity across four permutations
27169        // (`:para` × `:port` including a non-default port to exercise
27170        // the honor-verbatim arm and a non-cart `:para` to exercise
27171        // destination-agnostic identity) so a future refactor that
27172        // silently split either accessor's apex behavior surfaces at
27173        // caixa-core build time — a subtle `destination()` renaming
27174        // that returned `entrada.host.as_str()` instead of
27175        // `entrada.para.as_str()` would blow this pin loudly, closing
27176        // the last quiet failure mode the two lifts admit in composition.
27177        //
27178        // Peer discipline with the sibling caixa-mesh cross-crate pin
27179        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
27180        // on the two-renderer pair-invariant axis; this pin encodes the
27181        // same two-consumer coherence rule at the substrate-primitive
27182        // level so the invariant survives even if every renderer is
27183        // deleted.
27184        for (para, port) in [
27185            ("cart", DEFAULT_SERVICO_PORT),
27186            ("cart", 8443u16),
27187            ("payment", 9090u16),
27188            ("catalog", 443u16),
27189        ] {
27190            let mut spec = three_member_spec();
27191            if let Some(e) = spec.entrada.as_mut() {
27192                e.para = para.into();
27193                e.port = port;
27194            }
27195            let expected_port = spec
27196                .entrada()
27197                .expect("three_member_spec carries a typed `:entrada` block")
27198                .port();
27199            let composed_port = {
27200                let entrada = spec.entrada().expect("entrada present");
27201                spec.port_for_destination(entrada.destination())
27202            };
27203            assert_eq!(
27204                composed_port, expected_port,
27205                "`spec.port_for_destination(entrada.destination())` must \
27206                 equal `entrada.port` under today's single-destination \
27207                 `:entrada` slot — this is the apex-identity contract \
27208                 every downstream ingress-apex L4 port reader relies on. \
27209                 Input :entrada :para: {para:?}, :entrada :port: {port}"
27210            );
27211        }
27212    }
27213
27214    #[test]
27215    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
27216        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
27217        // per-`:entrada` apex-arm membership probe must key off
27218        // [`Entrada::destination`], not the raw `.para` field access.
27219        // Structurally: setting ONLY the `:entrada :para` field to a
27220        // fresh non-cart destination on an otherwise-well-formed
27221        // Aplicacao must (1) leave `e.destination()` byte-equal to
27222        // `e.para.as_str()` (the accessor is byte-projective by
27223        // definition), and (2) cause the resolver's apex arm to fire
27224        // and return `entrada.port` at exactly that new destination
27225        // while every other destination string falls through to
27226        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
27227        // membership check. Pins against a future silent detour that
27228        // (a) re-derived the apex-arm membership probe off
27229        // `e.para == destination` in `port_for_destination` instead of
27230        // `e.destination() == destination`, silently disagreeing with
27231        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
27232        // consumers (`entrada.destination()` at
27233        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
27234        // caixa-mesh/src/lib.rs:2739) that already reach through the
27235        // accessor, (b) accessor-side introduced a per-tenant alias
27236        // arm the caller was unaware of, silently rewriting an
27237        // author-declared `:para "cart"` value to a canary-aliased
27238        // form — the raw-field-access resolver would fall through to
27239        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
27240        // while the peer emit-site consumers landed on the aliased
27241        // destination, splitting the ingress-apex L4 port at
27242        // cluster-apply time.
27243        //
27244        // Peer of the sibling
27245        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
27246        // (d0de220) composition pin on the per-`:membros` refusal-arm
27247        // axis — same "the shape-gate predicate must route through the
27248        // substrate-primitive typed dispatch" discipline extended onto
27249        // the per-`:entrada` apex-arm membership-probe axis. Closes
27250        // the last unlifted `.para` production-code read site on
27251        // `Entrada` in `caixa-core` — after this converge every
27252        // `caixa-core` `.para` field access outside the accessor's own
27253        // body and outside the `WitContract` per-`:contratos` sibling
27254        // axis is either a test-side field-setter or a doc-comment
27255        // reference.
27256        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
27257            let mut spec = three_member_spec();
27258            if let Some(e) = spec.entrada.as_mut() {
27259                e.para = para.into();
27260                e.port = port;
27261            }
27262            let e = spec
27263                .entrada
27264                .as_ref()
27265                .expect("three_member_spec carries a typed `:entrada` block");
27266            assert_eq!(
27267                e.destination(),
27268                e.para.as_str(),
27269                "Entrada::destination must byte-equal the .para field \
27270                 access — an accessor-side detour that no longer \
27271                 projects the raw field would silently split this \
27272                 drift-detection test from the port_for_destination \
27273                 apex-arm membership probe",
27274            );
27275            assert_eq!(
27276                spec.port_for_destination(para),
27277                port,
27278                "port_for_destination must key off the accessor-projected \
27279                 destination and return `entrada.port` on the apex arm — \
27280                 input :entrada :para: {para:?}, :entrada :port: {port}",
27281            );
27282            assert_eq!(
27283                spec.port_for_destination("ghost-destination-never-a-member"),
27284                DEFAULT_SERVICO_PORT,
27285                "port_for_destination must fall through to \
27286                 DEFAULT_SERVICO_PORT on a non-matching destination \
27287                 under the accessor-projected membership check — input \
27288                 :entrada :para: {para:?}, :entrada :port: {port}",
27289            );
27290        }
27291    }
27292
27293    #[test]
27294    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
27295        // The canonical per-`:politicas :rate-limit` `:rate`
27296        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
27297        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
27298        // typed `u32` verbatim, byte-equal to the raw field access
27299        // across every representative value in the accept-set — `1` (the
27300        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
27301        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
27302        // carves out on the sibling `PolicyRateLimitZero` refusal),
27303        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
27304        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
27305        // `0` (a past-the-guard sentinel that pins the accessor doesn't
27306        // perform a silent bounds-collapse into `1` on the zero arm —
27307        // validate rejects zero but the accessor must ship the raw slot
27308        // verbatim so a validate-time gate regression surfaces at the
27309        // emit boundary rather than being silently absorbed), `u32::MAX`
27310        // (a past-the-guard sentinel that pins the accessor doesn't
27311        // perform a silent bounds-collapse through
27312        // `POLICY_RATE_LIMIT_MAX` at the return path).
27313        //
27314        // First sub-struct required-scalar accessor pin on the
27315        // `RateLimit` axis — sibling in shape to the peer
27316        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
27317        // required-`u32` accessor pin on the peer per-sub-struct
27318        // required-axis. Pins against a future silent detour that
27319        // re-derived the token capacity from a peer axis (an accidental
27320        // `self.window.as_secs() as u32` collapse that read the
27321        // rate-limit window duration as a token count), a `0 → 1`
27322        // cluster-default projection (which would silently absorb the
27323        // `PolicyRateLimitZero` refusal case at the accessor boundary),
27324        // or a bounds-collapsing accessor that clamped the return
27325        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
27326        // gate owns the bounds; the accessor must ship the raw slot
27327        // verbatim).
27328        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27329            let rl = RateLimit {
27330                rate,
27331                window: Duration::from_secs(1),
27332            };
27333            assert_eq!(
27334                rl.rate(),
27335                rate,
27336                "RateLimit::rate must return :politicas :rate-limit :rate \
27337                 verbatim (got {}, expected {rate})",
27338                rl.rate(),
27339            );
27340            assert_eq!(
27341                rl.rate(),
27342                rl.rate,
27343                "RateLimit::rate must byte-equal the raw .rate field \
27344                 access across every value in the u32 accept-set",
27345            );
27346        }
27347    }
27348
27349    #[test]
27350    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
27351        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27352        // `:rate-limit :rate` zero-floor arm must key off
27353        // [`RateLimit::rate`], not the raw `.rate` field access.
27354        // Structurally: a `RateLimit { rate: 0, window:
27355        // Duration::from_secs(1) }` embedded in a `:politicas
27356        // :rate-limit` slot must surface the `PolicyRateLimitZero`
27357        // refusal exactly, and a `RateLimit { rate: 1, window:
27358        // Duration::from_secs(1) }` (the lower boundary of the
27359        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
27360        // The pair jointly pins the accessor + validate-gate composition:
27361        // any future silent detour that had the accessor return a fresh
27362        // `1` on the zero arm (a `.rate().max(1)` collapse) would
27363        // silently absorb the `PolicyRateLimitZero` refusal at the
27364        // accessor boundary and the validate gate would accept a
27365        // struct-literal `RateLimit { rate: 0, .. }` — the composition
27366        // pin catches that at caixa-core build time.
27367        //
27368        // Peer of the sibling per-`CircuitBreaker`
27369        // [`CircuitBreaker::max_failures`] (3a74062) /
27370        // [`CircuitBreaker::window`] (373957f) accessor-composition
27371        // pins on the peer required-scalar axes — same "the validate /
27372        // shape-gate predicate must route through the substrate-primitive
27373        // typed dispatch" discipline extended onto the peer
27374        // per-`RateLimit` required-`u32` composition axis.
27375        let mut spec = three_member_spec();
27376        spec.politicas = MeshPolicy {
27377            rate_limit: Some(RateLimit {
27378                rate: 0,
27379                window: Duration::from_secs(1),
27380            }),
27381            ..MeshPolicy::default()
27382        };
27383        assert!(
27384            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
27385            "validate_politicas must reject rate == 0 with \
27386             PolicyRateLimitZero — the accessor and the validate gate \
27387             must route through the same substrate-primitive typed \
27388             dispatch on the :rate zero-floor arm",
27389        );
27390        spec.politicas = MeshPolicy {
27391            rate_limit: Some(RateLimit {
27392                rate: 1,
27393                window: Duration::from_secs(1),
27394            }),
27395            ..MeshPolicy::default()
27396        };
27397        assert!(
27398            spec.validate().is_ok(),
27399            "validate_politicas must accept rate == 1 (the lower \
27400             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
27401        );
27402    }
27403
27404    #[test]
27405    fn rate_limit_rate_projects_u32_by_copy() {
27406        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
27407        // `u32` is `Copy` and the accessor must return by value, not by
27408        // reference. Peer of the sibling per-`CircuitBreaker`
27409        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
27410        // peer required-scalar `:max-failures` axis, extended onto the
27411        // peer per-`RateLimit` required-`u32` copy-invariant shape —
27412        // the accessor's returned `u32` must outlive `&self` (multiple
27413        // calls must return equal values from a dropped-`&self` copy,
27414        // since the returned scalar carries no borrow), and calling the
27415        // accessor twice on the same RateLimit must yield the same
27416        // `u32` verbatim (idempotent, no side effects on `&self`).
27417        //
27418        // Pins against a future silent detour that returned `&u32`
27419        // (which would type-check but silently break every downstream
27420        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
27421        // first parameter is `u32`, and `&u32` would fold to a detached
27422        // copy at the call site with a `*` deref the sibling accessors
27423        // don't need), an accidental `.rate.wrapping_add(0)` detour that
27424        // returned a fresh copy through an arithmetic no-op (breaking a
27425        // future `const fn` regression), or a one-arm-only accessor
27426        // that returned a saturating value on some sentinel input
27427        // (breaking the pass-through invariant the sibling required-
27428        // scalar accessors carry).
27429        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27430            let rl = RateLimit {
27431                rate,
27432                window: Duration::from_secs(1),
27433            };
27434            let first = rl.rate();
27435            let second = rl.rate();
27436            assert_eq!(
27437                first, second,
27438                "RateLimit::rate must be idempotent — two successive \
27439                 calls on the same &self must return the same u32",
27440            );
27441            assert_eq!(
27442                first, rate,
27443                "RateLimit::rate must return :politicas :rate-limit :rate \
27444                 verbatim by copy — got {first}, expected {rate}",
27445            );
27446        }
27447    }
27448
27449    #[test]
27450    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
27451        // The canonical per-`:politicas :rate-limit` `:window`
27452        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
27453        // pin: [`RateLimit::window`] must return the
27454        // `:politicas :rate-limit :window` typed `Duration` verbatim,
27455        // byte-equal to the raw field access across every
27456        // representative value in the accept-set — `Duration::from_secs(1)`
27457        // (the `"s"` canonical window, the lower row of
27458        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
27459        // [`AplicacaoSpec::validate_politicas`] gate accepts via
27460        // [`is_canonical_rate_limit_window`]),
27461        // `Duration::from_secs(60)` (the `"m"` canonical window, the
27462        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
27463        // window, the upper row), `Duration::ZERO` (a past-the-guard
27464        // sentinel that pins the accessor doesn't perform a silent
27465        // bounds-collapse into `Duration::from_secs(1)` on the zero
27466        // arm — validate rejects an off-set window through
27467        // `PolicyRateLimitWindowNotCanonical` but the accessor must
27468        // ship the raw slot verbatim so a validate-time gate
27469        // regression surfaces at the emit boundary rather than being
27470        // silently absorbed), `Duration::from_millis(500)` (a
27471        // sub-canonical past-the-guard sentinel that pins the accessor
27472        // doesn't silently normalize a non-canonical fractional
27473        // magnitude onto the nearest canonical row).
27474        //
27475        // Second sub-struct required-scalar accessor pin on the
27476        // `RateLimit` axis — sibling in shape to the just-landed
27477        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
27478        // accessor pin on the peer per-sub-struct required-axis,
27479        // extended onto the per-`RateLimit` required-`Duration` axis.
27480        // Pins against a future silent detour that re-derived the
27481        // refill period from a peer axis (an accidental
27482        // `Duration::from_secs(self.rate as u64)` collapse that read
27483        // the rate-limit token capacity as a refill-interval
27484        // duration), a `Duration::ZERO → Duration::from_secs(1)`
27485        // canonical-default projection (which would silently absorb
27486        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
27487        // accessor boundary), or a canonical-set-collapsing accessor
27488        // that clamped the return through [`rate_limit_window_unit`]
27489        // (the `AplicacaoSpec::validate` gate owns the canonical-set
27490        // membership; the accessor must ship the raw slot verbatim).
27491        for window in [
27492            Duration::from_secs(1),
27493            Duration::from_secs(60),
27494            Duration::from_secs(3600),
27495            Duration::ZERO,
27496            Duration::from_millis(500),
27497        ] {
27498            let rl = RateLimit { rate: 100, window };
27499            assert_eq!(
27500                rl.window(),
27501                window,
27502                "RateLimit::window must return :politicas :rate-limit :window \
27503                 verbatim (got {:?}, expected {window:?})",
27504                rl.window(),
27505            );
27506            assert_eq!(
27507                rl.window(),
27508                rl.window,
27509                "RateLimit::window must byte-equal the raw .window field \
27510                 access across every value in the Duration accept-set",
27511            );
27512        }
27513    }
27514
27515    #[test]
27516    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
27517        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27518        // `:rate-limit :window` canonical-set arm must key off
27519        // [`RateLimit::window`], not the raw `.window` field access.
27520        // Structurally: a `RateLimit { window: Duration::from_millis(500),
27521        // .. }` embedded in a `:politicas :rate-limit` slot must
27522        // surface the `PolicyRateLimitWindowNotCanonical` refusal
27523        // exactly (with the sub-canonical `Duration::from_millis(500)`
27524        // magnitude carried through verbatim), and a `RateLimit
27525        // { window: Duration::from_secs(1), .. }` (the lower row of
27526        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
27527        // The pair jointly pins the accessor + validate-gate
27528        // composition: any future silent detour that had the accessor
27529        // normalize the off-set window to the nearest canonical row
27530        // (a `.window().max(Duration::from_secs(1))` collapse, or a
27531        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
27532        // collapse) would silently absorb the
27533        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
27534        // boundary — including a drift in the error's `window` payload
27535        // (the emit-side diagnostic reader keys off the offending
27536        // magnitude verbatim, so a normalization at the accessor
27537        // boundary would silently pin the wrong magnitude in the
27538        // refusal). The composition pin catches that at caixa-core
27539        // build time.
27540        //
27541        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
27542        // (7f81a60) accessor-composition pin on the peer required-
27543        // scalar `:rate` axis — same "the validate / shape-gate
27544        // predicate must route through the substrate-primitive typed
27545        // dispatch, and the error payload must project through the
27546        // same accessor" discipline extended onto the peer
27547        // per-`RateLimit` required-`Duration` composition axis.
27548        let mut spec = three_member_spec();
27549        spec.politicas = MeshPolicy {
27550            rate_limit: Some(RateLimit {
27551                rate: 100,
27552                window: Duration::from_millis(500),
27553            }),
27554            ..MeshPolicy::default()
27555        };
27556        match spec.validate() {
27557            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
27558                assert_eq!(
27559                    window,
27560                    Duration::from_millis(500),
27561                    "PolicyRateLimitWindowNotCanonical must carry the \
27562                     offending :window magnitude verbatim through the \
27563                     accessor — got {window:?}, expected 500ms",
27564                );
27565            }
27566            other => panic!(
27567                "validate_politicas must reject non-canonical :window \
27568                 with PolicyRateLimitWindowNotCanonical — the accessor \
27569                 and the validate gate must route through the same \
27570                 substrate-primitive typed dispatch on the :window \
27571                 canonical-set arm; got {other:?}",
27572            ),
27573        }
27574        spec.politicas = MeshPolicy {
27575            rate_limit: Some(RateLimit {
27576                rate: 100,
27577                window: Duration::from_secs(1),
27578            }),
27579            ..MeshPolicy::default()
27580        };
27581        assert!(
27582            spec.validate().is_ok(),
27583            "validate_politicas must accept window == Duration::from_secs(1) \
27584             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
27585        );
27586    }
27587
27588    #[test]
27589    fn rate_limit_window_projects_duration_by_copy() {
27590        // The by-copy pin: [`RateLimit::window`] returns `Duration`
27591        // by copy — `Duration` is `Copy` and the accessor must return
27592        // by value, not by reference. Peer of the sibling per-`RateLimit`
27593        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
27594        // required-scalar `:rate` axis, extended onto the peer
27595        // per-`RateLimit` required-`Duration` copy-invariant shape —
27596        // the accessor's returned `Duration` must outlive `&self`
27597        // (multiple calls must return equal values from a
27598        // dropped-`&self` copy, since the returned scalar carries no
27599        // borrow), and calling the accessor twice on the same
27600        // RateLimit must yield the same `Duration` verbatim
27601        // (idempotent, no side effects on `&self`).
27602        //
27603        // Pins against a future silent detour that returned
27604        // `&Duration` (which would type-check but silently break every
27605        // downstream `Duration`-by-value consumer —
27606        // [`is_canonical_rate_limit_window`]'s first parameter is
27607        // `Duration`, and `&Duration` would fold to a detached copy at
27608        // the call site with a `*` deref the sibling accessors don't
27609        // need), an accidental `.window + Duration::ZERO` detour that
27610        // returned a fresh copy through an arithmetic no-op (breaking
27611        // a future `const fn` regression), or a one-arm-only accessor
27612        // that returned a canonical fallback on some sentinel input
27613        // (breaking the pass-through invariant the sibling required-
27614        // scalar accessors carry).
27615        for window in [
27616            Duration::from_secs(1),
27617            Duration::from_secs(60),
27618            Duration::from_secs(3600),
27619            Duration::ZERO,
27620            Duration::from_millis(500),
27621        ] {
27622            let rl = RateLimit { rate: 100, window };
27623            let first = rl.window();
27624            let second = rl.window();
27625            assert_eq!(
27626                first, second,
27627                "RateLimit::window must be idempotent — two successive \
27628                 calls on the same &self must return the same Duration",
27629            );
27630            assert_eq!(
27631                first, window,
27632                "RateLimit::window must return :politicas :rate-limit :window \
27633                 verbatim by copy — got {first:?}, expected {window:?}",
27634            );
27635        }
27636    }
27637
27638    #[test]
27639    fn placement_estrategia_default_pins_m3_canonical_value() {
27640        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
27641        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
27642        // active-active-across-every-named-cluster arm, the closest
27643        // canonical M3 production reference the substrate carries and
27644        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
27645        // for every un-`:placement`-declared Aplicacao. Pinning the arm
27646        // here surfaces a future rebrand of the M3-canonical
27647        // distribution default (a widening to `Sharded` once the
27648        // substrate discovers hash-keyed distribution as the more
27649        // common production shape, a tightening to `SingleNode` for
27650        // stateful Erlang/OTP distributed-app-takeover semantics
27651        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
27652        // operator pins through a future `:placement-overrides` slot)
27653        // as a deliberate test edit, not a silent contract migration.
27654        // Peer of the sibling M2 per-supervisor value pins
27655        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
27656        // /
27657        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
27658        // extended onto the M3 mesh-primitive-defining `:placement
27659        // :estrategia` axis.
27660        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
27661    }
27662
27663    #[test]
27664    fn placement_strategy_default_routes_through_lifted_default() {
27665        // Composition pin: the [`Default for PlacementStrategy`] impl's
27666        // return arm must route through the substrate-canonical
27667        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
27668        // a raw `Self::Replicated` arm. Prior to the lift the impl
27669        // carried an inline `Self::Replicated` arm with no compile-time
27670        // link back to the shared M3-canonical `Replicated` arm the
27671        // paired [`Default for Placement`] impl's struct-literal
27672        // `estrategia` field, the serde-side `#[serde(default)]` on
27673        // [`Placement::estrategia`] that resolves an author-omitted
27674        // wire-form `:placement :estrategia` scalar through the impl,
27675        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
27676        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
27677        // routes through [`Placement::default`] which routes through the
27678        // strategy default) all key off — so a future rebrand of the
27679        // M3-canonical distribution default would have had to be threaded
27680        // through the `Default` impl and the three peer routes in
27681        // lockstep or the four consumers would silently split. Byte-
27682        // parity against the lifted constant closes the split. Peer of
27683        // the sibling
27684        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
27685        // /
27686        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
27687        // composition pins on the M2 per-supervisor axes.
27688        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
27689    }
27690
27691    #[test]
27692    fn placement_default_estrategia_routes_through_lifted_default() {
27693        // Composition pin: the [`Default for Placement`] impl's
27694        // struct-literal `estrategia` field must route through the
27695        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
27696        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
27697        // impl that the sibling
27698        // `placement_strategy_default_routes_through_lifted_default` pin
27699        // already routes onto the constant). Structurally: every
27700        // `Placement::default()` call must yield an `estrategia` field
27701        // byte-equal to the lifted constant so the two paired defaults —
27702        // the [`Default for PlacementStrategy`] impl arm and the
27703        // struct-literal default arm here — cannot silently split on any
27704        // future M3-canonical distribution-default rebrand. Peer of the
27705        // sibling M2
27706        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
27707        // byte-parity pin on the [`Default for SupervisorSpec`]
27708        // struct-literal `estrategia` field extended onto the M3
27709        // mesh-primitive-defining slot family.
27710        assert_eq!(
27711            Placement::default().estrategia,
27712            PLACEMENT_ESTRATEGIA_DEFAULT,
27713        );
27714    }
27715
27716    #[test]
27717    fn placement_serde_default_estrategia_routes_through_lifted_default() {
27718        // Composition pin: the serde-side `#[serde(default)]` on
27719        // [`Placement::estrategia`] — the wire-format author-omitted
27720        // `:placement :estrategia` arm — must resolve onto the substrate-
27721        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
27722        // (via the [`Default for PlacementStrategy`] impl the sibling
27723        // `placement_strategy_default_routes_through_lifted_default` pin
27724        // already routes onto the constant). Structurally: a `Placement`
27725        // deserialized from a payload that omits the `estrategia` key
27726        // must yield an `estrategia` field byte-equal to the lifted
27727        // constant, so the wire-format author-omitted arm and the
27728        // [`PlacementStrategy::default`] impl arm cannot silently split
27729        // on any future M3-canonical distribution-default rebrand. Peer
27730        // of the sibling M2
27731        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
27732        // byte-parity pin on the wire-format author-omitted `:children
27733        // :restart` scalar extended onto the M3 mesh-primitive-defining
27734        // slot family.
27735        let omitted: Placement = serde_json::from_str("{}")
27736            .expect("Placement must deserialize with the estrategia key omitted");
27737        assert_eq!(
27738            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
27739            "an author-omitted :placement :estrategia slot must degrade onto \
27740             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
27741             {:?}, expected {:?})",
27742            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
27743        );
27744    }
27745}