Skip to main content

caixa_core/
aplicacao.rs

1//! Typed Aplicacao — the fourth caixa kind that turns a graph of
2//! Servicos into a single declarative application (mesh).
3//!
4//! See `theory/MESH-COMPOSITION.md` for the design frame: an
5//! Aplicacao composes [`crate::CaixaKind::Servico`] caixas via WIT-typed
6//! `:contratos` (inter-Servico edges), declares mesh-level
7//! `:politicas` (timeouts, retries, breakers, mTLS), pins
8//! `:placement` strategy (single-node / replicated / sharded), and
9//! exposes `:entrada` (gateway).
10//!
11//! ```lisp
12//! (defcaixa
13//!   :nome      "checkout"
14//!   :versao    "0.1.0"
15//!   :kind      Aplicacao
16//!   :membros   ((:caixa "catalog"     :versao "^0.1")
17//!               (:caixa "cart"        :versao "^0.1")
18//!               (:caixa "payment"     :versao "^0.2"))
19//!   :contratos ((:de "cart" :para "catalog"
20//!                :wit "wasi:http/proxy" :endpoint "/products/:id")
21//!               (:de "cart" :para "payment"
22//!                :wit "wasi:http/proxy" :endpoint "/charge"))
23//!   :politicas ((:timeout "30s")
24//!               (:retries 3)
25//!               (:circuit-breaker (:max-failures 5 :window "60s"))
26//!               (:mtls-required t))
27//!   :placement (:estrategia replicated
28//!               :clusters   ("rio" "mar" "plo"))
29//!   :entrada   (:host  "checkout.quero.cloud"
30//!               :para  "cart"
31//!               :paths ("/api/cart" "/api/products")))
32//! ```
33//!
34//! All the typed slots compose with the M2 primitives the Servicos
35//! they reference already declare (`:limits`, `:behavior`,
36//! `:upgrade-from`). The Aplicacao adds the *graph-level*
37//! standardization on top.
38
39use std::time::Duration;
40
41use serde::{Deserialize, Serialize};
42use thiserror::Error;
43
44use crate::supervisor; // we reuse the duration-string codec at module scope
45
46// ── inter-Servico contracts ──────────────────────────────────────────
47
48/// One typed edge in the Aplicacao graph. The build refuses any
49/// contract whose `:de` or `:para` doesn't appear in `:membros`, and
50/// (M3+) cross-checks the `:wit` shape against both Servicos'
51/// declared imports/exports.
52#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
53#[serde(rename_all = "camelCase")]
54pub struct WitContract {
55    /// Caller Servico — must reference an entry in the Aplicacao's
56    /// `:membros`. The Servico's caixa.lisp must declare a matching
57    /// `:capabilities` import for the `:wit` world.
58    pub de: String,
59
60    /// Callee Servico — must reference an entry in `:membros`. The
61    /// Servico must declare a matching `:capabilities` export.
62    pub para: String,
63
64    /// WIT world reference — e.g. `"wasi:http/proxy"`,
65    /// `"wasi:keyvalue/store"`, `"nats:pub-sub"`. Strings for V0;
66    /// M4 promotes these to a typed enum once the WIT registry
67    /// stabilizes in tatara-lisp.
68    pub wit: String,
69
70    /// HTTP endpoint path, present when `:wit` is HTTP-shaped.
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub endpoint: Option<String>,
73
74    /// NATS / event-stream subject, present when `:wit` is pub-sub-shaped.
75    #[serde(default, skip_serializing_if = "Option::is_none")]
76    pub subject: Option<String>,
77
78    /// Key/value or queue slot, present when `:wit` is store-shaped.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub slot: Option<String>,
81}
82
83/// Canonical lowercase byte-prefix set the substrate's WIT-shape
84/// dispatch routes `wasi:http/*` / `http:*` values through as the
85/// HTTP-shaped arm. The single source of truth every consumer that
86/// classifies a `:wit` value as HTTP-shaped consults —
87/// [`WitContract::is_http`] on the typed contract, the
88/// `AplicacaoSpec::validate` positive-sweep test's payload-dispatch
89/// helper, and every future renderer that routes an L7 emission off a
90/// bare `&str` (the M4 per-edge WIT registry resolver, the future
91/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer). Spelled
92/// exactly as the [`is_wit_world_ref`][iwr] predicate documents the
93/// canonical lowercase prefixes ("`wasi:http/`, `nats:`,
94/// `wasi:keyvalue/`, `kafka:`, `kv:`, `http:`") so drift between the
95/// substrate's accept-set and this crate's dispatch-set is a
96/// build-time compile error (unused-import), not a per-renderer
97/// silent L7-→-L4 demotion at apply time.
98///
99/// [iwr]: crate::render::is_wit_world_ref
100pub const WIT_HTTP_SHAPE_PREFIXES: &[&str] = &["wasi:http/", "http:"];
101
102/// Canonical lowercase byte-prefix set the substrate's WIT-shape
103/// dispatch routes `nats:*` / `kafka:*` values through as the
104/// pub-sub-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
105/// [`WIT_STORE_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
106/// HTTP constant's docstring for the full lift rationale.
107pub const WIT_PUBSUB_SHAPE_PREFIXES: &[&str] = &["nats:", "kafka:"];
108
109/// Canonical lowercase byte-prefix set the substrate's WIT-shape
110/// dispatch routes `wasi:keyvalue/*` / `kv:*` values through as the
111/// key/value-store-shaped arm. Peer of [`WIT_HTTP_SHAPE_PREFIXES`] /
112/// [`WIT_PUBSUB_SHAPE_PREFIXES`] on the shape-dispatch axis; see the
113/// HTTP constant's docstring for the full lift rationale.
114pub const WIT_STORE_SHAPE_PREFIXES: &[&str] = &["wasi:keyvalue/", "kv:"];
115
116/// True when `wit` — a raw `:contratos :wit` value — starts with any
117/// entry in the `prefixes` accept-set. The single canonical
118/// prefix-driven WIT-shape classification combinator every peer
119/// per-shape predicate ([`wit_shape_is_http`], [`wit_shape_is_pubsub`],
120/// [`wit_shape_is_store`]) routes through, closing the 3-site
121/// duplication of the `PREFIXES.iter().any(|p| wit.starts_with(p))`
122/// combinator the prior open-coded implementations each carried.
123///
124/// A future 4th WIT-shape dispatch arm (a hypothetical `wasi:sockets/*`
125/// / `tcp:*` transport-layer shape, an `oci:*` capability-import
126/// carrier) becomes exactly one new [`WIT_*_SHAPE_PREFIXES`] const +
127/// one new `wit_shape_is_<name>` one-liner routing through this
128/// combinator, not a fourth copy of the `iter().any(starts_with)`
129/// combinator paired to its own prefix-set. Same "one canonical
130/// combinator, thin per-arm projections" discipline the peer
131/// [`WitTarget::payload_pair`] (6788ed6) already established for the
132/// downstream per-arm `(field, payload)` dispatch, extended to the
133/// upstream per-arm `PREFIXES → bool` dispatch.
134///
135/// Declared `pub const fn` — the four peer classifiers
136/// ([`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
137/// [`wit_shape_is_store`] / [`wit_shape_is_capability`]) route through
138/// this combinator in `const`-eval context, so the raw `&str → bool`
139/// WIT-shape dispatch reaches every substrate-side `const`-context
140/// consumer (the module-scope `const _: () = assert!(…)` canonical-
141/// accept-set + partition-witness pins immediately below the four
142/// peer classifiers, any future M4
143/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
144/// webhook `const fn` per-`:contratos :wit` shape-arm resolver over a
145/// raw &str, any future `const fn` per-`:contratos`-edge WIT-registry
146/// prefix-set overlay resolver over the substrate primitive that fans
147/// on the shape arm at compile time) through the same typed dispatch
148/// on the substrate primitive at const-eval time as at runtime. The
149/// prior `prefixes.iter().any(|p| wit.starts_with(p))` body carried
150/// non-`const` bounds on stable Rust 1.94 (`.iter()` / `.any()` /
151/// `str::starts_with(&str)` via the non-`const` `Pattern` trait); the
152/// new body routes the per-prefix probe through a manual byte-level
153/// `starts_with` loop over the paired `str::as_bytes` (`pub const fn`)
154/// slice projections, dispatching through primitive-`u8` `!=` and
155/// `usize` comparison + `pub const fn` `<[u8]>::len` and const-stable
156/// slice indexing (since Rust 1.79) — every operation `const`-eval-
157/// callable on stable, no iterator methods, no `Pattern` trait.
158#[must_use]
159pub const fn wit_shape_matches(wit: &str, prefixes: &[&str]) -> bool {
160    let bytes = wit.as_bytes();
161    let mut i = 0;
162    while i < prefixes.len() {
163        let prefix = prefixes[i].as_bytes();
164        if prefix.len() <= bytes.len() {
165            let mut j = 0;
166            let mut matches = true;
167            while j < prefix.len() {
168                if bytes[j] != prefix[j] {
169                    matches = false;
170                    break;
171                }
172                j += 1;
173            }
174            if matches {
175                return true;
176            }
177        }
178        i += 1;
179    }
180    false
181}
182
183/// True when `wit` — a raw `:contratos :wit` value — targets an
184/// HTTP-shaped WIT world (starts with any prefix in
185/// [`WIT_HTTP_SHAPE_PREFIXES`]). The single dispatch predicate every
186/// consumer routes L7-HTTP emission through, whether they carry a
187/// full [`WitContract`] on hand ([`WitContract::is_http`] delegates
188/// here) or only the raw `wit` string (the positive-sweep test's
189/// payload-dispatch helper, future renderers that classify off a
190/// bare `&str`). Lifting to a free function makes the shape-dispatch
191/// arm reachable without materializing a scratch [`WitContract`] at
192/// every classification point, and pins the six-prefix accept-set at
193/// one place so future additions (e.g. an `"https:"` peer of
194/// `"http:"`) reach every consumer by construction. Routes through
195/// the lifted [`wit_shape_matches`] combinator so the
196/// `PREFIXES.iter().any(|p| wit.starts_with(p))` scan lives at one
197/// canonical primitive, not one open-coded copy per peer arm.
198///
199/// Declared `pub const fn` — routes through the peer `pub const fn`
200/// [`wit_shape_matches`] combinator so every substrate-side
201/// `const`-context WIT-shape-arm-classifier consumer (the module-scope
202/// `const _: () = assert!(…)` canonical-accept-set + partition-witness
203/// pins immediately below, any future M4 admission-webhook
204/// `const fn` per-`:contratos :wit` HTTP-arm resolver over a raw &str)
205/// reaches through the same typed dispatch on the substrate primitive
206/// at const-eval time as at runtime.
207#[must_use]
208pub const fn wit_shape_is_http(wit: &str) -> bool {
209    wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES)
210}
211
212/// True when `wit` — a raw `:contratos :wit` value — targets a
213/// pub-sub-shaped WIT world (starts with any prefix in
214/// [`WIT_PUBSUB_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
215/// [`wit_shape_is_store`] on the shape-dispatch axis; see
216/// [`wit_shape_is_http`] for the lift rationale. Routes through the
217/// lifted [`wit_shape_matches`] combinator.
218///
219/// Declared `pub const fn` — sibling in `const`-eval posture to the
220/// peer [`wit_shape_is_http`] classifier; see that function's `const`
221/// posture-block for the full rationale.
222#[must_use]
223pub const fn wit_shape_is_pubsub(wit: &str) -> bool {
224    wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES)
225}
226
227/// True when `wit` — a raw `:contratos :wit` value — targets a
228/// key/value-store-shaped WIT world (starts with any prefix in
229/// [`WIT_STORE_SHAPE_PREFIXES`]). Peer of [`wit_shape_is_http`] /
230/// [`wit_shape_is_pubsub`] on the shape-dispatch axis; see
231/// [`wit_shape_is_http`] for the lift rationale. Routes through the
232/// lifted [`wit_shape_matches`] combinator.
233///
234/// Declared `pub const fn` — sibling in `const`-eval posture to the
235/// peer [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] classifiers;
236/// see [`wit_shape_is_http`]'s `const` posture-block for the full
237/// rationale.
238#[must_use]
239pub const fn wit_shape_is_store(wit: &str) -> bool {
240    wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES)
241}
242
243/// True when `wit` — a raw `:contratos :wit` value — targets *none* of
244/// the three known payload-shape WIT worlds; the payload-less
245/// capability arm of the 4-way WIT-shape partition on the raw
246/// `:contratos :wit` axis. Peer of [`wit_shape_is_http`] /
247/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] on the shape-
248/// dispatch axis — closes the free-function classifier family the
249/// three payload-arm predicates opened onto the exact-inverse
250/// disjunction of the trio, so any downstream consumer that must
251/// classify a raw `:wit` `&str` onto the payload-less capability arm
252/// (a future substrate-side capability-shape-only emitter — the M4
253/// per-Aplicacao WIT-registry capability-import materializer, the
254/// future `feira app graph --capability` filter, the future per-
255/// cluster capability-scope reconciler that skips L4/L7 emission for
256/// payload-less edges, the future `mesh.pleme.io/v1alpha1/Aplicacao`
257/// CR admission webhook's per-shape histogram) reaches for exactly
258/// one typed dispatch at the substrate primitive rather than an
259/// open-coded per-consumer `!wit_shape_is_http(wit) &&
260/// !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)` triplet
261/// negation — each of which would silently misclassify a future 4th
262/// payload-arm addition (a hypothetical `wasi:sockets/*` transport-
263/// layer shape, an `oci:*` capability-import carrier per the sibling
264/// [`wit_shape_matches`] docstring's trajectory bullet) as
265/// capability without a compile-time signal at the consumer site.
266///
267/// Fourth arm on the free-function WIT-shape-predicate family — closes
268/// the {[`wit_shape_is_http`], [`wit_shape_is_pubsub`],
269/// [`wit_shape_is_store`]} trio into a 4-way partition witness on the
270/// raw `:contratos :wit` `&str` axis, mirroring the paired sibling
271/// [`WitContract`]-surface [`WitContract::is_capability`] predicate and
272/// the post-projection [`WitTarget`]-side
273/// `gen_platform::IsVariant`-derived [`WitTarget::is_capability`]
274/// (7f6aa98 `IsVariant` derive lift on the peer arm-set). Every
275/// [`WitTarget`] variant now carries a matched peer predicate on both
276/// the raw `&str` axis (this function + [`wit_shape_is_http`] /
277/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`]) and the
278/// [`WitContract`] surface (the sibling 4-arm predicate family
279/// [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
280/// [`WitContract::is_store`] / [`WitContract::is_capability`]),
281/// pinned in load-bearing by the sibling
282/// [`tests::wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis`]
283/// partition-witness pin and the peer
284/// [`tests::wit_contract_shape_methods_delegate_to_free_functions`]
285/// delegation pin.
286///
287/// Prior to this lift the "not one of the three known payload shapes"
288/// classification only reached the raw `&str` axis by materializing a
289/// scratch [`WitContract`] and delegating through
290/// [`WitContract::is_capability`] — a five-field constructor at every
291/// classification point for a pure `&str → bool` question, and a
292/// dependency on the payload-carrier scalar layout the classifier
293/// does not read. Same "one canonical combinator, thin per-arm
294/// projections" discipline the peer [`wit_shape_is_http`] /
295/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] trio already
296/// established, extended to close the 4-arm partition on the raw
297/// `&str` axis.
298///
299/// Note: purely syntactic classification on the negated `:wit` prefix-
300/// set — unlike [`WitContract::target`], which additionally rejects
301/// value-shape-invalid `:wit` strings (uppercase, hyphen-for-colon
302/// typo, empty package) via [`crate::render::is_wit_world_ref`] and
303/// payload-shape mismatches. An empty or structurally malformed `wit`
304/// string returns `true` here (the prefix set matches nothing), and
305/// the surrounding validate-side gate cascade is where the
306/// [`AplicacaoError::EmptyWit`] / [`AplicacaoError::ContratoWitInvalid`]
307/// diagnostic surfaces — this function is the classifier, not the
308/// validator.
309///
310/// Declared `pub const fn` — closes the 4-arm classifier family's
311/// `const`-eval-surface pass on the payload-less capability arm,
312/// peer of the sibling `pub const fn` [`wit_shape_is_http`] /
313/// [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] classifiers, so
314/// the raw `&str → bool` WIT-shape partition on the capability arm
315/// reaches every substrate-side `const`-context consumer through one
316/// typed dispatch. See [`wit_shape_is_http`]'s `const` posture-block
317/// for the full rationale.
318#[must_use]
319pub const fn wit_shape_is_capability(wit: &str) -> bool {
320    !wit_shape_is_http(wit) && !wit_shape_is_pubsub(wit) && !wit_shape_is_store(wit)
321}
322
323// Compile-time pins on the 4-arm WIT-shape classifier family — the
324// module-scope const-eval assertions below trip at caixa-core build
325// time (not test time) if a future edit rewires any of the four
326// classifier's arm-set away from the accept-set MESH-COMPOSITION §II.3
327// pins. Anchor the `const`-eval-surface posture of the four peer
328// classifiers on canonical accept-set samples (one per WIT_*_SHAPE_PREFIXES
329// prefix) plus pairwise-exclusion samples asserting the trio partitions
330// the payload-carrying arm-set and the capability arm carries the
331// complementary payload-less remainder. Any future accidental downgrade
332// of one classifier to non-`const` fails these items at caixa-core build
333// time; any future prefix-set edit that overlaps two arms (e.g. a `kv:`
334// prefix accidentally re-emitted under `WIT_HTTP_SHAPE_PREFIXES`) trips
335// the corresponding partition-witness item. Peer of the sibling M3
336// [`PlacementStrategy::requires_shard_key`] partition pins at
337// aplicacao.rs:5121-5123 on the sibling closed-set typed-enum
338// discriminator axis.
339const _: () = assert!(wit_shape_is_http("wasi:http/proxy"));
340const _: () = assert!(wit_shape_is_http("http:incoming"));
341const _: () = assert!(wit_shape_is_pubsub("nats:events"));
342const _: () = assert!(wit_shape_is_pubsub("kafka:topic"));
343const _: () = assert!(wit_shape_is_store("wasi:keyvalue/store"));
344const _: () = assert!(wit_shape_is_store("kv:cache"));
345const _: () = assert!(wit_shape_is_capability("wasi:filesystem/preopens"));
346const _: () = assert!(wit_shape_is_capability(""));
347// Pairwise-exclusion pins — the three payload-carrying arms are
348// pairwise disjoint on the canonical accept-set samples, and the
349// capability arm is the exact-inverse disjunction of the trio
350// (the free-function classifier family's 4-way partition witness).
351const _: () = assert!(!wit_shape_is_http("nats:events"));
352const _: () = assert!(!wit_shape_is_http("kv:cache"));
353const _: () = assert!(!wit_shape_is_pubsub("wasi:http/proxy"));
354const _: () = assert!(!wit_shape_is_pubsub("wasi:keyvalue/store"));
355const _: () = assert!(!wit_shape_is_store("wasi:http/proxy"));
356const _: () = assert!(!wit_shape_is_store("nats:events"));
357const _: () = assert!(!wit_shape_is_capability("wasi:http/proxy"));
358const _: () = assert!(!wit_shape_is_capability("nats:events"));
359const _: () = assert!(!wit_shape_is_capability("wasi:keyvalue/store"));
360
361impl WitContract {
362    /// Substrate-canonical per-`:contratos` caller-Servico scalar
363    /// accessor every consumer that reads the edge's source endpoint
364    /// keys off — returns the author-declared `:contratos :de`
365    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
366    /// own [`String`] storage.
367    ///
368    /// The `:contratos :de` slot names the caller-side member Servico
369    /// on a typed inter-Servico edge (validated by
370    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
371    /// Aplicacao declares — a stray `:de` that doesn't name a member is
372    /// [`AplicacaoError::ContratoMemberMissing`], not a silent
373    /// caller-attachment miss at cluster-apply time). Peer of the
374    /// sibling [`WitContract::destination`] accessor on the same
375    /// per-`:contratos` entry — the pair `( source(), destination() )`
376    /// jointly names the typed edge every renderer that fans on the
377    /// caller-callee identity keys off (the
378    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)`
379    /// grouping, the [`AplicacaoSpec::detect_sync_cycles`] adjacency
380    /// map, the per-edge dedup key, the per-edge membership-lookup
381    /// diagnostic).
382    ///
383    /// Prior to this lift the `.de` byte-string was accessed inline at
384    /// four caixa-core sites (the two validate-side membership lookups
385    /// at `!names.contains(c.de.as_str())`, the per-edge dedup-key
386    /// tuple's caller-arm at
387    /// `(c.de.as_str(), c.para.as_str(), c.wit.as_str(), ...)`, the
388    /// `detect_sync_cycles` adjacency `adj.entry(c.de.as_str())`) and
389    /// one caixa-mesh site (the per-`(:de, :para)` CNP grouping's
390    /// caller-arm at `groups.entry((c.de.as_str(), c.para.as_str()))`)
391    /// — five open-coded `.de.as_str()` field-accesses that expressed
392    /// no compile-time link back to the typed slot. A future extension
393    /// of the `:contratos :de` axis to a richer author surface (a
394    /// multi-caller weighted-fan-in overlay per MESH-COMPOSITION §III.2
395    /// canary flow, a per-cluster caller-alias table the operator pins
396    /// through a future `:placement`-scoped slot, the M4
397    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
398    /// admission-webhook that promotes the scalar to a caller-set
399    /// projection) would have had to be threaded through every
400    /// open-coded copy in lockstep or one consumer would silently
401    /// disagree with the peers on which caller Servico a given edge
402    /// resolves to. Lifting the resolution rule to a typed method on
403    /// the substrate primitive means every downstream caller-facing
404    /// consumer reaches for one typed dispatch — the resolver's
405    /// accept-set migrates as a unit on any future axis addition.
406    ///
407    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
408    /// (6db982c) accessor on the analogous per-ingress-Servico scalar
409    /// axis — same "one typed dispatch on the substrate primitive,
410    /// thin projections at each consumer" discipline extended onto the
411    /// per-`:contratos` caller-Servico byte-string axis.
412    ///
413    /// Declared `pub const fn` — the body composes exclusively through
414    /// the `pub const fn` [`String::as_str`] projection (const-stable
415    /// since Rust 1.87, well within the workspace MSRV), so every
416    /// downstream `const`-context consumer of the per-`:contratos`
417    /// caller-Servico byte-string reaches through the same substrate-
418    /// primitive dispatch at const-eval time as at runtime. Peer of
419    /// the sibling `pub const fn` [`Self::destination`] /
420    /// [`Self::world_ref`] scalar accessors on the same
421    /// per-`:contratos` byte-string trio (the family closure the
422    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
423    /// locks load-bearing), and mirror on the method-surface of the
424    /// sibling free-function [`wit_shape_matches`] +
425    /// [`wit_shape_is_http`] / [`wit_shape_is_pubsub`] /
426    /// [`wit_shape_is_store`] / [`wit_shape_is_capability`] `const`-
427    /// eval-surface pass (d46420c) on the raw `&str → bool` WIT-shape
428    /// dispatch family.
429    #[must_use]
430    pub const fn source(&self) -> &str {
431        self.de.as_str()
432    }
433
434    /// Substrate-canonical per-`:contratos` callee-Servico scalar
435    /// accessor every consumer that reads the edge's destination
436    /// endpoint keys off — returns the author-declared
437    /// `:contratos :para` byte-string verbatim as a `&str`, borrowed
438    /// from the typed slot's own [`String`] storage.
439    ///
440    /// The `:contratos :para` slot names the callee-side member Servico
441    /// on a typed inter-Servico edge (validated by
442    /// [`AplicacaoSpec::validate`] to be a [`Membro::caixa`] the
443    /// Aplicacao declares — a stray `:para` that doesn't name a member
444    /// is [`AplicacaoError::ContratoMemberMissing`], not a silent
445    /// callee-attachment miss at cluster-apply time). Callee-side twin
446    /// of the sibling [`WitContract::source`] accessor — the pair
447    /// jointly names the typed edge every renderer that fans on the
448    /// caller-callee identity keys off, and this accessor is also the
449    /// per-`(:de, :para)` L4 port resolver's canonical destination arg:
450    /// under today's typed surface [`AplicacaoSpec::port_for_destination`]
451    /// composes with `destination()` at every emit site that projects a
452    /// per-edge destination Servico's L4 listener port.
453    ///
454    /// Prior to this lift the `.para` byte-string was accessed inline
455    /// at five sites — four caixa-core (the validate-side membership
456    /// lookup at `!names.contains(c.para.as_str())`, the per-edge
457    /// dedup-key tuple's callee-arm, the `detect_sync_cycles`
458    /// adjacency `.insert(c.para.as_str())`, the CNP grouping's
459    /// callee-arm) and one caixa-mesh (the per-`(:de, :para)` CNP L4
460    /// port resolver's destination arg `spec.port_for_destination(&c.para)`)
461    /// — with no compile-time link back to the typed slot. A future
462    /// extension of the `:contratos :para` axis to a richer author
463    /// surface (a multi-callee weighted-fan-out overlay for canary /
464    /// blue-green routing on typed edges, a per-cluster callee-alias
465    /// table the operator pins through a future `:placement`-scoped
466    /// slot, the M4 CR materializer's per-CR admission-webhook that
467    /// promotes the scalar to a callee-set projection) would have had
468    /// to be threaded through every open-coded copy in lockstep or one
469    /// consumer would silently disagree on which callee Servico a given
470    /// edge resolves to (a per-CNP `endpointSelector` that names a
471    /// different destination than its L4 port resolver reads for, a
472    /// dedup-key that treats `(cart, catalog-v2)` and `(cart, catalog)`
473    /// as distinct while the adjacency map collapses them, or vice
474    /// versa). Lifting to a typed method on the substrate primitive
475    /// means every downstream callee-facing consumer reaches for one
476    /// typed dispatch.
477    ///
478    /// Peer of the sibling per-`:entrada` [`Entrada::destination`]
479    /// (6db982c) accessor — both name the "destination-Servico
480    /// byte-string" concept on their respective mesh-slot atoms (per-
481    /// ingress apex vs. per-typed-edge callee), and both extend the
482    /// substrate-primitive-owns-the-resolver discipline onto the
483    /// per-slot destination-Servico scalar axis. Composes with
484    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) at every
485    /// emit-side per-edge L4 port reader — the composition
486    /// `spec.port_for_destination(c.destination())` pins the CNP per-
487    /// `(:de, :para)` L4 port axis to the same typed dispatch the peer
488    /// `HTTPRoute` `backendRefs[0].port` axis reaches through with
489    /// `spec.port_for_destination(entrada.destination())`.
490    ///
491    /// Declared `pub const fn` — sibling in `const`-eval posture to the
492    /// peer `pub const fn` [`Self::source`] / [`Self::world_ref`]
493    /// per-`:contratos` byte-string scalar accessors, all three
494    /// projecting through the `pub const fn` [`String::as_str`]
495    /// (const-stable since Rust 1.87). See [`Self::source`] for the
496    /// family-closure rationale.
497    #[must_use]
498    pub const fn destination(&self) -> &str {
499        self.para.as_str()
500    }
501
502    /// Substrate-canonical per-`:contratos` WIT-world-reference scalar
503    /// accessor every consumer that reads the edge's WIT world
504    /// discriminator keys off — returns the author-declared
505    /// `:contratos :wit` byte-string verbatim as a `&str`, borrowed from
506    /// the typed slot's own [`String`] storage.
507    ///
508    /// The `:contratos :wit` slot names the WIT world the typed edge
509    /// carries (e.g. `"wasi:http/proxy"`, `"nats:pub-sub"`,
510    /// `"wasi:keyvalue/store"`); validated by [`WitContract::target`] to
511    /// be a well-shaped WIT world reference via
512    /// [`crate::render::is_wit_world_ref`] and by
513    /// [`AplicacaoSpec::validate`] to be non-empty via the narrower
514    /// [`AplicacaoError::EmptyWit`] variant. Peer of the sibling
515    /// [`WitContract::source`] / [`WitContract::destination`] accessors
516    /// on the same per-`:contratos` entry — the triple
517    /// `( source(), destination(), world_ref() )` jointly names the
518    /// typed edge every renderer that fans on the caller-callee-shape
519    /// identity keys off (the per-edge dedup key at
520    /// [`AplicacaoSpec::validate`]'s duplicate-`:contratos` gate, the
521    /// per-`(:de, :para)` CNP grouping's shape-arm classifier at
522    /// [`caixa_mesh::cilium_network_policies`], the
523    /// [`WitContract::is_http`] / [`is_pubsub`][WitContract::is_pubsub]
524    /// / [`is_store`][WitContract::is_store] shape-dispatch predicates,
525    /// the [`feira app graph`][fag] per-edge printer's WIT-shape label).
526    ///
527    /// Prior to this lift the `.wit` byte-string was accessed inline at
528    /// five sites — three caixa-core (the `WitContract::is_*` shape-
529    /// dispatch predicates' `&self.wit` arg, the validate-side empty
530    /// check at `if c.wit.is_empty()`, the per-edge dedup-key tuple's
531    /// shape arm at `c.wit.as_str()`) and one caixa-feira (the app-graph
532    /// printer's `{}` format-slot at `c.wit`) — five open-coded
533    /// `.wit` field-accesses that expressed no compile-time link back to
534    /// the typed slot. A future extension of the `:contratos :wit` axis
535    /// to a richer author surface (an M4 promotion from `String` to a
536    /// typed WIT-world enum once the WIT registry stabilizes in tatara-
537    /// lisp per this struct's own `:wit` field docstring, a per-cluster
538    /// WIT-alias table the operator pins through a future
539    /// `:placement`-scoped slot, a canonicalization pass that lowercases
540    /// `wasi:*` prefixes) would have had to be threaded through every
541    /// open-coded copy in lockstep or one consumer would silently
542    /// disagree with the peers on which WIT shape a given edge resolves
543    /// to (a per-CNP L7 emission that read `wasi:http/proxy` while the
544    /// dedup key read the pre-canonicalized `WASI:HTTP/proxy`, an
545    /// empty-check that missed a whitespace-only string a peer accessor
546    /// stripped, or vice versa). Lifting to a typed method on the
547    /// substrate primitive means every downstream WIT-shape-facing
548    /// consumer reaches for one typed dispatch — the resolver's
549    /// accept-set migrates as a unit on any future axis addition.
550    ///
551    /// Sibling of the peer per-`:contratos` [`WitContract::source`] /
552    /// [`WitContract::destination`] (7f0fd43), per-`:entrada`
553    /// [`Entrada::hostname`] / [`Entrada::destination`] (11f3dfe /
554    /// 6db982c), per-`:membros` [`Membro::nome`] /
555    /// [`Membro::versao_requirement`] (4a32abf / a40b0e3) accessors on
556    /// the mesh-slot-atom scalar-value axes — same "one typed dispatch
557    /// on the substrate primitive, thin projections at each consumer"
558    /// discipline extended onto the last unlifted per-`:contratos`
559    /// scalar (the WIT-world-reference arm).
560    ///
561    /// [fag]: caixa-feira/src/cmd/app.rs
562    ///
563    /// Declared `pub const fn` — sibling in `const`-eval posture to the
564    /// peer `pub const fn` [`Self::source`] / [`Self::destination`]
565    /// per-`:contratos` byte-string scalar accessors on the trio, and
566    /// the load-bearing enabler for the paired `pub const fn`
567    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
568    /// [`Self::is_capability`] WIT-shape-predicate family (each
569    /// composes as `wit_shape_is_<arm>(self.world_ref())` and inherits
570    /// the `const`-eval posture by construction once this accessor
571    /// carries it). See [`Self::source`] for the family-closure
572    /// rationale and the paired
573    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
574    /// for the load-bearing witness.
575    #[must_use]
576    pub const fn world_ref(&self) -> &str {
577        self.wit.as_str()
578    }
579
580    /// Substrate-canonical per-`:contratos` `:endpoint` HTTP-shaped
581    /// payload-target scalar accessor every consumer that reads the
582    /// edge's L7 HTTP request path payload keys off — returns the
583    /// author-declared `:contratos :endpoint` byte-string verbatim as
584    /// an `Option<&str>`, borrowed from the typed slot's own
585    /// `Option<String>` storage; `None` when the slot is absent (the
586    /// canonical shape of a non-HTTP-`:wit`-world edge — pub-sub
587    /// `nats:*`/`kafka:*` carries `:subject` instead, key/value
588    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
589    /// [`WitTarget::Capability`] edge carries none of the three).
590    ///
591    /// The `:contratos :endpoint` slot carries the HTTP request path
592    /// payload (Cilium L7 `path:` + Gateway API v1 `PathPrefix` grammar
593    /// — same shape required of `:entrada :paths`, gated by the shared
594    /// [`crate::render::is_gateway_api_http_path`] predicate) that
595    /// [`WitContract::target`] projects onto the [`WitTarget::Http`]
596    /// arm's `endpoint: &'a str` payload when the edge's `:wit` world
597    /// matches the [`WIT_HTTP_SHAPE_PREFIXES`] accept-set. Every
598    /// downstream consumer that reads the payload keys off this scalar
599    /// (the [`WitContract::target`] Http-arm payload extraction that
600    /// materializes [`WitTarget::Http { endpoint }`] under the paired
601    /// [`WitTarget::HTTP_FIELD_NAME`] label, the
602    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
603    /// key's endpoint arm that pins the payload as part of the six-tuple
604    /// dedup key alongside the sibling `:subject`/`:slot` arms, the
605    /// future M4 per-edge WIT registry resolver's HTTP-arm materializer,
606    /// the future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
607    /// per-edge L7 admission webhook, the future caixa-mesh L7 CNP
608    /// emission path that lands the payload verbatim as a Cilium L7
609    /// `path:` rule).
610    ///
611    /// Prior to this lift the `.endpoint` field was accessed inline at
612    /// two production sites in `caixa-core/src/aplicacao.rs` — the
613    /// [`WitContract::target`] payload-shape dispatch's `let endpoint =
614    /// self.endpoint.as_deref();` binding at the top of the method, and
615    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
616    /// tuple's `c.endpoint.as_deref()` HTTP-arm slot — two open-coded
617    /// field-accesses that expressed no compile-time link back to the
618    /// typed slot. A future extension of the `:contratos :endpoint`
619    /// axis to a richer author surface (an M4 promotion from
620    /// `Option<String>` to a typed HTTP path-template enum once the
621    /// WIT registry stabilizes path-parameter shapes in tatara-lisp per
622    /// this struct's own `:wit` field docstring, a per-cluster endpoint-
623    /// alias table the operator pins through a future `:placement`-
624    /// scoped slot, a canonicalization pass that percent-encodes non-
625    /// ASCII path segments, a per-CR fully-qualified rewrite the M4 CR
626    /// materializer applies per-tenant) would have had to be threaded
627    /// through both open-coded copies in lockstep or the two consumers
628    /// would silently disagree on which HTTP path a given edge resolves
629    /// to — the [`WitContract::target`] payload-extraction reading
630    /// `"/lookup"` while the [`AplicacaoSpec::validate`] dedup key read
631    /// the operator-resolved `"/tenant-a/lookup"` would silently split
632    /// the [`WitTarget::Http`]-arm rendered payload from the actual
633    /// dedup-key uniqueness axis, a two-consumer split at the validator
634    /// far from the source `caixa.lisp` with no field naming the
635    /// payload-drift root cause. Lifting the resolution rule to a typed
636    /// method on the substrate primitive means every downstream
637    /// HTTP-payload-facing consumer of the Aplicacao's per-`:contratos`
638    /// L7-payload surface reaches for exactly one typed dispatch — the
639    /// resolver's accept-set migrates as a unit on any future axis
640    /// addition.
641    ///
642    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
643    /// (7cd2a28) / [`Placement::affinity`] (74ec2d3) `Option<&str>`
644    /// accessors on the M3 mesh-slot family — same "one typed dispatch
645    /// on the substrate primitive, thin projections at each consumer"
646    /// discipline extended onto the per-`:contratos` HTTP-shaped
647    /// payload-carrier `Option<String>` optional-scalar axis. First
648    /// `Option<&str>`-return accessor on the per-`:contratos` mesh-slot
649    /// atom — opens the "optional per-slot payload-carrier scalar"
650    /// projection pattern the sibling per-`:contratos` `:subject` /
651    /// `:slot` future lifts fold on, matching the closed
652    /// per-`:contratos` scalar-value accessor family
653    /// ([`WitContract::source`] / [`WitContract::destination`] /
654    /// [`WitContract::world_ref`]) already lifted onto the mandatory-
655    /// scalar `String` axes. Named `endpoint()` to match the storage
656    /// field's name and the paired [`WitTarget::HTTP_FIELD_NAME`]
657    /// author-facing label const; the accessor's identity name maps
658    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
659    /// docstring already carries.
660    #[must_use]
661    pub const fn endpoint(&self) -> Option<&str> {
662        match &self.endpoint {
663            Some(s) => Some(s.as_str()),
664            None => None,
665        }
666    }
667
668    /// Substrate-canonical per-`:contratos` `:subject` pub-sub-shaped
669    /// payload-target scalar accessor every consumer that reads the
670    /// edge's NATS / Kafka publish subject payload keys off — returns
671    /// the author-declared `:contratos :subject` byte-string verbatim
672    /// as an `Option<&str>`, borrowed from the typed slot's own
673    /// `Option<String>` storage; `None` when the slot is absent (the
674    /// canonical shape of a non-pub-sub-`:wit`-world edge — HTTP
675    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, key/value
676    /// `wasi:keyvalue/*`/`kv:*` carries `:slot` instead, and a plain
677    /// [`WitTarget::Capability`] edge carries none of the three).
678    ///
679    /// The `:contratos :subject` slot carries the NATS / Kafka publish
680    /// subject payload (the [`WIT_PUBSUB_SHAPE_PREFIXES`] dispatch arm's
681    /// per-edge target selector — `orders.paid`, `events.>`, whatever
682    /// subject namespace the author names on the pub-sub edge) that
683    /// [`WitContract::target`] projects onto the [`WitTarget::PubSub`]
684    /// arm's `subject: &'a str` payload when the edge's `:wit` world
685    /// matches the [`WIT_PUBSUB_SHAPE_PREFIXES`] accept-set. Every
686    /// downstream consumer that reads the payload keys off this scalar
687    /// (the [`WitContract::target`] PubSub-arm payload extraction that
688    /// materializes [`WitTarget::PubSub { subject }`] under the paired
689    /// [`WitTarget::PUBSUB_FIELD_NAME`] label, the
690    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
691    /// key's subject arm that pins the payload as part of the six-tuple
692    /// dedup key alongside the sibling `:endpoint`/`:slot` arms, the
693    /// future M4 per-edge WIT registry resolver's pub-sub-arm
694    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
695    /// materializer's per-edge NATS admission webhook, the future
696    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
697    /// as a NATS subject the operator pins per-CR).
698    ///
699    /// Prior to this lift the `.subject` field was accessed inline at
700    /// two production sites in `caixa-core/src/aplicacao.rs` — the
701    /// [`WitContract::target`] payload-shape dispatch's `let subject =
702    /// self.subject.as_deref();` binding at the top of the method, and
703    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
704    /// tuple's `c.subject.as_deref()` pub-sub-arm slot — two open-coded
705    /// field-accesses that expressed no compile-time link back to the
706    /// typed slot. A future extension of the `:contratos :subject` axis
707    /// to a richer author surface (an M4 promotion from `Option<String>`
708    /// to a typed NATS-subject-template enum once the WIT registry
709    /// stabilizes wildcard / hierarchy shapes in tatara-lisp per this
710    /// struct's own `:wit` field docstring, a per-cluster subject-alias
711    /// table the operator pins through a future `:placement`-scoped
712    /// slot, a canonicalization pass that lowercases / dedupes wildcard
713    /// segments, a per-CR fully-qualified rewrite the M4 CR materializer
714    /// applies per-tenant) would have had to be threaded through both
715    /// open-coded copies in lockstep or the two consumers would silently
716    /// disagree on which NATS subject a given edge resolves to — the
717    /// [`WitContract::target`] payload-extraction reading `"orders.paid"`
718    /// while the [`AplicacaoSpec::validate`] dedup key read the operator-
719    /// resolved `"tenant-a.orders.paid"` would silently split the
720    /// [`WitTarget::PubSub`]-arm rendered payload from the actual dedup-
721    /// key uniqueness axis, a two-consumer split at the validator far
722    /// from the source `caixa.lisp` with no field naming the payload-
723    /// drift root cause. Lifting the resolution rule to a typed method
724    /// on the substrate primitive means every downstream pub-sub-payload-
725    /// facing consumer of the Aplicacao's per-`:contratos` L4-payload
726    /// surface reaches for exactly one typed dispatch — the resolver's
727    /// accept-set migrates as a unit on any future axis addition.
728    ///
729    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
730    /// (7020470) `Option<&str>` accessor on the M3 mesh-slot payload-
731    /// carrier axis — second `Option<&str>`-return accessor on the
732    /// per-`:contratos` mesh-slot atom, extending the "optional per-slot
733    /// payload-carrier scalar" projection pattern the [`WitContract::endpoint`]
734    /// HTTP-arm lift opened onto the pub-sub arm; leaves the [`WitContract::slot`]
735    /// key/value-store arm as the last unlifted per-`:contratos`
736    /// `Option<String>` axis. Named `subject()` to match the storage
737    /// field's name and the paired [`WitTarget::PUBSUB_FIELD_NAME`]
738    /// author-facing label const; the accessor's identity name maps
739    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
740    /// docstring already carries.
741    #[must_use]
742    pub const fn subject(&self) -> Option<&str> {
743        match &self.subject {
744            Some(s) => Some(s.as_str()),
745            None => None,
746        }
747    }
748
749    /// Substrate-canonical per-`:contratos` `:slot` key/value-store-
750    /// shaped payload-target scalar accessor every consumer that reads
751    /// the edge's `wasi:keyvalue/*` / `kv:*` key-template payload keys
752    /// off — returns the author-declared `:contratos :slot` byte-string
753    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
754    /// own `Option<String>` storage; `None` when the slot is absent
755    /// (the canonical shape of a non-store-`:wit`-world edge — HTTP
756    /// `wasi:http/*`/`http:*` carries `:endpoint` instead, pub-sub
757    /// `nats:*`/`kafka:*` carries `:subject` instead, and a plain
758    /// [`WitTarget::Capability`] edge carries none of the three).
759    ///
760    /// The `:contratos :slot` slot carries the key/value store
761    /// key-template payload (the [`WIT_STORE_SHAPE_PREFIXES`] dispatch
762    /// arm's per-edge target selector — `carts/{cart_id}`,
763    /// `sessions/{tenant}/{sid}`, whatever key-template the author
764    /// names on the store edge) that [`WitContract::target`] projects
765    /// onto the [`WitTarget::Store`] arm's `slot: &'a str` payload when
766    /// the edge's `:wit` world matches the [`WIT_STORE_SHAPE_PREFIXES`]
767    /// accept-set. Every downstream consumer that reads the payload
768    /// keys off this scalar (the [`WitContract::target`] Store-arm
769    /// payload extraction that materializes [`WitTarget::Store { slot }`]
770    /// under the paired [`WitTarget::STORE_FIELD_NAME`] label, the
771    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` [`ContratoIdentity`]
772    /// key's store arm that pins the payload as part of the six-tuple
773    /// dedup key alongside the sibling `:endpoint`/`:subject` arms,
774    /// the future M4 per-edge WIT registry resolver's store-arm
775    /// materializer, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
776    /// materializer's per-edge key/value admission webhook, the future
777    /// caixa-mesh L4 CNP emission path that lands the payload verbatim
778    /// as a key-template the operator pins per-CR).
779    ///
780    /// Prior to this lift the `.slot` field was accessed inline at two
781    /// production sites in `caixa-core/src/aplicacao.rs` — the
782    /// [`WitContract::target`] payload-shape dispatch's `let slot =
783    /// self.slot.as_deref();` binding at the top of the method, and
784    /// the [`AplicacaoSpec::validate`] duplicate-`:contratos` dedup-key
785    /// tuple's `c.slot.as_deref()` store-arm slot — two open-coded
786    /// field-accesses that expressed no compile-time link back to the
787    /// typed slot. A future extension of the `:contratos :slot` axis
788    /// to a richer author surface (an M4 promotion from `Option<String>`
789    /// to a typed key-template enum once the WIT registry stabilizes
790    /// key-template parameter shapes in tatara-lisp per this struct's
791    /// own `:wit` field docstring, a per-cluster slot-alias table the
792    /// operator pins through a future `:placement`-scoped slot, a
793    /// canonicalization pass that lowercases the bucket prefix, a
794    /// per-CR fully-qualified rewrite the M4 CR materializer applies
795    /// per-tenant) would have had to be threaded through both
796    /// open-coded copies in lockstep or the two consumers would
797    /// silently disagree on which key-template a given edge resolves
798    /// to — the [`WitContract::target`] payload-extraction reading
799    /// `"carts/{cart_id}"` while the [`AplicacaoSpec::validate`] dedup
800    /// key read the operator-resolved `"tenant-a/carts/{cart_id}"`
801    /// would silently split the [`WitTarget::Store`]-arm rendered
802    /// payload from the actual dedup-key uniqueness axis, a
803    /// two-consumer split at the validator far from the source
804    /// `caixa.lisp` with no field naming the payload-drift root cause.
805    /// Lifting the resolution rule to a typed method on the substrate
806    /// primitive means every downstream store-payload-facing consumer
807    /// of the Aplicacao's per-`:contratos` payload surface reaches for
808    /// exactly one typed dispatch — the resolver's accept-set migrates
809    /// as a unit on any future axis addition.
810    ///
811    /// Peer of the sibling per-`:contratos` [`WitContract::endpoint`]
812    /// (7020470) / [`WitContract::subject`] (90de675) `Option<&str>`
813    /// accessors on the M3 mesh-slot payload-carrier axis — third and
814    /// final `Option<&str>`-return accessor on the per-`:contratos`
815    /// mesh-slot atom, closes the last unlifted per-`:contratos`
816    /// `Option<String>` axis and completes the "optional per-slot
817    /// payload-carrier scalar" projection pattern the peer HTTP /
818    /// pub-sub arms established across the three payload-shape
819    /// dispatch arms. Named `slot()` to match the storage field's
820    /// name and the paired [`WitTarget::STORE_FIELD_NAME`]
821    /// author-facing label const; the accessor's identity name maps
822    /// onto the canonical MESH-COMPOSITION §II.3 vocabulary the slot's
823    /// docstring already carries.
824    #[must_use]
825    pub const fn slot(&self) -> Option<&str> {
826        match &self.slot {
827            Some(s) => Some(s.as_str()),
828            None => None,
829        }
830    }
831
832    /// Substrate-canonical per-`:contratos` `(caller, callee)` owned-form
833    /// caller-callee-pair accessor every consumer that constructs an
834    /// [`AplicacaoError`] variant carrying the per-edge `(de, para)`
835    /// caller-callee pair keys off — returns the author-declared
836    /// `:contratos :de` / `:contratos :para` byte-strings verbatim as an
837    /// owned `(String, String)` tuple, projected through the lifted
838    /// [`WitContract::source`] / [`WitContract::destination`] scalar
839    /// accessors so any future rebrand on the caller-arm / callee-arm
840    /// projection axis (an M4 per-cluster caller-alias table the
841    /// operator pins through a future `:placement`-scoped slot, a
842    /// namespace-qualified rewrite the M4 CR materializer applies per-CR,
843    /// a per-`:membros` alias overlay from the future `:membros
844    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
845    /// acknowledges) reaches every diagnostic-construction site by
846    /// construction.
847    ///
848    /// The `(de, para)` pair is the "typed-edge caller-callee identity in
849    /// owned form" primitive every per-`:contratos` diagnostic variant on
850    /// [`AplicacaoError`] carries alongside its payload-shape arm — the
851    /// nine variants [`AplicacaoError::EmptyWit`],
852    /// [`AplicacaoError::ContratoEndpointEmpty`],
853    /// [`AplicacaoError::ContratoEndpointNotAbsolute`],
854    /// [`AplicacaoError::ContratoEndpointInvalid`],
855    /// [`AplicacaoError::ContratoSubjectEmpty`],
856    /// [`AplicacaoError::ContratoSubjectInvalid`],
857    /// [`AplicacaoError::ContratoSlotEmpty`],
858    /// [`AplicacaoError::ContratoSlotInvalid`], and
859    /// [`AplicacaoError::ContratoDuplicate`] each carry a `de: String,
860    /// para: String` field pair the constructor site reads verbatim off
861    /// the [`WitContract`] the diagnostic points at, so a diagnostic
862    /// whose `de:` and `para:` labels silently drift off the source
863    /// caller/callee — a per-cluster caller-alias rewrite that landed on
864    /// one variant's inline `de: c.de.clone()` field access but not on
865    /// its sibling variant's, an accidental swap of the `de:` and `para:`
866    /// arms in a copy-paste of the constructor block — would emit a
867    /// build-time error whose "which caixa is at fault" question the
868    /// operator answers wrongly, far from the source `caixa.lisp`.
869    ///
870    /// Prior to this lift the `(self.de.clone(), self.para.clone())`
871    /// pair was inlined at seven [`WitContract::target`] error-
872    /// construction sites (the [`AplicacaoError::ContratoEndpointEmpty`]
873    /// / [`AplicacaoError::ContratoEndpointNotAbsolute`] /
874    /// [`AplicacaoError::ContratoEndpointInvalid`] HTTP-arm variants,
875    /// the [`AplicacaoError::ContratoSubjectEmpty`] /
876    /// [`AplicacaoError::ContratoSubjectInvalid`] pub-sub-arm variants,
877    /// the [`AplicacaoError::ContratoSlotEmpty`] /
878    /// [`AplicacaoError::ContratoSlotInvalid`] store-arm variants) and
879    /// two [`AplicacaoSpec::validate`] error-construction sites (the
880    /// [`AplicacaoError::EmptyWit`] empty-`:wit` gate, the
881    /// [`AplicacaoError::ContratoDuplicate`] duplicate-`:contratos`
882    /// insert-first-seen closure) — nine open-coded `.de.clone() +
883    /// .para.clone()` pairs that expressed no compile-time contract that
884    /// the caller-arm and callee-arm arms of the same diagnostic
885    /// construction reach for the same [`WitContract`] instance or that
886    /// the `de:` and `para:` label pair binds to the fields the author
887    /// declared. Any future rebrand on the axis — an M4 per-cluster
888    /// caller/callee-alias rewrite the operator pins through a future
889    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
890    /// per-CR fully-qualified namespace prefix the M4
891    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
892    /// per-tenant, a canonicalization pass that lowercases the caller +
893    /// callee identifiers post-parse — would have had to be threaded
894    /// through every open-coded copy in lockstep or one variant's
895    /// diagnostic would silently name a different caller/callee pair
896    /// than its peer, silently degrading the "which caixa is at fault"
897    /// self-locating signal every operator-facing typed diagnostic
898    /// exists to carry. Lifting the pair to a typed method on the
899    /// substrate primitive means every downstream diagnostic-construction
900    /// site reaches for exactly one typed dispatch — the resolver's
901    /// projection migrates as a unit on any future axis addition.
902    ///
903    /// Peer of the sibling per-`:contratos` scalar accessor family
904    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43)
905    /// / [`WitContract::world_ref`] (6226bf4) on the mesh-slot-atom
906    /// scalar-value axes — first composite-projection accessor on the
907    /// per-`:contratos` mesh-slot atom, folds the two open-coded owned-
908    /// form `.clone()` field-accesses that pair the sibling
909    /// caller/callee accessors' `&str`-return borrowed-form outputs onto
910    /// one typed dispatch. Named `edge_pair()` to reflect the identity
911    /// name of the projected tuple (the typed-edge caller-callee pair,
912    /// distinct from the sibling triple-projection
913    /// [`WitContract::edge_triple`] accessor that folds the local `edge`
914    /// closure in [`WitContract::target`] + the paired
915    /// [`AplicacaoError::ContratoDuplicate`] diagnostic constructor
916    /// site's `(de, para, wit)` triple onto one typed dispatch).
917    #[must_use]
918    pub fn edge_pair(&self) -> (String, String) {
919        (self.source().to_string(), self.destination().to_string())
920    }
921
922    /// Owned form of the `(:contratos :de, :contratos :para, :contratos
923    /// :wit)` triple every per-edge diagnostic constructor that names
924    /// all three axes threads verbatim into its `de:` / `para:` /
925    /// `wit:` fields — the [`WitTarget::target`] dispatch's wrong-target
926    /// / missing-target / invalid-wit / capability-with-payload arms
927    /// (eight sites all shape `let (de, para, wit) = edge();
928    /// AplicacaoError::Contrato* { de, para, wit, .. }` before this
929    /// accessor landed) and the sibling
930    /// [`AplicacaoError::ContratoDuplicate`] duplicate-gate diagnostic
931    /// constructor (which paired `edge_pair()` for the `(de, para)`
932    /// prefix with a raw `c.wit.clone()` for the `wit:` tail — a mixed
933    /// typed-dispatch + raw-field-access shape the sibling accessor
934    /// family already flagged as a drift risk). Nine total call sites
935    /// collapse onto this helper.
936    ///
937    /// Lifted with the same one-source-of-truth discipline
938    /// [`WitContract::edge_pair`] carries on the paired
939    /// caller-callee-only axis: the returned tuple's `.0` / `.1` / `.2`
940    /// arms compose through the lifted [`WitContract::source`] /
941    /// [`WitContract::destination`] / [`WitContract::world_ref`]
942    /// scalar accessors byte-for-byte (pinned by the paired
943    /// [`tests::wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`]
944    /// composition-pin), so any future rebrand on the per-`:contratos`
945    /// caller / callee / world-ref axis (an M4 per-cluster
946    /// caller/callee-alias rewrite the operator pins through a future
947    /// `:placement :caller-alias` / `:placement :callee-alias` slot, a
948    /// per-CR fully-qualified namespace prefix the M4
949    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
950    /// per-tenant, an M4-typed-caller-enum `Display` re-canonicalization
951    /// on `source()` / `destination()`, a per-CR canonicalization pass
952    /// that lowercases the WIT world ref post-parse) migrates as a
953    /// single caixa-core edit rather than a coordinated rewrite of
954    /// nine open-coded triple-constructors.
955    ///
956    /// Peer of the sibling per-`:contratos` composite-projection
957    /// [`WitContract::edge_pair`] accessor on the mesh-slot-atom
958    /// composite-value axes — closes the last unlifted owned-form
959    /// composite-tuple axis on the per-`:contratos` diagnostic-
960    /// construction surface. Named `edge_triple()` to reflect the
961    /// identity name of the projected tuple (the typed-edge
962    /// caller-callee-wit triple, sibling to the caller-callee-only
963    /// pair `edge_pair()` returns).
964    #[must_use]
965    pub fn edge_triple(&self) -> (String, String, String) {
966        (
967            self.source().to_string(),
968            self.destination().to_string(),
969            self.world_ref().to_string(),
970        )
971    }
972
973    /// Borrowed [`ContratoIdentity`] six-tuple every consumer that
974    /// dedups typed edges keys off — routes through the lifted
975    /// [`WitContract::source`] / [`WitContract::destination`] /
976    /// [`WitContract::world_ref`] / [`WitContract::endpoint`] /
977    /// [`WitContract::subject`] / [`WitContract::slot`] scalar
978    /// accessors so the tuple's six arms and the [`ContratoIdentity`]
979    /// type alias's six axes migrate as a unit on any future axis
980    /// addition (adding a seventh field to [`WitContract`] is one
981    /// [`ContratoIdentity`] alias edit + one accessor addition + one
982    /// arm here, not a coordinated rewrite of every open-coded
983    /// six-tuple builder that dedups on the identity axis).
984    ///
985    /// Sibling of [`WitContract::edge_pair`] /
986    /// [`WitContract::edge_triple`] on the composite-projection axis:
987    /// the pair projects the caller-callee axes, the triple extends it
988    /// with the world-ref, this method extends it with the three
989    /// payload-carrier axes. Every projection returns the same six
990    /// scalar accessors' outputs; the three methods differ only in
991    /// which arms they surface.
992    ///
993    /// Declared `pub const fn` — every callee is itself `pub const fn`
994    /// ([`Self::source`] / [`Self::destination`] / [`Self::world_ref`]
995    /// project through `pub const fn` [`String::as_str`], const-stable
996    /// since Rust 1.87; [`Self::endpoint`] / [`Self::subject`] /
997    /// [`Self::slot`] project through the same `String::as_str` under a
998    /// `match &self.<field> { Some(s) => Some(s.as_str()), None => None }`
999    /// arm — the sibling `Option<String> → Option<&str>` shape 0650f64
1000    /// closed the const-eval surface on) and tuple construction from
1001    /// borrowed-reference / `Option`-of-borrowed-reference arms is
1002    /// itself trivially const. The `ContratoIdentity<'_>` alias
1003    /// resolves to a `(&str, &str, &str, Option<&str>, Option<&str>,
1004    /// Option<&str>)` tuple whose every arm is `Copy` — no destructor,
1005    /// no heap allocation, no non-const call folded through the tuple's
1006    /// construction. Sibling in `const`-eval posture to the peer
1007    /// `pub const fn` [`WitContract::is_http`] / [`Self::is_pubsub`] /
1008    /// [`Self::is_store`] / [`Self::is_capability`] WIT-shape-predicate
1009    /// composite-projection family the sibling
1010    /// [`wit_contract_pre_projection_accessor_family_is_const_fn`] pin
1011    /// already anchors — this extends the same `const`-eval-surface
1012    /// posture onto the peer six-arm composite-projection axis where
1013    /// the projection surfaces the full identity tuple rather than a
1014    /// per-`(:de, :para, :wit)`-triple boolean shape probe. Pinned load-
1015    /// bearing by
1016    /// [`wit_contract_identity_projection_accessor_is_const_fn`] below
1017    /// (a future accidental downgrade fires E0015 at the wrapper at
1018    /// caixa-core build time).
1019    #[must_use]
1020    pub const fn identity(&self) -> ContratoIdentity<'_> {
1021        (
1022            self.source(),
1023            self.destination(),
1024            self.world_ref(),
1025            self.endpoint(),
1026            self.subject(),
1027            self.slot(),
1028        )
1029    }
1030
1031    /// True when this contract targets an HTTP-shaped WIT world.
1032    ///
1033    /// Declared `pub const fn` — routes through the paired `pub const
1034    /// fn` [`Self::world_ref`] scalar accessor and the substrate's
1035    /// `pub const fn` free-function classifier [`wit_shape_is_http`]
1036    /// (d46420c). Sibling in `const`-eval posture to the peer
1037    /// `pub const fn` [`Self::is_pubsub`] / [`Self::is_store`] /
1038    /// [`Self::is_capability`] WIT-shape-predicate family; the closed
1039    /// 4-arm partition on the raw `:contratos :wit` axis now carries
1040    /// the same `const`-eval-surface posture as the free-function
1041    /// classifier family it composes through. Pinned load-bearing by
1042    /// the [`wit_contract_pre_projection_accessor_family_is_const_fn`]
1043    /// test (a future accidental downgrade to non-`const` fires E0015
1044    /// at the corresponding `<arm>_via_const_fn` wrapper at caixa-core
1045    /// build time).
1046    #[must_use]
1047    pub const fn is_http(&self) -> bool {
1048        wit_shape_is_http(self.world_ref())
1049    }
1050
1051    /// True when this contract targets a pub-sub-shaped WIT world.
1052    ///
1053    /// Declared `pub const fn` — sibling in `const`-eval posture to
1054    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_store`] /
1055    /// [`Self::is_capability`] WIT-shape-predicate family. See
1056    /// [`Self::is_http`] for the family-closure rationale.
1057    #[must_use]
1058    pub const fn is_pubsub(&self) -> bool {
1059        wit_shape_is_pubsub(self.world_ref())
1060    }
1061
1062    /// True when this contract targets a key/value-shaped WIT world.
1063    ///
1064    /// Declared `pub const fn` — sibling in `const`-eval posture to
1065    /// the peer `pub const fn` [`Self::is_http`] / [`Self::is_pubsub`] /
1066    /// [`Self::is_capability`] WIT-shape-predicate family. See
1067    /// [`Self::is_http`] for the family-closure rationale.
1068    #[must_use]
1069    pub const fn is_store(&self) -> bool {
1070        wit_shape_is_store(self.world_ref())
1071    }
1072
1073    /// True when this contract targets *none* of the three known payload-
1074    /// shape WIT worlds — the fourth (payload-less) arm of the WIT-shape
1075    /// partition [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1076    /// open on the [`WitContract`] surface. Returns the exact-inverse
1077    /// disjunction of the peer trio — `true` when none of the three
1078    /// prefix-set predicates matches the raw `:contratos :wit` value; the
1079    /// author-declared WIT world is a pure typed capability edge with no
1080    /// payload selector (the shape [`WitContract::target`] projects onto
1081    /// the payload-less [`WitTarget::Capability`] arm, MESH-COMPOSITION
1082    /// §II.3 — the fourth typed [`WitTarget`] arm the substrate admits).
1083    ///
1084    /// The `:contratos :wit` shape-space is closed at four arms
1085    /// ([`WIT_HTTP_SHAPE_PREFIXES`] / [`WIT_PUBSUB_SHAPE_PREFIXES`] /
1086    /// [`WIT_STORE_SHAPE_PREFIXES`] on the payload-carrying arms;
1087    /// everything else on the payload-less capability arm), and every
1088    /// downstream consumer that must filter contratos by shape-class
1089    /// keys off the four sibling predicates (the [`WitContract::target`]
1090    /// dispatch's implicit `else` after the three payload-shape arm
1091    /// checks at aplicacao.rs:959–1129 that admits [`WitTarget::Capability`],
1092    /// every future substrate-side capability-shape-only emitter — the
1093    /// M4 per-Aplicacao WIT-registry capability-import materializer, the
1094    /// future `feira app graph --capability` per-Aplicacao capability-
1095    /// column filter, the future per-cluster capability-scope reconciler
1096    /// that skips L4/L7 emission for payload-less edges since Cilium
1097    /// can't introspect WASI capability calls, the future
1098    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR admission webhook's per-
1099    /// shape shape-count histogram). Every such consumer reaches for one
1100    /// typed dispatch on the substrate primitive so the "which arm
1101    /// carries the capability-only shape?" answer lives at one caixa-core
1102    /// edit rather than open-coded across per-consumer
1103    /// `!c.is_http() && !c.is_pubsub() && !c.is_store()` triplet
1104    /// negations, each of which would silently drop a future fourth
1105    /// payload-arm addition without a compile-time signal at the
1106    /// consumer site.
1107    ///
1108    /// Prior to this lift the "not one of the three known payload
1109    /// shapes" classification sat inline at [`WitContract::target`]'s
1110    /// implicit `else`-branch (aplicacao.rs:1131 — the payload-less
1111    /// [`WitTarget::Capability`] admission arm after the three `if
1112    /// self.is_http() { … } if self.is_pubsub() { … } if self.is_store()
1113    /// { … }` guards) with no named accessor for downstream consumers
1114    /// to reach through. A future substrate-side capability-only
1115    /// filter or a future capability-scope reconciler would have had to
1116    /// re-inline the same triplet negation at every emit site with no
1117    /// compile-time link back to the sibling trio, and a future arm
1118    /// addition (a hypothetical fourth payload-shape prefix set — a
1119    /// `wasi:sockets/*` transport-layer shape or an `oci:*` capability-
1120    /// import carrier per the sibling [`wit_shape_matches`] docstring's
1121    /// trajectory bullet) would land the new predicate on the payload-
1122    /// carrying trio and silently misclassify the new shape as
1123    /// capability at every triplet-negation consumer site, propagating
1124    /// the drift far from the caixa-core prefix-set commit.
1125    ///
1126    /// Fourth arm on the [`WitContract`] WIT-shape-predicate family —
1127    /// closes the {[`Self::is_http`], [`Self::is_pubsub`], [`Self::is_store`]}
1128    /// trio into a 4-way partition witness on the raw `:contratos :wit`
1129    /// axis, mirroring the paired post-projection [`WitTarget`]
1130    /// `gen_platform::IsVariant`-derived 4-way predicate set
1131    /// ([`WitTarget::is_http`] / [`WitTarget::is_pubsub`] /
1132    /// [`WitTarget::is_store`] / [`WitTarget::is_capability`]) on the
1133    /// typed-view surface (7f6aa98 `IsVariant` derive lift on the peer
1134    /// arm-set). The two typed axes — pre-projection on the raw
1135    /// `:contratos :wit` string, post-projection on the validated typed
1136    /// view — now carry a matched 4-arm predicate discipline: every
1137    /// arm on the closed [`WitTarget`] set has a peer pre-projection
1138    /// predicate on the [`WitContract`] surface, and any future
1139    /// [`WitTarget`] variant addition (an M4 `Rest` / `Grpc` split of
1140    /// [`WitTarget::Http`] once the WIT registry stabilizes gRPC-shaped
1141    /// worlds per [`WitTarget`]'s own docstring at aplicacao.rs:1341-1343,
1142    /// a `Queue`-shaped peer of [`WitTarget::Store`]) reaches this
1143    /// pre-projection axis through a matching peer prefix-set + peer
1144    /// predicate lift by construction — the compile-time exhaustiveness
1145    /// on [`WitTarget::payload_pair`]'s single dispatch already enforces
1146    /// the post-projection accessor family stays in sync, and the sibling
1147    /// [`tests::wit_contract_is_capability_partitions_the_wit_shape_space`]
1148    /// partition-witness pin locks the pre-projection classification in
1149    /// load-bearing so a peer prefix-set addition that widened one arm's
1150    /// accept-set without shrinking the [`Self::is_capability`] accept-set
1151    /// surfaces as a test failure at caixa-core build time rather than a
1152    /// silent per-consumer split at renderer emit time.
1153    ///
1154    /// Composes byte-for-byte through the lifted peer trio
1155    /// [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] so
1156    /// any future rebrand of any prefix-set const flows through this
1157    /// method by construction without a coordinated per-consumer rewrite
1158    /// (pinned by the sibling
1159    /// [`tests::wit_contract_is_capability_composes_through_shape_predicate_negation`]
1160    /// composition-witness).
1161    ///
1162    /// Note: purely syntactic classification on the `:wit` prefix-set —
1163    /// unlike [`Self::target`], which additionally rejects value-shape-
1164    /// invalid `:wit` strings (uppercase, hyphen-for-colon typo, empty
1165    /// package) via [`crate::render::is_wit_world_ref`] and payload-
1166    /// shape mismatches. A [`WitContract`] whose `:wit` is empty or
1167    /// structurally malformed returns `true` from `is_capability()` (the
1168    /// prefix set matches nothing), and the surrounding
1169    /// [`AplicacaoSpec::validate`] / [`WitContract::target`] gate cascade
1170    /// is where the [`AplicacaoError::EmptyWit`] /
1171    /// [`AplicacaoError::ContratoWitInvalid`] diagnostic surfaces — this
1172    /// predicate is the classifier, not the validator.
1173    ///
1174    /// Declared `pub const fn` — closes the WIT-shape-predicate
1175    /// family's `const`-eval-surface pass at the fourth (payload-less)
1176    /// arm; peer of the sibling `pub const fn` [`Self::is_http`] /
1177    /// [`Self::is_pubsub`] / [`Self::is_store`] payload-arm predicates.
1178    /// See [`Self::is_http`] for the family-closure rationale.
1179    #[must_use]
1180    pub const fn is_capability(&self) -> bool {
1181        wit_shape_is_capability(self.world_ref())
1182    }
1183
1184    /// True when this contract's caller equals its callee — a
1185    /// structurally degenerate typed edge that no `:contratos` entry can
1186    /// legitimately carry (MESH-COMPOSITION §III.1 — "Servico A calls
1187    /// Servico B" is an *inter*-Servico contract between two distinct
1188    /// graph nodes). A Servico contracting with itself resolves to an
1189    /// in-process call the wasm-engine never routes through the mesh at
1190    /// all, so no rendered `CiliumNetworkPolicy` / `HTTPRoute` /
1191    /// per-edge policy can express the intended shape — the pub-sub
1192    /// path silently rendered a self-allow rule that is a no-op (intra-
1193    /// pod traffic bypasses the mesh entirely), and the synchronous
1194    /// paths surfaced as a misleading `ContratoCycle` whose path was
1195    /// `["cart", "cart"]` — framing a self-edge as a multi-node
1196    /// deadlock. Every downstream consumer that must reject the shape
1197    /// (the [`AplicacaoSpec::validate`] per-`:contratos` self-loop
1198    /// gate at caixa-core/src/aplicacao.rs:5559, every future
1199    /// per-`:contratos`-edge policy resolver on the M4 CR materializer
1200    /// axis, every future adjacency-graph builder that must skip self-
1201    /// edges rather than fold them into an incidental cycle) now keys
1202    /// off exactly one typed dispatch on the substrate primitive, so
1203    /// any future rebrand on the axis (an M4-typed-caller enum whose
1204    /// identity comparison rule the accessor could route through, an
1205    /// operator-side per-cluster caller/callee-alias table the
1206    /// materializer resolves per-CR before the equality probe, a
1207    /// promotion of the pointwise `==` to a set-membership check once
1208    /// SimpleOneForOne-shaped dynamic replicas come into typed scope
1209    /// so a per-replica self-edge is rejected under the same predicate)
1210    /// migrates as a single caixa-core edit rather than a coordinated
1211    /// rewrite of every downstream self-edge consumer. Composes
1212    /// byte-for-byte through the lifted [`Self::source`] /
1213    /// [`Self::destination`] scalar accessors — the accessor pair every
1214    /// per-`:contratos` scalar-value axis already routes through — so
1215    /// any future rebrand of the underlying `:de` / `:para` storage
1216    /// (a lift from `String` to a typed `ServicoName(String)` newtype,
1217    /// a per-Aplicacao interning arena the M4 CR materializer authors,
1218    /// a `smol_str::SmolStr` inline-buffer swap) flows through the
1219    /// same one body without a coordinated per-consumer rewrite.
1220    ///
1221    /// Sibling in shape to the peer per-`:contratos` shape-predicate
1222    /// family [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`]
1223    /// on the `:wit` world-ref axis — extended onto the per-edge
1224    /// endpoint-equality axis: `is_http` / `is_pubsub` / `is_store`
1225    /// partition the WIT-shape-space; `is_self_loop` partitions the
1226    /// caller-callee identity-space. Named `is_self_loop()` to reflect
1227    /// the graph-theoretic identity of the shape (a loop from a graph
1228    /// node to itself, distinct from the sibling multi-node
1229    /// `ContratoCycle` shape [`Self::detect_sync_cycles`] rejects) and
1230    /// to match the [`AplicacaoError::ContratoSelfLoop`] diagnostic
1231    /// variant already carrying the term.
1232    ///
1233    /// Declared `pub const fn` — closes the last unlifted per-`:contratos`
1234    /// shape-predicate on the substrate's `const`-eval surface. The peer
1235    /// per-`:contratos` shape-predicate family [`Self::is_http`] /
1236    /// [`Self::is_pubsub`] / [`Self::is_store`] / [`Self::is_capability`]
1237    /// (d46420c / 84c2325 / 279823b) already carries the `pub const fn`
1238    /// posture on the WIT-world-ref classifier axis; this lift extends it
1239    /// onto the peer caller-callee identity-space predicate. The body
1240    /// projects the `:de` / `:para` `String` storage through the sibling
1241    /// `pub const fn` [`Self::source`] / [`Self::destination`] scalar
1242    /// accessors, then compares the resulting `&str` byte-slices under a
1243    /// manual `while`-loop through `str::as_bytes` (`pub const fn`,
1244    /// const-stable since Rust 1.39), primitive-`usize` `!=` on
1245    /// [`<[u8]>::len`], and const-stable slice indexing (since Rust 1.79)
1246    /// — every operation `const`-eval-callable on stable Rust, no
1247    /// iterator methods, no `PartialEq for str` trait dispatch (which
1248    /// remains non-`const` on stable). Mirrors the peer `pub const fn`
1249    /// [`wit_shape_matches`] combinator's manual byte-level `starts_with`
1250    /// loop verbatim on the paired-slice-equality shape. Every downstream
1251    /// substrate-side `const`-context consumer of the per-`:contratos`
1252    /// self-edge partition (a future `const _: () = assert!(…)` module-
1253    /// scope invariant pin over a per-fixture typed [`WitContract`] once
1254    /// the type's carriers admit `const`-context construction, a future
1255    /// M4 admission-webhook `const fn` self-edge resolver, any `const fn`
1256    /// composer that fans on the identity-space partition at compile
1257    /// time) reaches through the same typed dispatch on the substrate
1258    /// primitive at const-eval time as at runtime. Pinned by
1259    /// [`tests::wit_contract_is_self_loop_predicate_is_const_fn`] which
1260    /// witnesses the `const`-eval posture via a `const fn` wrapper so any
1261    /// future accidental downgrade to non-`const` trips at caixa-core
1262    /// build time with E0015 (`cannot call non-const method`), strictly
1263    /// stronger than a runtime `assert!`.
1264    #[must_use]
1265    pub const fn is_self_loop(&self) -> bool {
1266        // Compose through the paired `pub const fn` [`Self::source`] /
1267        // [`Self::destination`] scalar accessors so any future rebrand of
1268        // the underlying `:de` / `:para` storage (a lift from `String` to
1269        // a typed `ServicoName(String)` newtype, a per-Aplicacao interning
1270        // arena the M4 CR materializer authors, a `smol_str::SmolStr`
1271        // inline-buffer swap) flows through the same one body without a
1272        // coordinated per-consumer rewrite. Peer of the sibling
1273        // [`Self::is_http`] / [`Self::is_pubsub`] / [`Self::is_store`] /
1274        // [`Self::is_capability`] shape-predicate family — each of which
1275        // composes through the paired [`Self::world_ref`] scalar accessor
1276        // onto the peer `pub const fn` [`wit_shape_is_http`] /
1277        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
1278        // [`wit_shape_is_capability`] free-function classifier — the same
1279        // "typed dispatch composes with typed dispatch, not raw field
1280        // access" discipline extended onto the caller-callee identity-
1281        // space partition. Pinned by
1282        // [`tests::wit_contract_is_self_loop_routes_through_source_destination_accessors`]
1283        // above.
1284        let a = self.source().as_bytes();
1285        let b = self.destination().as_bytes();
1286        if a.len() != b.len() {
1287            return false;
1288        }
1289        // Manual byte-level equality loop — mirrors the peer
1290        // [`wit_shape_matches`] combinator's manual `starts_with` loop
1291        // verbatim on the paired-slice-equality shape. `PartialEq for
1292        // str` remains non-`const` on stable Rust 1.94 (the `Pattern`
1293        // trait dispatch it routes through is not `const`), so a naive
1294        // `self.source() == self.destination()` body would trip on
1295        // `const`-eval-callability; the byte-slice loop dispatches
1296        // through primitive-`u8` `!=`, primitive-`usize` comparison, and
1297        // const-stable slice indexing (since Rust 1.79) — every
1298        // operation `const`-eval-callable on stable.
1299        let mut i = 0;
1300        while i < a.len() {
1301            if a[i] != b[i] {
1302                return false;
1303            }
1304            i += 1;
1305        }
1306        true
1307    }
1308
1309    /// Typed view of the contract's payload target. Enforces that the
1310    /// `:wit` shape and the carried `:endpoint`/`:subject`/`:slot`
1311    /// fields agree, and that each carried value is itself
1312    /// value-shape valid:
1313    ///
1314    ///   - HTTP world (`wasi:http/*`, `http:*`) ⇒ exactly `:endpoint`,
1315    ///     non-empty, leading-`/` (Cilium L7 `path` + Gateway API
1316    ///     `PathPrefix` invariant — same shape required of `:entrada
1317    ///     :paths`)
1318    ///   - `PubSub` world (`nats:*`, `kafka:*`) ⇒ exactly `:subject`,
1319    ///     non-empty (NATS / Kafka publish without a subject is a
1320    ///     no-op subscribe, never the author's intent)
1321    ///   - Store world (`wasi:keyvalue/*`, `kv:*`) ⇒ exactly `:slot`,
1322    ///     non-empty (an empty slot template addresses the bucket
1323    ///     root, defeating the per-key isolation the slot exists for)
1324    ///   - Anything else ⇒ none of the three; the contract is a pure
1325    ///     typed capability edge with no payload selector.
1326    ///
1327    /// Translates the Apollo Federation discipline ("conflicts are
1328    /// errors at compile time, not warnings at runtime";
1329    /// MESH-COMPOSITION §II.3) onto pleme-io's typed Aplicacao surface:
1330    /// a contract whose WIT shape disagrees with its target field, or
1331    /// whose target field carries a value-shape-invalid string, is a
1332    /// build error — not a silent renderer drop. The returned
1333    /// [`WitTarget`] view's `&str` payload is therefore guaranteed
1334    /// non-empty (and absolute, for `Http`); every downstream consumer
1335    /// (caixa-mesh's L7 emission, the M3 Gateway/HTTPRoute renderer,
1336    /// the M4 per-edge policy resolver) can rely on that without
1337    /// re-checking.
1338    pub fn target(&self) -> Result<WitTarget<'_>, AplicacaoError> {
1339        // Route the HTTP-shaped payload-target extraction through the
1340        // lifted [`WitContract::endpoint`] accessor rather than the raw
1341        // `self.endpoint.as_deref()` field access — the two production
1342        // consumers of the per-`:contratos :endpoint` HTTP-shaped
1343        // payload-carrier scalar (this method's Http-arm payload
1344        // extraction, the [`AplicacaoSpec::validate`] duplicate-
1345        // `:contratos` [`ContratoIdentity`] dedup-key HTTP arm) now key
1346        // off exactly one typed dispatch on the substrate primitive, so
1347        // any future rebrand on the axis (an M4 per-cluster endpoint-
1348        // alias rewrite, a per-CR fully-qualified path prefix the M4
1349        // materializer applies per-tenant, an M4 promotion from
1350        // `Option<String>` to a typed HTTP path-template enum) migrates
1351        // as a single caixa-core edit rather than a coordinated rewrite
1352        // of the two call sites — peer of the sibling M3 per-`:placement`
1353        // [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
1354        // (74ec2d3) `Option<&str>` typed-dispatch discipline extended
1355        // onto the per-`:contratos` HTTP-shaped payload-carrier axis.
1356        let endpoint = self.endpoint();
1357        let subject = self.subject();
1358        // Route the store-arm payload-carrier scalar through the
1359        // lifted [`WitContract::slot`] accessor rather than the raw
1360        // `self.slot.as_deref()` field access — the two production
1361        // consumers of the per-`:contratos :slot` key/value-store-
1362        // shaped payload-carrier scalar (this method's Store-arm
1363        // payload extraction, the [`AplicacaoSpec::validate`]
1364        // duplicate-`:contratos` [`ContratoIdentity`] dedup-key store
1365        // arm) now key off exactly one typed dispatch on the substrate
1366        // primitive. Closes the last unlifted per-`:contratos`
1367        // `Option<String>` axis, completing the payload-carrier
1368        // accessor family peer of the sibling per-`:contratos`
1369        // [`WitContract::endpoint`] (7020470) / [`WitContract::subject`]
1370        // (90de675) lifts across the HTTP / pub-sub arms.
1371        let slot = self.slot();
1372        // Route the local `(de, para, wit)` triple-projection closure
1373        // through the lifted [`WitContract::edge_triple`] typed accessor
1374        // rather than re-inlining `(self.de.clone(), self.para.clone(),
1375        // self.wit.clone())` — the eight [`AplicacaoError::Contrato*`]
1376        // triple-carrying diagnostic constructors below (wrong-target /
1377        // missing-target on all three payload arms + capability-with-
1378        // payload + invalid-wit) now key off exactly one typed dispatch
1379        // on the substrate-primitive composite projection, sibling to
1380        // the peer [`WitContract::edge_pair`]-routed
1381        // [`AplicacaoError::Empty*`]/`ContratoEndpointEmpty`/
1382        // `ContratoSubjectEmpty`/`ContratoSlotEmpty` pair-carrying
1383        // diagnostic constructors on the same per-`:contratos`
1384        // diagnostic-construction surface.
1385        let edge = || self.edge_triple();
1386
1387        // The `:wit` value drives every downstream dispatch — the
1388        // is_http/is_pubsub/is_store prefix matchers below, the
1389        // caixa-mesh L7-vs-L4 emission, the cycle-detector's pub-sub
1390        // exclusion. Until this gate landed `target()` accepted any
1391        // non-empty string and silently demoted unrecognized shapes to
1392        // a capability-only edge (`:wit "WASI:HTTP/proxy"` — uppercase
1393        // typo, `:wit "wasi-http/proxy"` — hyphen-instead-of-colon typo,
1394        // `:wit "wasi:http proxy"` — whitespace, `:wit "wasi:"` — empty
1395        // package, the paste-from-binary footgun a multi-line blob
1396        // accidentally landing in the slot, the un-percent-encoded
1397        // non-ASCII byte) — the canonical "I thought I had L7 HTTP
1398        // routing, got L4-only" footgun. Empty is still pre-checked at
1399        // the [`AplicacaoSpec::validate`] call site via the narrower
1400        // [`AplicacaoError::EmptyWit`] variant (and fires first at the
1401        // validate layer); the value-shape gate here picks up the
1402        // structurally-invalid non-empty cases the empty check misses,
1403        // and remains correct under direct `target()` calls outside
1404        // validate (the predicate's defensive empty arm returns a
1405        // parser-shaped reason rather than silently falling through to
1406        // the Capability arm). Same trajectory as c4213a4 (WitContract
1407        // endpoint/subject/slot value-shape gates lifted into
1408        // `target()`) on the peer payload axes.
1409        //
1410        // Routed through the lifted [`WitContract::world_ref`] accessor
1411        // rather than the raw `&self.wit` field access — the two
1412        // production consumers of the per-`:contratos :wit` world-ref
1413        // byte-string on the value-shape axis (this method's invalid-
1414        // wit gate, the [`AplicacaoSpec::validate`] duplicate-
1415        // `:contratos` [`ContratoIdentity`] dedup-key world-ref arm via
1416        // [`WitContract::identity`]) now key off exactly one typed
1417        // dispatch on the substrate primitive, so any future rebrand on
1418        // the axis (an M4 promotion from `String` to a typed WIT
1419        // world-ref enum once the WIT registry stabilizes in
1420        // tatara-lisp, a per-CR canonicalization pass that lowercases
1421        // the WIT world ref post-parse, a promoted `smol_str::SmolStr`
1422        // inline-buffer swap on the storage arm) migrates as a single
1423        // caixa-core edit rather than a coordinated rewrite of the two
1424        // call sites — sibling of the peer [`WitContract::endpoint`] /
1425        // [`WitContract::subject`] / [`WitContract::slot`] accessor-
1426        // routed payload-carrier extractions above on the same
1427        // [`WitContract::target`] body, completing the per-`:contratos`
1428        // scalar-accessor-routing pass at the last unlifted raw-field-
1429        // access site inside `impl WitContract`. Same "typed dispatch
1430        // composes with typed dispatch, not with raw field access"
1431        // discipline the sibling [`WitContract::edge_pair`] /
1432        // [`WitContract::edge_triple`] / [`WitContract::identity`]
1433        // composite-projection accessors and the
1434        // [`WitContract::is_self_loop`] identity-space predicate
1435        // already route through. Pinned by
1436        // [`tests::wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor`].
1437        if let Err(reason) = crate::render::is_wit_world_ref(self.world_ref()) {
1438            let (de, para, wit) = edge();
1439            return Err(AplicacaoError::ContratoWitInvalid {
1440                de,
1441                para,
1442                wit,
1443                reason,
1444            });
1445        }
1446
1447        if self.is_http() {
1448            if subject.is_some() || slot.is_some() {
1449                let (de, para, wit) = edge();
1450                return Err(AplicacaoError::ContratoWrongTarget {
1451                    de,
1452                    para,
1453                    wit,
1454                    expected: WitTarget::HTTP_FIELD_NAME,
1455                });
1456            }
1457            let ep = endpoint.ok_or_else(|| {
1458                let (de, para, wit) = edge();
1459                AplicacaoError::ContratoMissingTarget {
1460                    de,
1461                    para,
1462                    wit,
1463                    expected: WitTarget::HTTP_FIELD_NAME,
1464                }
1465            })?;
1466            if ep.is_empty() {
1467                let (de, para) = self.edge_pair();
1468                return Err(AplicacaoError::ContratoEndpointEmpty { de, para });
1469            }
1470            if !ep.starts_with('/') {
1471                let (de, para) = self.edge_pair();
1472                return Err(AplicacaoError::ContratoEndpointNotAbsolute {
1473                    de,
1474                    para,
1475                    endpoint: ep.to_string(),
1476                });
1477            }
1478            // The `:endpoint` lands verbatim as a Cilium L7 `path:` rule
1479            // (caixa-mesh/src/lib.rs:311) and shares the K8s Gateway
1480            // API v1 HTTPPathMatch.value admission grammar with the
1481            // sibling `:entrada :paths` axis. Until this gate landed
1482            // `target()` only refused the empty string + the missing-
1483            // leading-`/` form; a structurally invalid endpoint
1484            // (`"/charge?token=X"` — query in path slot, `"/foo bar"` —
1485            // un-percent-encoded whitespace, `"/api/café"` — non-ASCII,
1486            // `"/api//bar"` — consecutive slash, `"/api/../etc"` —
1487            // path-traversal segment, the >1024-byte slug) silently
1488            // passed validate and the failure surfaced at apply time
1489            // as a Cilium policy rejection / silent traffic drop, far
1490            // from the source caixa.lisp. Same Gateway API HTTPPathMatch
1491            // grammar `:entrada :paths` already gates (55410e4), now
1492            // shared with `:contratos :endpoint` through the lifted
1493            // `crate::render::is_gateway_api_http_path` predicate.
1494            if let Err(reason) = crate::render::is_gateway_api_http_path(ep) {
1495                let (de, para) = self.edge_pair();
1496                return Err(AplicacaoError::ContratoEndpointInvalid {
1497                    de,
1498                    para,
1499                    endpoint: ep.to_string(),
1500                    reason,
1501                });
1502            }
1503            return Ok(WitTarget::Http { endpoint: ep });
1504        }
1505        if self.is_pubsub() {
1506            if endpoint.is_some() || slot.is_some() {
1507                let (de, para, wit) = edge();
1508                return Err(AplicacaoError::ContratoWrongTarget {
1509                    de,
1510                    para,
1511                    wit,
1512                    expected: WitTarget::PUBSUB_FIELD_NAME,
1513                });
1514            }
1515            let s = subject.ok_or_else(|| {
1516                let (de, para, wit) = edge();
1517                AplicacaoError::ContratoMissingTarget {
1518                    de,
1519                    para,
1520                    wit,
1521                    expected: WitTarget::PUBSUB_FIELD_NAME,
1522                }
1523            })?;
1524            if s.is_empty() {
1525                let (de, para) = self.edge_pair();
1526                return Err(AplicacaoError::ContratoSubjectEmpty { de, para });
1527            }
1528            // The `:subject` lands at runtime as the NATS subject the
1529            // producer publishes to and the consumer subscribes from.
1530            // Until this gate landed `target()` only refused the
1531            // empty string; a structurally invalid subject
1532            // (`"foo..bar"` — empty token between separators,
1533            // `"foo.>.bar"` — non-trailing `>` wildcard the NATS
1534            // server's subject parser rejects, `"foo bar"` —
1535            // un-percent-encoded whitespace, `"foo.café"` —
1536            // un-percent-encoded non-ASCII, `".foo"` / `"foo."` —
1537            // empty leading/trailing tokens, the >256-byte
1538            // paste-from-binary slug) silently passed validate and
1539            // the failure surfaced at runtime as a NATS server-side
1540            // `-ERR 'Invalid Subject'` on publish / subscribe, or as
1541            // a silent message drop, far from the source caixa.lisp.
1542            // Same Gateway API HTTPPathMatch / WIT-IDL grammar
1543            // trajectory `:contratos :endpoint` (4f0390b) and
1544            // `:contratos :wit` (6226bf4) already gate, now shared
1545            // with `:contratos :subject` through the lifted
1546            // `crate::render::is_nats_subject` predicate.
1547            if let Err(reason) = crate::render::is_nats_subject(s) {
1548                let (de, para) = self.edge_pair();
1549                return Err(AplicacaoError::ContratoSubjectInvalid {
1550                    de,
1551                    para,
1552                    subject: s.to_string(),
1553                    reason,
1554                });
1555            }
1556            return Ok(WitTarget::PubSub { subject: s });
1557        }
1558        if self.is_store() {
1559            if endpoint.is_some() || subject.is_some() {
1560                let (de, para, wit) = edge();
1561                return Err(AplicacaoError::ContratoWrongTarget {
1562                    de,
1563                    para,
1564                    wit,
1565                    expected: WitTarget::STORE_FIELD_NAME,
1566                });
1567            }
1568            let sl = slot.ok_or_else(|| {
1569                let (de, para, wit) = edge();
1570                AplicacaoError::ContratoMissingTarget {
1571                    de,
1572                    para,
1573                    wit,
1574                    expected: WitTarget::STORE_FIELD_NAME,
1575                }
1576            })?;
1577            if sl.is_empty() {
1578                let (de, para) = self.edge_pair();
1579                return Err(AplicacaoError::ContratoSlotEmpty { de, para });
1580            }
1581            // Value-shape gate on the third (and last) typed payload
1582            // axis the `WitContract::target` dispatch carries — the
1583            // peer of [`crate::render::is_gateway_api_http_path`] for
1584            // `:endpoint` (4f0390b) and [`crate::render::is_nats_subject`]
1585            // for `:subject` (63e18a0). Until this gate landed
1586            // `target()` only refused the empty string; a structurally
1587            // invalid slot (`"check out/$order"` — un-percent-encoded
1588            // whitespace whose runtime behavior varies unpredictably
1589            // across kv backends, `"checkout/\x01order"` — control
1590            // character that Redis admits but corrupts on next read
1591            // and DynamoDB rejects outright, `"chéckout/$order"` —
1592            // un-percent-encoded non-ASCII byte each backend re-encodes
1593            // differently, `"checkout\n/$order"` — embedded newline,
1594            // the 513-byte paste-from-binary slug) silently passed
1595            // validate and surfaced at runtime as a per-backend kv
1596            // write rejection (DynamoDB / etcd) or as a silent
1597            // next-read corruption (Redis-via-RESP3), far from the
1598            // source caixa.lisp with no field naming which `:contratos`
1599            // edge carried the typo. The lifted predicate makes the
1600            // kv-backend intersection-floor a substrate-level
1601            // invariant at validate time, not a runtime "this passed
1602            // validate but the kv backend rejected on first write"
1603            // surprise — closes the typed payload-axis value-shape
1604            // trajectory across all three legs of the four
1605            // [`WitTarget`] arms (HTTP / PubSub / Store / Capability)
1606            // that caixa-mesh + the future kv emitters land in.
1607            if let Err(reason) = crate::render::is_wasi_keyvalue_slot(sl) {
1608                let (de, para) = self.edge_pair();
1609                return Err(AplicacaoError::ContratoSlotInvalid {
1610                    de,
1611                    para,
1612                    slot: sl.to_string(),
1613                    reason,
1614                });
1615            }
1616            return Ok(WitTarget::Store { slot: sl });
1617        }
1618
1619        // Unrecognized WIT world — must not carry any payload target.
1620        if endpoint.is_some() || subject.is_some() || slot.is_some() {
1621            let (de, para, wit) = edge();
1622            return Err(AplicacaoError::ContratoWrongTarget {
1623                de,
1624                para,
1625                wit,
1626                expected: WitTarget::CAPABILITY_EXPECTED,
1627            });
1628        }
1629        Ok(WitTarget::Capability)
1630    }
1631
1632    /// Substrate-canonical post-validation projection of the typed
1633    /// [`WitTarget`] view — the panic-on-failure shorthand every renderer
1634    /// downstream of an [`AplicacaoSpec`] that has already crossed the
1635    /// [`AplicacaoSpec::validate`] gate (typically via a caixa-mesh
1636    /// [`typed_view`]-shaped entry point that composes `validate` into
1637    /// the projection) reaches through when it needs the typed
1638    /// [`WitTarget`] and knows the containing [`AplicacaoSpec::validate`]
1639    /// has already admitted the `(:wit, :endpoint/:subject/:slot)` shape
1640    /// coherence for every `:contratos` entry. The peer accessor to the
1641    /// [`Self::target`] `Result`-returning validator on the same
1642    /// per-`:contratos` typed-projection axis — [`Self::target`] is the
1643    /// pre-validation validator that computes the projection *and* raises
1644    /// the [`AplicacaoError::Contrato*`] diagnostic cascade on any
1645    /// (`:wit`, payload) mismatch; this method is the post-validation
1646    /// projection every downstream consumer reaches through once the
1647    /// pre-validation gate has succeeded.
1648    ///
1649    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1650    ///
1651    /// Prior to this lift the "call `.target()` then `.expect(…)` with
1652    /// the same message" pattern sat inline at two production sites with
1653    /// no compile-time link between them: the
1654    /// [`caixa_mesh::cilium_network_policies`] per-`(:de, :para)` CNP
1655    /// L7 introspection branch at `caixa-mesh/src/lib.rs:2825`
1656    /// (`c.target().expect("validated by typed_view").http_endpoint()`)
1657    /// and the [`caixa_feira::cmd::app`] `feira app graph` per-`:contratos`
1658    /// payload-column printer at `caixa-feira/src/cmd/app.rs:110`
1659    /// (`c.target().expect("validated by typed_view").graph_label()`),
1660    /// each open-coding the same `.target().expect("validated by
1661    /// typed_view")` pair with the message spelled twice. A future
1662    /// vocabulary shift on the panic-message axis (a tightening from
1663    /// `"validated by typed_view"` to `"validated by AplicacaoSpec::
1664    /// validate"` as the substrate's validator entry-point vocabulary
1665    /// sharpens, a per-consumer disambiguation, an M4 promotion of the
1666    /// panic to a `debug_assert` under a `--release` build profile) would
1667    /// have had to be threaded through both open-coded call sites in
1668    /// lockstep or one consumer would silently disagree with the peer on
1669    /// which invariant the panic message names. Same "same shape written
1670    /// verbatim ≥ 2 times becomes a typed helper" duplication-budget
1671    /// discipline the sibling [`Self::edge_pair`] /
1672    /// [`Self::edge_triple`] / [`Self::identity`] composite-projection
1673    /// lifts already establish on the paired composite-projection axis;
1674    /// this lift extends it onto the post-validation typed-view axis.
1675    ///
1676    /// Every future downstream consumer of the projected typed view
1677    /// (the future M4 per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao`
1678    /// CR materializer's per-edge admission webhook, the future
1679    /// Envoy-side per-typed-arm `local_rate_limit.descriptor_entries`
1680    /// bucket-key resolver, the future per-`:contratos`-edge mTLS overlay
1681    /// resolver, the future `feira app graph --l7` / `--pubsub` /
1682    /// `--kv` per-shape column emitters) reaches through this one typed
1683    /// dispatch on the substrate primitive rather than an open-coded
1684    /// per-consumer `.target().expect(…)` pair with the message
1685    /// re-inlined. The invariant the accessor's panic path pins — "this
1686    /// call is only reachable after [`AplicacaoSpec::validate`] has
1687    /// succeeded on the containing spec" — is the substrate's answer to
1688    /// give exactly once, at the primitive, not once per consumer.
1689    ///
1690    /// # Panics
1691    ///
1692    /// Panics with [`Self::PROJECTED_INVARIANT_MSG`] if [`Self::target`]
1693    /// would return an `Err` — i.e. if this contract's
1694    /// (`:wit`, `:endpoint`/`:subject`/`:slot`) shape has not been
1695    /// crossed by the [`AplicacaoSpec::validate`] gate cascade. Call
1696    /// this accessor only from a code path that has already reached the
1697    /// containing [`AplicacaoSpec`] through a validating entry-point
1698    /// (caixa-mesh's [`typed_view`], caixa-feira's `feira app graph`'s
1699    /// [`typed_view`] compose, the future M4 CR admission webhook's
1700    /// per-CR validate). Use [`Self::target`] instead on any pre-
1701    /// validation code path.
1702    ///
1703    /// [`typed_view`]: https://docs.rs/caixa-mesh/latest/caixa_mesh/fn.typed_view.html
1704    #[must_use]
1705    pub fn target_projected(&self) -> WitTarget<'_> {
1706        self.target().expect(Self::PROJECTED_INVARIANT_MSG)
1707    }
1708
1709    /// Canonical panic message the [`Self::target_projected`]
1710    /// post-validation projection accessor threads through when the
1711    /// caller has violated the "call only after [`AplicacaoSpec::validate`]
1712    /// has succeeded" precondition. Lifted as a `pub const` on the
1713    /// [`WitContract`] surface so the byte-string lives in one place
1714    /// across the substrate — the [`Self::target_projected`] method
1715    /// body, the two prior production call sites' comments now naming
1716    /// the const, and every future consumer that must format-match the
1717    /// panic-message shape (a future test suite that asserts the panic-
1718    /// message byte-string across a fuzzed invalid-contract corpus,
1719    /// a future custom-panic hook in `caixa-operator` that surfaces the
1720    /// message with per-`:contratos` telemetry, the future admission
1721    /// webhook's per-CR validate-error report) reaches through the same
1722    /// canonical `&'static str`. A future rebrand on the panic-message
1723    /// axis (a tightening from `"validated by typed_view"` to `"validated
1724    /// by AplicacaoSpec::validate"` as the substrate's validator
1725    /// entry-point vocabulary sharpens once caixa-core grows a
1726    /// `Caixa::validated_aplicacao_view` companion to caixa-mesh's
1727    /// [`typed_view`]) lands at one caixa-core edit rather than a
1728    /// coordinated per-consumer sweep — same "one canonical declaration
1729    /// per axis, next to the accessor that reads it" discipline the peer
1730    /// [`WitTarget::CAPABILITY_LABEL`] / [`WitTarget::CAPABILITY_EXPECTED`]
1731    /// / [`WitTarget::CAPABILITY_GRAPH_LABEL`] payload-less-arm scalar-
1732    /// const family already establishes on the paired per-consumer-axis
1733    /// diagnostic-scalar surface.
1734    pub const PROJECTED_INVARIANT_MSG: &'static str = "validated by typed_view";
1735}
1736
1737/// Borrowed identity key for the typed-graph duplicate-`:contratos`
1738/// gate (see [`AplicacaoSpec::validate`]): every field that
1739/// distinguishes one contract from another, in declaration order
1740/// (`(de, para, wit, endpoint, subject, slot)`). Two [`WitContract`]s
1741/// with equal [`ContratoIdentity`]s are the same typed edge declared
1742/// twice — the graph-edge analogue of duplicate `:membros` /
1743/// `:placement :clusters` / `:entrada :paths` entries. Lifted as a
1744/// type alias so the duplicate-gate's `HashSet<…>` type doesn't trip
1745/// clippy's `type_complexity` lint (and so a future axis added to
1746/// `WitContract` is one alias edit, not a coordinated rewrite of
1747/// every set instantiation).
1748pub type ContratoIdentity<'a> = (
1749    &'a str,
1750    &'a str,
1751    &'a str,
1752    Option<&'a str>,
1753    Option<&'a str>,
1754    Option<&'a str>,
1755);
1756
1757/// Typed view of a [`WitContract`]'s payload target. Each variant
1758/// carries the field its WIT shape requires; constructing a `Http`
1759/// view without an endpoint is impossible by the type system.
1760///
1761/// Renderers (caixa-mesh L7 rules, feira app graph) match on this
1762/// instead of probing `Option<String>` fields one by one — the
1763/// "which payload field is set?" question is answered once, at
1764/// validation time.
1765#[derive(Debug, Clone, Copy, PartialEq, Eq, gen_platform::IsVariant)]
1766pub enum WitTarget<'a> {
1767    /// HTTP-shaped WIT world. Carries the configured request path.
1768    Http { endpoint: &'a str },
1769    /// Pub-sub-shaped WIT world. Carries the event-stream subject.
1770    ///
1771    /// The `IsVariant` derive would auto-name the predicate `is_pub_sub`
1772    /// (`discriminant_to_snake("PubSub") == "pub_sub"`); the explicit
1773    /// `#[is_variant(name = "pubsub")]` override keeps the emitted
1774    /// method name byte-identical to the sibling
1775    /// [`WitContract::is_pubsub`] predicate (the paired shape-side
1776    /// arm-discriminator that routes through
1777    /// [`wit_shape_is_pubsub`] on the wit-world-ref scalar rather than
1778    /// through `matches!` on the variant), so the two arm-discriminator
1779    /// axes — target-side variant-arm and shape-side ref-prefix — reach
1780    /// every downstream consumer through the same `is_pubsub()` name.
1781    #[is_variant(name = "pubsub")]
1782    PubSub { subject: &'a str },
1783    /// Key-value-shaped WIT world. Carries the slot template.
1784    Store { slot: &'a str },
1785    /// A typed capability edge with no payload selector — the WIT
1786    /// world stands on its own (rare; reserved for plain capability
1787    /// imports or M4-and-later WIT worlds we haven't shaped yet).
1788    Capability,
1789}
1790
1791impl<'a> WitTarget<'a> {
1792    /// Canonical author-facing `:contratos` payload field name for the
1793    /// HTTP-shaped arm — the `expected: &'static str` scalar the
1794    /// [`AplicacaoError::ContratoMissingTarget`] /
1795    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1796    /// through, the `:endpoint "…"` keyword the [`WitTarget::label`]
1797    /// duplicate-edge diagnostic emits, and the `endpoint=…` prefix
1798    /// the `feira app graph` verb prints. Peer of
1799    /// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
1800    /// on the payload-field-name axis; declared as a peer const next
1801    /// to the [`WitTarget::Http`] variant so a future rename on the
1802    /// author-surface `(defcaixa … :contratos ((:de … :para … :wit …
1803    /// :endpoint …)))` field lands in exactly one place, not scattered
1804    /// across the [`WitContract::target`] gate's six `expected:`
1805    /// literals, the label template, and every downstream consumer
1806    /// that prints a per-arm prefix. Same trajectory as the peer
1807    /// [`WitTarget::label`] lift (174e96a): a single source of truth
1808    /// for the arm's shape, next to the variant declaration.
1809    pub const HTTP_FIELD_NAME: &'static str = "endpoint";
1810    /// Canonical author-facing `:contratos` payload field name for the
1811    /// pub-sub-shaped arm. Peer of [`WitTarget::HTTP_FIELD_NAME`] /
1812    /// [`WitTarget::STORE_FIELD_NAME`] on the payload-field-name axis;
1813    /// see [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1814    pub const PUBSUB_FIELD_NAME: &'static str = "subject";
1815    /// Canonical author-facing `:contratos` payload field name for the
1816    /// key/value-store-shaped arm. Peer of
1817    /// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`]
1818    /// on the payload-field-name axis; see
1819    /// [`WitTarget::HTTP_FIELD_NAME`] for the full lift rationale.
1820    pub const STORE_FIELD_NAME: &'static str = "slot";
1821
1822    /// Canonical stable human-readable label the payload-less
1823    /// [`WitTarget::Capability`] arm renders as under [`Self::label`] —
1824    /// the byte-string every consumer that formats a payload-less
1825    /// typed capability edge as text lands on (the
1826    /// [`AplicacaoSpec::validate`] duplicate-`:contratos` diagnostic
1827    /// naming which identical edge was declared twice, the future
1828    /// `feira app graph` verb's per-arm prefix, the future M4 per-edge
1829    /// policy resolver's audit view, the operator's mesh-graph audit).
1830    /// Peer of the payload-arm [`Self::HTTP_FIELD_NAME`] /
1831    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`]
1832    /// author-facing label-scalar consts — the same
1833    /// "one canonical declaration per arm, next to the variant, so a
1834    /// future rename lands in one place" discipline extended to the
1835    /// payload-less arm. Until this lift landed the byte-string sat
1836    /// twice — once inline in [`Self::label`]'s [`WitTarget::Capability`]
1837    /// match arm, once in the pin test asserting the label's
1838    /// [`WitTarget::Capability`] output — with no compile-time link
1839    /// between the two: a rebrand on either side (an operator-facing
1840    /// vocabulary shift, a per-consumer disambiguation like
1841    /// `"(capability — no payload; typed edge only)"`) would silently
1842    /// desynchronize until a downstream consumer surfaced the drift at
1843    /// runtime.
1844    pub const CAPABILITY_LABEL: &'static str = "(capability — no payload)";
1845
1846    /// Canonical `expected:` scalar the
1847    /// [`AplicacaoError::ContratoWrongTarget`] diagnostic threads
1848    /// through for the payload-less [`WitTarget::Capability`] arm — the
1849    /// byte-string authors read as "this WIT world's shape is not one
1850    /// of {`HTTP`, `PubSub`, `Store`}, so it must not carry
1851    /// `:endpoint` / `:subject` / `:slot`". Peer of the payload-arm
1852    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1853    /// [`Self::STORE_FIELD_NAME`] consts on the
1854    /// `ContratoWrongTarget::expected` axis — the fourth arm of the
1855    /// same "which payload field name goes in the diagnostic" dispatch
1856    /// the three payload-arm consts cover, extended to the payload-less
1857    /// arm. Until this lift landed the byte-string sat twice — once
1858    /// inline in the [`Self::target`] Capability-arm rejection at the
1859    /// production dispatch, once in the pin test asserting the
1860    /// diagnostic's `expected:` scalar carries `"none"` verbatim — with
1861    /// no compile-time link between the two: a rebrand on either side
1862    /// (an author-facing vocabulary shift to `"capability"` /
1863    /// `"(none)"` / `"no-payload"` as the WIT registry's shape
1864    /// vocabulary sharpens, a per-consumer disambiguation as M4 splits
1865    /// [`WitTarget::Capability`] into per-shape peers) would silently
1866    /// desynchronize until a downstream consumer surfaced the drift at
1867    /// runtime. Same "one canonical declaration per arm, next to the
1868    /// variant, so a future rename lands in one place" discipline the
1869    /// peer [`Self::CAPABILITY_LABEL`] lift (7ed03a3-era) already
1870    /// established for the payload-less arm's human-readable label
1871    /// axis; this lift extends it onto the peer diagnostic-scalar axis
1872    /// so both halves of the "how does the Capability arm surface at
1873    /// its two consumer axes (human-readable label, wrong-target
1874    /// diagnostic)" pipeline route through peer consts declared next
1875    /// to the variant.
1876    ///
1877    /// Pairwise-distinctness against the three payload-arm scalars
1878    /// ([`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1879    /// [`Self::STORE_FIELD_NAME`]) is pinned by the sibling
1880    /// `wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`
1881    /// test — the 4-way closure of the 3-way
1882    /// `wit_target_field_names_are_pairwise_distinct` sibling pin onto
1883    /// the `ContratoWrongTarget::expected` axis, matching the peer
1884    /// `m3_placement_estrategia_consts_are_pairwise_distinct` closed-set
1885    /// scalar-value distinctness discipline the sibling M3 typed-enum
1886    /// discriminator axis already carries.
1887    pub const CAPABILITY_EXPECTED: &'static str = "none";
1888
1889    /// Canonical `feira app graph` per-`:contratos`-edge payload-column
1890    /// byte-string the payload-less [`WitTarget::Capability`] arm renders
1891    /// as under [`Self::graph_label`] — the sibling
1892    /// [`WitTarget::CAPABILITY_LABEL`] scalar on the peer graph-verb
1893    /// payload-column axis (the graph verb spells payload-less as
1894    /// `(capability-only)`, distinct from the duplicate-`:contratos`
1895    /// diagnostic's `(capability — no payload)` on the human-readable
1896    /// [`Self::label`] axis). Peer of [`Self::CAPABILITY_LABEL`] /
1897    /// [`Self::CAPABILITY_EXPECTED`] on the payload-less-arm scalar-const
1898    /// family — extends the "one canonical declaration per arm, next to
1899    /// the variant, so a future rename lands in one place" discipline
1900    /// onto the third payload-less-arm consumer axis (`feira app graph`
1901    /// payload column, joining the [`Self::label`] duplicate-`:contratos`
1902    /// diagnostic axis and the [`Self::target`] wrong-target diagnostic
1903    /// axis).
1904    ///
1905    /// Until this lift landed the byte-string sat inline in
1906    /// [`caixa-feira`]'s `cmd::app::GraphArgs::run` per-`:contratos` payload-
1907    /// column match at `caixa-feira/src/cmd/app.rs:111` as a raw
1908    /// `"(capability-only)".to_string()` literal, with no compile-time link
1909    /// back to the [`WitTarget::Capability`] variant declaration nor to
1910    /// the sibling [`Self::CAPABILITY_LABEL`] / [`Self::CAPABILITY_EXPECTED`]
1911    /// peer consts already carrying the "one canonical declaration per
1912    /// payload-less-arm consumer axis" discipline. A rebrand on either
1913    /// side (the graph verb's operator-facing vocabulary tightening from
1914    /// `"(capability-only)"` to `"capability"` / `"(capability edge)"` as
1915    /// the WIT registry vocabulary sharpens, an M4 split of
1916    /// [`Self::Capability`] into per-shape peers) would silently
1917    /// desynchronize the graph-verb byte-string from the paired
1918    /// per-arm-adjacent const and land two spellings of the same axis in
1919    /// two spots.
1920    pub const CAPABILITY_GRAPH_LABEL: &'static str = "(capability-only)";
1921
1922    /// The `(author-facing field name, payload)` pair this typed target
1923    /// arm carries — `Some((HTTP_FIELD_NAME, endpoint))` for
1924    /// [`Self::Http`], `Some((PUBSUB_FIELD_NAME, subject))` for
1925    /// [`Self::PubSub`], `Some((STORE_FIELD_NAME, slot))` for
1926    /// [`Self::Store`], `None` for the payload-less
1927    /// [`Self::Capability`] arm.
1928    ///
1929    /// Lifted as the single 4-arm dispatch that both [`Self::label`]
1930    /// (formats `":{field} {payload:?}"` on `Some`, falls to
1931    /// [`Self::CAPABILITY_LABEL`] on `None`) and [`Self::field_name`]
1932    /// (returns the first component) route through, so a future
1933    /// [`WitTarget`] variant addition — the M4-and-later per-edge WIT
1934    /// registry may split [`Self::Http`] into `Rest` / `Grpc` peers,
1935    /// or extend [`Self::Store`] with a `Queue`-shaped peer — becomes
1936    /// exactly one new match-arm here (a compile-time exhaustiveness
1937    /// error otherwise), not a coordinated three-way rewrite of the
1938    /// prior [`Self::label`] template + [`Self::field_name`] dispatch
1939    /// + every downstream consumer that reaches for the pair.
1940    ///
1941    /// Until this lift landed the three payload arms sat in
1942    /// [`Self::label`] as three near-identical `format!(":{} {…:?}", …)`
1943    /// invocations (one per variant, each hand-quoting the paired
1944    /// [`Self::HTTP_FIELD_NAME`] / [`Self::PUBSUB_FIELD_NAME`] /
1945    /// [`Self::STORE_FIELD_NAME`] const) — the canonical
1946    /// "same shape, written N times" duplication THEORY.md §I.3.5
1947    /// ("Generation first, composition second, hand-authoring last;
1948    /// the duplication budget is zero") promotes to a build-time
1949    /// concern, with each per-arm site paired to its own const with no
1950    /// compile-time link between the format template and the arm's
1951    /// payload extraction.
1952    #[must_use]
1953    pub const fn payload_pair(&self) -> Option<(&'static str, &'a str)> {
1954        match *self {
1955            WitTarget::Http { endpoint } => Some((Self::HTTP_FIELD_NAME, endpoint)),
1956            WitTarget::PubSub { subject } => Some((Self::PUBSUB_FIELD_NAME, subject)),
1957            WitTarget::Store { slot } => Some((Self::STORE_FIELD_NAME, slot)),
1958            WitTarget::Capability => None,
1959        }
1960    }
1961
1962    /// The canonical author-facing `:contratos` payload field name
1963    /// this typed target arm carries (`Http` → `Some("endpoint")`,
1964    /// `PubSub` → `Some("subject")`, `Store` → `Some("slot")`), or
1965    /// `None` for the payload-less `Capability` arm.
1966    ///
1967    /// Routes through [`Self::payload_pair`] — the single 4-arm
1968    /// dispatch [`Self::label`] also reads — so a future variant
1969    /// addition is one match-arm edit at [`Self::payload_pair`], not a
1970    /// per-consumer rewrite. Same "exhaustive-match at one canonical
1971    /// dispatch, thin projections at each consumer" trajectory the
1972    /// peer [`PlacementStrategy::as_str`] / [`std::fmt::Display`]
1973    /// pair (0a2f653) landed on the sibling M3 typed-enum axis.
1974    #[must_use]
1975    pub const fn field_name(&self) -> Option<&'static str> {
1976        match self.payload_pair() {
1977            Some((f, _)) => Some(f),
1978            None => None,
1979        }
1980    }
1981
1982    /// The underlying scalar the payload-carrying arm carries — the
1983    /// per-arm request path ([`Self::Http`] `:endpoint`), event-stream
1984    /// subject ([`Self::PubSub`] `:subject`), or slot template
1985    /// ([`Self::Store`] `:slot`), borrowed from the typed slot's own
1986    /// `&'a str` storage — or `None` on the payload-less
1987    /// [`Self::Capability`] arm.
1988    ///
1989    /// Thin projection onto the single 4-arm [`Self::payload_pair`]
1990    /// dispatch (`self.payload_pair().map(|(_, p)| p)` in `const fn`
1991    /// form) — peer of [`Self::field_name`] (`.payload_pair().0`) on
1992    /// the paired sub-selector axis. Both per-half accessors read from
1993    /// one authoritative match, so a future [`WitTarget`] variant
1994    /// addition (`Rest`/`Grpc` split of [`Self::Http`], `Queue`-shaped
1995    /// peer of [`Self::Store`]) lands at exactly one caixa-core edit
1996    /// on [`Self::payload_pair`] and both per-half projections + every
1997    /// downstream consumer picks the new arm up by construction — no
1998    /// coordinated N-way rewrite across the paired accessor dispatches,
1999    /// the [`Self::label`] / [`Self::graph_label`] format templates,
2000    /// and every future WIT-registry-shaped consumer.
2001    ///
2002    /// Peer of the sibling [`caixa-flux`][caixa-flux-crate]
2003    /// `GitRefSpec::ref_value` projection on the `FluxCD` source-
2004    /// controller `spec.ref.<field>` axis — same "one paired dispatch,
2005    /// both per-half projections as thin readers, every downstream
2006    /// consumer through the same match" discipline extended onto the
2007    /// M3 `:contratos` payload-arm axis. Closes the discipline-parity
2008    /// gap between the two paired-dispatch surfaces: the peer
2009    /// [`Self::payload_pair`] + [`Self::field_name`] pair carried only
2010    /// the first-component projection until this lift; the second-
2011    /// component sibling now sits alongside so both halves reach every
2012    /// future consumer through the same substrate-primitive dispatch.
2013    ///
2014    /// [caixa-flux-crate]: https://docs.rs/caixa-flux/latest/caixa_flux/enum.GitRefSpec.html#method.ref_value
2015    #[must_use]
2016    pub const fn payload(&self) -> Option<&'a str> {
2017        match self.payload_pair() {
2018            Some((_, p)) => Some(p),
2019            None => None,
2020        }
2021    }
2022
2023    /// Substrate-canonical per-arm HTTP-endpoint scalar accessor every
2024    /// consumer that fans on the L7-HTTP-shaped payload keys off —
2025    /// returns the [`Self::Http`]-arm's author-declared request path
2026    /// verbatim as an `Option<&'a str>`, `Some(endpoint)` when the
2027    /// projected target is [`Self::Http { endpoint }`], `None` on the
2028    /// three sibling arms ([`Self::PubSub`] / [`Self::Store`] /
2029    /// [`Self::Capability`], each of which carries no HTTP endpoint by
2030    /// definition).
2031    ///
2032    /// The [`Self::Http`] arm carries the Cilium L7 `HTTPNetworkPolicy`
2033    /// `path:` rule payload every substrate-side L7-introspecting
2034    /// per-`(:de, :para)` `CiliumNetworkPolicy` emitter reads (today: the
2035    /// [`caixa_mesh::cilium_network_policies`] per-edge `toPorts[].rules
2036    /// .http[0].path` scalar the HTTP-shape-only L7 rule builder emits
2037    /// on the L7 introspection branch; every peer WIT shape stays
2038    /// L4-only because Cilium can't introspect NATS / key-value / plain
2039    /// capability edges), and every future L7-introspecting consumer
2040    /// of the projected target's HTTP endpoint (the future M4
2041    /// per-`(:de, :para)` `mesh.pleme.io/v1alpha1/Aplicacao` CR
2042    /// materializer's per-edge L7 admission-webhook overlay, the
2043    /// future Envoy-side `local_rate_limit.descriptor_entries` per-HTTP-
2044    /// path bucket-key resolver, the future per-`:contratos`-edge
2045    /// mTLS-required overlay's HTTP-shape scope filter, the future
2046    /// `feira app graph --l7` per-Aplicacao HTTP-path column) reaches
2047    /// through the same typed dispatch.
2048    ///
2049    /// Prior to this lift the sole production consumer of the projected-
2050    /// target HTTP endpoint — the [`caixa_mesh::cilium_network_policies`]
2051    /// per-edge L7 introspection branch at `caixa-mesh/src/lib.rs:2759`
2052    /// (`if let WitTarget::Http { endpoint } = c.target().expect(…) {
2053    /// http_rule.insert_string(CILIUM_KEY_PATH, endpoint.to_string()); …
2054    /// }`) — reached the payload through a raw per-arm `if let` pattern-
2055    /// match that expressed no compile-time link back to the substrate
2056    /// primitive's typed dispatch, sibling to the [`WitContract`] pre-
2057    /// projection [`WitContract::endpoint`] (7020470) `Option<&str>`
2058    /// scalar accessor on the peer per-`:contratos` raw-field axis but
2059    /// with no post-projection peer on the typed-view surface. A future
2060    /// [`WitTarget`] variant addition that splits [`Self::Http`] into
2061    /// peers (a `Rest`/`Grpc` split once the WIT registry stabilizes
2062    /// gRPC-shaped worlds per this enum's own docstring at
2063    /// aplicacao.rs:1341-1343 — with a `Rest`-arm `endpoint: &'a str`
2064    /// payload alongside a `Grpc`-arm `service_method: &'a str` payload)
2065    /// would have had to be threaded through the caixa-mesh L7 emit
2066    /// branch's raw `if let` in lockstep — either coalescing the two
2067    /// L7-HTTP-family arms under a shared `path:` emit, or splitting the
2068    /// emit path per-arm — with no substrate-primitive dispatch making
2069    /// the "which arms count as L7-HTTP-shaped for path-emission
2070    /// purposes" question the substrate's answer to give. Lifting the
2071    /// resolution to a typed method on the substrate primitive means
2072    /// every downstream L7-HTTP-facing consumer of the Aplicacao's
2073    /// projected-target HTTP endpoint reaches for exactly one typed
2074    /// dispatch — the resolver's accept-set migrates as a unit on any
2075    /// future arm-family widening, and the caixa-mesh L7 emit branch
2076    /// reads through the same substrate primitive.
2077    ///
2078    /// Peer of the sibling pre-projection [`WitContract::endpoint`]
2079    /// (7020470) `Option<&str>` scalar accessor on the raw
2080    /// `:contratos :endpoint` field-access axis — same "one typed
2081    /// dispatch on the substrate primitive, thin projections at each
2082    /// consumer" discipline extended onto the peer post-projection typed-
2083    /// view surface (the [`WitContract::endpoint`] pre-projection
2084    /// accessor returns `Some` for any author-declared `:endpoint`
2085    /// value regardless of the paired `:wit` world's HTTP-shape
2086    /// classification — the raw slot before validation crosses it —
2087    /// while this post-projection [`Self::http_endpoint`] accessor
2088    /// returns `Some` iff the target has been projected onto the
2089    /// [`Self::Http`] arm, i.e. only after the [`WitContract::target`]
2090    /// gate has admitted the `(:wit, :endpoint/:subject/:slot)` shape
2091    /// coherence; the two accessors close the pre-projection /
2092    /// post-projection pair on the HTTP-endpoint axis). Sibling of the
2093    /// unified pan-arm [`Self::payload`] (`Option<&'a str>` for any of
2094    /// the three payload-carrying arms) — extends the per-arm
2095    /// projection family onto the [`Self::Http`] specialization axis
2096    /// that the pan-arm accessor's shape blends into a single arm-
2097    /// agnostic view; paired with [`Self::pubsub_subject`] /
2098    /// [`Self::store_slot`] on the sibling per-arm axes so every
2099    /// per-payload-arm shape carries a named post-projection accessor
2100    /// on the same shape as `http_endpoint`, closing the per-arm-shape
2101    /// accept-set the substrate primitive owns.
2102    #[must_use]
2103    pub const fn http_endpoint(&self) -> Option<&'a str> {
2104        match *self {
2105            WitTarget::Http { endpoint } => Some(endpoint),
2106            WitTarget::PubSub { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2107        }
2108    }
2109
2110    /// Substrate-canonical per-arm pub-sub-subject scalar accessor every
2111    /// consumer that fans on the pub-sub-shaped payload keys off —
2112    /// returns the [`Self::PubSub`]-arm's author-declared event-stream
2113    /// subject verbatim as an `Option<&'a str>`, `Some(subject)` when
2114    /// the projected target is [`Self::PubSub { subject }`], `None` on
2115    /// the three sibling arms ([`Self::Http`] / [`Self::Store`] /
2116    /// [`Self::Capability`], each of which carries no NATS-shaped
2117    /// subject by definition).
2118    ///
2119    /// The [`Self::PubSub`] arm carries the NATS-server-accepted subject
2120    /// the future substrate-side pub-sub-introspecting per-`(:de, :para)`
2121    /// consumer keys off (the M4 per-Aplicacao NATS `Stream` / `Consumer`
2122    /// CR materializer's `spec.subjects[]` projection, the future
2123    /// Envoy-side per-subject `local_rate_limit.descriptor_entries`
2124    /// bucket-key resolver, the future `feira app graph --pubsub`
2125    /// per-Aplicacao subject column, any future substrate-lifted
2126    /// pub-sub-shape emitter that reads a projected `WitTarget` in the
2127    /// same shape [`caixa_mesh::cilium_network_policies`] reads the
2128    /// HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today). Every
2129    /// future pub-sub-shape consumer reaches for the same typed
2130    /// dispatch this accessor exposes so the "which arm carries the
2131    /// subject scalar?" answer lives at one caixa-core edit rather
2132    /// than open-coded across per-consumer `if let WitTarget::PubSub
2133    /// { subject } = c.target()…` pattern-matches.
2134    ///
2135    /// Peer of the sibling [`Self::http_endpoint`] (5d6dc92 trajectory)
2136    /// per-arm HTTP-endpoint accessor on the peer per-arm axis and of
2137    /// the pre-projection [`WitContract::subject`] scalar accessor on
2138    /// the raw `:contratos :subject` field-access axis — same "one
2139    /// typed dispatch on the substrate primitive, thin projections at
2140    /// each consumer" discipline extended onto the per-arm pub-sub
2141    /// post-projection axis. The pre-projection accessor returns
2142    /// `Some` for any author-declared `:subject` value regardless of
2143    /// the paired `:wit` world's pub-sub-shape classification (the raw
2144    /// slot before validation crosses it); this post-projection
2145    /// accessor returns `Some` iff the target has been projected onto
2146    /// the [`Self::PubSub`] arm, i.e. only after the
2147    /// [`WitContract::target`] gate has admitted the
2148    /// `(:wit, :endpoint/:subject/:slot)` shape coherence — closing
2149    /// the pre-/post-projection pair on the pub-sub-subject axis to
2150    /// match the pair the [`WitContract::endpoint`] +
2151    /// [`Self::http_endpoint`] surfaces already close on the peer
2152    /// HTTP-endpoint axis.
2153    ///
2154    /// Sibling of the unified pan-arm [`Self::payload`]
2155    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2156    /// extends the per-arm projection family onto the [`Self::PubSub`]
2157    /// specialization axis that the pan-arm accessor's shape blends
2158    /// into a single arm-agnostic view; the pair
2159    /// (`pubsub_subject`, `store_slot`) closes the trio
2160    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) so every
2161    /// payload arm now carries its own per-arm-shape post-projection
2162    /// accessor.
2163    #[must_use]
2164    pub const fn pubsub_subject(&self) -> Option<&'a str> {
2165        match *self {
2166            WitTarget::PubSub { subject } => Some(subject),
2167            WitTarget::Http { .. } | WitTarget::Store { .. } | WitTarget::Capability => None,
2168        }
2169    }
2170
2171    /// Substrate-canonical per-arm key/value-store-slot scalar accessor
2172    /// every consumer that fans on the store-shaped payload keys off —
2173    /// returns the [`Self::Store`]-arm's author-declared slot template
2174    /// verbatim as an `Option<&'a str>`, `Some(slot)` when the
2175    /// projected target is [`Self::Store { slot }`], `None` on the
2176    /// three sibling arms ([`Self::Http`] / [`Self::PubSub`] /
2177    /// [`Self::Capability`], each of which carries no
2178    /// key/value-store slot by definition).
2179    ///
2180    /// The [`Self::Store`] arm carries the WASI-key/value-accepted slot
2181    /// template (validated by [`crate::render::is_wasi_keyvalue_slot`])
2182    /// every future substrate-side store-introspecting per-`(:de,
2183    /// :para)` consumer keys off (the M4 per-Aplicacao WASI-key/value
2184    /// namespace / prefix reconciler's per-slot projection, the future
2185    /// per-store-backend routing overlay's slot-shape gate, the future
2186    /// `feira app graph --store` per-Aplicacao slot column, any future
2187    /// substrate-lifted store-shape emitter that reads a projected
2188    /// `WitTarget` in the same shape [`caixa_mesh::cilium_network_policies`]
2189    /// reads the HTTP-shape one at `caixa-mesh/src/lib.rs:2780` today).
2190    /// Every future store-shape consumer reaches for the same typed
2191    /// dispatch this accessor exposes so the "which arm carries the
2192    /// slot scalar?" answer lives at one caixa-core edit rather than
2193    /// open-coded across per-consumer
2194    /// `if let WitTarget::Store { slot } = c.target()…`
2195    /// pattern-matches.
2196    ///
2197    /// Peer of the sibling [`Self::http_endpoint`] +
2198    /// [`Self::pubsub_subject`] per-arm accessors on the peer per-arm
2199    /// axes and of the pre-projection [`WitContract::slot`] scalar
2200    /// accessor on the raw `:contratos :slot` field-access axis — same
2201    /// "one typed dispatch on the substrate primitive, thin projections
2202    /// at each consumer" discipline extended onto the per-arm store
2203    /// post-projection axis. Closes the pre-/post-projection pair on
2204    /// the store-slot axis to match the pairs the
2205    /// [`WitContract::endpoint`] + [`Self::http_endpoint`] and
2206    /// [`WitContract::subject`] + [`Self::pubsub_subject`] surfaces
2207    /// already close on the peer HTTP-endpoint and pub-sub-subject
2208    /// axes; the substrate-side pre-/post-projection accessor family
2209    /// now spans all three payload arms as a matched trio, so any
2210    /// future arm-shape widening (a `Rest`/`Grpc` split of
2211    /// [`Self::Http`], a `Queue`-shaped peer of [`Self::Store`]) that
2212    /// lands one accessor without threading through the sibling
2213    /// pre-projection or the peer per-arm post-projection surfaces a
2214    /// compile-time exhaustiveness error at the substrate primitive,
2215    /// not a silent per-consumer split at renderer emit time.
2216    ///
2217    /// Sibling of the unified pan-arm [`Self::payload`]
2218    /// (`Option<&'a str>` for any of the three payload-carrying arms) —
2219    /// closes the per-arm projection family onto the [`Self::Store`]
2220    /// specialization axis that the pan-arm accessor's shape blends
2221    /// into a single arm-agnostic view. The trio
2222    /// (`http_endpoint`, `pubsub_subject`, `store_slot`) partitions the
2223    /// pan-arm accept-set on every payload-carrying arm: exactly one
2224    /// per-arm accessor returns `Some(payload)` and the two peers
2225    /// return `None`, and every payload-less [`Self::Capability`]
2226    /// input returns `None` on all three — the partition the sibling
2227    /// `wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`
2228    /// pin locks in load-bearing.
2229    #[must_use]
2230    pub const fn store_slot(&self) -> Option<&'a str> {
2231        match *self {
2232            WitTarget::Store { slot } => Some(slot),
2233            WitTarget::Http { .. } | WitTarget::PubSub { .. } | WitTarget::Capability => None,
2234        }
2235    }
2236
2237    /// Render this typed target as a stable human-readable label
2238    /// (`:endpoint "/charge"`, `:subject "events.x"`,
2239    /// `:slot "checkout/$order"`, or `(capability — no payload)` when
2240    /// the WIT world is a pure capability edge).
2241    ///
2242    /// Used by the [`AplicacaoSpec::validate`] duplicate-`:contratos`
2243    /// gate so the diagnostic names *which* identical edge was
2244    /// declared twice (not just which `(de, para, wit)` triple).
2245    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2246    /// on the payload-carrying arms (`Some((field, payload)) →
2247    /// format!(":{field} {payload:?}")`) and through the lifted
2248    /// [`Self::CAPABILITY_LABEL`] const on the payload-less
2249    /// [`Self::Capability`] arm — so a future variant addition (the
2250    /// M4-and-later per-edge WIT registry may split [`Self::Http`]
2251    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2252    /// `Queue`-shaped peer) becomes a single new match-arm on
2253    /// [`Self::payload_pair`] rather than a rewrite of this template
2254    /// (and every downstream consumer that reaches for the label
2255    /// shape: the per-edge policy resolver in M4, the `feira app
2256    /// graph` view, the operator's mesh-graph audit). Until this
2257    /// lift landed the three payload arms carried three near-identical
2258    /// per-arm `format!(":{} {…:?}", …)` invocations, and the
2259    /// [`Self::Capability`] arm carried the payload-less byte-string
2260    /// twice (once inline here, once in the pin test) — closing the
2261    /// duplication trajectory the peer [`Self::HTTP_FIELD_NAME`] /
2262    /// [`Self::PUBSUB_FIELD_NAME`] / [`Self::STORE_FIELD_NAME`] (174e96a
2263    /// / 4a1e490) peer-const lifts already established for the
2264    /// payload-carrying arms.
2265    #[must_use]
2266    pub fn label(&self) -> String {
2267        match self.payload_pair() {
2268            Some((field, payload)) => format!(":{field} {payload:?}"),
2269            None => Self::CAPABILITY_LABEL.to_string(),
2270        }
2271    }
2272
2273    /// Render this typed target as the `feira app graph` per-`:contratos`
2274    /// payload-column byte-string (`endpoint=/charge`, `subject=events.x`,
2275    /// `slot=checkout/$order`, or [`Self::CAPABILITY_GRAPH_LABEL`] on the
2276    /// payload-less arm).
2277    ///
2278    /// Routes through the single 4-arm [`Self::payload_pair`] dispatch
2279    /// on the payload-carrying arms (`Some((field, payload)) →
2280    /// format!("{field}={payload}")`) and through the lifted
2281    /// [`Self::CAPABILITY_GRAPH_LABEL`] const on the payload-less
2282    /// [`Self::Capability`] arm — so a future variant addition
2283    /// (the M4-and-later per-edge WIT registry may split [`Self::Http`]
2284    /// into `Rest` / `Grpc`, or extend [`Self::Store`] with a
2285    /// `Queue`-shaped peer) becomes one match-arm edit at
2286    /// [`Self::payload_pair`], propagating through this graph-verb
2287    /// projection at zero call-site cost, sibling to the peer
2288    /// [`Self::label`] duplicate-`:contratos` diagnostic emission on the
2289    /// same 4-arm dispatch.
2290    ///
2291    /// Until this lift landed the [`caixa-feira`]
2292    /// `cmd::app::GraphArgs::run` per-`:contratos` payload column
2293    /// (`caixa-feira/src/cmd/app.rs:101-112`) hand-rolled the same 4-arm
2294    /// dispatch inline, re-projecting `HTTP_FIELD_NAME` /
2295    /// `PUBSUB_FIELD_NAME` / `STORE_FIELD_NAME` under a per-arm
2296    /// `format!("{}={endpoint}", ...)` template and hard-coding
2297    /// `"(capability-only)"` as a fifth payload-less scalar with no link
2298    /// back to the paired [`WitTarget::Capability`] variant declaration.
2299    /// A future variant addition would have had to be threaded through
2300    /// both [`Self::label`] (via [`Self::payload_pair`]) *and* the graph
2301    /// verb's inline match in lockstep or the two projections would
2302    /// silently disagree on the arm-set the graph verb prints — the
2303    /// duplicate-`:contratos` diagnostic reading one shape while the
2304    /// graph verb's payload column silently dropped the new arm to
2305    /// `(capability-only)`. Lifting the graph-verb projection onto the
2306    /// same substrate-primitive [`Self::payload_pair`] dispatch closes
2307    /// the axis: both projections migrate as a unit.
2308    ///
2309    /// The `field=payload` (no colon prefix, `=` separator, no `Debug`
2310    /// quoting) shape is graph-verb-canonical — distinct from the
2311    /// sibling [`Self::label`] `":{field} {payload:?}"` shape the
2312    /// duplicate-`:contratos` diagnostic seeds (see
2313    /// [`Self::CAPABILITY_LABEL`] vs. [`Self::CAPABILITY_GRAPH_LABEL`]
2314    /// on the payload-less axis for the paired distinction).
2315    #[must_use]
2316    pub fn graph_label(&self) -> String {
2317        match self.payload_pair() {
2318            Some((field, payload)) => format!("{field}={payload}"),
2319            None => Self::CAPABILITY_GRAPH_LABEL.to_string(),
2320        }
2321    }
2322}
2323
2324/// [`std::fmt::Display`] routed through [`WitTarget::label`], so the
2325/// pretty-printed byte-string every consumer that formats a typed
2326/// payload target as user-facing text lands on (the
2327/// [`AplicacaoError::ContratoDuplicate`] diagnostic's `target:` carry
2328/// the [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds via
2329/// [`WitTarget::label`] at aplicacao.rs:5491, the future `feira app
2330/// graph` per-`:contratos`-edge payload column that reaches the graph
2331/// verb through `format!("{target}")`, the future M4 per-edge policy
2332/// resolver's per-edge audit-log line, the operator's mesh-graph
2333/// per-edge inspection view) reaches for the same lifted
2334/// [`WitTarget::HTTP_FIELD_NAME`] / [`WitTarget::PUBSUB_FIELD_NAME`] /
2335/// [`WitTarget::STORE_FIELD_NAME`] / [`WitTarget::CAPABILITY_LABEL`]
2336/// const set the [`WitTarget::payload_pair`] 4-arm dispatch already
2337/// routes through — extending the three-path-convergence
2338/// (`Debug` for structural inspection, `Display` for user-facing text,
2339/// per-arm typed accessor for the canonical byte-string) discipline the
2340/// sibling M3 [`PlacementStrategy`] and M2 [`crate::supervisor::RestartStrategy`]
2341/// / [`crate::supervisor::RestartPolicy`] OTP-shape typed enums carry
2342/// onto the fourth (and only remaining) typed-shape-discriminator axis
2343/// on the caixa surface.
2344///
2345/// Pre-lift the two paths were structurally independent — every consumer
2346/// reaching for a payload byte-string past the [`WitTarget::label`]
2347/// helper had to pick between three paths ([`WitTarget::label`],
2348/// `format!("{v:?}")` on the `Debug` derive, hand-rolled per-arm
2349/// formatting through the [`WitTarget::HTTP_FIELD_NAME`] /
2350/// [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`] /
2351/// [`WitTarget::CAPABILITY_LABEL`] const set), and a future consumer
2352/// that reached for `format!("{target}")` — the canonical shape every
2353/// user-facing pretty-print site on the sibling typed-enum axes already
2354/// uses — would silently land on the `Debug` derive's structural output
2355/// (`Http { endpoint: "/charge" }` — Rust struct-literal syntax) rather
2356/// than the `label()` helper's stable byte-string (`:endpoint
2357/// "/charge"` — the author-facing `:contratos` keyword form) the
2358/// substrate-side duplicate-`:contratos` gate at aplicacao.rs:5491
2359/// already threads through. The two spellings would diverge silently in
2360/// every downstream diagnostic / graph / audit line reached through
2361/// `format!` rather than through the `label()` helper. Routing
2362/// [`std::fmt::Display`] through [`WitTarget::label`] closes the third
2363/// path: every `format!("{v}")` call reaches the same
2364/// [`WitTarget::payload_pair`]-shaped byte-string the `label()` helper
2365/// and the duplicate-`:contratos` gate already route through, so a
2366/// future variant addition (the M4-and-later per-edge WIT registry may
2367/// split [`WitTarget::Http`] into `Rest` / `Grpc` peers, or extend
2368/// [`WitTarget::Store`] with a `Queue`-shaped peer) reaches every
2369/// consumer at exactly one place — the [`WitTarget::payload_pair`]
2370/// match — rather than fanning out through hand-rolled per-arm
2371/// [`std::fmt::Display`] arms.
2372///
2373/// The dispatcher-catalog identity remains unaffected — [`WitTarget`]
2374/// is the typed view returned by [`WitContract::target`], not a
2375/// closed-set discriminator enum with a gen-platform Discriminant
2376/// registration, so the `Debug` derive's structural output (which every
2377/// `{v:?}` consumer still reaches) stays distinct from the `Display`
2378/// helper's stable pretty-printed byte-string. `Debug` reveals variant
2379/// shape for structural inspection; `Display` (via `label`) reveals the
2380/// stable author-facing payload projection.
2381///
2382/// Pin tests
2383/// [`tests::wit_target_display_routes_through_label_helper`] and
2384/// [`tests::wit_target_display_matches_duplicate_contratos_diagnostic_carrier`]
2385/// assert the two paths agree byte-for-byte on every variant, so a
2386/// future variant addition or `label()` reimplementation that hand-rolls
2387/// the arms instead of delegating to [`WitTarget::payload_pair`] is a
2388/// build error visible at caixa-core test time, not a silent
2389/// per-consumer dispatch miss at diagnostic / audit / graph time.
2390impl std::fmt::Display for WitTarget<'_> {
2391    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2392        f.write_str(&self.label())
2393    }
2394}
2395
2396// ── one Aplicacao member ─────────────────────────────────────────────
2397
2398/// A Servico participating in the Aplicacao. Same shape as
2399/// `crate::supervisor::ChildSpec` but without a restart policy —
2400/// supervision is per-Servico (each member has its own
2401/// `:supervisor`), the Aplicacao orchestrates *placement*.
2402#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
2403#[serde(rename_all = "camelCase")]
2404pub struct Membro {
2405    /// Member caixa's `:nome`. Resolves through the same dep
2406    /// resolution path as `crate::dep::Dep`.
2407    pub caixa: String,
2408
2409    /// Semver constraint.
2410    pub versao: String,
2411}
2412
2413impl Membro {
2414    /// Substrate-canonical per-`:membros` member-caixa `:nome` scalar
2415    /// accessor every consumer that reads the member's Servico identity
2416    /// keys off — returns the author-declared `:membros :caixa`
2417    /// byte-string verbatim as a `&str`, borrowed from the typed slot's
2418    /// own [`String`] storage.
2419    ///
2420    /// The `:membros :caixa` slot carries the caixa `:nome` of a Servico
2421    /// participating in the Aplicacao — validated by
2422    /// [`AplicacaoSpec::validate`] to be a non-empty DNS-1123 label
2423    /// (via [`validate_membro_caixa`]), unique across the Aplicacao's
2424    /// `:membros` list, distinct from the Aplicacao's own `:nome` (via
2425    /// [`validate_no_self_membership`]) — and every downstream consumer
2426    /// that fans on the member's identity keys off this scalar (the
2427    /// [`AplicacaoSpec::validate`] `:contratos`/`:entrada` member-set
2428    /// lookup, the per-`:membros` duplicate gate's dedup key, the
2429    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency map's node
2430    /// identity, the self-membership gate, the
2431    /// [`caixa_mesh::fleet_programs`] per-member programs.yaml entry
2432    /// `name:` axis, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
2433    /// CR materializer's per-member resolver).
2434    ///
2435    /// Prior to this lift the `.caixa` byte-string was read inline at
2436    /// five caixa-core sites (the [`AplicacaoSpec::validate`] member-name
2437    /// set collector at
2438    /// `self.membros.iter().map(|m| m.caixa.as_str())`, the
2439    /// [`validate_membros`] validation-side member-caixa gate at
2440    /// `validate_membro_caixa(&m.caixa)`, the [`validate_membros`]
2441    /// per-member duplicate-gate dedup key at
2442    /// `insert_first_seen(&mut seen, m.caixa.as_str(), …)`, the
2443    /// [`AplicacaoSpec::detect_sync_cycles`] adjacency-map seed at
2444    /// `adj.entry(m.caixa.as_str()).or_default()`, and the
2445    /// [`validate_no_self_membership`] self-loop gate at
2446    /// `m.caixa == parent_nome`) — five open-coded field-accesses that
2447    /// expressed no compile-time link back to the typed slot. Every
2448    /// caixa-mesh `metadata.name` derived from a `:membros :caixa`
2449    /// value flows through the [`caixa_mesh::fleet_programs`] per-entry
2450    /// `name:` axis, so a future extension of the `:membros :caixa`
2451    /// axis to a richer author surface — a per-cluster alias table the
2452    /// operator pins through a future `:placement`-scoped slot, a
2453    /// namespace-qualified rewrite the M4 CR materializer applies
2454    /// per-CR, a per-member overlay from the future `:membros
2455    /// :nome-suffix` slot the MESH-COMPOSITION §III.2 roadmap
2456    /// acknowledges — would have had to be threaded through every
2457    /// open-coded copy in lockstep or one consumer would silently
2458    /// disagree with the peers on which caixa a given member resolves
2459    /// to. A member-set lookup that treated the name as `"cart"` while
2460    /// the peer adjacency map treated it as `"tenant-a/cart"` would
2461    /// silently split the `:contratos` membership-lookup diagnostic from
2462    /// the cycle-detector's node identity — a two-consumer split at the
2463    /// validator far from the source `caixa.lisp` with no field naming
2464    /// the identity-drift root cause. Lifting the resolution rule to a
2465    /// typed method on the substrate primitive means every downstream
2466    /// consumer of the Aplicacao's per-`:membros` identity surface
2467    /// reaches for exactly one typed dispatch — the resolver's
2468    /// accept-set migrates as a unit on any future axis addition.
2469    ///
2470    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2471    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2472    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2473    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2474    /// destination-Servico scalar accessors — same "one typed dispatch
2475    /// on the substrate primitive, thin projections at each consumer"
2476    /// discipline extended onto the per-`:membros` member-caixa `:nome`
2477    /// byte-string axis. Named `nome()` to match the tatara-lisp
2478    /// author-surface term the field's docstring already reaches for
2479    /// ("Member caixa's `:nome`") and the peer [`crate::Caixa::nome`] /
2480    /// [`crate::dep::Dep::nome`] field-name discipline the substrate
2481    /// already carries — the accessor's name maps directly onto the
2482    /// canonical caixa-identity vocabulary rather than shadowing the
2483    /// field's storage-side `caixa` label.
2484    #[must_use]
2485    pub const fn nome(&self) -> &str {
2486        self.caixa.as_str()
2487    }
2488
2489    /// Substrate-canonical per-`:membros` member-caixa `:versao` semver-
2490    /// requirement scalar accessor every consumer that reads the
2491    /// member's version pin keys off — returns the author-declared
2492    /// `:membros :versao` byte-string verbatim as a `&str`, borrowed
2493    /// from the typed slot's own [`String`] storage.
2494    ///
2495    /// The `:membros :versao` slot carries the Cargo-shaped semver
2496    /// requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`, `"*"`) that
2497    /// pins which release of the member-caixa the Aplicacao composes
2498    /// against — the same requirement grammar the peer `:deps :versao`
2499    /// / `:children :versao` axes carry, resolved through the shared
2500    /// [`crate::render::require_valid_versao_requirement`] cascade and
2501    /// the shared [`crate::version::parse_requirement`] parser. Every
2502    /// downstream consumer that fans on the member's version pin keys
2503    /// off this scalar (the [`validate_membros`] per-member requirement
2504    /// gate at `require_valid_versao_requirement(m.versao_requirement(),
2505    /// …)`, the [`feira app graph`] per-member `println!("    - {} {}",
2506    /// m.nome(), m.versao_requirement())` line, every future per-cluster
2507    /// version-lock overlay the operator pins through a future
2508    /// `:placement`-scoped slot, the future
2509    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-member
2510    /// version resolver, the future `feira app deploy` pipeline's
2511    /// per-member lacre BLAKE3-closure lookup).
2512    ///
2513    /// Prior to this lift the `.versao` byte-string was accessed inline
2514    /// at two `&str`-shaped sites — the [`validate_membros`]
2515    /// requirement-gate call `require_valid_versao_requirement(&m.versao,
2516    /// …)` and the `feira app graph` per-member printer's `println!(
2517    /// "    - {} {}", m.caixa, m.versao)` (caixa-feira/src/cmd/app.rs:78
2518    /// prior to this lift) — two open-coded field-accesses that expressed
2519    /// no compile-time link back to the typed slot. A future extension of
2520    /// the `:membros :versao` axis to a richer author surface (a
2521    /// per-cluster version-pin overlay per MESH-COMPOSITION §III.2 canary
2522    /// flow, a lacre-projected concrete-version rewrite the operator
2523    /// materializes at CR-admission time, a future `:membros :versao-lock`
2524    /// per-cluster override slot) would have had to be threaded through
2525    /// every open-coded copy in lockstep or one consumer would silently
2526    /// disagree with the peers on which release constraint a given
2527    /// member resolves to. Lifting the resolution rule to a typed method
2528    /// on the substrate primitive means every downstream requirement-
2529    /// facing consumer reaches for exactly one typed dispatch — the
2530    /// resolver's accept-set migrates as a unit on any future axis
2531    /// addition.
2532    ///
2533    /// Sibling of the peer per-`:membros` [`Membro::nome`] (4a32abf)
2534    /// member-caixa `:nome` scalar accessor — the pair
2535    /// `(nome(), versao_requirement())` jointly projects the
2536    /// `(caixa, versao)` field pair every renderer that fans on
2537    /// per-member identity + version pin keys off, closing the last
2538    /// unlifted per-`:membros` scalar axis so every downstream
2539    /// per-`:membros` reader now routes through a typed dispatch on the
2540    /// substrate primitive. Named `versao_requirement()` rather than
2541    /// `versao()` because the field's storage-side `.versao` label is
2542    /// already the author-surface term (`:versao`); the accessor's name
2543    /// carries the semantic role — the semver *requirement* string the
2544    /// shared [`crate::version::parse_requirement`] entry-point consumes
2545    /// — so a raw field access and a typed dispatch read differently at
2546    /// every consumer site.
2547    ///
2548    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
2549    /// [`WitContract::destination`] (7f0fd43) caller/callee-Servico
2550    /// scalar-accessor pair and per-`:entrada` [`Entrada::destination`]
2551    /// (6db982c) / [`Entrada::hostname`] (11f3dfe) DNS-hostname /
2552    /// destination-Servico scalar accessors — same "one typed dispatch
2553    /// on the substrate primitive, thin projections at each consumer"
2554    /// discipline extended onto the per-`:membros` member-`:versao`
2555    /// semver-requirement byte-string axis.
2556    #[must_use]
2557    pub const fn versao_requirement(&self) -> &str {
2558        self.versao.as_str()
2559    }
2560}
2561
2562// ── mesh-level policies ──────────────────────────────────────────────
2563
2564/// Mesh policies that apply to every `:contratos` edge unless
2565/// overridden per-edge in M4. V0 is a single global policy block.
2566#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
2567#[serde(rename_all = "camelCase")]
2568pub struct MeshPolicy {
2569    /// Per-call timeout. Authored as a duration string (`"30s"`).
2570    #[serde(
2571        default,
2572        skip_serializing_if = "Option::is_none",
2573        with = "supervisor::duration_codec"
2574    )]
2575    pub timeout: Option<Duration>,
2576
2577    /// Number of retries on transient failure. None = no retries.
2578    #[serde(default, skip_serializing_if = "Option::is_none")]
2579    pub retries: Option<u32>,
2580
2581    /// Circuit breaker config. Trips after N failures within W
2582    /// duration; closes after a cooldown.
2583    #[serde(default, skip_serializing_if = "Option::is_none")]
2584    pub circuit_breaker: Option<CircuitBreaker>,
2585
2586    /// Whether mTLS is required for every contrato. Default: true
2587    /// (sandboxing-by-default; explicit opt-out only).
2588    #[serde(default, skip_serializing_if = "Option::is_none")]
2589    pub mtls_required: Option<bool>,
2590
2591    /// Token-bucket rate limit. Authored as `"100/s"` or
2592    /// `"5000/m"`; stored as `(rate, window)`.
2593    #[serde(
2594        default,
2595        skip_serializing_if = "Option::is_none",
2596        with = "rate_limit_codec"
2597    )]
2598    pub rate_limit: Option<RateLimit>,
2599}
2600
2601impl MeshPolicy {
2602    /// True when no `:politicas` axis carries a value — every field is
2603    /// `None`. The same emptiness contract every other M2/M3 typed
2604    /// surface carries ([`crate::LimitsSpec::is_empty`],
2605    /// [`crate::BehaviorSpec::is_empty`]): renderers that overlay the
2606    /// typed slot onto a cluster artifact key off this predicate to
2607    /// decide "emit the slot" vs "skip the slot entirely", so an
2608    /// authored-but-unset `:politicas (())` round-trips to a rendered
2609    /// artifact that's structurally identical to one that omits the
2610    /// slot. Lifted as a typed predicate (rather than per-renderer
2611    /// inline `politicas.timeout.is_none() && politicas.retries.is_none()
2612    /// && …` chains) so a future axis added to `MeshPolicy` (per-edge
2613    /// :politicas overlay in M4, per-Aplicacao traffic-shaping in M5)
2614    /// is one struct-field edit + one `&& self.<axis>.is_none()` here,
2615    /// not a coordinated rewrite of every consumer that's reaching
2616    /// for the emptiness semantic.
2617    #[must_use]
2618    pub const fn is_empty(&self) -> bool {
2619        self.timeout().is_none()
2620            && self.retries().is_none()
2621            && self.circuit_breaker().is_none()
2622            && self.mtls_required().is_none()
2623            && self.rate_limit().is_none()
2624    }
2625
2626    /// Substrate-canonical per-`:politicas` `:timeout` Gateway-API-mesh
2627    /// per-call-deadline scalar accessor every consumer of the
2628    /// Aplicacao's Gateway API v1.x per-rule request-timeout keys off —
2629    /// returns the author-declared `:politicas :timeout` typed
2630    /// [`Duration`] verbatim as an `Option<Duration>`, copied out of the
2631    /// typed slot's own `Option<Duration>` storage (`Option<Duration>`
2632    /// is `Copy`, so the accessor returns by value; no borrow of
2633    /// `&self` past the call). `None` when the slot is absent (the
2634    /// "cluster default applies — typically the gateway class's
2635    /// implementation-side per-request wall-clock cap" arm caixa-mesh's
2636    /// `timeout_overlay` builder documents at caixa-mesh/src/lib.rs:2911
2637    /// — [`MeshPolicy::is_empty`]'s `timeout.is_none()` arm reads this
2638    /// predicate too, so an authored-but-unset `:politicas (:timeout ())`
2639    /// round-trips to a rendered `HTTPRoute` structurally identical to
2640    /// one that omits the slot).
2641    ///
2642    /// The `:politicas :timeout` slot carries the "no infinite blocking"
2643    /// per-call deadline contract (MESH-COMPOSITION §V CSE invariant) —
2644    /// the typed slot's `Option<Duration>` accept-set (zero-floor
2645    /// rejected through [`AplicacaoError::PolicyTimeoutZero`], canonical-
2646    /// form rejected through [`AplicacaoError::PolicyTimeoutNotCanonical`],
2647    /// upper-bounded by [`POLICY_TIMEOUT_MAX`]) maps onto the Gateway API
2648    /// v1.x `HTTPRoute.spec.rules[].timeouts.request` per-rule request-
2649    /// deadline scalar the caixa-mesh `timeout_overlay` builder writes.
2650    /// Every downstream consumer that reads the per-call cap keys off
2651    /// this scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2652    /// renderers key off to decide "emit :politicas overlay" vs "skip
2653    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2654    /// `timeouts.request` builder at caixa-mesh/src/lib.rs:2979 that
2655    /// fans the deadline into every rule via
2656    /// [`crate::render::single_field_overlay`], the future M4 per-
2657    /// Aplicacao Gateway API reconciler materialization pass, the
2658    /// future per-`:contratos`-edge timeout-override overlay the
2659    /// MESH-COMPOSITION §III.2 roadmap acknowledges).
2660    ///
2661    /// Prior to this lift the `.timeout` field was accessed inline at
2662    /// two sites — [`MeshPolicy::is_empty`]'s `self.timeout.is_none()`
2663    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.timeout,
2664    /// …)` call — two open-coded field-accesses that expressed no
2665    /// compile-time link back to the typed slot. A future extension of
2666    /// the `:politicas :timeout` axis to a richer author surface — a
2667    /// per-`:contratos`-edge timeout override the operator pins through
2668    /// a future `:contratos :timeout` slot the MESH-COMPOSITION §III.2
2669    /// roadmap acknowledges, a per-cluster timeout-default overlay the
2670    /// M4 CR materializer resolves per-CR, a split of the single
2671    /// per-call `Duration` into a richer `{request, backendRequest}`
2672    /// pair once the Gateway API's per-rule `timeouts` block grows the
2673    /// upstream-facing backendRequest arm alongside the client-facing
2674    /// request arm — would have had to be threaded through both open-
2675    /// coded copies in lockstep or the emptiness predicate and the
2676    /// caixa-mesh emit path would silently disagree on which per-call
2677    /// deadline a given [`MeshPolicy`] resolves to (a `:politicas` block
2678    /// whose only axis is a `Some :timeout` would satisfy `is_empty()
2679    /// == false` while the renderer's overlay-emit path silently read
2680    /// a drifted other value, or vice versa: an author's `:timeout
2681    /// "30s"` would omit the `HTTPRoute` `timeouts.request` block while
2682    /// the emptiness predicate still classified the policy as non-
2683    /// empty, and every `kubectl -n tatara-system get httproute -o yaml
2684    /// | grep -A2 timeouts` audit would land on a route whose author's
2685    /// typed slot value silently vanished at the renderer layer).
2686    /// Lifting the resolution to a typed method on the substrate
2687    /// primitive means every downstream consumer of the Aplicacao's
2688    /// per-`:politicas` deadline surface reaches for exactly one typed
2689    /// dispatch — the resolver's accept-set migrates as a unit on any
2690    /// future axis addition.
2691    ///
2692    /// Third `Option<Copy-T>`-return accessor on the M3 mesh-slot
2693    /// family (sibling of the peer per-`:politicas`
2694    /// [`MeshPolicy::retries`] bdfb399 `Option<u32>` accessor and the
2695    /// per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1
2696    /// `Option<bool>` accessor — same "one typed dispatch on the
2697    /// substrate primitive, thin projections at each consumer"
2698    /// discipline extended onto the peer per-`:politicas` typed-
2699    /// [`Duration`] optional-scalar axis; closes the "optional per-slot
2700    /// numeric-Copy-T scalar" projection pattern the sibling
2701    /// `Option<u32>` / `Option<bool>` lifts opened, since every
2702    /// remaining `MeshPolicy` axis (`circuit_breaker: Option<CircuitBreaker>`,
2703    /// `rate_limit: Option<RateLimit>`) carries a struct payload rather
2704    /// than a scalar). Named `timeout()` to match the storage field's
2705    /// name; the accessor's identity maps onto the canonical MESH-
2706    /// COMPOSITION §III.2 vocabulary the slot's docstring already carries.
2707    #[must_use]
2708    pub const fn timeout(&self) -> Option<Duration> {
2709        self.timeout
2710    }
2711
2712    /// Substrate-canonical per-`:politicas` `:retries` transient-failure-
2713    /// retry-budget scalar accessor every consumer of the Aplicacao's
2714    /// Gateway API v1.x per-rule retry-cap keys off — returns the
2715    /// author-declared `:politicas :retries` typed `u32` verbatim as an
2716    /// `Option<u32>`, copied out of the typed slot's own `Option<u32>`
2717    /// storage (`Option<u32>` is `Copy`, so the accessor returns by
2718    /// value; no borrow of `&self` past the call). `None` when the slot
2719    /// is absent (the "cluster default applies — typically 'no retries
2720    /// beyond a single dispatch attempt'" arm the caixa-mesh
2721    /// `retry_overlay` builder documents at caixa-mesh/src/lib.rs:2985
2722    /// — [`MeshPolicy::is_empty`]'s `retries.is_none()` arm reads
2723    /// this predicate too, so an authored-but-unset `:politicas
2724    /// (:retries ())` round-trips to a rendered `HTTPRoute` structurally
2725    /// identical to one that omits the slot).
2726    ///
2727    /// The `:politicas :retries` slot carries the "transient failure
2728    /// retry cap" contract (MESH-COMPOSITION §III.2 #2) — the typed
2729    /// slot's `Option<u32>` accept-set (lower-bounded by 1 through
2730    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2731    /// [`POLICY_RETRIES_MAX`]) maps onto the Gateway API v1.x
2732    /// `HTTPRoute.spec.rules[].retry.attempts` per-rule retry-attempt-
2733    /// count scalar the caixa-mesh `retry_overlay` builder writes.
2734    /// Every downstream consumer that reads the retry cap keys off this
2735    /// scalar (the [`MeshPolicy::is_empty`] emptiness predicate the
2736    /// renderers key off to decide "emit :politicas overlay" vs "skip
2737    /// entirely", the caixa-mesh per-`:entrada` `HTTPRoute`
2738    /// `retry.attempts` builder at caixa-mesh/src/lib.rs:3007 that fans
2739    /// the value into every rule via [`crate::render::single_field_overlay`],
2740    /// the future M4 per-Aplicacao Gateway API reconciler
2741    /// materialization pass, the future per-`:contratos`-edge retry-
2742    /// override overlay the MESH-COMPOSITION §III.2 #2 roadmap
2743    /// acknowledges).
2744    ///
2745    /// Prior to this lift the `.retries` field was accessed inline at
2746    /// two sites — [`MeshPolicy::is_empty`]'s `self.retries.is_none()`
2747    /// arm and caixa-mesh's `single_field_overlay(spec.politicas.retries,
2748    /// …)` call — two open-coded field-accesses that expressed no
2749    /// compile-time link back to the typed slot. A future extension of
2750    /// the `:politicas :retries` axis to a richer author surface — a
2751    /// per-`:contratos`-edge retry override the operator pins through a
2752    /// future `:contratos :retries` slot, a per-cluster retry-default
2753    /// overlay the M4 CR materializer resolves per-CR, a promotion of
2754    /// the plain `u32` attempt-count to a richer `{attempts, codes,
2755    /// backoff}` sub-block once the Gateway API grows the peer
2756    /// `retry.codes` / `retry.backoff` axes — would have had to be
2757    /// threaded through both open-coded copies in lockstep or the
2758    /// emptiness predicate and the caixa-mesh emit path would silently
2759    /// disagree on which retry budget a given [`MeshPolicy`] resolves to
2760    /// (a `:politicas` block whose only axis is a `Some :retries` would
2761    /// satisfy `is_empty() == false` while the renderer's overlay-emit
2762    /// path silently read a drifted other value, or vice versa: an
2763    /// author's `:retries 3` would omit the `HTTPRoute` `retry.attempts`
2764    /// block while the emptiness predicate still classified the policy
2765    /// as non-empty). Lifting the resolution to a typed method on the
2766    /// substrate primitive means every downstream consumer of the
2767    /// Aplicacao's per-`:politicas` retry surface reaches for exactly
2768    /// one typed dispatch — the resolver's accept-set migrates as a
2769    /// unit on any future axis addition.
2770    ///
2771    /// Second `Option<Copy-T>`-return accessor on the M3 mesh-slot
2772    /// family (sibling of the peer per-`:politicas`
2773    /// [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` accessor —
2774    /// same "one typed dispatch on the substrate primitive, thin
2775    /// projections at each consumer" discipline extended onto the
2776    /// peer per-`:politicas` typed-`u32` optional-scalar axis; opens
2777    /// the "optional per-slot numeric-Copy-T scalar" projection pattern
2778    /// the sibling per-`:politicas` `:timeout` (Option<Duration>) /
2779    /// per-`CircuitBreaker` `:max-failures` / `:window` future lifts
2780    /// fold on). Named `retries()` to match the storage field's name;
2781    /// the accessor's identity maps onto the canonical MESH-COMPOSITION
2782    /// §III.2 vocabulary the slot's docstring already carries.
2783    #[must_use]
2784    pub const fn retries(&self) -> Option<u32> {
2785        self.retries
2786    }
2787
2788    /// Substrate-canonical per-`:politicas` `:mtls-required` mTLS-
2789    /// enforcement-toggle scalar accessor every consumer of the
2790    /// Aplicacao's Cilium-mesh L4 mutual-authentication policy keys off
2791    /// — returns the author-declared `:politicas :mtls-required` typed
2792    /// bool verbatim as an `Option<bool>`, copied out of the typed
2793    /// slot's own `Option<bool>` storage (`Option<bool>` is `Copy`, so
2794    /// the accessor returns by value; no borrow of `&self` past the
2795    /// call). `None` when the slot is absent (the "cluster default
2796    /// applies — typically 'disabled' cluster-wide" arm the caixa-mesh
2797    /// `mtls_overlay` builder documents at caixa-mesh/src/lib.rs:2540
2798    /// — [`MeshPolicy::is_empty`]'s `mtls_required.is_none()` arm reads
2799    /// this predicate too, so an authored-but-unset `:politicas
2800    /// (:mtls-required ())` round-trips to a rendered
2801    /// `CiliumNetworkPolicy` structurally identical to one that omits
2802    /// the slot).
2803    ///
2804    /// The `:politicas :mtls-required` slot carries the "explicit opt-
2805    /// out only, sandboxing-by-default" mTLS-enforcement toggle
2806    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's three-way
2807    /// `{None, Some(true), Some(false)}` accept-set maps onto the
2808    /// Cilium `authentication.mode` bijection through
2809    /// [`crate::cilium_auth_mode`]: `Some(true) → "required"` (mTLS
2810    /// handshake enforced), `Some(false) → "disabled"` (handshake
2811    /// skipped — the debug-edge opt-out), `None` → omit the block
2812    /// (cluster default applies). Every downstream consumer that
2813    /// reads the toggle keys off this scalar (the
2814    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2815    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2816    /// caixa-mesh per-`(:de, :para)` CNP `mtls_overlay` builder at
2817    /// caixa-mesh/src/lib.rs:2549 that fans the toggle into every
2818    /// ingress rule via [`crate::render::single_field_overlay`], the
2819    /// future M4 per-Aplicacao Cilium `authentication.mode` reconciler
2820    /// materialization pass, the future per-`:contratos`-edge mTLS
2821    /// override MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2822    ///
2823    /// Prior to this lift the `.mtls_required` field was accessed
2824    /// inline at two sites — [`MeshPolicy::is_empty`]'s
2825    /// `self.mtls_required.is_none()` arm and caixa-mesh's
2826    /// `single_field_overlay(spec.politicas.mtls_required, …)` call —
2827    /// two open-coded field-accesses that expressed no compile-time
2828    /// link back to the typed slot. A future extension of the
2829    /// `:politicas :mtls-required` axis to a richer author surface —
2830    /// a per-`:contratos`-edge mTLS override the operator pins through
2831    /// a future `:contratos :mtls` slot the MESH-COMPOSITION §III.2
2832    /// #3 roadmap acknowledges, a per-cluster mTLS-default overlay the
2833    /// M4 CR materializer resolves per-CR, a three-valued
2834    /// `{None, Some(true), Some(false), Some(Optional)}` promotion
2835    /// once Cilium's `authentication.mode` grows an `"optional"` arm —
2836    /// would have had to be threaded through both open-coded copies in
2837    /// lockstep or the emptiness predicate and the caixa-mesh emit
2838    /// path would silently disagree on which toggle a given
2839    /// [`MeshPolicy`] resolves to (a `:politicas` block whose only
2840    /// axis is a `Some`
2841    /// `:mtls-required` would satisfy `is_empty() == false` while the
2842    /// renderer's overlay-emit path silently read a drifted other
2843    /// value, or vice versa). Lifting the resolution to a typed method
2844    /// on the substrate primitive means every downstream consumer of
2845    /// the Aplicacao's per-`:politicas` mTLS-toggle surface reaches
2846    /// for exactly one typed dispatch — the resolver's accept-set
2847    /// migrates as a unit on any future axis addition.
2848    ///
2849    /// First `Option<Copy-T>`-return accessor on the M3 mesh-slot
2850    /// family (peer of the sibling per-`:placement`
2851    /// [`Placement::shard_key`] 7cd2a28 `Option<&str>` accessor —
2852    /// same "one typed dispatch on the substrate primitive, thin
2853    /// projections at each consumer" discipline extended onto the
2854    /// peer per-`:politicas` typed-bool optional-scalar axis; opens
2855    /// the "optional per-slot Copy-T scalar" projection pattern the
2856    /// sibling per-`:politicas` `:retries` (Option<u32>) /
2857    /// `:timeout` (Option<Duration>) future lifts fold on). Named
2858    /// `mtls_required()` to match the storage field's name; the
2859    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2860    /// §III.2 vocabulary the slot's docstring already carries.
2861    #[must_use]
2862    pub const fn mtls_required(&self) -> Option<bool> {
2863        self.mtls_required
2864    }
2865
2866    /// Substrate-canonical per-`:politicas` `:rate-limit` Envoy-
2867    /// `local_rate_limit`-mesh token-bucket-declaration scalar
2868    /// accessor every consumer of the Aplicacao's per-`:politicas`
2869    /// per-`(rate, window)` rate-limit surface keys off — returns the
2870    /// author-declared `:politicas :rate-limit` typed [`RateLimit`]
2871    /// verbatim as an `Option<RateLimit>`, copied out of the typed
2872    /// slot's own `Option<RateLimit>` storage ([`RateLimit`] is
2873    /// `Copy`, so the accessor returns by value; no borrow of `&self`
2874    /// past the call). `None` when the slot is absent (the "cluster
2875    /// default applies — typically 'no per-Aplicacao rate declaration,
2876    /// gateway-class per-listener default applies'" arm the future
2877    /// caixa-mesh `local_rate_limit_overlay` emitter MESH-COMPOSITION
2878    /// §III.2 #3 names — [`MeshPolicy::is_empty`]'s
2879    /// `rate_limit().is_none()` arm reads this predicate too, so an
2880    /// authored-but-unset `:politicas (:rate-limit ())` round-trips
2881    /// to a rendered `CiliumClusterwideEnvoyConfig` structurally
2882    /// identical to one that omits the slot).
2883    ///
2884    /// The `:politicas :rate-limit` slot carries the "per-Aplicacao
2885    /// token-bucket rate declaration" contract (MESH-COMPOSITION
2886    /// §III.2 #3) — the typed slot's `Option<RateLimit>` accept-set
2887    /// (rate lower-bounded by 1 through
2888    /// [`AplicacaoSpec::validate_politicas`], upper-bounded by
2889    /// [`POLICY_RATE_LIMIT_MAX`], window canonically bijected to the
2890    /// three-unit `{"s", "m", "h"}` [`rate_limit_codec`] table through
2891    /// [`is_canonical_rate_limit_window`]) maps onto the Envoy
2892    /// `local_rate_limit.token_bucket.{max_tokens, fill_interval}`
2893    /// bijection the future `CiliumClusterwideEnvoyConfig` per-
2894    /// `:politicas` overlay emits. Every downstream consumer that
2895    /// reads the rate declaration keys off this scalar (the
2896    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2897    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2898    /// [`AplicacaoSpec::validate_politicas`] per-value-shape gate that
2899    /// brackets `rl.rate` against [`POLICY_RATE_LIMIT_MAX`] and pins
2900    /// `rl.window` against [`is_canonical_rate_limit_window`], the
2901    /// future M4 per-Aplicacao Envoy reconciler materialization pass,
2902    /// the future per-`:contratos`-edge rate-limit override the
2903    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2904    ///
2905    /// Prior to this lift the `.rate_limit` field was accessed inline
2906    /// at two sites — [`MeshPolicy::is_empty`]'s
2907    /// `self.rate_limit.is_none()` arm and the `validate_politicas`
2908    /// gate's `if let Some(rl) = &p.rate_limit` bind — two open-coded
2909    /// field-accesses that expressed no compile-time link back to the
2910    /// typed slot. A future extension of the `:politicas :rate-limit`
2911    /// axis to a richer author surface — a per-`:contratos`-edge
2912    /// rate-limit override the operator pins through a future
2913    /// `:contratos :rate-limit` slot the MESH-COMPOSITION §III.2 #3
2914    /// roadmap acknowledges, a per-cluster rate-limit-default overlay
2915    /// the M4 CR materializer resolves per-CR, a promotion of the
2916    /// plain `(rate, window)` scalar pair to a richer
2917    /// `{rate, window, burst, key}` sub-block once Envoy's
2918    /// `local_rate_limit` grows the peer `burst_size` /
2919    /// `descriptor_key` axes — would have had to be threaded through
2920    /// both open-coded copies in lockstep or the emptiness predicate
2921    /// and the validate gate would silently disagree on which rate
2922    /// declaration a given [`MeshPolicy`] resolves to (a `:politicas`
2923    /// block whose only axis is a `Some :rate-limit` would satisfy
2924    /// `is_empty() == false` while the validate path silently read a
2925    /// drifted other value, or vice versa: an author's
2926    /// `:rate-limit "100/s"` would omit the value-shape gate while the
2927    /// emptiness predicate still classified the policy as non-empty).
2928    /// Lifting the resolution to a typed method on the substrate
2929    /// primitive means every downstream consumer of the Aplicacao's
2930    /// per-`:politicas` rate-limit surface reaches for exactly one
2931    /// typed dispatch — the resolver's accept-set migrates as a unit
2932    /// on any future axis addition.
2933    ///
2934    /// First `Option<Copy-composite-T>`-return accessor on the M3
2935    /// mesh-slot family — closes the last un-lifted per-`:politicas`
2936    /// scalar-value axis. Peer of the sibling per-`:politicas`
2937    /// [`MeshPolicy::timeout`] (7073d0f) / [`MeshPolicy::retries`]
2938    /// (bdfb399) / [`MeshPolicy::mtls_required`] (c0110f1)
2939    /// `Option<Copy-T>` accessors on the primitive-Copy axes — same
2940    /// "one typed dispatch on the substrate primitive, thin
2941    /// projections at each consumer" discipline extended onto the
2942    /// peer per-`:politicas` composite-Copy shape (`RateLimit` is
2943    /// `#[derive(Copy)]`; peer of [`CircuitBreaker`] which lives
2944    /// behind [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
2945    /// sub-accessors rather than a top-level accessor because
2946    /// consumers reach for the axes not the aggregate). Named
2947    /// `rate_limit()` to match the storage field's name; the
2948    /// accessor's identity maps onto the canonical MESH-COMPOSITION
2949    /// §III.2 vocabulary the slot's docstring already carries.
2950    #[must_use]
2951    pub const fn rate_limit(&self) -> Option<RateLimit> {
2952        self.rate_limit
2953    }
2954
2955    /// Substrate-canonical per-`:politicas` `:circuit-breaker`
2956    /// Envoy-`outlier_detection`-mesh consecutive-failure-ejection-
2957    /// declaration scalar accessor every consumer of the Aplicacao's
2958    /// per-`:politicas` breaker declaration keys off — returns the
2959    /// author-declared `:politicas :circuit-breaker` typed
2960    /// [`CircuitBreaker`] verbatim as an `Option<CircuitBreaker>`,
2961    /// copied out of the typed slot's own `Option<CircuitBreaker>`
2962    /// storage ([`CircuitBreaker`] is `Copy`, so the accessor returns
2963    /// by value; no borrow of `&self` past the call). `None` when the
2964    /// slot is absent (the "cluster default applies — typically 'no
2965    /// per-Aplicacao breaker declaration, gateway-class per-listener
2966    /// default applies'" arm the future caixa-mesh
2967    /// `outlier_detection_overlay` emitter MESH-COMPOSITION §III.2 #3
2968    /// names — [`MeshPolicy::is_empty`]'s `circuit_breaker().is_none()`
2969    /// arm reads this predicate too, so an authored-but-unset
2970    /// `:politicas (:circuit-breaker ())` round-trips to a rendered
2971    /// `CiliumClusterwideEnvoyConfig` structurally identical to one
2972    /// that omits the slot).
2973    ///
2974    /// The `:politicas :circuit-breaker` slot carries the
2975    /// "per-Aplicacao consecutive-transient-failure trip declaration"
2976    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
2977    /// `Option<CircuitBreaker>` accept-set (per-`:max-failures`
2978    /// zero-floor rejected through
2979    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
2980    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]; per-`:window` zero-floor
2981    /// rejected through [`AplicacaoError::PolicyBreakerZeroWindow`],
2982    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`],
2983    /// canonical-form pinned through
2984    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`]) maps onto
2985    /// the Envoy `outlier_detection.{consecutive_5xx, interval}`
2986    /// bijection the future `CiliumClusterwideEnvoyConfig`
2987    /// per-`:politicas` overlay emits. Every downstream consumer that
2988    /// reads the breaker declaration keys off this scalar (the
2989    /// [`MeshPolicy::is_empty`] emptiness predicate the renderers key
2990    /// off to decide "emit :politicas overlay" vs "skip entirely", the
2991    /// [`AplicacaoSpec::validate_politicas`] per-sub-struct-axis gate
2992    /// that brackets `cb.max_failures()` against
2993    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`] and `cb.window()` against
2994    /// [`POLICY_BREAKER_WINDOW_MAX`] via
2995    /// [`crate::render::require_positive_canonical_bounded_duration`],
2996    /// the future M4 per-Aplicacao Envoy reconciler materialization
2997    /// pass, the future per-`:contratos`-edge breaker override the
2998    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
2999    ///
3000    /// Prior to this lift the `.circuit_breaker` field was accessed
3001    /// inline at two sites — [`MeshPolicy::is_empty`]'s
3002    /// `self.circuit_breaker.is_none()` arm and the
3003    /// `validate_politicas` gate's `if let Some(cb) = &p.circuit_breaker`
3004    /// bind — two open-coded field-accesses that expressed no
3005    /// compile-time link back to the typed slot. A future extension of
3006    /// the `:politicas :circuit-breaker` axis to a richer author
3007    /// surface — a per-`:contratos`-edge breaker override the operator
3008    /// pins through a future `:contratos :circuit-breaker` slot the
3009    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a per-cluster
3010    /// breaker-default overlay the M4 CR materializer resolves per-CR,
3011    /// a promotion of the plain `(max_failures, window)` scalar pair to
3012    /// a richer `{max_failures, window, base_ejection_time, max_ejection_percent}`
3013    /// sub-block once Envoy's `outlier_detection` grows the peer
3014    /// ejection-percentage / ejection-time axes — would have had to be
3015    /// threaded through both open-coded copies in lockstep or the
3016    /// emptiness predicate and the validate gate would silently
3017    /// disagree on which breaker declaration a given [`MeshPolicy`]
3018    /// resolves to (a `:politicas` block whose only axis is a
3019    /// `Some :circuit-breaker` would satisfy `is_empty() == false` while
3020    /// the validate path silently read a drifted other value, or vice
3021    /// versa: an author's `(:circuit-breaker (:max-failures 5 :window
3022    /// "60s"))` would omit the value-shape gate while the emptiness
3023    /// predicate still classified the policy as non-empty). Lifting
3024    /// the resolution to a typed method on the substrate primitive
3025    /// means every downstream consumer of the Aplicacao's
3026    /// per-`:politicas` breaker surface reaches for exactly one typed
3027    /// dispatch — the resolver's accept-set migrates as a unit on any
3028    /// future axis addition.
3029    ///
3030    /// Second `Option<Copy-composite-T>`-return accessor on the M3
3031    /// mesh-slot family (sibling of the peer per-`:politicas`
3032    /// [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>` accessor
3033    /// on the same composite-Copy shape, and of the sibling per-
3034    /// `:politicas` [`MeshPolicy::timeout`] 7073d0f
3035    /// `Option<Duration>` / [`MeshPolicy::retries`] bdfb399
3036    /// `Option<u32>` / [`MeshPolicy::mtls_required`] c0110f1
3037    /// `Option<bool>` accessors on the sibling primitive-Copy axes —
3038    /// same "one typed dispatch on the substrate primitive, thin
3039    /// projections at each consumer" discipline extended onto the last
3040    /// unlifted per-`:politicas` scalar-value axis (the composite-Copy
3041    /// `Option<CircuitBreaker>` arm). Named `circuit_breaker()` to
3042    /// match the storage field's name; the accessor's identity maps
3043    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3044    /// docstring already carries. Closes the last unlifted
3045    /// [`MeshPolicy`] accessor axis so every downstream per-`:politicas`
3046    /// reader now routes through a typed dispatch on the substrate
3047    /// primitive.
3048    #[must_use]
3049    pub const fn circuit_breaker(&self) -> Option<CircuitBreaker> {
3050        self.circuit_breaker
3051    }
3052}
3053
3054#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
3055#[serde(rename_all = "camelCase")]
3056pub struct CircuitBreaker {
3057    pub max_failures: u32,
3058    #[serde(with = "supervisor::duration_codec_required")]
3059    pub window: Duration,
3060}
3061
3062impl CircuitBreaker {
3063    /// Substrate-canonical per-`:politicas :circuit-breaker`
3064    /// `:max-failures` Envoy-outlier-detection trip-threshold scalar
3065    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3066    /// breaker trip-count keys off — returns the author-declared
3067    /// `:politicas :circuit-breaker :max-failures` typed `u32` verbatim,
3068    /// copied out of the typed slot's own `u32` storage (`u32` is `Copy`,
3069    /// so the accessor returns by value; no borrow of `&self` past the
3070    /// call). Non-optional (the surrounding `Option<CircuitBreaker>` is
3071    /// the "slot present?" projection at the parent [`MeshPolicy::circuit_breaker`]
3072    /// axis; a `CircuitBreaker` past pattern-match is definitionally
3073    /// present, and its `:max-failures` field carries the trip count as a
3074    /// required-axis scalar).
3075    ///
3076    /// The `:politicas :circuit-breaker :max-failures` axis carries the
3077    /// "consecutive-transient-failure trip threshold" contract
3078    /// (MESH-COMPOSITION §III.2 #3) — the typed slot's `u32` accept-set
3079    /// (zero-floor rejected through
3080    /// [`AplicacaoError::PolicyBreakerZeroFailures`], upper-bounded by
3081    /// [`POLICY_BREAKER_MAX_FAILURES_MAX`]) maps onto the Envoy
3082    /// `outlier_detection.consecutive_5xx` per-cluster ejection-threshold
3083    /// scalar (equivalently the future `CiliumClusterwideEnvoyConfig`
3084    /// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 acknowledges).
3085    /// Every downstream consumer that reads the trip threshold keys off
3086    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3087    /// cap bracket at caixa-core/src/aplicacao.rs:4022 that gates on the
3088    /// canonical `require_positive_bounded_u32` helper, the future M4
3089    /// per-Aplicacao Envoy config reconciler materialization pass, the
3090    /// future per-`:contratos`-edge breaker-override overlay the
3091    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3092    ///
3093    /// Prior to this lift the `.max_failures` field was accessed inline
3094    /// at one production site — [`AplicacaoSpec::validate_politicas`]'s
3095    /// `require_positive_bounded_u32(cb.max_failures, …)` call — one
3096    /// open-coded field-access that expressed no compile-time link back
3097    /// to the typed sub-struct axis. A future extension of the
3098    /// `:max-failures` axis to a richer author surface — a
3099    /// per-`:contratos`-edge breaker override the operator pins through a
3100    /// future `:contratos :max-failures` slot the MESH-COMPOSITION §III.2
3101    /// #3 roadmap acknowledges, a per-cluster max-failures-default
3102    /// overlay the M4 CR materializer resolves per-CR, a promotion of the
3103    /// plain `u32` trip count to a richer
3104    /// `{consecutive_5xx, consecutive_gateway_failure, consecutive_local_origin_failure}`
3105    /// tuple once Envoy's `outlier_detection` block's peer axes come into
3106    /// scope, a per-Envoy-cluster minimum-request-volume gate before the
3107    /// count arms — would have had to be threaded through every open-
3108    /// coded copy in lockstep or the validate gate and the future M4
3109    /// emit path would silently disagree on which trip threshold a given
3110    /// [`CircuitBreaker`] resolves to (an author's `:max-failures 5`
3111    /// would satisfy validate while the emit path silently read a drifted
3112    /// other value, or vice versa: a validated typed slot would land at
3113    /// the emit boundary as a no-op breaker whose trip threshold is
3114    /// structurally never reached). Lifting the resolution to a typed
3115    /// method on the substrate primitive means every downstream consumer
3116    /// of the Aplicacao's per-`:politicas :circuit-breaker`
3117    /// trip-threshold surface reaches for exactly one typed dispatch —
3118    /// the resolver's accept-set migrates as a unit on any future axis
3119    /// addition.
3120    ///
3121    /// First sub-struct scalar accessor on the M3 mesh-slot family
3122    /// (opens the "per-`CircuitBreaker` / per-`RateLimit` required-axis
3123    /// scalar" projection pattern the sibling `CircuitBreaker::window` /
3124    /// `RateLimit::rate` / `RateLimit::window` future lifts fold on —
3125    /// closes the last unlifted per-`:politicas` scalar-value axis after
3126    /// the c0110f1 / bdfb399 / 7073d0f trajectory closed every scalar-
3127    /// shaped axis on the parent [`MeshPolicy`] optional-slot surface).
3128    /// Same "one typed dispatch on the substrate primitive, thin
3129    /// projections at each consumer" discipline the peer
3130    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3131    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3132    /// [`Membro::versao_requirement`] (a40b0e3),
3133    /// [`Entrada::destination`] (6db982c) accessors carry on their
3134    /// respective per-mesh-slot-atom scalar-value axes, extended onto the
3135    /// per-sub-struct required-`u32` axis. Named `max_failures()` to
3136    /// match the storage field's name; the accessor's identity maps onto
3137    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3138    /// docstring already carries.
3139    #[must_use]
3140    pub const fn max_failures(&self) -> u32 {
3141        self.max_failures
3142    }
3143
3144    /// Substrate-canonical per-`:politicas :circuit-breaker` `:window`
3145    /// Envoy-outlier-detection rolling-observation-interval scalar
3146    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3147    /// breaker rolling-window duration keys off — returns the
3148    /// author-declared `:politicas :circuit-breaker :window` typed
3149    /// `Duration` verbatim, copied out of the typed slot's own
3150    /// `Duration` storage (`Duration` is `Copy`, so the accessor returns
3151    /// by value; no borrow of `&self` past the call). Non-optional (the
3152    /// surrounding `Option<CircuitBreaker>` is the "slot present?"
3153    /// projection at the parent [`MeshPolicy::circuit_breaker`] axis; a
3154    /// `CircuitBreaker` past pattern-match is definitionally present,
3155    /// and its `:window` field carries the rolling-observation interval
3156    /// as a required-axis scalar).
3157    ///
3158    /// The `:politicas :circuit-breaker :window` axis carries the
3159    /// "consecutive-transient-failure rolling-observation interval"
3160    /// contract (MESH-COMPOSITION §III.2 #3) — the typed slot's
3161    /// `Duration` accept-set (zero-floor rejected through
3162    /// [`AplicacaoError::PolicyBreakerZeroWindow`], sub-millisecond
3163    /// residue rejected through
3164    /// [`AplicacaoError::PolicyBreakerWindowNotCanonical`],
3165    /// upper-bounded by [`POLICY_BREAKER_WINDOW_MAX`]) maps onto the
3166    /// Envoy `outlier_detection.interval` per-cluster
3167    /// ejection-observation-interval scalar (equivalently the future
3168    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3169    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3170    /// consumer that reads the rolling-observation interval keys off
3171    /// this scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3172    /// integer-millisecond canonical-form + cap bracket at
3173    /// caixa-core/src/aplicacao.rs:4121 that gates on the canonical
3174    /// [`crate::render::require_positive_canonical_bounded_duration`]
3175    /// helper, the future M4 per-Aplicacao Envoy config reconciler
3176    /// materialization pass, the future per-`:contratos`-edge
3177    /// breaker-override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3178    /// acknowledges).
3179    ///
3180    /// Prior to this lift the `.window` field was accessed inline at
3181    /// one production site — [`AplicacaoSpec::validate_politicas`]'s
3182    /// `require_positive_canonical_bounded_duration(cb.window, …)`
3183    /// call — one open-coded field-access that expressed no compile-
3184    /// time link back to the typed sub-struct axis. A future extension
3185    /// of the `:window` axis to a richer author surface — a
3186    /// per-`:contratos`-edge window override the operator pins through
3187    /// a future `:contratos :window` slot the MESH-COMPOSITION §III.2
3188    /// #3 roadmap acknowledges, a per-cluster window-default overlay
3189    /// the M4 CR materializer resolves per-CR, a promotion of the plain
3190    /// `Duration` observation interval to a richer
3191    /// `{interval, base_ejection_time, max_ejection_percent}` tuple
3192    /// once Envoy's `outlier_detection` block's peer axes come into
3193    /// scope, a per-Envoy-cluster minimum-request-volume gate before
3194    /// the window arms — would have had to be threaded through every
3195    /// open-coded copy in lockstep or the validate gate and the future
3196    /// M4 emit path would silently disagree on which observation
3197    /// interval a given [`CircuitBreaker`] resolves to (an author's
3198    /// `:window "60s"` would satisfy validate while the emit path
3199    /// silently read a drifted other value, or vice versa: a validated
3200    /// typed slot would land at the emit boundary as a breaker whose
3201    /// observation window is structurally so wide that no realistic
3202    /// failure-rate shape can trip it). Lifting the resolution to a
3203    /// typed method on the substrate primitive means every downstream
3204    /// consumer of the Aplicacao's per-`:politicas :circuit-breaker`
3205    /// observation-window surface reaches for exactly one typed
3206    /// dispatch — the resolver's accept-set migrates as a unit on any
3207    /// future axis addition.
3208    ///
3209    /// Second sub-struct scalar accessor on the M3 mesh-slot family —
3210    /// sibling in shape to the just-landed [`CircuitBreaker::max_failures`]
3211    /// (3a74062) required-`u32` accessor on the peer per-`CircuitBreaker`
3212    /// required-axis, extended onto the per-sub-struct required-`Duration`
3213    /// axis; closes the last unlifted per-`CircuitBreaker` scalar-value
3214    /// axis. Same "one typed dispatch on the substrate primitive, thin
3215    /// projections at each consumer" discipline the peer
3216    /// [`WitContract::source`] / [`WitContract::destination`] (7f0fd43),
3217    /// [`WitContract::world_ref`] (0804823), [`Membro::nome`] (4a32abf),
3218    /// [`Membro::versao_requirement`] (a40b0e3),
3219    /// [`Entrada::destination`] (6db982c) accessors carry on their
3220    /// respective per-mesh-slot-atom scalar-value axes, extended onto
3221    /// the per-sub-struct required-`Duration` axis. Named `window()` to
3222    /// match the storage field's name; the accessor's identity maps onto
3223    /// the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3224    /// docstring already carries.
3225    #[must_use]
3226    pub const fn window(&self) -> Duration {
3227        self.window
3228    }
3229}
3230
3231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3232pub struct RateLimit {
3233    /// Requests per window.
3234    pub rate: u32,
3235    /// Window duration.
3236    pub window: Duration,
3237}
3238
3239impl RateLimit {
3240    /// Substrate-canonical per-`:politicas :rate-limit` `:rate`
3241    /// Envoy-local-rate-limit-mesh token-bucket capacity scalar accessor
3242    /// every consumer of the Aplicacao's per-`:contratos`-edge
3243    /// rate-limit-bucket capacity keys off — returns the author-declared
3244    /// `:politicas :rate-limit` typed `u32` verbatim, copied out of the
3245    /// typed slot's own `u32` storage (`u32` is `Copy`, so the accessor
3246    /// returns by value; no borrow of `&self` past the call). Non-optional
3247    /// (the surrounding `Option<RateLimit>` is the "slot present?"
3248    /// projection at the parent [`MeshPolicy::rate_limit`] axis; a
3249    /// `RateLimit` past pattern-match is definitionally present, and its
3250    /// `:rate` field carries the token-bucket capacity as a required-axis
3251    /// scalar).
3252    ///
3253    /// The `:politicas :rate-limit` `:rate` axis carries the
3254    /// "token-bucket capacity" contract (MESH-COMPOSITION §III.2 #3) —
3255    /// the typed slot's `u32` accept-set (zero-floor rejected through
3256    /// [`AplicacaoError::PolicyRateLimitZero`], upper-bounded by
3257    /// [`POLICY_RATE_LIMIT_MAX`]) maps onto the Envoy
3258    /// `local_rate_limit.token_bucket.max_tokens` per-cluster
3259    /// token-bucket-capacity scalar (equivalently the future
3260    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3261    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3262    /// consumer that reads the token-bucket capacity keys off this
3263    /// scalar (the [`AplicacaoSpec::validate_politicas`] zero-floor +
3264    /// cap bracket that gates on the canonical
3265    /// [`crate::render::require_positive_bounded_u32`] helper, the
3266    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3267    /// emits the `<n>/<s|m|h>` author surface, the future M4
3268    /// per-Aplicacao Envoy config reconciler materialization pass, the
3269    /// future per-`:contratos`-edge rate-limit-override overlay the
3270    /// MESH-COMPOSITION §III.2 #3 roadmap acknowledges).
3271    ///
3272    /// Prior to this lift the `.rate` field was accessed inline at three
3273    /// production sites — [`AplicacaoSpec::validate_politicas`]'s
3274    /// `require_positive_bounded_u32(rl.rate, …)` call, and the two
3275    /// [`rate_limit_codec::render`] format-arm arms (canonical-window
3276    /// `format!("{}/{unit}", rl.rate)` and non-canonical-window
3277    /// `format!("{}/{}s", rl.rate, …)` fallback). Three open-coded
3278    /// field-accesses that expressed no compile-time link back to the
3279    /// typed sub-struct axis. A future extension of the `:rate` axis
3280    /// to a richer author surface — a per-`:contratos`-edge rate
3281    /// override the operator pins through a future `:contratos :rate`
3282    /// slot the MESH-COMPOSITION §III.2 #3 roadmap acknowledges, a
3283    /// per-cluster rate-default overlay the M4 CR materializer resolves
3284    /// per-CR, a promotion of the plain `u32` token capacity to a
3285    /// richer `{max_tokens, tokens_per_fill}` tuple once Envoy's
3286    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3287    /// axis comes into scope, a per-Envoy-cluster descriptor-key gate
3288    /// before the token arms — would have had to be threaded through
3289    /// every open-coded copy in lockstep or the validate gate, the
3290    /// codec's render path, and the future M4 emit path would silently
3291    /// disagree on which token capacity a given [`RateLimit`] resolves
3292    /// to (an author's `:rate-limit "100/s"` would satisfy validate
3293    /// while the render / emit paths silently read a drifted other
3294    /// value, or vice versa: a validated typed slot would land at the
3295    /// emit boundary as a no-op limiter whose token capacity is
3296    /// structurally so high that no realistic per-edge traffic shape
3297    /// can drain it). Lifting the resolution to a typed method on the
3298    /// substrate primitive means every downstream consumer of the
3299    /// Aplicacao's per-`:politicas :rate-limit` token-capacity surface
3300    /// reaches for exactly one typed dispatch — the resolver's
3301    /// accept-set migrates as a unit on any future axis addition.
3302    ///
3303    /// First sub-struct scalar accessor on the `RateLimit` axis — sibling
3304    /// in shape to the peer per-`CircuitBreaker`
3305    /// [`CircuitBreaker::max_failures`] (3a74062) required-`u32` accessor
3306    /// on the peer per-sub-struct required-axis, extended onto the
3307    /// per-`RateLimit` required-`u32` axis; opens the "per-`RateLimit`
3308    /// required-axis scalar" projection pattern the sibling
3309    /// [`RateLimit::window`] future lift folds on. Same "one typed
3310    /// dispatch on the substrate primitive, thin projections at each
3311    /// consumer" discipline the peer [`WitContract::source`] /
3312    /// [`WitContract::destination`] (7f0fd43), [`WitContract::world_ref`]
3313    /// (0804823), [`Membro::nome`] (4a32abf),
3314    /// [`Membro::versao_requirement`] (a40b0e3),
3315    /// [`Entrada::destination`] (6db982c),
3316    /// [`CircuitBreaker::max_failures`] (3a74062),
3317    /// [`CircuitBreaker::window`] (373957f) accessors carry on their
3318    /// respective per-mesh-slot-atom scalar-value axes. Named `rate()`
3319    /// to match the storage field's name; the accessor's identity maps
3320    /// onto the canonical MESH-COMPOSITION §III.2 vocabulary the slot's
3321    /// docstring already carries.
3322    #[must_use]
3323    pub const fn rate(&self) -> u32 {
3324        self.rate
3325    }
3326
3327    /// Substrate-canonical per-`:politicas :rate-limit` `:window`
3328    /// Envoy-local-rate-limit-mesh token-bucket refill-period scalar
3329    /// accessor every consumer of the Aplicacao's per-`:contratos`-edge
3330    /// rate-limit-bucket refill period keys off — returns the
3331    /// author-declared `:politicas :rate-limit` typed `Duration`
3332    /// verbatim, copied out of the typed slot's own `Duration` storage
3333    /// (`Duration` is `Copy`, so the accessor returns by value; no
3334    /// borrow of `&self` past the call). Non-optional (the surrounding
3335    /// `Option<RateLimit>` is the "slot present?" projection at the
3336    /// parent [`MeshPolicy::rate_limit`] axis; a `RateLimit` past
3337    /// pattern-match is definitionally present, and its `:window`
3338    /// field carries the token-bucket refill period as a required-axis
3339    /// scalar).
3340    ///
3341    /// The `:politicas :rate-limit` `:window` axis carries the
3342    /// "token-bucket refill period" contract (MESH-COMPOSITION §III.2 #3)
3343    /// — the typed slot's `Duration` accept-set (constrained to the
3344    /// three canonical windows `{1s, 60s, 3600s}` the
3345    /// [`RATE_LIMIT_UNIT_TABLE`] lifts, rejected off-set through
3346    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]) maps
3347    /// onto the Envoy `local_rate_limit.token_bucket.fill_interval`
3348    /// per-cluster token-bucket-refill-period scalar (equivalently the
3349    /// future `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3350    /// MESH-COMPOSITION §III.2 #3 acknowledges). Every downstream
3351    /// consumer that reads the token-bucket refill period keys off
3352    /// this scalar (the [`AplicacaoSpec::validate_politicas`]
3353    /// canonical-window gate that keys off
3354    /// [`is_canonical_rate_limit_window`], the
3355    /// [`rate_limit_codec::render`] `Duration → unit` projection that
3356    /// emits the `<n>/<s|m|h>` author surface — canonical arm via
3357    /// [`rate_limit_window_unit`] and non-canonical fallback via
3358    /// `.as_secs()`, the future M4 per-Aplicacao Envoy config
3359    /// reconciler materialization pass, the future per-`:contratos`-
3360    /// edge rate-limit-override overlay the MESH-COMPOSITION §III.2 #3
3361    /// roadmap acknowledges).
3362    ///
3363    /// Prior to this lift the `.window` field was accessed inline at
3364    /// three production sites — [`AplicacaoSpec::validate_politicas`]'s
3365    /// `is_canonical_rate_limit_window(rl.window)` shape-gate call
3366    /// plus the sibling [`AplicacaoError::PolicyRateLimitWindowNotCanonical`]
3367    /// error-payload construction on refusal, and the two
3368    /// [`rate_limit_codec::render`] arms
3369    /// (canonical-window `rate_limit_window_unit(rl.window)` dispatch
3370    /// and non-canonical-window `rl.window.as_secs()` fallback). Three
3371    /// open-coded field-accesses that expressed no compile-time link
3372    /// back to the typed sub-struct axis. A future extension of the
3373    /// `:window` axis to a richer author surface — a per-`:contratos`-
3374    /// edge window override the operator pins through a future
3375    /// `:contratos :window` slot the MESH-COMPOSITION §III.2 #3 roadmap
3376    /// acknowledges, a per-cluster window-default overlay the M4 CR
3377    /// materializer resolves per-CR, a promotion of the plain
3378    /// `Duration` refill period to a richer
3379    /// `{fill_interval, tokens_per_fill}` tuple once Envoy's
3380    /// `local_rate_limit.token_bucket` block's peer `tokens_per_fill`
3381    /// axis comes into scope, an addition of a `"d"` day suffix once
3382    /// Envoy's `rate_limit_action` grows daily-bucket support — would
3383    /// have had to be threaded through every open-coded copy in
3384    /// lockstep or the validate gate, the codec's render path, and
3385    /// the future M4 emit path would silently disagree on which
3386    /// refill period a given [`RateLimit`] resolves to (an author's
3387    /// `:rate-limit "100/s"` would satisfy validate while the render
3388    /// / emit paths silently read a drifted other value, or vice
3389    /// versa: a validated typed slot would land at the emit boundary
3390    /// as a limiter whose refill period is structurally so long that
3391    /// no realistic per-edge traffic shape stays inside the token
3392    /// budget). Lifting the resolution to a typed method on the
3393    /// substrate primitive means every downstream consumer of the
3394    /// Aplicacao's per-`:politicas :rate-limit` refill-period surface
3395    /// reaches for exactly one typed dispatch — the resolver's
3396    /// accept-set migrates as a unit on any future axis addition.
3397    ///
3398    /// Second sub-struct scalar accessor on the `RateLimit` axis —
3399    /// sibling in shape to the just-landed [`RateLimit::rate`]
3400    /// (7f81a60) required-`u32` accessor on the peer per-`RateLimit`
3401    /// required-axis, extended onto the per-sub-struct
3402    /// required-`Duration` axis; closes the last unlifted
3403    /// per-`RateLimit` scalar-value axis (the M3 mesh-slot family's
3404    /// per-sub-struct accessor coverage is now complete across both
3405    /// `CircuitBreaker` and `RateLimit`). Same "one typed dispatch on
3406    /// the substrate primitive, thin projections at each consumer"
3407    /// discipline the peer [`CircuitBreaker::max_failures`] (3a74062),
3408    /// [`CircuitBreaker::window`] (373957f), [`RateLimit::rate`]
3409    /// (7f81a60), [`WitContract::source`] / [`WitContract::destination`]
3410    /// (7f0fd43), [`WitContract::world_ref`] (0804823),
3411    /// [`Membro::nome`] (4a32abf),
3412    /// [`Membro::versao_requirement`] (a40b0e3),
3413    /// [`Entrada::destination`] (6db982c) accessors carry on their
3414    /// respective per-mesh-slot-atom scalar-value axes. Named
3415    /// `window()` to match the storage field's name; the accessor's
3416    /// identity maps onto the canonical MESH-COMPOSITION §III.2
3417    /// vocabulary the slot's docstring already carries.
3418    #[must_use]
3419    pub const fn window(&self) -> Duration {
3420        self.window
3421    }
3422
3423    /// Recognize this rate-limit's `:window` as a canonical
3424    /// [`RateLimitUnit`] arm — `Some(RateLimitUnit)` when the window
3425    /// exactly matches one of the three closed-set arm-Durations
3426    /// (`1s` / `60s` / `3600s`), `None` when the window carries a
3427    /// non-canonical magnitude the codec's round-trip would break on
3428    /// (sub-second residue, or a second-magnitude outside the set
3429    /// [`RateLimitUnit::ALL`] enumerates).
3430    ///
3431    /// Every validated [`RateLimit`] past [`AplicacaoSpec::validate_politicas`]
3432    /// returns `Some` here — the validate gate's
3433    /// [`AplicacaoError::PolicyRateLimitWindowNotCanonical`] arm
3434    /// rejects every window this accessor returns `None` on. Downstream
3435    /// consumers past validate (the codec's [`rate_limit_codec::render`]
3436    /// path, the future M4 per-Aplicacao Envoy config reconciler's
3437    /// materialization pass, the future per-`:contratos`-edge rate-limit-
3438    /// override overlay the MESH-COMPOSITION §III.2 #3 roadmap
3439    /// acknowledges) that read the typed unit off a validated slot can
3440    /// pattern-match on the returned `Some` without re-checking
3441    /// canonicality at the consumer layer — the typed enum surface is
3442    /// the load-bearing carrier of the canonicality invariant.
3443    ///
3444    /// Preferred over the free [`is_canonical_rate_limit_window`]
3445    /// module-private helper at any call site that has the typed
3446    /// [`RateLimit`] in hand (the codec's `render` arm at
3447    /// [`rate_limit_codec::render`], the validate gate's canonical-form
3448    /// arm in [`AplicacaoSpec::validate_politicas`], any future
3449    /// per-`:contratos` edge-override overlay resolver): those consumers
3450    /// reach for the typed enum without going through the
3451    /// `.window()` scalar-projection layer, and get the enum value
3452    /// directly (which the codec's render arm can then format via
3453    /// [`RateLimitUnit::as_suffix`] / [`std::fmt::Display`]). Same
3454    /// "typed sub-struct scalar accessor, one dispatch on the substrate
3455    /// primitive" discipline the sibling [`RateLimit::rate`] and
3456    /// [`RateLimit::window`] accessors carry on the peer per-sub-struct
3457    /// scalar-value axes, extended onto the per-`RateLimit` typed-unit
3458    /// projection axis (the third scalar accessor on the [`RateLimit`]
3459    /// axis, first typed-enum-return projection).
3460    ///
3461    /// `pub const fn` — the typed-`RateLimit`-projection dispatch onto
3462    /// the canonical [`RateLimitUnit`] arm now carries the same
3463    /// `const`-eval-surface posture the sibling `pub const fn`
3464    /// [`Self::rate`] / [`Self::window`] scalar-projection accessors on
3465    /// this typed sub-struct already carry, composing through the
3466    /// peer-lifted `pub const fn` [`RateLimitUnit::from_window`]
3467    /// reverse-resolver in `const` context. Any downstream substrate-
3468    /// side `const`-context consumer of the typed unit (a module-scope
3469    /// `const _:() = assert!(matches!(rl.canonical_unit(), Some(RateLimitUnit::Second)))`
3470    /// invariant pin on a typed fixture, a future M4 admission-webhook
3471    /// `const fn` per-`:politicas :rate-limit :window` canonical-arm
3472    /// resolver over a typed [`RateLimit`], any future `const fn`
3473    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3474    /// the substrate primitive) now reaches the same typed dispatch on
3475    /// the substrate primitive at const-eval time as at runtime.
3476    ///
3477    /// Pinned load-bearing at the substrate-primitive level by
3478    /// [`tests::rate_limit_canonical_unit_accessor_is_const_fn`] (const-
3479    /// eval-surface pin via `const fn` wrapper).
3480    #[must_use]
3481    pub const fn canonical_unit(&self) -> Option<RateLimitUnit> {
3482        RateLimitUnit::from_window(self.window)
3483    }
3484}
3485
3486/// Typed closed-set enum for the three canonical `:politicas :rate-limit`
3487/// `:window` units — `Second` / `Minute` / `Hour` — the `rate_limit_codec`
3488/// round-trips losslessly (`"<n>/s"` / `"<n>/m"` / `"<n>/h"`).
3489///
3490/// The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer of
3491/// the `:politicas :rate-limit` unit surface reads from
3492/// ([`rate_limit_codec::parse`]'s `unit → Duration` dispatch,
3493/// [`rate_limit_codec::render`]'s `Duration → unit` projection, the
3494/// [`is_canonical_rate_limit_window`] predicate the
3495/// [`AplicacaoSpec::validate_politicas`] gate keys off, the future M4
3496/// per-Aplicacao Envoy config reconciler's `local_rate_limit.token_bucket.fill_interval`
3497/// projection) now lives inside this typed enum's `match self` arms — a
3498/// future rate-limit-unit addition (a `"d"` day suffix once Envoy's
3499/// `rate_limit_action` grows daily-bucket support) is one new variant
3500/// plus the exhaustiveness arms on the four methods, so every consumer
3501/// picks it up by compile-time construction rather than a runtime
3502/// table-scan miss.
3503///
3504/// The prior `RATE_LIMIT_UNIT_TABLE: &[(&str, u64)]` slice-of-tuples was
3505/// scanned via `find_map` at every projection call — an untyped runtime
3506/// walk that carried no compile-time link between the parse arm's
3507/// accepted suffixes, the render arm's emitted suffixes, and the
3508/// validate gate's accepted windows. A future rate-limit-unit addition
3509/// that landed one row without threading through the other consumers
3510/// (or a copy-paste flip that collapsed two rows onto one suffix) would
3511/// silently split the accepted-set across the three consumers — the
3512/// parse arm accepts `"d"` and rejects `"s"`, the render arm emits `"h"`
3513/// for a 24h window that parse can't round-trip, the validate gate
3514/// misses one canonical window. Lifting the pairs onto a typed
3515/// closed-set enum with exhaustive `match` arms makes any such
3516/// half-landed extension a caixa-core build error (the compiler enforces
3517/// arm coverage on every method), not a silent per-consumer drift
3518/// surfacing at apply time. Same "closed-set typed-enum discriminator"
3519/// discipline the sibling [`PlacementStrategy`] (cc8f749),
3520/// [`crate::supervisor::RestartStrategy`],
3521/// [`crate::supervisor::RestartPolicy`],
3522/// [`crate::upgrade::UpgradeInstruction`], and [`crate::CaixaKind`]
3523/// closed-set typed enums carry on their respective closed-set axes —
3524/// extended onto the seventh closed-set typed-enum discriminator axis
3525/// on the caixa typed surface (the `:politicas :rate-limit :window`
3526/// canonical-unit axis).
3527#[derive(
3528    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
3529)]
3530pub enum RateLimitUnit {
3531    /// 1-second window — canonical author-surface suffix `"s"`
3532    /// (`"<n>/s"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3533    /// with a 1s magnitude.
3534    Second,
3535    /// 1-minute window — canonical author-surface suffix `"m"`
3536    /// (`"<n>/m"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3537    /// with a 60s magnitude.
3538    Minute,
3539    /// 1-hour window — canonical author-surface suffix `"h"`
3540    /// (`"<n>/h"`), maps onto Envoy's `local_rate_limit.token_bucket.fill_interval`
3541    /// with a 3600s magnitude.
3542    Hour,
3543}
3544
3545impl RateLimitUnit {
3546    /// Exhaustive iteration surface for every consumer that reads the
3547    /// full canonical-unit set (the byte-parity witness against the
3548    /// prior `RATE_LIMIT_UNIT_TABLE` shape, the future M4 admission
3549    /// webhook's accepted-suffix listing in its rejection body, any
3550    /// future round-trip fuzz harness). A future variant addition to
3551    /// [`RateLimitUnit`] extends this slice as a single edit and every
3552    /// consumer picks up the new entry by construction — the compiler-
3553    /// checked exhaustiveness on the sibling method `match` arms is the
3554    /// build-time guarantee that no arm forgets to grow.
3555    pub const ALL: &'static [Self] = &[Self::Second, Self::Minute, Self::Hour];
3556
3557    /// Canonical author-surface suffix — the `"s"` / `"m"` / `"h"` byte-
3558    /// string every `<n>/<unit>` rate-limit shape carries after its
3559    /// `/` separator. The single source of truth the codec's parse and
3560    /// render arms both dispatch on: the parse arm matches an incoming
3561    /// suffix against every [`RateLimitUnit::ALL`] entry's `as_suffix`
3562    /// output; the render arm emits the entry's `as_suffix` verbatim
3563    /// after the rate magnitude.
3564    #[must_use]
3565    pub const fn as_suffix(self) -> &'static str {
3566        match self {
3567            Self::Second => "s",
3568            Self::Minute => "m",
3569            Self::Hour => "h",
3570        }
3571    }
3572
3573    /// Canonical `Duration` for this unit — the token-bucket refill
3574    /// period the [`RateLimit::window`] axis carries when the surrounding
3575    /// slot's `:rate-limit` author surface named this unit.
3576    #[must_use]
3577    pub const fn window(self) -> Duration {
3578        Duration::from_secs(match self {
3579            Self::Second => 1,
3580            Self::Minute => 60,
3581            Self::Hour => 3_600,
3582        })
3583    }
3584
3585    /// Parse the `<n>/<unit>`-shaped suffix into the typed enum, or
3586    /// `None` when `suffix` is outside the closed-set arm-string set
3587    /// [`Self::as_suffix`] emits. The single `str → Self` projection
3588    /// [`rate_limit_codec::parse`] consumes.
3589    #[must_use]
3590    pub fn from_suffix(suffix: &str) -> Option<Self> {
3591        Self::ALL.iter().copied().find(|u| u.as_suffix() == suffix)
3592    }
3593
3594    /// Recognize a canonical rate-limit `Duration` as one of the three
3595    /// arms, or `None` when `window` carries sub-second residue or a
3596    /// second-magnitude outside the closed-set arm-window set
3597    /// [`Self::window`] emits. The single `Duration → Self` projection
3598    /// [`rate_limit_codec::render`] + [`is_canonical_rate_limit_window`]
3599    /// both consume.
3600    ///
3601    /// `pub const fn` — the reverse `Duration → Self` projection now
3602    /// carries the same `const`-eval-surface posture the sibling
3603    /// `pub const fn` [`Self::as_suffix`] / [`Self::window`] scalar-
3604    /// projection accessors on this closed-set typed enum already
3605    /// carry, and the paired `pub const fn` [`RateLimit::canonical_unit`]
3606    /// typed-`RateLimit`-projection sibling composes through in `const`
3607    /// context. Routes byte-for-byte through the peer `pub const fn`
3608    /// [`Self::window`] canonical-`Duration` projection so any future
3609    /// arm-magnitude edit on the sibling accessor reaches this reverse
3610    /// resolver by construction — the `s == Self::<Arm>.window().as_secs()`
3611    /// per-arm probes each dispatch through one `pub const fn` on the
3612    /// substrate primitive rather than a hand-authored per-arm second-
3613    /// magnitude literal that would silently drift on any future
3614    /// [`Self::window`] arm-magnitude edit.
3615    ///
3616    /// Prior to the `const` lift the body dispatched through
3617    /// `Self::ALL.iter().copied().find(|u| u.window() == window)` — an
3618    /// iterator-driven linear scan whose iterator methods
3619    /// (`.iter()` / `.copied()` / `.find()`) and `Duration`-side
3620    /// `PartialEq` dispatch each carry non-`const` bounds on stable
3621    /// Rust 1.94, so any downstream substrate-side `const`-context
3622    /// consumer of the reverse resolver (a module-scope
3623    /// `const _:() = assert!(RateLimitUnit::from_window(<canonical>).is_some())`
3624    /// invariant pin on a typed fixture, a future M4
3625    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer admission-
3626    /// webhook `const fn` per-`:politicas` canonical-window floor over a
3627    /// typed [`RateLimit`] scalar, any future `const fn`
3628    /// per-`:contratos`-edge rate-limit-override overlay resolver over
3629    /// the substrate primitive that wants to fan on the canonical unit
3630    /// at compile time) surfaced as a downstream E0015 far from the
3631    /// resolver's own declaration. The `pub const fn` posture closes
3632    /// the drift structurally at caixa-core build time.
3633    ///
3634    /// Pinned load-bearing at the substrate-primitive level by
3635    /// [`tests::rate_limit_unit_from_window_accessor_is_const_fn`] (const-
3636    /// eval-surface pin via `const fn` wrapper) and
3637    /// [`tests::rate_limit_unit_from_window_composes_through_window_accessor`]
3638    /// (composition-witness pin against the peer `Self::window` scalar
3639    /// dispatch).
3640    #[must_use]
3641    pub const fn from_window(window: Duration) -> Option<Self> {
3642        if window.subsec_nanos() != 0 {
3643            return None;
3644        }
3645        // Route through the peer `pub const fn` [`Self::window`]
3646        // canonical-`Duration` projection so any future arm-magnitude
3647        // edit on the sibling accessor reaches this reverse resolver by
3648        // construction — the per-arm `secs` comparison keys off
3649        // `Duration::as_secs` (`pub const fn`), not a hand-authored
3650        // per-arm second-magnitude literal that would silently drift.
3651        let secs = window.as_secs();
3652        if secs == Self::Second.window().as_secs() {
3653            Some(Self::Second)
3654        } else if secs == Self::Minute.window().as_secs() {
3655            Some(Self::Minute)
3656        } else if secs == Self::Hour.window().as_secs() {
3657            Some(Self::Hour)
3658        } else {
3659            None
3660        }
3661    }
3662
3663    /// Canonical rate-limit `Duration` for a unit suffix, or `None` when
3664    /// `suffix` is outside the closed-set arm-string set [`Self::as_suffix`]
3665    /// emits. Composes [`Self::from_suffix`] with [`Self::window`] — the
3666    /// single `&str → Duration` projection [`rate_limit_codec::parse`]
3667    /// consumes.
3668    ///
3669    /// The peer `Duration → &'static str` axis folded onto the substrate
3670    /// primitive [`RateLimit::canonical_unit`] typed accessor once both
3671    /// production consumers ([`rate_limit_codec::render`] and
3672    /// [`AplicacaoSpec::validate_politicas`]'s canonical-window gate)
3673    /// migrated (61421a6): the free helper's `Duration → &str` projection
3674    /// is now the two-step composition
3675    /// `rl.canonical_unit().map(RateLimitUnit::as_suffix)` every consumer
3676    /// reads through the typed accessor. This lift closes the peer
3677    /// `&str → Duration` axis by folding the vestigial module-private
3678    /// `rate_limit_window_from_unit` delegate onto this associated method
3679    /// — the codec's parse arm and every future wire-side consumer of the
3680    /// `&str → Duration` projection (a future admission-webhook that
3681    /// reads a `:rate-limit` shape off a CR spec's `raw string` value
3682    /// before it's promoted to a validated typed slot, a future
3683    /// `feira lint` shape-probe that reads the author-surface bytes
3684    /// verbatim) now reach for exactly one typed dispatch on the
3685    /// substrate primitive.
3686    ///
3687    /// Same "closed-set typed-enum discriminator with canonical
3688    /// projections per axis" discipline the sibling [`Self::as_suffix`]
3689    /// / [`Self::window`] / [`Self::from_suffix`] / [`Self::from_window`]
3690    /// methods carry — this associated method closes the fifth (and last
3691    /// unlifted) projection axis on the arm-table, so the closed-set enum
3692    /// now owns every `str ↔ Duration ↔ Self` typed dispatch every
3693    /// consumer of the `:politicas :rate-limit :window` axis reaches
3694    /// through. A future rate-limit-unit addition (a `"d"` day suffix
3695    /// once Envoy's `rate_limit_action` grows daily-bucket support, a
3696    /// `"ms"` sub-second window once high-throughput per-edge policies
3697    /// come into scope per MESH-COMPOSITION §III.2 #3) is one new
3698    /// variant plus one arm per method — the compiler enforces
3699    /// exhaustiveness on every consumer's `match self` arms and picks
3700    /// the new unit up by construction across all five projections.
3701    #[must_use]
3702    pub fn window_from_suffix(suffix: &str) -> Option<Duration> {
3703        Self::from_suffix(suffix).map(Self::window)
3704    }
3705}
3706
3707/// Route [`std::fmt::Display`] through [`RateLimitUnit::as_suffix`], so
3708/// every consumer that formats a canonical rate-limit unit as user-
3709/// facing text (future M4 admission-webhook rejection bodies naming
3710/// the accepted-suffix set, future `feira app graph` per-`:politicas`
3711/// unit column) lands on the same `"s"` / `"m"` / `"h"` byte-string the
3712/// codec's parse arm accepts and the render arm emits. Same
3713/// as_str-through-Display convergence discipline the sibling
3714/// [`PlacementStrategy`], [`crate::CaixaKind`],
3715/// [`crate::supervisor::RestartStrategy`], and
3716/// [`crate::supervisor::RestartPolicy`] closed-set typed enums carry.
3717impl std::fmt::Display for RateLimitUnit {
3718    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3719        f.write_str(self.as_suffix())
3720    }
3721}
3722
3723/// Upper-bound ceiling on the `:politicas :timeout` axis — every
3724/// validated [`MeshPolicy::timeout`] past
3725/// [`AplicacaoSpec::validate_politicas`] lies in `1ms..=POLICY_TIMEOUT_MAX`
3726/// (inclusive on both ends, integer-millisecond magnitudes by the
3727/// canonical-form gate immediately preceding).
3728///
3729/// The typed field is `Option<Duration>` (the zero-floor arm
3730/// [`AplicacaoError::PolicyTimeoutZero`] already rejects
3731/// `Duration::ZERO`, and the canonical-form arm
3732/// [`AplicacaoError::PolicyTimeoutNotCanonical`] already rejects
3733/// sub-millisecond residue), so a programmatic struct literal
3734/// (`MeshPolicy { timeout: Some(Duration::from_secs(86_400)), .. }` —
3735/// 24h) and the equivalent author-surface form
3736/// (`(:politicas (:timeout "24h"))` — the codec emits `"h"` for any
3737/// integer-hour magnitude) both round-trip cleanly through serde — a
3738/// structurally unbounded `Duration` ceiling. A `:timeout` value far
3739/// above the documented production-playbook band (Envoy default `15s`,
3740/// Istio per-route typical `≤ 30s`, AWS App Mesh `httpRouteTimeout`
3741/// schema typical `≤ 60s`, Linkerd `request_timeout` typical `10s`,
3742/// Kubernetes ingress-nginx `proxy_read_timeout` default `60s` capped
3743/// at `~3600s`) silently degenerates the mesh-policy contract: the
3744/// per-call deadline is structurally so long that no realistic
3745/// synchronous-`:contratos` traversal can reach it, so the typed slot
3746/// becomes a no-op carried on every emitted Envoy / Cilium L7 timeout
3747/// overlay — the MESH-COMPOSITION §V CSE invariant "no infinite
3748/// blocking" degenerates to a nominal-only contract on the
3749/// synchronous-call path. Pairs with the [`POLICY_RETRIES_MAX`] cap on
3750/// the sibling `:politicas :retries` axis and the
3751/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap on the sibling
3752/// `:politicas :circuit-breaker :max-failures` axis — all three close
3753/// the "structurally unbounded ceiling on a typed `:politicas` axis"
3754/// footgun the prior zero-floor-and-canonical-form-only checks left
3755/// open.
3756///
3757/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3758/// shared duration codec emits (`"<n>h"` for any integer-hour
3759/// magnitude) — every value in the canonical authoring form's
3760/// `<integer><unit>` grammar at or below this cap renders to a clean
3761/// canonical string. The cap sits an order of magnitude above every
3762/// documented production-playbook recommendation band (Envoy default
3763/// `15s`, Istio production `≤ 30s`, Linkerd production `≤ 10s`, AWS
3764/// App Mesh production `≤ 60s`) and at the Kubernetes ingress-nginx
3765/// configured maximum (`proxy_read_timeout` typical max `3600s`),
3766/// below the clearly-pathological "effectively no timeout" floor
3767/// (`24h`, `7d`, `Duration::MAX`): a value the author can plausibly
3768/// want for a long-running synchronous workflow, but a hard wall above
3769/// which the mesh-level deadline is structurally a non-deadline.
3770/// Lifted as a typed `pub const` so the bound has exactly one source
3771/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3772/// materializer's admission webhook and the caixa-mesh-side
3773/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3774/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3775/// other typed upper bound in this crate carries
3776/// ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3777/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3778/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3779/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3780pub const POLICY_TIMEOUT_MAX: Duration = Duration::from_secs(3600);
3781
3782/// Upper-bound ceiling on the `:politicas :retries` axis — every
3783/// validated [`MeshPolicy::retries`] past
3784/// [`AplicacaoSpec::validate_politicas`] lies in `1..=POLICY_RETRIES_MAX`.
3785///
3786/// The typed slot is `Option<u32>` (`None` = no retries on transient
3787/// failure; `Some(0)` already rejected by the
3788/// [`AplicacaoError::PolicyRetriesZero`] zero-floor arm), so a
3789/// programmatic struct literal (`MeshPolicy { retries: Some(100_000),
3790/// .. }`) and the equivalent author-surface form
3791/// (`(:politicas (:retries 100000))`) both round-trip cleanly through
3792/// serde / the codec — a structurally unbounded `u32` ceiling. The
3793/// runtime substrate that consumes the value (Envoy's
3794/// `retry_policy.num_retries`, the `CiliumClusterwideEnvoyConfig`
3795/// per-`:politicas` overlay MESH-COMPOSITION §III.2 #3 names, AWS
3796/// App Mesh's `gRPCRouteRetryPolicy.maxRetries` whose schema-side
3797/// admission cap is 10) translates a four-billion-retry policy into a
3798/// thundering-herd amplification vector on transient failure — the
3799/// caller's one request fans out to `retries` server-side calls per
3800/// edge per traversal, multiplying load by `(retries+1)^depth` across
3801/// the synchronous-`:contratos` subgraph. The MESH-COMPOSITION §V CSE
3802/// invariant "no infinite blocking" pairs with a no-runaway-amplification
3803/// invariant on the retry axis; both belong at the typed-slot layer.
3804///
3805/// The `10` ceiling matches AWS App Mesh's explicit hard cap (the only
3806/// upstream mesh-policy schema that documents one) and sits above the
3807/// Envoy / Istio practical-recommendation band (`num_retries ≤ 5` in
3808/// every documented production playbook): a value the author can
3809/// plausibly want, but a hard wall above which the policy is
3810/// structurally a footgun. Lifted as a typed `pub const` so the bound
3811/// has exactly one source of truth — a future axis reaching for the
3812/// same value (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3813/// materializer's admission webhook, the caixa-mesh-side
3814/// `CiliumClusterwideEnvoyConfig` overlay's per-edge cap) reads from
3815/// one place. Same shape every other typed upper bound in this crate
3816/// carries ([`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3817/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3818/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`],
3819/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3820pub const POLICY_RETRIES_MAX: u32 = 10;
3821
3822/// Upper-bound ceiling on the `:politicas :circuit-breaker :max-failures`
3823/// axis — every validated [`CircuitBreaker::max_failures`] past
3824/// [`AplicacaoSpec::validate_politicas`] lies in
3825/// `1..=POLICY_BREAKER_MAX_FAILURES_MAX`.
3826///
3827/// The typed field is `u32` (the zero-floor arm
3828/// [`AplicacaoError::PolicyBreakerZeroFailures`] already rejects
3829/// `0` — a breaker that trips on the first call), so a programmatic
3830/// struct literal (`CircuitBreaker { max_failures: u32::MAX, .. }`)
3831/// and the equivalent author-surface form
3832/// (`(:circuit-breaker (:max-failures 4294967295))`) both round-trip
3833/// cleanly through serde — a structurally unbounded `u32` ceiling. A
3834/// `max_failures` value far above the documented production-playbook
3835/// band (Hystrix `circuitBreaker.requestVolumeThreshold` default 20,
3836/// Istio `outlierDetection.consecutive5xxErrors` default 5, Envoy
3837/// `outlier_detection.consecutive_5xx` default 5, Polly / Resilience4j
3838/// typical 5–50) silently disables the breaker's protection role:
3839/// the threshold is structurally so high that no realistic
3840/// failures-per-`:window` traffic shape can reach it, so the breaker
3841/// never trips and the typed slot becomes a no-op carried on every
3842/// emitted Envoy / Cilium L7 overlay. Pairs with the
3843/// [`POLICY_RETRIES_MAX`] cap on the sibling `:politicas :retries`
3844/// axis — both close the "structurally unbounded `u32` ceiling on a
3845/// typed policy axis" footgun the prior zero-floor-only checks left
3846/// open.
3847///
3848/// The `1000` ceiling sits an order of magnitude above every
3849/// documented upstream production-playbook recommendation band (the
3850/// highest is Hystrix's 20-default `requestVolumeThreshold`, the
3851/// Istio / Envoy / Polly / Resilience4j ones all sit ≤ 50) and below
3852/// the clearly-pathological "effectively no protection"
3853/// floor (`10_000`, `100_000`, `u32::MAX`): a value the author can
3854/// plausibly want at hyperscale, but a hard wall above which the
3855/// policy is structurally a no-op. Lifted as a typed `pub const` so
3856/// the bound has exactly one source of truth — the future M4
3857/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3858/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3859/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3860/// one place. Same shape every other typed upper bound in this crate
3861/// carries ([`POLICY_RETRIES_MAX`],
3862/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3863/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3864/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3865pub const POLICY_BREAKER_MAX_FAILURES_MAX: u32 = 1000;
3866
3867/// Upper-bound ceiling on the `:politicas :circuit-breaker :window` axis —
3868/// every validated [`CircuitBreaker::window`] past
3869/// [`AplicacaoSpec::validate_politicas`] lies in
3870/// `1ms..=POLICY_BREAKER_WINDOW_MAX` (inclusive on both ends,
3871/// integer-millisecond magnitudes by the canonical-form gate
3872/// immediately preceding).
3873///
3874/// The typed field is `Duration` (the zero-floor arm
3875/// [`AplicacaoError::PolicyBreakerZeroWindow`] already rejects
3876/// `Duration::ZERO`, and the canonical-form arm
3877/// [`AplicacaoError::PolicyBreakerWindowNotCanonical`] already rejects
3878/// sub-millisecond residue), so a programmatic struct literal
3879/// (`CircuitBreaker { window: Duration::from_secs(86_400), .. }` — 24h)
3880/// and the equivalent author-surface form
3881/// (`(:circuit-breaker (:window "24h"))` — the codec emits `"h"` for any
3882/// integer-hour magnitude) both round-trip cleanly through serde — a
3883/// structurally unbounded `Duration` ceiling. A `:window` value far
3884/// above the documented production-playbook band (Hystrix
3885/// `metrics.rollingStats.timeInMilliseconds` default `10s`,
3886/// resilience4j `slidingWindowSize` time-based typical `10s..=60s`,
3887/// Istio `outlierDetection.interval` default `10s`, Envoy
3888/// `outlier_detection.interval` default `10s`, AWS App Mesh
3889/// circuit-breaker time-window typical `30s..=300s`) degenerates the
3890/// breaker's role: a rolling-window failure counter whose window is
3891/// hours long is operationally a lifetime counter, the breaker's
3892/// "recent failures" memory is structurally so long that transient
3893/// failures are never forgotten, and the typed slot becomes a no-op
3894/// trigger that trips once and stays tripped for the lifetime of the
3895/// component carried on every emitted Envoy / Cilium L7 overlay.
3896///
3897/// The 1h (3600s = `3_600_000` ms) ceiling matches the largest unit the
3898/// shared duration codec emits (`"<n>h"` for any integer-hour
3899/// magnitude) — every value in the canonical authoring form's
3900/// `<integer><unit>` grammar at or below this cap renders to a clean
3901/// canonical string — and matches the sibling [`POLICY_TIMEOUT_MAX`]
3902/// cap on the first typed-`Duration` `:politicas` axis: the two
3903/// duration-typed `:politicas` axes now share a single uniform top
3904/// edge so the next typed-slot wiring (the future caixa-mesh
3905/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay, the M4
3906/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-policy
3907/// admission webhook) reaches for either field knowing the value is
3908/// in `1ms..=1h` without re-validating at the renderer layer. The cap
3909/// sits two orders of magnitude above every documented upstream
3910/// production-playbook recommendation band (Hystrix / resilience4j /
3911/// Istio / Envoy all default to 10s; AWS App Mesh maxes out at ~5m)
3912/// and below the clearly-pathological "rolling window degenerates to
3913/// lifetime counter" floor (`24h`, `7d`, `Duration::MAX`): a value the
3914/// author can plausibly want for a very-low-traffic long-tail
3915/// failure-detection window, but a hard wall above which the breaker's
3916/// rolling-window contract is structurally a lifetime-counter contract.
3917/// Lifted as a typed `pub const` so the bound has exactly one source
3918/// of truth — the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
3919/// materializer's admission webhook and the caixa-mesh-side
3920/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3921/// (MESH-COMPOSITION §III.2 #3) read from one place. Same shape every
3922/// other typed upper bound in this crate carries
3923/// ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3924/// [`POLICY_BREAKER_MAX_FAILURES_MAX`],
3925/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3926/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3927/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3928pub const POLICY_BREAKER_WINDOW_MAX: Duration = Duration::from_secs(3600);
3929
3930/// Upper-bound ceiling on the `:politicas :rate-limit` rate axis —
3931/// every validated [`RateLimit::rate`] past
3932/// [`AplicacaoSpec::validate_politicas`] lies in
3933/// `1..=POLICY_RATE_LIMIT_MAX`.
3934///
3935/// The typed field is `u32` (the zero-floor arm
3936/// [`AplicacaoError::PolicyRateLimitZero`] already rejects `0` — a
3937/// zero-rate limit denies every request, the canonical "I forgot
3938/// that 0 means deny-everything" footgun), so a programmatic struct
3939/// literal (`RateLimit { rate: u32::MAX, window: Duration::from_secs(1) }`)
3940/// and the equivalent author-surface form (`(:rate-limit "4294967295/s")`
3941/// — the `rate_limit_codec` parses any `u32`-shaped magnitude) both
3942/// round-trip cleanly through serde — a structurally unbounded `u32`
3943/// ceiling. The runtime substrate consuming the value (Envoy's
3944/// `local_rate_limit.token_bucket.max_tokens`, the future
3945/// `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
3946/// MESH-COMPOSITION §III.2 #3 names) translates a four-billion-token
3947/// rate-limit into a no-op rate-limiter: the bucket capacity is
3948/// structurally so high no realistic per-edge traffic shape can
3949/// drain it, the limiter never trips, and the typed slot becomes a
3950/// "rate-limit declared, no enforcement" footgun — the canonical
3951/// declared-but-inert shape every other `:politicas` cap arm
3952/// closes ([`POLICY_RETRIES_MAX`] thundering-herd amplification,
3953/// [`POLICY_BREAKER_MAX_FAILURES_MAX`] no-op-breaker, etc.).
3954///
3955/// The `1_000_000` (1M) ceiling sits two-to-three orders of magnitude
3956/// above every documented upstream production-playbook recommendation
3957/// band (Envoy `local_rate_limit` typical `10..=10_000` RPS, Istio
3958/// `RateLimitFilter` typical `10..=10_000` RPS, Cloudflare WAF
3959/// rate-rule Free / Pro `10_000` req/min, AWS API Gateway account
3960/// default `10_000` RPS, Kong typical `100..=10_000`, NGINX
3961/// `limit_req_zone` typical `1..=1_000` RPS) and below the
3962/// clearly-pathological "paste-from-binary blob" floor (`100_000_000`,
3963/// `u32::MAX`): a value the author can plausibly want at hyperscale
3964/// (Cloudflare Enterprise rate-plans run to ~6M/min ≈ 1M/h on the
3965/// /h-window arm), but a hard wall above which the policy is
3966/// structurally a no-op carried verbatim on every emitted Envoy /
3967/// Cilium L7 overlay. The cap brackets all three canonical windows
3968/// the [`rate_limit_codec`] accepts: at `1M/s` (absurd hyperscale
3969/// ceiling, ~1M RPS per edge), at `1M/m` (~16.7k RPS, the
3970/// hyperscale-tier WAF band), at `1M/h` (~277 RPS, the common
3971/// per-endpoint API band). Lifted as a typed `pub const` so the bound
3972/// has exactly one source of truth — the future M4
3973/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's admission
3974/// webhook and the caixa-mesh-side `CiliumClusterwideEnvoyConfig`
3975/// per-`:politicas` overlay (MESH-COMPOSITION §III.2 #3) read from
3976/// one place. Same shape every other typed upper bound in this crate
3977/// carries ([`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
3978/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
3979/// [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`],
3980/// [`crate::LIMITS_WALL_CLOCK_MAX`],
3981/// [`crate::render::DNS_1123_LABEL_MAX_LEN`],
3982/// [`crate::render::NATS_SUBJECT_MAX_LEN`]).
3983pub const POLICY_RATE_LIMIT_MAX: u32 = 1_000_000;
3984
3985// `:entrada :host` total-length and per-label cap axes route through
3986// the lifted [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] (253) and
3987// [`crate::render::DNS_1123_LABEL_MAX_LEN`] (63) canonical bounds. The
3988// pair of aplicacao-private aliases the previous `validate_entrada_host`
3989// arms consumed (`ENTRADA_HOST_MAX_LEN = 253`, `ENTRADA_HOST_LABEL_MAX_LEN
3990// = 63`) were structurally the same K8s Gateway API v1 Hostname
3991// admission-schema bounds — the total-length cap on the OpenAPI
3992// `Hostname` type and the per-`.`-separated-label DNS-1123 cap on the
3993// same regex — that the peer axes at the caixa-core::render level pin,
3994// so hoisting both readers onto the shared lifted constants closes the
3995// third-occurrence duplication threshold structurally: the M4
3996// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-host / per-
3997// label validator, the future per-`Certificate` SAN emitter, and every
3998// other per-Gateway-API-Hostname landing site reach the same one place
3999// as the `:entrada :host` gate does — no per-axis alias drift surface
4000// between them, by construction.
4001
4002/// Max byte length for an Akka-cluster-sharding `:placement :shard-key`
4003/// extractor expression — the upper bound `validate_placement_shard_key`
4004/// enforces on every well-shaped shard-key past validate. The realistic
4005/// shard-key forms in the wild (`tenantId`, `customerId`, `$tenantId`,
4006/// `metadata.tenantId`, `${tenant}`, `$.user.id`) all sit well under 64
4007/// bytes; the 63-byte cap mirrors the DNS-1123 label cap on the peer
4008/// `:placement :affinity` / `:placement :clusters` identifier-shaped
4009/// axes and surfaces the canonical "paste-from-doc multi-line blob landed
4010/// in `:shard-key`" footgun at validate time rather than at the future
4011/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass.
4012const PLACEMENT_SHARD_KEY_MAX_LEN: usize = 63;
4013
4014/// Reject `:membros :caixa` values the K8s apiserver would refuse at
4015/// admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4016/// that maps the shared parser-shaped reason into the
4017/// [`AplicacaoError::MembroCaixaInvalid`] variant, so the diagnostic
4018/// is self-locating (the offending `caixa:` is named verbatim) and
4019/// the author can grep their caixa.lisp for `:caixa "<name>"` and
4020/// fix it in one edit. Same diagnostic shape as
4021/// [`AplicacaoError::EntradaHostInvalid`] (c7d05ec) and
4022/// [`AplicacaoError::MembroVersaoInvalid`] (9888b13).
4023fn validate_membro_caixa(caixa: &str) -> Result<(), AplicacaoError> {
4024    // Empty is already gated by `MembroCaixaEmpty` at the call site;
4025    // re-checking here keeps the predicate usable from any future
4026    // call site (the M4 CR materializer) without an empty-check
4027    // footgun. The shared
4028    // [`crate::render::require_valid_dns_1123_label`] helper brackets
4029    // the empty-first + shape cascade every peer name axis
4030    // (`:placement :clusters`, `:placement :affinity`, `:contratos
4031    // :de`/`:para`, `:entrada :para`, `:children :caixa`, `:nome`,
4032    // `:upgrade-from :module`) routes through, so drift between the
4033    // eight axes' accepted DNS-1123-label sets is structurally
4034    // impossible.
4035    crate::render::require_valid_dns_1123_label(
4036        caixa,
4037        || AplicacaoError::MembroCaixaEmpty,
4038        |reason| AplicacaoError::MembroCaixaInvalid {
4039            caixa: caixa.to_string(),
4040            reason,
4041        },
4042    )
4043}
4044
4045/// Reject `:placement :clusters` entries the K8s apiserver would refuse
4046/// at admission time. Thin wrapper around [`crate::render::is_dns_1123_label`]
4047/// that maps the shared parser-shaped reason into the
4048/// [`AplicacaoError::PlacementClusterInvalid`] variant.
4049///
4050/// Cluster names land in DNS-1123-label territory across every consumer:
4051/// the K8s context name keying `kubeconfig`, the `clusters[]` filter
4052/// the `lareira-fleet-programs` aggregator applies to scope programs to
4053/// their owning cluster (caixa-mesh's `placement.clusters` overlay,
4054/// 4d91c0b), the namespace prefix the future cross-cluster fan-out
4055/// emits per entry, and the `cluster.x-k8s.io/v1beta1/Cluster.metadata.name`
4056/// cluster identity the M4 CR materializer round-trips. Each apiserver-
4057/// side schema enforces the DNS-1123 label rule on admission; a
4058/// structurally invalid cluster name (`"Rio"`, `"my_cluster"`,
4059/// `"team.rio"`, `"-rio"`, `"rio-"`, the >63-byte UUID-shaped
4060/// mistaken-identity slug) silently passes the prior empty-/duplicate-
4061/// only gate and the failure surfaces as a no-match at filter time —
4062/// the workload doesn't land in the named cluster, with no diagnostic
4063/// naming the offending `:clusters` entry. Lifting the gate to caixa-
4064/// build time mirrors the `:membros :caixa` value-shape trajectory
4065/// (3f9d7a0) on the peer name axis.
4066///
4067/// The diagnostic carries the offending `cluster:` verbatim plus a
4068/// parser-shaped `reason:` naming the specific violation, so the
4069/// author can grep their caixa.lisp for `:clusters` and fix it in
4070/// one edit. Same diagnostic shape as
4071/// [`AplicacaoError::MembroCaixaInvalid`] (3f9d7a0).
4072fn validate_placement_cluster(cluster: &str) -> Result<(), AplicacaoError> {
4073    // Empty is already gated by `PlacementClusterEmpty` at the call
4074    // site; re-checking here keeps the predicate usable from any
4075    // future call site (the M4 CR materializer's per-cluster validator)
4076    // without an empty-check footgun. Routes through the shared
4077    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4078    // name axes each land on.
4079    crate::render::require_valid_dns_1123_label(
4080        cluster,
4081        || AplicacaoError::PlacementClusterEmpty,
4082        |reason| AplicacaoError::PlacementClusterInvalid {
4083            cluster: cluster.to_string(),
4084            reason,
4085        },
4086    )
4087}
4088
4089/// Reject `:placement :affinity` hints whose shape can never legitimately
4090/// land in any downstream selector or label-keyed routing axis. Thin
4091/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4092/// shared parser-shaped reason into the
4093/// [`AplicacaoError::PlacementAffinityInvalid`] variant, so the
4094/// diagnostic is self-locating (the offending `:affinity` is named
4095/// verbatim) and the author can grep their caixa.lisp for
4096/// `:affinity "<hint>"` and fix it in one edit.
4097///
4098/// The `:affinity` slot carries a placement-engine hint — canonical
4099/// examples in the M3 surface are `"data-locality"`, `"low-latency"`,
4100/// `"anti-affinity"` — that flows verbatim into the M3 Adaptive
4101/// compression overlay and the future M4 placement-engine's per-hint
4102/// routing axis. Each downstream consumer (caixa-mesh's
4103/// `placement.affinity` overlay at caixa-mesh/src/lib.rs:126, the
4104/// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
4105/// `spec.placement.affinity` admission rule, the future M4 per-hint
4106/// node-affinity / pod-affinity rule generator keying off the same
4107/// value as a K8s `app.pleme.io/affinity-hint=<value>` label
4108/// selector) requires the value to be a DNS-1123 label — K8s label
4109/// values are bounded by `[a-z0-9A-Z_.-]{,63}` with a stricter
4110/// `[a-z0-9]([-a-z0-9]*[a-z0-9])?` floor in every identity-keyed
4111/// admission rule the apiserver enforces.
4112///
4113/// Until this gate landed an `:affinity "DataLocality"` (the canonical
4114/// TitleCase-from-an-ADR typo), `:affinity "data_locality"` (the
4115/// Python-module-name leak), `:affinity "data.locality"` (the
4116/// namespace-dot-on-a-label confusion), `:affinity "-data-locality"` /
4117/// `:affinity "data-locality-"` (boundary-hyphen violation),
4118/// `:affinity "data locality"` (paste-from-doc whitespace),
4119/// `:affinity "data-localité"` (un-Punycode-encoded IDN), or the
4120/// 64-byte over-cap slug silently passed the empty-only check and the
4121/// failure surfaced as a no-match at the M3 Adaptive compression
4122/// overlay's filter time (`placement.affinity` carried a malformed
4123/// value, no node matched, the workload landed on the default
4124/// heuristic) — the canonical "declared-but-inert" footgun mirroring
4125/// the empty-:affinity / empty-shard-key / zero-:politicas /
4126/// empty-:contratos-target gates already close on every other
4127/// declare-but-no-opinion axis. Lifting the rejection to a build-time
4128/// gate closes the fifth typed slot on the Aplicacao surface to land
4129/// on the canonical DNS-1123 label floor (after the four Servico-name
4130/// reference axes: `:membros :caixa` 3f9d7a0, `:placement :clusters`
4131/// 6c8c00b, `:contratos :de`/`:para` 8d5af6b, `:entrada :para`
4132/// b0e8748).
4133///
4134/// Same diagnostic shape as [`AplicacaoError::PlacementClusterInvalid`]
4135/// (6c8c00b) on the sibling `:placement :clusters` axis — both axes'
4136/// validated values are guaranteed-accepted by the apiserver without
4137/// re-validation at any downstream renderer or admission layer.
4138fn validate_placement_affinity(affinity: &str) -> Result<(), AplicacaoError> {
4139    // Empty is gated separately at the call site for a self-locating
4140    // diagnostic; re-checking here keeps the predicate usable from any
4141    // future call site (the M4 CR materializer's per-affinity
4142    // validator) without an empty-check footgun. Routes through the
4143    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4144    // peer name axes each land on.
4145    crate::render::require_valid_dns_1123_label(
4146        affinity,
4147        || AplicacaoError::PlacementAffinityEmpty,
4148        |reason| AplicacaoError::PlacementAffinityInvalid {
4149            affinity: affinity.to_string(),
4150            reason,
4151        },
4152    )
4153}
4154
4155/// Reject `:placement :shard-key` extractor expressions whose shape can
4156/// never legitimately drive the future M4 Akka-style cluster-sharding
4157/// reconciler's hash-extractor pass. Maps the per-byte / length checks
4158/// into the [`AplicacaoError::ShardKeyInvalid`] variant, so the
4159/// diagnostic is self-locating (the offending `:shard-key` value is
4160/// named verbatim alongside the parser-shaped reason) and the author can
4161/// grep their caixa.lisp for `:shard-key "<expr>"` and fix it in one
4162/// edit.
4163///
4164/// The `:shard-key` slot is the Akka-cluster-sharding `ExtractEntityId`
4165/// axis (MESH-COMPOSITION §II.4) — a single-token entity-id extractor
4166/// expression naming the message property to hash on. The realistic
4167/// shapes in the wild (`tenantId` / `customerId` / `userId` — bare
4168/// property name; `$tenantId` — Akka entity-id placeholder;
4169/// `metadata.tenantId` / `$.user.id` — JSONPath-style nested reference;
4170/// `${tenant}` — interpolation-style template) all sit in the printable
4171/// ASCII subset; the realistic *non-shapes* (a paste-from-doc
4172/// multi-line blob landing in `:shard-key`, an embedded space from a
4173/// paste-from-aligned-doc, a trailing newline from a paste-from-shell
4174/// heredoc, a non-ASCII byte from a paste-from-Unicode-doc, the
4175/// `:shard-key "tenant Id"` typo) silently passed the prior empty-only
4176/// check and the failure surfaces at the future M4 reconciler's hash
4177/// pass as a runtime extractor-evaluation error far from the source
4178/// `caixa.lisp`, with no field naming which member's `:shard-key`
4179/// carried the offending value.
4180///
4181/// The contract — the printable ASCII single-token intersection-floor
4182/// every Akka-style entity-id extractor implementation admits:
4183///
4184///   - 1..=[`PLACEMENT_SHARD_KEY_MAX_LEN`] (63) bytes — same cap as the
4185///     peer DNS-1123-label-shaped `:placement :affinity` /
4186///     `:placement :clusters` identifier axes; realistic shard-keys sit
4187///     well under 32 bytes, the cap surfaces paste-from-doc multi-line
4188///     blob footguns at validate time;
4189///   - every byte in the printable ASCII range `0x21..=0x7E` —
4190///     rejects whitespace (space, tab, CR, LF — `"$tenant Id"` /
4191///     `"$tenantId\n"` from paste-from-aligned-doc /
4192///     paste-from-shell-heredoc), control characters (`\x00..\x1F`,
4193///     `\x7F` — the canonical "embedded null from a copy-paste-binary
4194///     footgun"), and non-ASCII bytes (`"$tenàntId"` —
4195///     un-Punycode-encoded IDN that round-trips inconsistently across
4196///     NFC/NFD normalization).
4197///
4198/// The accepted set is broader than the DNS-1123 label floor the peer
4199/// `:placement :clusters` / `:placement :affinity` axes use because the
4200/// `:shard-key` value is not a K8s `metadata.name` / label-selector
4201/// landing site; it's an extractor expression the future Akka-style
4202/// reconciler reads as a property reference. The realistic forms
4203/// (`$tenantId`, `metadata.tenantId`, `${tenant}`, `$.user.id`) carry
4204/// `$` / `.` / `{` / `}` characters that the DNS-1123 grammar forbids
4205/// but every Akka-style entity-id extractor parses. The
4206/// printable-ASCII-token floor accepts every shape any such extractor
4207/// would accept while rejecting the cross-implementation footguns
4208/// (whitespace breaks token boundaries; non-ASCII round-trips
4209/// inconsistently across YAML emitters and NFC/NFD normalization;
4210/// control characters silently corrupt the next read).
4211///
4212/// Until this gate landed `validate_placement` only refused the
4213/// `Some("")` empty arm via [`AplicacaoError::ShardedKeyEmpty`]; a
4214/// structurally invalid `:shard-key` (`":shard-key \" $tenantId\""` —
4215/// leading space from paste-from-aligned-doc, `":shard-key \"$tenant
4216/// Id\""` — embedded space, `":shard-key \"$tenantId\\n\""` — trailing
4217/// newline from paste-from-shell-heredoc, `":shard-key \"$tenàntId\""`
4218/// — un-Punycode-encoded IDN, `":shard-key \"$tenantId\\x01\""` —
4219/// control character from paste-from-binary, the 64-byte over-cap
4220/// paste-from-doc multi-line slug) silently passed validate. The future
4221/// M4 Akka-style cluster-sharding reconciler's hash-extractor pass
4222/// would then surface the malformed value either as a runtime
4223/// extractor-evaluation error (whitespace breaks the extractor's token
4224/// boundary, no match) or as a silently-different shard assignment
4225/// across YAML emitters (non-ASCII normalizes differently between the
4226/// caixa-mesh-side YAML emitter and the in-cluster reconciler's YAML
4227/// parser, the same entity ID maps to two distinct shards on a
4228/// re-render). Lifting the shape gate to caixa-build time makes the
4229/// extractor-floor invariant a structural property of every validated
4230/// `Placement`: every `Sharded` placement past `validate_placement` has
4231/// a `:shard-key` the future M4 reconciler can hash without
4232/// re-validating at the runtime layer.
4233///
4234/// Mirrors the [`AplicacaoError::ContratoSlotInvalid`] /
4235/// [`AplicacaoError::ContratoSubjectInvalid`] /
4236/// [`AplicacaoError::ContratoEndpointInvalid`] payload-axis shape gates
4237/// on the peer `:contratos` payload axes — each lifts the
4238/// runtime-side parser's intersection-floor to a caixa-build-time gate,
4239/// closing the canonical "this passed validate but the runtime parser
4240/// rejected it" surprise.
4241fn validate_placement_shard_key(key: &str) -> Result<(), AplicacaoError> {
4242    // Empty is gated separately at the call site via the more
4243    // self-locating [`AplicacaoError::ShardedKeyEmpty`] diagnostic;
4244    // re-checking here keeps the predicate usable from any future call
4245    // site (the M4 CR materializer's per-shard-key validator) without
4246    // an empty-check footgun.
4247    if key.is_empty() {
4248        return Err(AplicacaoError::ShardedKeyEmpty);
4249    }
4250    if key.len() > PLACEMENT_SHARD_KEY_MAX_LEN {
4251        return Err(AplicacaoError::ShardKeyInvalid {
4252            shard_key: key.to_string(),
4253            reason: format!(
4254                "exceeds :shard-key max length of {PLACEMENT_SHARD_KEY_MAX_LEN} bytes \
4255                 (got {} bytes; realistic Akka-style entity-id extractor expressions \
4256                 — `tenantId`, `$tenantId`, `metadata.tenantId`, `${{tenant}}` — sit \
4257                 well under 32 bytes, this length suggests a paste-from-doc \
4258                 multi-line blob landed in `:shard-key` instead of a single-token \
4259                 extractor expression)",
4260                key.len()
4261            ),
4262        });
4263    }
4264    for &b in key.as_bytes() {
4265        if (0x21..=0x7E).contains(&b) {
4266            continue;
4267        }
4268        let reason = if b == b' ' {
4269            "contains a space (Akka-style entity-id extractor expressions are \
4270             single-token references like `tenantId` / `$tenantId` / `metadata.tenantId`; \
4271             whitespace breaks the extractor's token boundary at the runtime layer, \
4272             and the paste-from-aligned-doc / paste-from-CSV footgun silently lands \
4273             a multi-token blob in one `:shard-key` slot)"
4274                .to_string()
4275        } else if b == b'\t' {
4276            "contains a tab character (paste-from-aligned-doc footgun; the \
4277             Akka-style entity-id extractor reads `:shard-key` as a single-token \
4278             reference, embedded whitespace breaks the token boundary at the \
4279             runtime hash-extractor pass)"
4280                .to_string()
4281        } else if b == b'\n' || b == b'\r' {
4282            format!(
4283                "contains line terminator 0x{b:02x} (paste-from-shell-heredoc / \
4284                 paste-from-multiline-doc footgun; the Akka-style entity-id \
4285                 extractor reads `:shard-key` as a single-token reference, embedded \
4286                 newlines either truncate the value at the YAML emitter layer or \
4287                 break the token boundary at the runtime hash-extractor pass)"
4288            )
4289        } else if b < 0x20 || b == 0x7F {
4290            format!(
4291                "contains control character 0x{b:02x} (the canonical \
4292                 paste-from-binary / paste-from-screen-cleared-terminal footgun; \
4293                 control characters silently corrupt round-trip serialization \
4294                 across YAML emitters and break the runtime hash-extractor's \
4295                 single-token parser)"
4296            )
4297        } else {
4298            format!(
4299                "contains non-ASCII byte 0x{b:02x} (the canonical \
4300                 paste-from-Unicode-doc footgun; non-ASCII bytes round-trip \
4301                 inconsistently across NFC/NFD normalization on APFS / ext4 / \
4302                 across YAML emitter implementations — the same entity ID can \
4303                 silently map to two distinct shards on a re-render. Use a \
4304                 printable-ASCII extractor expression like `tenantId`, \
4305                 `$tenantId`, or `metadata.tenantId`)"
4306            )
4307        };
4308        return Err(AplicacaoError::ShardKeyInvalid {
4309            shard_key: key.to_string(),
4310            reason,
4311        });
4312    }
4313    Ok(())
4314}
4315
4316/// Reject `:contratos :de` / `:contratos :para` values whose shape
4317/// can never legitimately match a validated `:membros :caixa`. Thin
4318/// wrapper around [`crate::render::is_dns_1123_label`] that maps the
4319/// shared parser-shaped reason into the
4320/// [`AplicacaoError::ContratoCaixaInvalid`] variant, so the per-edge
4321/// diagnostic is self-locating (which slot — `:de` or `:para` — and
4322/// the offending value verbatim) and the author can grep their
4323/// caixa.lisp for `:de "<name>"` / `:para "<name>"` and fix it in
4324/// one edit.
4325///
4326/// Until this gate landed an empty or DNS-1123-malformed `:de` /
4327/// `:para` (`:de ""`, `:de "Cart"` the canonical TitleCase-from-an-ADR
4328/// typo, `:de "my_cart"` the Python-module-name leak, `:de "team.cart"`
4329/// the namespace-dot-on-a-label confusion, `:de "-cart"` / `:de "cart-"`
4330/// the boundary-hyphen violation, the 64-byte over-cap slug, `:de "café"`
4331/// un-Punycode-encoded IDN) silently passed the per-axis check and
4332/// surfaced as [`AplicacaoError::ContratoMemberMissing`] at the
4333/// membership lookup — diagnostic-framed as "this caixa is not in
4334/// `:membros`" when the root cause is "this `:de` value is not a
4335/// well-shaped Servico-name identifier and could never legitimately
4336/// match any validated member". Because every `:membros :caixa` is
4337/// shape-validated through [`validate_membro_caixa`] (3f9d7a0), the
4338/// `names` HashSet structurally never contains an empty / malformed
4339/// string, so the membership lookup arm misframes every empty /
4340/// malformed input. Lifting the shape arm ahead of the lookup
4341/// preserves the legitimate `ContratoMemberMissing` arm (a
4342/// well-shaped `:de` that simply isn't in `:membros` — a phantom
4343/// reference) while routing every structurally-impossible-to-match
4344/// input through the narrower self-locating shape diagnostic.
4345///
4346/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4347/// (3f9d7a0) and [`AplicacaoError::PlacementClusterInvalid`]
4348/// (6c8c00b) — the third Aplicacao-level Servico-name reference axis
4349/// to land on the canonical [`crate::render::is_dns_1123_label`]
4350/// floor. The `slot: &'static str` field carries the kebab-case
4351/// `:de` / `:para` tag verbatim, mirroring [`BehaviorSpec::validate`]'s
4352/// per-callback-slot diagnostic shape and the
4353/// [`ManifestError::CodePathDuplicate`] (e113ace) / [`DepError::DepIsSelf`]
4354/// (85f102c) cross-list-tag pattern.
4355fn validate_contrato_caixa(slot: &'static str, caixa: &str) -> Result<(), AplicacaoError> {
4356    // Routes through the shared
4357    // [`crate::render::require_valid_dns_1123_label`] gate the peer
4358    // name axes each land on. The `slot: &'static str` field flows
4359    // through both error variants so the diagnostic names which
4360    // per-edge axis (`:de` vs `:para`) the offending value came from.
4361    crate::render::require_valid_dns_1123_label(
4362        caixa,
4363        || AplicacaoError::ContratoCaixaEmpty { slot },
4364        |reason| AplicacaoError::ContratoCaixaInvalid {
4365            slot,
4366            caixa: caixa.to_string(),
4367            reason,
4368        },
4369    )
4370}
4371
4372/// Reject `:entrada :para` values whose shape can never legitimately
4373/// match a validated `:membros :caixa`. Thin wrapper around
4374/// [`crate::render::is_dns_1123_label`] that maps the shared parser-
4375/// shaped reason into the [`AplicacaoError::EntradaParaInvalid`]
4376/// variant, so the diagnostic is self-locating (the offending
4377/// `:entrada :para` value is named verbatim) and the author can grep
4378/// their caixa.lisp for `:para "<name>"` and fix it in one edit.
4379///
4380/// Until this gate landed an empty or DNS-1123-malformed `:entrada
4381/// :para` (`:para ""`, `:para "Cart"` the canonical TitleCase-from-an-
4382/// ADR typo, `:para "my_cart"` the Python-module-name leak,
4383/// `:para "team.cart"` the namespace-dot-on-a-label confusion,
4384/// `:para "-cart"` / `:para "cart-"` the boundary-hyphen violation,
4385/// the 64-byte over-cap slug, `:para "café"` un-Punycode-encoded IDN)
4386/// silently passed the per-axis check and surfaced as
4387/// [`AplicacaoError::EntradaMemberMissing`] at the membership lookup
4388/// — diagnostic-framed as "this caixa is not in `:membros`" when the
4389/// root cause is "this `:entrada :para` value is not a well-shaped
4390/// Servico-name identifier and could never legitimately match any
4391/// validated member". Because every `:membros :caixa` is shape-
4392/// validated through [`validate_membro_caixa`] (3f9d7a0), the `names`
4393/// `HashSet` structurally never contains an empty / malformed string,
4394/// so the membership lookup arm misframes every empty / malformed
4395/// input. Lifting the shape arm ahead of the lookup preserves the
4396/// legitimate `EntradaMemberMissing` arm (a well-shaped `:para` that
4397/// simply isn't in `:membros` — a phantom reference) while routing
4398/// every structurally-impossible-to-match input through the narrower
4399/// self-locating shape diagnostic.
4400///
4401/// Same diagnostic shape as [`AplicacaoError::MembroCaixaInvalid`]
4402/// (3f9d7a0), [`AplicacaoError::PlacementClusterInvalid`] (6c8c00b),
4403/// and [`AplicacaoError::ContratoCaixaInvalid`] (8d5af6b) — the
4404/// fourth and last Aplicacao-level Servico-name reference axis to
4405/// land on the canonical [`crate::render::is_dns_1123_label`] floor.
4406/// No `slot: &'static str` field because there is only one axis
4407/// (`:entrada :para`), unlike the dual-axis `:contratos :de`/`:para`;
4408/// the simpler shape mirrors [`validate_membro_caixa`] and
4409/// [`validate_placement_cluster`].
4410fn validate_entrada_para(para: &str) -> Result<(), AplicacaoError> {
4411    // Empty is gated separately at the call site for a self-locating
4412    // diagnostic; re-checking here keeps the predicate usable from any
4413    // future call site (the M4 CR materializer's per-`:entrada`
4414    // validator) without an empty-check footgun. Routes through the
4415    // shared [`crate::render::require_valid_dns_1123_label`] gate the
4416    // peer name axes each land on.
4417    crate::render::require_valid_dns_1123_label(
4418        para,
4419        || AplicacaoError::EntradaParaEmpty,
4420        |reason| AplicacaoError::EntradaParaInvalid {
4421            para: para.to_string(),
4422            reason,
4423        },
4424    )
4425}
4426
4427/// Reject `:entrada :host` values the K8s Gateway API v1 apiserver
4428/// would refuse at admission time. The contract — exactly the regex
4429/// the Gateway API CRD's OpenAPI schema enforces on `Listener.hostname`
4430/// and `HTTPRoute.spec.hostnames[]`,
4431/// `^(\*\.)?[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$`
4432/// (max length 253; per-label max length 63):
4433///
4434///   - lowercase RFC 1123 DNS subdomain (`[a-z0-9-]` only; no
4435///     uppercase, no underscore, no Unicode/IDN — IDN must be
4436///     pre-encoded as Punycode `xn--…` by the author);
4437///   - exactly one optional leading wildcard label (`*.`); a wildcard
4438///     in any non-leading label position is rejected;
4439///   - each `.`-separated label is 1..=63 bytes, with non-hyphen
4440///     alphanumeric at both boundaries (no `-foo`, no `foo-`);
4441///   - total length 1..=253 bytes;
4442///   - no IPv4 literal (Gateway API forbids IP literals);
4443///   - no scheme (`https://`, `http://`), no port (`:8080`), no
4444///     whitespace, no path (`/`).
4445///
4446/// Lifted as a typed gate (rather than an inline cascade in
4447/// `validate()`) so the contract lives in one place — every future
4448/// per-host axis (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
4449/// materializer's host validator, the future per-`:entrada` SAN
4450/// emission for cert-manager Certificates, the multi-`:entrada`
4451/// host-collision gate when M4 lands `:entrada` as a `Vec`) reaches
4452/// for the same predicate, not its own. Same compounding shape as
4453/// `is_canonical_rate_limit_window` (808017c) and
4454/// [`WitTarget::label`] (previously the free `contrato_target_label`
4455/// helper, 5dbcfaf; lifted onto the typed [`WitTarget`] enum so the
4456/// per-variant label match is compiler-checked-exhaustive).
4457///
4458/// The diagnostic carries the offending `host:` verbatim plus a
4459/// parser-shaped `reason:` naming the specific violation, so the
4460/// author can grep their caixa.lisp for `:host "<host>"` and fix it
4461/// in one edit. Same diagnostic shape as `MembroVersaoInvalid`
4462/// (9888b13).
4463fn validate_entrada_host(host: &str) -> Result<(), AplicacaoError> {
4464    // Empty is already gated by `EmptyEntradaHost` at the call site;
4465    // re-checking here keeps the predicate usable from any future
4466    // call site (M4 CR materializer) without an empty-check footgun.
4467    if host.is_empty() {
4468        return Err(AplicacaoError::EmptyEntradaHost);
4469    }
4470    if host.len() > crate::render::GATEWAY_API_HOSTNAME_MAX_LEN {
4471        return Err(AplicacaoError::EntradaHostInvalid {
4472            host: host.to_string(),
4473            reason: format!(
4474                "exceeds Gateway API v1 Hostname max length of {cap} bytes \
4475                 (got {} bytes; the K8s apiserver rejects longer hostnames at admission time)",
4476                host.len(),
4477                cap = crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
4478            ),
4479        });
4480    }
4481    if host.contains("://") {
4482        return Err(AplicacaoError::EntradaHostInvalid {
4483            host: host.to_string(),
4484            reason: "must not carry a scheme (drop the `https://` or `http://` prefix; \
4485                     Gateway API takes the bare hostname)"
4486                .to_string(),
4487        });
4488    }
4489    if host.contains('/') {
4490        return Err(AplicacaoError::EntradaHostInvalid {
4491            host: host.to_string(),
4492            reason: "must not carry a path (drop the `/…` suffix; Gateway API path \
4493                     matching is in `:entrada :paths`)"
4494                .to_string(),
4495        });
4496    }
4497    // After the `://` scheme-prefix and `/` path arms have ruled out the
4498    // two `:`-bearing shapes the Gateway API actively rejects with
4499    // location-shaped diagnostics, any remaining `:` in the host body is
4500    // either the canonical "I put the port in the `:host` slot"
4501    // authoring footgun (`"checkout.quero.cloud:8080"` — the `:port`
4502    // slot lives one axis away on the same `:entrada` block) or an
4503    // unbracketed IPv6 literal (`"2001:db8::1"`) which Gateway API v1
4504    // Hostname forbids identically to the IPv4-literal arm below. Both
4505    // shapes silently fell through the `://` and `/` arms before this
4506    // lift and surfaced as a deep `label "<rest>:<port>" contains
4507    // invalid character ':'` diagnostic from the per-byte loop near the
4508    // bottom of this predicate, which named the offending byte but not
4509    // the canonical authoring fix — for the port case the author has to
4510    // know the `:entrada` block carries a separate `:port u16` slot
4511    // (`caixa-core/src/aplicacao.rs:1667`, `default_port = 8080`) and
4512    // move the value over; for the IPv6 case the author has to know
4513    // Gateway API v1 forbids IP literals across the board. The contract
4514    // doc-comment above already promises "no port (`:8080`)" verbatim
4515    // in the rejected-shape enumeration but the predicate's
4516    // implementation refused the `:` only as a side-effect of the
4517    // per-label `[a-z0-9-]` character-class loop; this arm brings the
4518    // implementation in line with the documented contract by surfacing
4519    // the canonical fix at the top-level shape gate, peer with how the
4520    // `://` arm names the scheme prefix and the `/` arm names the
4521    // `:entrada :paths` axis. Same compounding trajectory the recent
4522    // `is_gateway_api_http_path` (6a17961) per-byte tightening followed
4523    // — the typed slot's rejected set matches the apiserver's rejected
4524    // set, structurally, with a self-locating diagnostic at the
4525    // offending axis instead of a deep parser-shape leak.
4526    if host.contains(':') {
4527        return Err(AplicacaoError::EntradaHostInvalid {
4528            host: host.to_string(),
4529            reason: "must not contain `:` (the port belongs in the `:entrada :port` \
4530                     slot — a separate `u16` axis on the same `:entrada` block, \
4531                     defaulting to 8080 — not in the host body; drop the `:<port>` \
4532                     suffix and author the bare hostname. If you intended an IPv6 \
4533                     literal (`2001:db8::1` / `::1` / `fe80::1`), Gateway API v1 \
4534                     Hostname forbids IP literals identically to the IPv4-literal \
4535                     arm — use a DNS name)"
4536                .to_string(),
4537        });
4538    }
4539    // Routed through the lifted [`crate::render::find_ascii_whitespace_byte`]
4540    // predicate — the same single source of truth every peer
4541    // ASCII-whitespace scan in caixa-core flows through: the four
4542    // typed-magnitude codec sites (`limits::parse_byte_size` backing
4543    // `:limits :memory`, `limits::parse_duration` backing `:limits
4544    // :wall-clock`, `limits::parse_millicores` backing `:limits :cpu`,
4545    // `aplicacao::rate_limit_codec::parse` backing `:politicas
4546    // :rate-limit`) and the shared duration codec
4547    // (`supervisor::duration_codec::parse`) backing `:supervisor
4548    // :restart-window` / `:politicas :timeout` / `:politicas
4549    // :circuit-breaker :window`. This landing closes the last string-typed
4550    // slot in caixa-core still calling `.bytes().any(|b|
4551    // b.is_ascii_whitespace())` inline — every ASCII-whitespace scan
4552    // across every typed slot now shares one predicate, so a future
4553    // stricter classification (BOM `\u{FEFF}` / ZWSP `\u{200B}` / ZWJ
4554    // `\u{200D}` — the "invisible but not `char::is_whitespace`" class
4555    // deliberately excluded from the peer non-ASCII predicate) can
4556    // extend at this shared site in one edit rather than seven
4557    // independent scans diverging over time. Naming the offending byte
4558    // in the diagnostic (`0x20` space / `0x09` tab / `0x0a` LF / `0x0c`
4559    // FF / `0x0d` CR) matches the substrate-wide "the diagnostic carries
4560    // the offending byte verbatim" discipline every peer codec site
4561    // already carries (`limits.rs:722` / `limits.rs:784` / `limits.rs:845`
4562    // / `supervisor.rs:823` / `aplicacao.rs:1640`).
4563    if let Some(b) = crate::render::find_ascii_whitespace_byte(host) {
4564        return Err(AplicacaoError::EntradaHostInvalid {
4565            host: host.to_string(),
4566            reason: format!(
4567                "contains ASCII whitespace byte 0x{b:02x} (Gateway API v1 \
4568                 Hostname is a single-token DNS name — leading, trailing, \
4569                 or embedded whitespace breaks the K8s apiserver's Hostname \
4570                 regex at admission time; the paste-from-aligned-doc / \
4571                 paste-from-shell-history / paste-from-CSV footgun silently \
4572                 lands a multi-token blob in `:entrada :host`. Strip every \
4573                 whitespace byte and author the bare hostname — space \
4574                 `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d` all \
4575                 refuse identically)"
4576            ),
4577        });
4578    }
4579    // Peer of the ASCII-whitespace scan above: route the non-ASCII
4580    // subset of Unicode `White_Space` through the shared
4581    // [`crate::render::find_non_ascii_whitespace_char`] predicate — the
4582    // single source of truth every peer non-ASCII-whitespace scan in
4583    // caixa-core flows through: `limits::parse_byte_size` (`:limits
4584    // :memory`), `limits::parse_duration` (`:limits :wall-clock`),
4585    // `limits::parse_millicores` (`:limits :cpu`),
4586    // `aplicacao::rate_limit_codec::parse` (`:politicas :rate-limit`),
4587    // and `supervisor::duration_codec::parse` (`:supervisor
4588    // :restart-window` / `:politicas :timeout` / `:politicas
4589    // :circuit-breaker :window`). Before this arm, a NBSP-prefixed host
4590    // (`"\u{00A0}checkout.quero.cloud"` — paste-from-typography), a
4591    // LINE-SEPARATOR-suffixed host (`"checkout.quero.cloud\u{2028}"` —
4592    // paste-from-web-doc), or an EM-SPACE-split host
4593    // (`"checkout.\u{2003}quero.cloud"` — paste-from-typography)
4594    // survived this predicate's ASCII byte-scan (none of the UTF-8
4595    // bytes of `\u{00A0}` / `\u{2028}` / `\u{2003}` match
4596    // `u8::is_ascii_whitespace`), then landed on the per-label
4597    // `bytes[0].is_ascii_alphanumeric()` arm near the bottom of this
4598    // predicate with the generic `label "…" must start and end with an
4599    // alphanumeric` diagnostic — a "far from source at build-time"
4600    // leak that names the label-shape violation but not the
4601    // paste-from-typography origin the author actually needs to fix.
4602    // Peer with the four codec sites the 1b75b38 landing pinned: the
4603    // typed slot's diagnostic axis names the offending codepoint
4604    // (`U+XXXX`) verbatim rather than laundering the value through a
4605    // downstream label-shape arm, so the author can grep their
4606    // caixa.lisp for the invisible codepoint at the surfaced position
4607    // rather than eyeball a multi-byte host for embedded NBSP / LINE
4608    // SEPARATOR / EM-SPACE. Same "single lifted source of truth"
4609    // discipline the peer ASCII-whitespace arm (720ac3b) carries:
4610    // drift between any two typed-slot sites' non-ASCII-whitespace
4611    // rejection set becomes a single-edit fix at the shared predicate
4612    // rather than N independent inline scans diverging over time, and
4613    // a future stricter classification (BOM `\u{FEFF}` / ZWSP
4614    // `\u{200B}` / ZWJ `\u{200D}` — the "invisible but not
4615    // `char::is_whitespace`" class the peer non-ASCII predicate's
4616    // doc-comment names as the follow-up trajectory) extends at the
4617    // shared predicate in one edit rather than seven.
4618    if let Some(ch) = crate::render::find_non_ascii_whitespace_char(host) {
4619        return Err(AplicacaoError::EntradaHostInvalid {
4620            host: host.to_string(),
4621            reason: format!(
4622                "contains non-ASCII Unicode whitespace character {ch:?} \
4623                 (U+{codepoint:04X}) — Gateway API v1 Hostname is a \
4624                 single-token DNS name limited to `[a-z0-9-]` labels; \
4625                 the paste-from-typography footgun silently lands an \
4626                 invisible codepoint (NBSP `U+00A0`, LINE SEPARATOR \
4627                 `U+2028`, EM-SPACE `U+2003`, IDEOGRAPHIC SPACE \
4628                 `U+3000`, and every other member of the Unicode \
4629                 `White_Space` property outside the ASCII byte range) \
4630                 in `:entrada :host`, which the K8s apiserver's \
4631                 Hostname regex refuses at admission time far from the \
4632                 caixa.lisp source line. Strip every non-ASCII \
4633                 whitespace character and author the bare hostname \
4634                 with only ASCII bytes (write \"checkout.quero.cloud\" \
4635                 verbatim)",
4636                codepoint = ch as u32,
4637            ),
4638        });
4639    }
4640
4641    // Strip the optional single leading wildcard label *before* the
4642    // trailing-dot check so the bare `"*."` form surfaces the more
4643    // self-locating "wildcard without domain" diagnostic instead of
4644    // the generic "trailing dot" one.
4645    let (had_wildcard, rest) = match host.strip_prefix("*.") {
4646        Some(r) => (true, r),
4647        None => (false, host),
4648    };
4649    if had_wildcard && rest.is_empty() {
4650        return Err(AplicacaoError::EntradaHostInvalid {
4651            host: host.to_string(),
4652            reason: "wildcard `*.` must be followed by a domain (e.g. `*.example.com`)".to_string(),
4653        });
4654    }
4655    if rest.contains('*') {
4656        return Err(AplicacaoError::EntradaHostInvalid {
4657            host: host.to_string(),
4658            reason: "wildcard `*` is allowed only as the first label (`*.example.com`); \
4659                     no inner or trailing `*` labels"
4660                .to_string(),
4661        });
4662    }
4663    if rest.ends_with('.') {
4664        return Err(AplicacaoError::EntradaHostInvalid {
4665            host: host.to_string(),
4666            reason: "must not have a trailing `.` (Gateway API hostnames are not \
4667                     fully-qualified with a root dot; the apiserver regex rejects \
4668                     trailing dots)"
4669                .to_string(),
4670        });
4671    }
4672
4673    // Reject pure IPv4 literals: four dot-separated labels, every
4674    // label all-ASCII-digits. Gateway API v1 explicitly forbids IP
4675    // literals as Hostnames.
4676    let labels: Vec<&str> = rest.split('.').collect();
4677    if labels.len() == 4
4678        && labels
4679            .iter()
4680            .all(|l| !l.is_empty() && l.bytes().all(|b| b.is_ascii_digit()))
4681    {
4682        return Err(AplicacaoError::EntradaHostInvalid {
4683            host: host.to_string(),
4684            reason: "must not be an IPv4 literal (Gateway API v1 Hostname forbids IP \
4685                     literals; use a DNS name)"
4686                .to_string(),
4687        });
4688    }
4689
4690    // Per-label shape: 1..=63 bytes, lowercase ASCII alphanumeric +
4691    // hyphen, with non-hyphen at both boundaries.
4692    for label in &labels {
4693        if label.is_empty() {
4694            return Err(AplicacaoError::EntradaHostInvalid {
4695                host: host.to_string(),
4696                reason: "has an empty label (consecutive `..` or a leading `.`)".to_string(),
4697            });
4698        }
4699        if label.len() > crate::render::DNS_1123_LABEL_MAX_LEN {
4700            return Err(AplicacaoError::EntradaHostInvalid {
4701                host: host.to_string(),
4702                reason: format!(
4703                    "label {label:?} exceeds DNS-1123 label max length of \
4704                     {cap} bytes (got {} bytes)",
4705                    label.len(),
4706                    cap = crate::render::DNS_1123_LABEL_MAX_LEN,
4707                ),
4708            });
4709        }
4710        let bytes = label.as_bytes();
4711        if !bytes[0].is_ascii_alphanumeric() || !bytes[bytes.len() - 1].is_ascii_alphanumeric() {
4712            return Err(AplicacaoError::EntradaHostInvalid {
4713                host: host.to_string(),
4714                reason: format!(
4715                    "label {label:?} must start and end with an alphanumeric \
4716                     (no leading or trailing `-`)"
4717                ),
4718            });
4719        }
4720        for &b in bytes {
4721            let valid = b.is_ascii_digit() || b.is_ascii_lowercase() || b == b'-';
4722            if !valid {
4723                let msg = if b.is_ascii_uppercase() {
4724                    format!(
4725                        "label {label:?} contains uppercase character {ch:?} \
4726                         (Gateway API hostnames are lowercase-only; use {lower:?})",
4727                        ch = b as char,
4728                        lower = label.to_ascii_lowercase()
4729                    )
4730                } else if b == b'_' {
4731                    format!(
4732                        "label {label:?} contains `_` (Gateway API hostnames \
4733                         allow only `[a-z0-9-]`; use `-` instead)"
4734                    )
4735                } else {
4736                    format!(
4737                        "label {label:?} contains invalid character {ch:?} \
4738                         (Gateway API hostnames allow only `[a-z0-9-]`)",
4739                        ch = b as char
4740                    )
4741                };
4742                return Err(AplicacaoError::EntradaHostInvalid {
4743                    host: host.to_string(),
4744                    reason: msg,
4745                });
4746            }
4747        }
4748    }
4749    Ok(())
4750}
4751
4752/// Reject `:entrada :paths` entries the K8s Gateway API v1 apiserver
4753/// would refuse at admission time. Thin wrapper around
4754/// [`crate::render::is_gateway_api_http_path`] that maps the shared
4755/// parser-shaped reason into the [`AplicacaoError::EntradaPathInvalid`]
4756/// variant, preserving the more self-locating
4757/// [`AplicacaoError::EntradaPathEmpty`] /
4758/// [`AplicacaoError::EntradaPathNotAbsolute`] diagnostics when the
4759/// path fails those narrower invariants first.
4760///
4761/// The contract is the canonical HTTP-path grammar — `1..=
4762/// [`crate::render::GATEWAY_API_HTTP_PATH_MAX_LEN`] (1024) bytes,
4763/// leading `/`, no consecutive `/`, no `.`/`..` segments, no `?`/`#`/
4764/// whitespace/control/non-ASCII bytes — shared with the
4765/// `:contratos :endpoint` axis through the lifted predicate so drift
4766/// between either landing site and the K8s apiserver-side
4767/// HTTPPathMatch.value OpenAPI schema is a build error visible at
4768/// the predicate, not a per-renderer "this passed validate but failed
4769/// admission" surprise. The diagnostic carries the offending `path:`
4770/// verbatim plus a parser-shaped `reason:` naming the specific
4771/// violation, so the author can grep their caixa.lisp for `:paths`
4772/// and fix it in one edit. Same diagnostic shape as
4773/// [`AplicacaoError::ContratoEndpointInvalid`] on the peer HTTP-path
4774/// axis.
4775fn validate_entrada_path(path: &str) -> Result<(), AplicacaoError> {
4776    // Empty and missing-leading-`/` are already gated at the call
4777    // site by `EntradaPathEmpty` and `EntradaPathNotAbsolute`; re-
4778    // checking here keeps the per-axis narrower diagnostics in force
4779    // when the predicate is reached directly (and `is_gateway_api_http_path`
4780    // itself defends against `bytes[0]`-style indexing on empty
4781    // input).
4782    if path.is_empty() {
4783        return Err(AplicacaoError::EntradaPathEmpty);
4784    }
4785    if !path.starts_with('/') {
4786        return Err(AplicacaoError::EntradaPathNotAbsolute {
4787            path: path.to_string(),
4788        });
4789    }
4790    crate::render::is_gateway_api_http_path(path).map_err(|reason| {
4791        AplicacaoError::EntradaPathInvalid {
4792            path: path.to_string(),
4793            reason,
4794        }
4795    })
4796}
4797
4798mod rate_limit_codec {
4799    // `Duration` is no longer named here — the codec routes through
4800    // the substrate primitive [`super::RateLimitUnit::window_from_suffix`]
4801    // (parse arm, `&str → Duration`) and [`super::RateLimit::canonical_unit`]
4802    // (render arm, `Duration → RateLimitUnit`) typed dispatches that carry
4803    // the canonical `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection on the
4804    // closed-set enum's arm-table rather than through vestigial free-helper
4805    // delegates.
4806    use super::{RateLimit, RateLimitUnit};
4807    use serde::{Deserializer, Serializer};
4808
4809    pub fn serialize<S: Serializer>(v: &Option<RateLimit>, s: S) -> Result<S::Ok, S::Error> {
4810        // Route through the canonical [`crate::render::serialize_option_via_str`]
4811        // — the substrate-side single-owner primitive for the forward
4812        // arm of the typed-magnitude codec family. See its docstring
4813        // for the full sibling roster.
4814        crate::render::serialize_option_via_str(v, s, render)
4815    }
4816
4817    pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<RateLimit>, D::Error> {
4818        // Route through the canonical [`crate::render::deserialize_option_via_str`]
4819        // — the substrate-side single-owner primitive for the reverse
4820        // arm of the typed-magnitude codec family. See its docstring
4821        // for the full sibling roster.
4822        crate::render::deserialize_option_via_str(d, parse)
4823    }
4824
4825    fn parse(s: &str) -> Result<RateLimit, String> {
4826        // Paired whitespace-rejection arm — same canonical-form
4827        // render-determinism discipline as the peer
4828        // `limits::parse_byte_size` / `limits::parse_duration` /
4829        // `limits::parse_millicores` /
4830        // `supervisor::duration_codec::parse` sites: the ASCII
4831        // byte-scan closes the WhatWG-conformant whitespace bytes
4832        // (`0x20`, `0x09`, `0x0A`, `0x0C`, `0x0D`), the non-ASCII
4833        // `char::is_whitespace` scan closes the strictly-complementary
4834        // Unicode `White_Space` class (NBSP `\u{00A0}`, LINE SEPARATOR
4835        // `\u{2028}`, EM-SPACE `\u{2003}`, and the peer typography
4836        // codepoints) that `str::trim` at parse entry silently strips.
4837        // Either drift class would round-trip through `render` to a
4838        // *different* canonical form on next emit — breaking the
4839        // THEORY.md Part V render-determinism contract on
4840        // `:politicas :rate-limit`.
4841        //
4842        // Routed through the lifted [`crate::render::reject_whitespace`]
4843        // primitive — the substrate-side single-owner paired-arm gate
4844        // every typed-magnitude codec in caixa-core shares.
4845        crate::render::reject_whitespace::<String, _, _>(
4846            s,
4847            |b| {
4848                format!(
4849                    "rate-limit: value {s:?} contains whitespace byte 0x{b:02x} — the canonical \
4850                 authoring form for `:politicas :rate-limit` is `<integer>/<s|m|h>` (e.g. \
4851                 `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) with no whitespace bytes \
4852                 anywhere. A whitespace-carrying shape (`\" 100/s\"`, `\"100/s \"`, \
4853                 `\"100 /s\"`, `\"100/ s\"`, `\"100 / s\"`, `\"100/s\\n\"`, `\"\\t100/s\"`) \
4854                 round-trips through `render` to a *different* canonical form (`\"100/s\"`) \
4855                 on first serialize — breaking the THEORY.md Part V render-determinism \
4856                 contract every typed slot carries. Strip every whitespace byte (write \
4857                 `\"100/s\"` verbatim)"
4858                )
4859            },
4860            |ch| {
4861                format!(
4862                    "rate-limit: value {s:?} contains non-ASCII Unicode whitespace character \
4863                 {ch:?} (U+{cp:04X}) — the canonical authoring form for `:politicas \
4864                 :rate-limit` is `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, \
4865                 `\"10000/h\"`) with no whitespace characters anywhere (ASCII or Unicode). \
4866                 A non-ASCII-whitespace-carrying shape (`\"\\u{{00A0}}100/s\"`, \
4867                 `\"100/s\\u{{2028}}\"`, `\"100\\u{{2003}}/s\"`) survives the ASCII \
4868                 byte-scan but `str::trim` (which uses `char::is_whitespace` — the \
4869                 Unicode `White_Space` property, strictly wider than the ASCII byte set) \
4870                 silently strips it at parse entry, and the value round-trips through \
4871                 `render` to a *different* canonical form (`\"100/s\"`) on first \
4872                 serialize — breaking the THEORY.md Part V render-determinism contract \
4873                 every typed slot carries. Strip every non-ASCII whitespace character \
4874                 (write `\"100/s\"` verbatim with only ASCII bytes)",
4875                    cp = ch as u32
4876                )
4877            },
4878        )?;
4879        let s = s.trim();
4880        let (rate_str, unit) = s
4881            .split_once('/')
4882            .ok_or_else(|| format!("rate-limit must be `<n>/<unit>`, got {s:?}"))?;
4883        let rate_trim = rate_str.trim();
4884        // The canonical authoring form for `:politicas :rate-limit` is
4885        // `<integer>/<s|m|h>` — every magnitude [`render`] emits is a
4886        // non-negative integer with no decimal point and no leading
4887        // sign, so the parser's accepted set must match for
4888        // serialize/deserialize to round-trip without canonical-form
4889        // drift. Until this gate landed the parser accepted any
4890        // `u32::from_str`-shaped magnitude — and current Rust
4891        // `u32::from_str` permissively accepts a leading `+` (`"+100"`
4892        // → 100), so `"+100/s"` parsed to `RateLimit { 100, 1s }` and
4893        // serde silently round-tripped to `"100/s"` on the next emit
4894        // (a *different* canonical string) — breaking the THEORY.md
4895        // Part V render-determinism contract on the fifth typed-codec
4896        // surface in caixa-core (peer with the four duration codecs the
4897        // 1c55a2a / 818dd38 / d1fd67b / 737a676 / d53c922 trajectory
4898        // already covered: `supervisor::duration_codec` backing three
4899        // typed-duration slots, `limits::parse_duration` backing
4900        // `:limits :wall-clock`, `limits::parse_byte_size` backing
4901        // `:limits :memory`). The fractional / decimal-shaped sibling
4902        // (`"1.5/s"`, `"1.0/s"`, `"0.5/m"`) lands on `u32::from_str`'s
4903        // existing rejection arm, but the diagnostic is value-laundered
4904        // (the bare `"rate-limit rate \"1.5\" not a u32"` wording
4905        // doesn't name the canonical-form remediation or the round-trip
4906        // drift the next emit would produce); this gate lifts the
4907        // fractional arm onto the same canonical-form diagnostic the
4908        // peer codecs carry.
4909        //
4910        // Strict canonical form: every byte of the magnitude is an
4911        // ASCII digit (no `.`, no `+`, no `-`). On non-digit-only
4912        // inputs the gate distinguishes "non-canonical-but-numeric"
4913        // (parses as f64 or i64 — surfaced with a self-locating
4914        // diagnostic naming the canonical authoring form and the
4915        // round-trip drift the rejected shape would produce on first
4916        // serialize) from "garbage" (parses as neither — surfaced with
4917        // the existing narrower `"not a u32"` wording so its
4918        // diagnostic shape remains stable for the parser-shape footgun
4919        // case).
4920        //
4921        // Routed through the lifted
4922        // [`crate::render::is_digit_only_magnitude`] predicate — the
4923        // same source of truth the four peer typed-magnitude codec
4924        // sites share.
4925        let digit_only = crate::render::is_digit_only_magnitude(rate_trim);
4926        if !digit_only {
4927            let numeric = rate_trim.parse::<f64>().is_ok() || rate_trim.parse::<i64>().is_ok();
4928            if numeric {
4929                return Err(format!(
4930                    "rate-limit: rate {rate_trim:?} is not a non-negative integer — the \
4931                     canonical authoring form for `:politicas :rate-limit` is \
4932                     `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4933                     with no decimal point and no leading `+` / `-` sign. A fractional / \
4934                     signed magnitude (`\"1.5/s\"`, `\"+100/s\"`, `\"-1/s\"`) round-trips \
4935                     through `render` to a *different* canonical form (`\"1/s\"`, \
4936                     `\"100/s\"`, parser-reject) on first serialize — breaking the \
4937                     THEORY.md Part V render-determinism contract every typed slot \
4938                     carries. Pick an integer rate that fits the desired window \
4939                     (write `\"6000/m\"` instead of `\"1.66/s\"`)"
4940                ));
4941            }
4942            return Err(format!("rate-limit rate {rate_str:?} not a u32"));
4943        }
4944        // Leading-zero arm — peer with the prior `"+100/s"` arm above
4945        // (4eeae98's predecessor) on the same canonical-form
4946        // render-determinism axis. The digit-only gate accepts
4947        // `"0100/s"`, `"00/s"`, `"007/h"` as `u32::from_str` parses
4948        // them losslessly (= 100, 0, 7), but `render` emits the
4949        // leading-zero-stripped form (`"100/s"`, `"0/s"`, `"7/h"`) —
4950        // a *different* canonical string on the next emit, breaking
4951        // the THEORY.md Part V render-determinism contract the same
4952        // way `"+100/s"` did before the leading-`+` arm landed. The
4953        // single-byte magnitude `"0"` itself round-trips losslessly
4954        // through `render` (`render(0)` emits `"0/s"`) — the
4955        // downstream [`AplicacaoError::PolicyRateLimitZero`] gate is
4956        // what refuses rate-zero authoring, so `"0/s"` stays in the
4957        // accepted set at this codec layer and the diagnostic
4958        // partitioning between canonical-form drift (this arm) and
4959        // semantic-zero (the downstream gate) remains stable.
4960        // Peer with the future leading-zero arms on the three peer
4961        // typed-magnitude codecs the trajectory acknowledges:
4962        // `supervisor::duration_codec`, `limits::parse_duration`,
4963        // `limits::parse_byte_size` — each carries the same
4964        // canonical-form-drift class today; this gate lands the
4965        // discipline on the fourth typed-magnitude codec in
4966        // caixa-core first because the peer `"+100/s"` arm above is
4967        // the closest predecessor on the trajectory.
4968        //
4969        // Routed through the lifted
4970        // [`crate::render::is_leading_zero_padded_magnitude`]
4971        // predicate — the same source of truth the four peer
4972        // typed-magnitude codec sites share.
4973        if crate::render::is_leading_zero_padded_magnitude(rate_trim) {
4974            return Err(format!(
4975                "rate-limit: rate {rate_trim:?} has a non-canonical leading zero — the \
4976                 canonical authoring form for `:politicas :rate-limit` is \
4977                 `<integer>/<s|m|h>` (e.g. `\"100/s\"`, `\"5000/m\"`, `\"10000/h\"`) \
4978                 with no leading-zero padding on the magnitude. A leading-zero magnitude \
4979                 (`\"0100/s\"`, `\"00/s\"`, `\"007/h\"`) round-trips through `render` to \
4980                 a *different* canonical form (`\"100/s\"`, `\"0/s\"`, `\"7/h\"`) on \
4981                 first serialize — breaking the THEORY.md Part V render-determinism \
4982                 contract every typed slot carries. Strip the leading zeros (write \
4983                 `\"100/s\"` instead of `\"0100/s\"`)"
4984            ));
4985        }
4986        // The digit-only gate guarantees every byte is `[0-9]`, and
4987        // the leading-zero arm above guarantees the magnitude is
4988        // either the single byte `"0"` or starts with `[1-9]`, so
4989        // the only way `u32::from_str` can fail here is overflow
4990        // (the magnitude exceeds `u32::MAX`). Surface that with an
4991        // overflow-shaped wording so the diagnostic names the
4992        // offending magnitude verbatim rather than collapsing onto
4993        // the non-canonical arm. Same shape
4994        // `supervisor::duration_codec` (1c55a2a) carries on the peer
4995        // duration-codec axis.
4996        let rate: u32 = rate_trim.parse::<u32>().map_err(|_| {
4997            format!("rate-limit rate {rate_trim:?} (digit-only magnitude overflows u32)")
4998        })?;
4999        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives on
5000        // the closed-set typed enum [`super::RateLimitUnit`]; this parse
5001        // arm reads the `&str → Duration` projection through the
5002        // substrate primitive [`super::RateLimitUnit::window_from_suffix`]
5003        // (a two-step typed dispatch composing [`super::RateLimitUnit::from_suffix`]
5004        // with [`super::RateLimitUnit::window`]) rather than the vestigial
5005        // module-private `rate_limit_window_from_unit` free helper the
5006        // predecessor 61421a6 left as the last unlifted delegate on this
5007        // axis. One typed dispatch on the substrate primitive instead of
5008        // one runtime call through the free-helper delegate; the sole
5009        // production consumer of the `&str → Duration` axis (this parse
5010        // arm) now reaches for exactly one typed method on the closed-set
5011        // enum, sibling to the codec's render arm's
5012        // [`super::RateLimit::canonical_unit`] dispatch on the paired
5013        // `Duration → RateLimitUnit` axis and to the validate gate's
5014        // [`super::RateLimit::canonical_unit`] shape-probe on the
5015        // canonical-window axis. A future rate-limit-unit addition (a
5016        // `"d"` day suffix once Envoy's `rate_limit_action` grows
5017        // daily-bucket support, a `"ms"` sub-second window once
5018        // high-throughput per-edge policies come into scope per
5019        // MESH-COMPOSITION §III.2 #3) is one variant + one arm per method
5020        // on the closed-set enum, and the compiler enforces exhaustiveness
5021        // on every consumer's `match self` arms — this parse arm's
5022        // accepted-suffix set, the render arm's emitted-suffix set, the
5023        // validate gate's canonical-window set, and every future
5024        // per-`:contratos`-edge rate-limit-override overlay all pick it up
5025        // by construction.
5026        let unit = unit.trim();
5027        let window = RateLimitUnit::window_from_suffix(unit)
5028            .ok_or_else(|| format!("unknown rate-limit window unit {unit:?}"))?;
5029        Ok(RateLimit { rate, window })
5030    }
5031
5032    fn render(rl: RateLimit) -> String {
5033        // The `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection lives at
5034        // module scope on the closed-set typed enum [`super::RateLimitUnit`];
5035        // this render arm reads the `Duration → RateLimitUnit` projection
5036        // through the substrate primitive [`super::RateLimit::canonical_unit`]
5037        // (returns `None` on every non-canonical window — the sub-second /
5038        // non-`{1, 60, 3600}` shapes the validate gate rejects), then
5039        // formats the returned typed enum through its
5040        // [`std::fmt::Display`] impl (which routes through
5041        // [`super::RateLimitUnit::as_suffix`]). Two typed dispatches on
5042        // the substrate primitive instead of one runtime `find_map`
5043        // walk through the free-helper delegate chain
5044        // [`super::rate_limit_window_unit`] (the vestigial free helper's
5045        // sole production consumer was this arm; every other consumer of
5046        // the `Duration → unit` axis — the validate gate below and the
5047        // future M4 per-Aplicacao Envoy config reconciler — now reads
5048        // the same typed method).
5049        //
5050        // A future rate-limit-unit addition (a `"d"` day suffix once
5051        // Envoy's `rate_limit_action` grows daily-bucket support) is
5052        // one variant + one arm per method on the closed-set enum, and
5053        // the compiler enforces exhaustiveness on every consumer's
5054        // `match self` arms — the codec's `parse` accepted-suffix set,
5055        // this render arm's emitted-suffix set, the validate gate's
5056        // canonical-window set, and every future per-`:contratos`-edge
5057        // rate-limit-override overlay all pick it up by construction.
5058        if let Some(unit) = rl.canonical_unit() {
5059            format!("{}/{unit}", rl.rate())
5060        } else {
5061            // Defensive fallback for non-canonical windows. Note:
5062            // [`AplicacaoSpec::validate_politicas`] rejects any
5063            // non-canonical `:rate-limit :window` via
5064            // [`AplicacaoError::PolicyRateLimitWindowNotCanonical`], so
5065            // a validated `RateLimit` never reaches this branch. The
5066            // emitted `<n>/<k>s` form is *not* round-trippable through
5067            // [`parse`] (which accepts only the closed-set
5068            // [`super::RateLimitUnit`] suffixes, not `<k>s` with an
5069            // explicit count) — the validate gate is what makes the
5070            // round-trip a structural property; this branch exists only
5071            // so a programmatic non-validated serialize doesn't panic.
5072            format!("{}/{}s", rl.rate(), rl.window().as_secs())
5073        }
5074    }
5075}
5076
5077// ── placement strategy ───────────────────────────────────────────────
5078
5079/// How the Aplicacao distributes across clusters. Three options:
5080///
5081/// - `SingleNode` — one cluster runs the app at a time; takeover on
5082///   death (Erlang/OTP distributed-app semantics).
5083/// - `Replicated` — every named cluster runs an instance (active-active).
5084/// - `Sharded` — entities distribute by hash key across clusters
5085///   (Akka cluster sharding).
5086#[derive(
5087    Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, Hash, gen_platform::IsVariant,
5088)]
5089pub enum PlacementStrategy {
5090    SingleNode,
5091    Replicated,
5092    Sharded,
5093}
5094
5095/// Substrate-canonical M3-mesh-shaped per-`:placement :estrategia`
5096/// distribution-strategy default for the `:placement :estrategia` axis —
5097/// the [`PlacementStrategy::Replicated`] active-active-across-every-named-
5098/// cluster arm (MESH-COMPOSITION §II.2), extracted as a typed `pub const`
5099/// so every substrate-side consumer that resolves "what
5100/// [`PlacementStrategy`] variant does an author-omitted `:placement
5101/// :estrategia` slot degrade onto?" reaches for exactly one substrate-
5102/// primitive [`PlacementStrategy`].
5103///
5104/// The `:placement :estrategia` default axis has three production
5105/// consumers on the substrate side today: the [`Default for
5106/// PlacementStrategy`] impl's return arm, the [`Default for Placement`]
5107/// impl's struct-literal `estrategia` field, and the serde-side
5108/// `#[serde(default)]` on [`Placement::estrategia`] that resolves an
5109/// author-omitted `:placement :estrategia` scalar through the [`Default
5110/// for PlacementStrategy`] impl. Prior to this lift the three folded onto
5111/// a raw `Self::Replicated` arm at the [`Default for PlacementStrategy`]
5112/// impl and implicit `PlacementStrategy::default()` routes at the sibling
5113/// consumers, with no compile-time link back to the paired
5114/// [`crate::manifest::Caixa::aplicacao_view`] fold's
5115/// `.unwrap_or_default()` `Option<Placement>` collapse arm — the fourth
5116/// production consumer that resolves an author-omitted `:placement` slot
5117/// (entirely omitted, not just the `:estrategia` scalar within a declared
5118/// `:placement` block) through [`Placement::default`] which then routes
5119/// through this same discriminator. A future coherent rebrand of the
5120/// `:placement :estrategia` default (a widening to `Sharded` once the
5121/// substrate discovers hash-keyed distribution as the more common
5122/// production shape, a tightening to `SingleNode` for stateful Erlang/OTP
5123/// distributed-app-takeover semantics MESH-COMPOSITION §II.1 already
5124/// names, a per-cluster overlay the operator pins through a future
5125/// `:placement-overrides` slot) would have had to migrate a lifted
5126/// discriminator on one path and open-coded discriminators on the peers
5127/// in lockstep or the four consumers would silently drift out of
5128/// pairing. Lifting the resolution rule to a typed `pub const` on the
5129/// substrate primitive means the M3-mesh-canonical `:placement
5130/// :estrategia` default migrates as one unit on any future axis change.
5131///
5132/// The [`PlacementStrategy::Replicated`] value pins MESH-COMPOSITION
5133/// §II.2's active-active-across-every-named-cluster arm — the closest
5134/// canonical M3 production reference the substrate carries, matching the
5135/// caixa-mesh default axis every M3 renderer already keys off (a
5136/// `programs.yaml` fan-out that emits one `HelmRelease` per cluster is
5137/// the canonical shape a `:membros`+`:contratos`-declared Aplicacao lands on
5138/// under the substrate's fleet-programs aggregator without an explicit
5139/// `:placement :estrategia` override). The two alternatives the closed
5140/// [`PlacementStrategy::ALL`] accept-set carries
5141/// ([`PlacementStrategy::SingleNode`] — Erlang/OTP distributed-app
5142/// takeover, MESH-COMPOSITION §II.1; [`PlacementStrategy::Sharded`] —
5143/// Akka-style hash-keyed distribution across clusters,
5144/// MESH-COMPOSITION §II.4) express deliberate takeover / hash-keyed
5145/// postures an author declares explicitly, never a posture an omitted
5146/// slot should silently assume.
5147///
5148/// Lifted as a typed `pub const` so the M3-mesh-canonical default has
5149/// exactly one source of truth on the `:placement :estrategia` axis, on
5150/// the same substrate-primitive lift discipline the sibling M2
5151/// per-supervisor default set carries
5152/// ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`],
5153/// [`crate::supervisor::SUPERVISOR_MAX_RESTARTS_DEFAULT`],
5154/// [`crate::supervisor::SUPERVISOR_RESTART_WINDOW_DEFAULT`],
5155/// [`crate::supervisor::SUPERVISOR_CHILD_RESTART_DEFAULT`]) and the peer
5156/// per-renderer defaults on the caixa-flux / caixa-helm rendering axes
5157/// ([`crate::render::DEFAULT_NAMESPACE`],
5158/// [`crate::render::DEFAULT_LIBRARY_NAME`],
5159/// [`crate::render::DEFAULT_SERVICO_PORT`]). The first typed default on
5160/// the M3 mesh-primitive-defining slot family to converge onto the
5161/// substrate-primitive-lift discipline the M2 supervisor-slot family
5162/// already carries end-to-end.
5163pub const PLACEMENT_ESTRATEGIA_DEFAULT: PlacementStrategy = PlacementStrategy::Replicated;
5164
5165impl Default for PlacementStrategy {
5166    fn default() -> Self {
5167        // Route the [`Default for PlacementStrategy`] impl through the
5168        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
5169        // `pub const` rather than a raw `Self::Replicated` arm — one
5170        // source of truth for the M3-mesh-canonical active-active-
5171        // across-every-named-cluster `:placement :estrategia` default
5172        // (MESH-COMPOSITION §II.2), on the same substrate-primitive
5173        // lift discipline the sibling M2 per-supervisor default set
5174        // ([`crate::supervisor::SUPERVISOR_ESTRATEGIA_DEFAULT`] +
5175        // paired halves) carries end-to-end. Pinned by
5176        // `placement_strategy_default_routes_through_lifted_default`.
5177        PLACEMENT_ESTRATEGIA_DEFAULT
5178    }
5179}
5180
5181impl PlacementStrategy {
5182    /// Exhaustive iteration surface for every consumer that reads the
5183    /// full closed-set (the future M4 admission-webhook's accepted-
5184    /// strategy listing in its rejection body, a future `feira app
5185    /// placement --list` CLI-side surfacing of the accepted arm-set,
5186    /// any future round-trip fuzz harness). A future variant addition
5187    /// (an `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint
5188    /// names as a trajectory item) extends this slice as a single edit
5189    /// and every consumer picks up the new entry by construction — the
5190    /// compiler-checked exhaustiveness on the sibling method `match`
5191    /// arms is the build-time guarantee that no arm forgets to grow.
5192    /// Same shape as the sibling closed-set typed enums'
5193    /// [`RateLimitUnit::ALL`] (6bce03d) and
5194    /// [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
5195    /// surfaces — the third closed-set typed enum on the caixa surface
5196    /// to converge onto the same discipline.
5197    pub const ALL: &'static [Self] = &[Self::SingleNode, Self::Replicated, Self::Sharded];
5198
5199    /// Canonical camelCase-schema discriminator scalar this variant
5200    /// serializes as under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. The
5201    /// three arms return the paired [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
5202    /// / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5203    /// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] lifted constants so
5204    /// every substrate consumer that dispatches on the strategy (the
5205    /// `lareira-fleet-programs` aggregator, the future `app-operator`
5206    /// reconciler, the M3 Adaptive compression pass) reads the same
5207    /// byte-string the `Serialize` derive emits — the pin test in
5208    /// [`tests::placement_strategy_variants_serialize_to_lifted_scalar_values`]
5209    /// asserts the two paths agree.
5210    #[must_use]
5211    pub const fn as_str(self) -> &'static str {
5212        match self {
5213            Self::SingleNode => crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
5214            Self::Replicated => crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
5215            Self::Sharded => crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
5216        }
5217    }
5218
5219    /// Substrate-canonical reverse projection on the `:placement
5220    /// :estrategia` closed-set axis — parses the camelCase-schema
5221    /// discriminator scalar back to the typed variant, or `None` when
5222    /// `s` is outside the closed-set arm-string set [`Self::as_str`]
5223    /// emits. Dispatches on the same lifted
5224    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5225    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5226    /// [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] constants the
5227    /// [`Self::as_str`] emitter walks, so the parse and emit halves of
5228    /// the round-trip migrate through one caixa-core edit on any future
5229    /// arm addition (an `Anycast` mesh-anycast arm the MESH-COMPOSITION
5230    /// §II.5 hint names as a trajectory item lands one variant + one
5231    /// arm per method and the compiler enforces exhaustiveness on every
5232    /// consumer's `match self` arms).
5233    ///
5234    /// Prior to this lift the substrate carried only the forward
5235    /// `Self → &str` projection (the [`Self::as_str`] emitter, the
5236    /// [`std::fmt::Display`] impl routed through it, the `Serialize`
5237    /// derive that emits the same byte-string under
5238    /// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]) — every non-serde
5239    /// consumer that wanted to parse a wire-form strategy scalar had to
5240    /// re-inline a three-arm `match s { "SingleNode" => …, "Replicated"
5241    /// => …, "Sharded" => …, _ => … }` cascade that expressed no
5242    /// compile-time link back to the typed variant's canonical lifted
5243    /// constant. A future variant rename or a per-arm serde-attribute
5244    /// drift would silently split the wire byte-string one non-serde
5245    /// consumer parsed from the one the emitter wrote, with the
5246    /// failure surfacing at parse time far from the rebrand commit.
5247    ///
5248    /// Same closed-set-reverse-projection discipline the sibling
5249    /// [`crate::CaixaKind::from_wire`] (2aa6d23) and
5250    /// [`RateLimitUnit::from_suffix`] typed enums carry on the peer
5251    /// wire-side `str → Self` axes — extended onto the M3 mesh-primitive-
5252    /// defining `:placement :estrategia` closed-set axis, the third
5253    /// substrate-side closed-set typed enum to converge on the two-way
5254    /// `str ↔ Self` round-trip. Method-named `from_wire` (not `from_str`)
5255    /// to match the peer [`crate::CaixaKind::from_wire`] shape verbatim
5256    /// and side-step the [`std::str::FromStr`]-collision clippy
5257    /// (`clippy::should_implement_trait`) the plain `from_str` name
5258    /// carries; a future explicit [`std::str::FromStr`] impl can layer
5259    /// on top by delegating to this canonical arm-dispatch method.
5260    ///
5261    /// Returns `Option<Self>` (rather than `Result<Self, _>`) to match
5262    /// the sibling [`crate::CaixaKind::from_wire`] shape: the caller
5263    /// picks the diagnostic form appropriate for its use site — a
5264    /// future `feira app placement --set` CLI-side arg-parse that wants
5265    /// an `"unknown strategy: {s} (accepted: SingleNode, Replicated,
5266    /// Sharded)"` diagnostic builds one on top by iterating
5267    /// [`Self::ALL`], while the future M4 admission-webhook's rejection
5268    /// path folds `None` onto its per-CR structured refusal body.
5269    #[must_use]
5270    pub fn from_wire(s: &str) -> Option<Self> {
5271        match s {
5272            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE => Some(Self::SingleNode),
5273            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED => Some(Self::Replicated),
5274            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED => Some(Self::Sharded),
5275            _ => None,
5276        }
5277    }
5278
5279    /// Substrate-canonical per-arm predicate naming the cross-slot
5280    /// `:placement :estrategia` ↔ `:placement :shard-key` invariant on the
5281    /// closed-set typed [`PlacementStrategy`] enum: `true` iff the strategy
5282    /// consumes the paired [`Placement::shard_key`] axis (and therefore
5283    /// requires — and is the only strategy that permits — a non-empty
5284    /// `:shard-key` on the paired slot). Today the accept-set is the
5285    /// singleton `{Sharded}` — `Sharded` is the sole Akka-style
5286    /// hash-keyed distribution arm (MESH-COMPOSITION §II.4) that keys off a
5287    /// per-entity extractor expression; `SingleNode` (Erlang/OTP
5288    /// distributed-app takeover — §II.1) and `Replicated` (active-active
5289    /// across every named cluster) have no hash-keyed routing axis to
5290    /// consume the slot and refuse a declared-but-inert `:shard-key`
5291    /// through [`AplicacaoError::ShardKeyOnNonSharded`].
5292    ///
5293    /// Every validated [`Placement`] past [`AplicacaoSpec::validate_placement`]
5294    /// satisfies `placement.shard_key().is_some() ==
5295    /// placement.estrategia().requires_shard_key()` by construction — the
5296    /// cross-slot partition the pin
5297    /// [`tests::validate_placement_admits_paired_shape_iff_strategy_requires_shard_key`]
5298    /// locks load-bearing, so every downstream consumer that reaches for
5299    /// the paired shape (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
5300    /// CR materializer's per-CR shard-key resolver, the future
5301    /// [`feira app graph --shard-key`] per-Aplicacao column, the future
5302    /// per-cluster Akka-style cluster-sharding reconciler's per-entity
5303    /// hash-routing gate, the M5 adaptive-placement engine's per-strategy
5304    /// shard-key requirement probe, a future author-facing tatara-lisp
5305    /// linter that flags `(:placement (:estrategia Replicated :shard-key
5306    /// "tenantId"))` shapes before `feira lint` reaches
5307    /// [`AplicacaoSpec::validate`]) can reach for one typed dispatch on
5308    /// the substrate primitive — the predicate names *the cross-slot
5309    /// invariant*, not the arm identity.
5310    ///
5311    /// Prior to this lift the "does this strategy consume `:shard-key`"
5312    /// classification lived under the `gen_platform::IsVariant`-derived
5313    /// [`Self::is_sharded`] predicate at three fixture-builder sites in
5314    /// this crate (the [`tests::placement_strategy_variants_round_trip`]
5315    /// per-variant `Placement`-builder's `if s.is_sharded() { Some("$key"…)
5316    /// } else { None }` cascade, the
5317    /// [`tests::estrategia_returns_placement_estrategia_verbatim_across_permutations`]
5318    /// per-variant `Placement`-builder's `estrategia.is_sharded().then(||
5319    /// "tenantId".to_string())` cascade, and the
5320    /// [`tests::validate_placement_reads_through_lifted_estrategia_accessor`]
5321    /// per-variant spec-mutator's identical `.is_sharded().then(…)`
5322    /// cascade). Each site conflated two semantically distinct questions:
5323    /// "is the variant `Sharded`?" (arm-identity, what
5324    /// [`Self::is_sharded`] answers) and "does the variant consume
5325    /// `:shard-key`?" (cross-slot-invariant, what this predicate answers).
5326    /// The two questions land on the same three-way answer under today's
5327    /// closed accept-set (both trip on the singleton `{Sharded}`), but a
5328    /// future arm addition that consumed `:shard-key` under a different
5329    /// name (a hypothetical `Anycast` mesh-anycast arm the MESH-COMPOSITION
5330    /// §II.5 roadmap-hint names that hash-partitions across the cluster
5331    /// pool by client-IP hash rather than an author-declared extractor
5332    /// expression, a hypothetical `WeightedShard` variant that carries a
5333    /// shard-key + per-cluster weight table under a promoted M5
5334    /// adaptive-placement engine) or an addition that did *not* consume
5335    /// `:shard-key` on a semantically Sharded-shaped arm would silently
5336    /// split the two questions. Any consumer that read
5337    /// `.is_sharded().then(…)` for the shard-key requirement gate would
5338    /// silently misclassify the new arm as non-consuming — a fixture
5339    /// builder would omit `:shard-key` where the new arm required one and
5340    /// [`AplicacaoSpec::validate_placement`] would refuse the fixture with
5341    /// [`AplicacaoError::ShardedWithoutKey`] far from the arm-addition
5342    /// commit, a future M4 CR materializer would fall through the
5343    /// `.is_sharded()`-only branch to the non-shard-key resolver arm and
5344    /// silently emit an empty extractor at the Akka reconciler layer.
5345    ///
5346    /// Lifting the classification as a substrate-primitive method on the
5347    /// closed-set typed enum names the cross-slot invariant on the
5348    /// primitive that owns the partition: every future arm addition
5349    /// declares its `:shard-key` consumption in one place (this predicate's
5350    /// `match self` arm-set), and every downstream consumer that reaches
5351    /// for the paired shape reads through one typed dispatch. Same
5352    /// discipline as the sibling [`WitContract::is_capability`] (7b97d26)
5353    /// per-arm predicate on the pre-projection WIT-shape axis and the
5354    /// [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
5355    /// paired predicate on the post-projection typed-view axis — a
5356    /// per-arm semantic-classification predicate paired with the
5357    /// arm-identity predicate the derive already emits, closing the drift
5358    /// footgun on the cross-slot invariant axis.
5359    ///
5360    /// Method-named `requires_shard_key` (not `has_shard_key`, not
5361    /// `is_shard_keyed`, not `takes_shard_key`) because the cross-slot
5362    /// invariant reads as "this strategy *requires* the paired
5363    /// `:shard-key` axis" — the `SingleNode`/`Replicated` arms *refuse*
5364    /// the axis through [`AplicacaoError::ShardKeyOnNonSharded`], not
5365    /// merely omit it. The `has_*` framing would read as an accessor
5366    /// (returning the presence of an already-carried value) rather than a
5367    /// requirement (naming the invariant the paired slot must satisfy).
5368    /// Returns `bool` (not `Option<()>` or a marker-type witness), same
5369    /// shape as the sibling [`WitContract::is_capability`] /
5370    /// [`Self::is_sharded`] per-arm boolean predicates on the closed-set
5371    /// arm-family, so every consumer reaches for `.requires_shard_key()`
5372    /// as a drop-in replacement for the `.is_sharded()` conflated read
5373    /// without a return-shape migration.
5374    #[must_use]
5375    pub const fn requires_shard_key(self) -> bool {
5376        match self {
5377            Self::Sharded => true,
5378            Self::SingleNode | Self::Replicated => false,
5379        }
5380    }
5381}
5382
5383// Compile-time pins on the [`PlacementStrategy::requires_shard_key`]
5384// cross-slot-invariant per-arm predicate: the module-scope const-eval
5385// assertions below trip at caixa-core build time (not test time) if a
5386// future edit rewires the predicate's arm-set away from the singleton
5387// `{Sharded}` accept-set MESH-COMPOSITION §II.4 pins. The
5388// [`tests::placement_strategy_requires_shard_key_partitions_the_arm_set`]
5389// runtime pin covers the same truth-table with a more descriptive
5390// diagnostic on failure; these const-eval items add a build-time failure
5391// surface strictly stronger than the runtime pin (a downstream renderer's
5392// `const`-context reader that composed against a rebound predicate would
5393// still surface here before the test suite even ran) and side-step the
5394// `clippy::assertions_on_constants` lint the runtime `assert!(CONST)` pin
5395// would otherwise accumulate on the caixa-core module baseline.
5396const _: () = assert!(!PlacementStrategy::SingleNode.requires_shard_key());
5397const _: () = assert!(!PlacementStrategy::Replicated.requires_shard_key());
5398const _: () = assert!(PlacementStrategy::Sharded.requires_shard_key());
5399
5400/// [`std::fmt::Display`] routed through [`PlacementStrategy::as_str`], so
5401/// the pretty-printed byte-string every consumer that formats the strategy
5402/// as user-facing text lands on (the M3 [`AplicacaoError::PlacementWithoutClusters`]
5403/// / [`AplicacaoError::ShardKeyOnNonSharded`] `#[error(":placement
5404/// {estrategia} …")]` diagnostic templates, the future `feira app graph`
5405/// per-Aplicacao strategy line, the future M4 CR materializer's per-
5406/// admission-webhook rejection body) reaches for the same lifted
5407/// [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
5408/// [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
5409/// [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] const the wire-format
5410/// `Serialize` derive already emits under
5411/// [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] and the
5412/// [`PlacementStrategy::as_str`] helper already returns.
5413///
5414/// Until this lift landed the sibling OTP-shape typed enums —
5415/// [`crate::supervisor::RestartStrategy`] / [`crate::supervisor::RestartPolicy`]
5416/// (both derive `gen_platform::Discriminant` with `#[discriminant(also_display)]`
5417/// so [`std::fmt::Display`] routes through the same discriminant string
5418/// the wire format emits) — carried a stable [`std::fmt::Display`]
5419/// surface but [`PlacementStrategy`] did not; every consumer reaching
5420/// for a strategy byte-string past the wire format had to pick between
5421/// three paths ([`PlacementStrategy::as_str`], the [`Serialize`] derive's
5422/// serialized string, `format!("{variant:?}")` on the [`std::fmt::Debug`]
5423/// derive), any two of which a future variant rename or
5424/// `#[serde(rename_all = "kebab-case")]` attribute would silently
5425/// desynchronize — with the failure surfacing as a downstream renderer /
5426/// operator's per-strategy dispatch reading one spelling while the wire
5427/// format emitted another, far from the source rebrand commit and with
5428/// no field naming the drift. Routing `Display` through
5429/// [`PlacementStrategy::as_str`] makes the three paths
5430/// (`Debug` for structural inspection, `Display` for user-facing text,
5431/// `Serialize` for the wire format) converge on the same lifted
5432/// [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const set: the wire byte-string,
5433/// the diagnostic byte-string, and the pretty-printed byte-string move
5434/// as a single unit through one canonical declaration each, by
5435/// construction. Same trajectory as [`PlacementStrategy::as_str`]
5436/// (cc8f749) on the sibling wire-vs-const single-source axis — this lift
5437/// closes the third path.
5438///
5439/// Pin tests
5440/// [`tests::placement_strategy_display_routes_through_as_str_helper`]
5441/// and
5442/// [`tests::placement_strategy_display_matches_serialized_wire_byte_string`]
5443/// assert the three paths agree byte-for-byte on every variant, so a
5444/// future variant rename or per-arm serde attribute drift is a build
5445/// error visible at caixa-core test time, not a silent per-consumer
5446/// dispatch miss at apply / reconcile time.
5447impl std::fmt::Display for PlacementStrategy {
5448    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
5449        f.write_str(self.as_str())
5450    }
5451}
5452
5453/// Where the Aplicacao runs.
5454#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5455#[serde(rename_all = "camelCase")]
5456pub struct Placement {
5457    /// Distribution strategy.
5458    #[serde(default)]
5459    pub estrategia: PlacementStrategy,
5460
5461    /// Named clusters that host this Aplicacao. Required for
5462    /// `Replicated` and `SingleNode`; for `Sharded` declares the
5463    /// shard pool.
5464    #[serde(default)]
5465    pub clusters: Vec<String>,
5466
5467    /// Optional hint to the placement engine: `"data-locality"`,
5468    /// `"low-latency"`, etc. Drives M3 Adaptive compression weights.
5469    #[serde(default, skip_serializing_if = "Option::is_none")]
5470    pub affinity: Option<String>,
5471
5472    /// Sharding key — required when `:estrategia Sharded`. M3 deliverable.
5473    #[serde(default, skip_serializing_if = "Option::is_none")]
5474    pub shard_key: Option<String>,
5475}
5476
5477impl Placement {
5478    /// Substrate-canonical per-`:placement` Akka-cluster-sharding
5479    /// `:shard-key` extractor-expression scalar accessor every consumer
5480    /// of the Aplicacao's hash-keyed distribution routing keys off —
5481    /// returns the author-declared `:placement :shard-key` byte-string
5482    /// verbatim as an `Option<&str>`, borrowed from the typed slot's
5483    /// own `Option<String>` storage; `None` when the slot is absent
5484    /// (the canonical shape under `:estrategia Replicated` /
5485    /// `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
5486    /// enforced `shard_key.is_some() == matches!(estrategia, Sharded)`
5487    /// partition — `validate` refuses any `Placement` past this call
5488    /// that lands `Some` on a non-`Sharded` strategy or `None` on
5489    /// `Sharded`).
5490    ///
5491    /// The `:placement :shard-key` slot carries the Akka-style
5492    /// cluster-sharding entity-id extractor expression
5493    /// (MESH-COMPOSITION §II.4) — validated by
5494    /// [`validate_placement_shard_key`] to be a non-empty printable-
5495    /// ASCII single-token reference (`tenantId`, `$tenantId`,
5496    /// `metadata.tenantId`, `${tenant}` — the canonical shapes the
5497    /// future M4 Akka-style cluster-sharding reconciler hashes without
5498    /// re-validating at the runtime layer), and every downstream
5499    /// consumer that reads the key keys off this scalar (the
5500    /// [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape gate,
5501    /// the [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5502    /// declared-but-inert refusal diagnostic, the caixa-mesh
5503    /// per-Aplicacao `placement.shardKey` emit path the substrate
5504    /// operator's per-entity hash-routing reader consumes, the future
5505    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5506    /// per-shard-key resolver).
5507    ///
5508    /// Prior to this lift the `.shard_key` field was accessed inline at
5509    /// two caixa-core sites — the [`AplicacaoSpec::validate_placement`]
5510    /// `Sharded` arm's `match &self.placement.shard_key { None => …,
5511    /// Some(k) if k.is_empty() => …, Some(k) => … }` cascade and the
5512    /// non-`Sharded` arm's `if let Some(k) = &self.placement.shard_key
5513    /// { … ShardKeyOnNonSharded { shard_key: k.clone() } … }` refusal
5514    /// — two open-coded field-accesses that expressed no compile-time
5515    /// link back to the typed slot. A future extension of the
5516    /// `:placement :shard-key` axis to a richer author surface — a
5517    /// per-cluster override the operator pins through a future
5518    /// `:placement :shard-key-overrides` slot the MESH-COMPOSITION
5519    /// §II.4 roadmap acknowledges, a per-tenant extractor-expression
5520    /// alias table the M4 CR materializer resolves per-CR, a
5521    /// per-Aplicacao dynamic `:shard-key` derivation the future
5522    /// adaptive placement engine computes from `:affinity` weights —
5523    /// would have had to be threaded through both open-coded copies in
5524    /// lockstep or the `Sharded`-arm shape gate and the non-`Sharded`-
5525    /// arm refusal would silently disagree on which extractor
5526    /// expression a given Placement resolves to. Lifting the resolution
5527    /// rule to a typed method on the substrate primitive means every
5528    /// downstream consumer of the Aplicacao's per-`:placement`
5529    /// hash-key surface reaches for exactly one typed dispatch — the
5530    /// resolver's accept-set migrates as a unit on any future axis
5531    /// addition.
5532    ///
5533    /// Peer of the sibling per-`:contratos` [`WitContract::source`] /
5534    /// [`WitContract::destination`] / [`WitContract::world_ref`]
5535    /// (7f0fd43, 0804823) scalar accessors, per-`:membros`
5536    /// [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf,
5537    /// a40b0e3), and per-`:entrada` [`Entrada::destination`] /
5538    /// [`Entrada::hostname`] (6db982c, 11f3dfe) accessors — same "one
5539    /// typed dispatch on the substrate primitive, thin projections at
5540    /// each consumer" discipline extended onto the per-`:placement`
5541    /// Akka-cluster-sharding-key `Option<String>` optional-scalar axis.
5542    /// First `Option<&str>`-return accessor on the M3 mesh-slot family
5543    /// — opens the "optional per-slot scalar" projection pattern the
5544    /// sibling per-`:placement` `:affinity`, per-`:politicas`
5545    /// `:rate-limit` future lifts fold on. Named `shard_key()` to
5546    /// match the storage field's name; the accessor's identity name
5547    /// maps onto the canonical MESH-COMPOSITION §II.4 vocabulary the
5548    /// slot's docstring already carries.
5549    #[must_use]
5550    pub const fn shard_key(&self) -> Option<&str> {
5551        match &self.shard_key {
5552            Some(s) => Some(s.as_str()),
5553            None => None,
5554        }
5555    }
5556
5557    /// Substrate-canonical per-`:placement` `:affinity` M3-Adaptive-
5558    /// compression-hint scalar accessor every weighting-consumer of the
5559    /// Aplicacao's per-hint routing surface keys off — returns the
5560    /// author-declared `:placement :affinity` byte-string verbatim as
5561    /// an `Option<&str>`, borrowed from the typed slot's own
5562    /// `Option<String>` storage; `None` when the slot is absent (the
5563    /// canonical shape of an Aplicacao that leaves the compression
5564    /// weighting up to the placement engine's cluster-default arm — no
5565    /// author-authored `data-locality` / `low-latency` / etc. hint
5566    /// biases the routing).
5567    ///
5568    /// The `:placement :affinity` slot carries the M3 Adaptive-
5569    /// compression-weight bias hint (MESH-COMPOSITION §II.4) — validated
5570    /// by [`validate_placement_affinity`] to be a DNS-1123 label
5571    /// (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, 1..=63 bytes — the
5572    /// K8s-conformant label-selector shape every apiserver-side pod-
5573    /// affinity / node-affinity materializer already gates on
5574    /// admission), and every downstream consumer that reads the hint
5575    /// keys off this scalar (the [`AplicacaoSpec::validate_placement`]
5576    /// per-hint value-shape gate, the caixa-mesh per-Aplicacao
5577    /// `placement.affinity` overlay emit path the substrate operator's
5578    /// per-hint weighting-consumer reads, the future M4
5579    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-hint
5580    /// pod-affinity / node-affinity selector resolver).
5581    ///
5582    /// Prior to this lift the `.affinity` field was accessed inline at
5583    /// the sole caixa-core site — the
5584    /// [`AplicacaoSpec::validate_placement`] per-hint value-shape gate's
5585    /// `if let Some(a) = &self.placement.affinity { …
5586    /// validate_placement_affinity(a)? … }` cascade — one open-coded
5587    /// field-access that expressed no compile-time link back to the
5588    /// typed slot. A future extension of the `:placement :affinity`
5589    /// axis to a richer author surface — a per-cluster override the
5590    /// operator pins through a future `:placement :affinity-overrides`
5591    /// slot the MESH-COMPOSITION §II.4 roadmap acknowledges, a per-
5592    /// tenant hint alias table the M4 CR materializer resolves per-CR,
5593    /// a per-Aplicacao dynamic `:affinity` derivation the future
5594    /// adaptive placement engine computes from `:clusters` topology —
5595    /// would have had to be threaded through the open-coded copy in
5596    /// lockstep with any future caixa-mesh / caixa-flux / M4 CR
5597    /// materializer reader that landed on the axis, or the per-hint
5598    /// value-shape gate and its downstream weighting consumers would
5599    /// silently disagree on which hint a given Placement resolves to.
5600    /// Lifting the resolution rule to a typed method on the substrate
5601    /// primitive means every downstream consumer of the Aplicacao's
5602    /// per-`:placement` compression-hint surface reaches for exactly
5603    /// one typed dispatch — the resolver's accept-set migrates as a
5604    /// unit on any future axis addition.
5605    ///
5606    /// Peer of the sibling per-`:placement` [`Placement::shard_key`]
5607    /// (7cd2a28) `Option<&str>` accessor on the sibling per-`:placement`
5608    /// optional-scalar axis — same "one typed dispatch on the substrate
5609    /// primitive, thin projections at each consumer" discipline extended
5610    /// onto the per-`:placement` M3-Adaptive-compression-hint
5611    /// `Option<String>` optional-scalar axis. Second `Option<&str>`-
5612    /// return accessor on the M3 mesh-slot family; closes the last
5613    /// un-lifted per-`:placement` `Option<String>` axis. Named
5614    /// `affinity()` to match the storage field's name; the accessor's
5615    /// identity name maps onto the canonical MESH-COMPOSITION §II.4
5616    /// vocabulary the slot's docstring already carries.
5617    #[must_use]
5618    pub const fn affinity(&self) -> Option<&str> {
5619        match &self.affinity {
5620            Some(s) => Some(s.as_str()),
5621            None => None,
5622        }
5623    }
5624
5625    /// Substrate-canonical per-`:placement` `:estrategia` distribution-
5626    /// strategy scalar accessor every consumer that dispatches on the
5627    /// Aplicacao's per-cluster distribution shape keys off — returns the
5628    /// author-declared `:placement :estrategia` variant verbatim as a
5629    /// [`PlacementStrategy`], `Copy`-projected from the typed slot's own
5630    /// `PlacementStrategy` storage.
5631    ///
5632    /// The `:placement :estrategia` slot carries the closed-set
5633    /// distribution-strategy discriminator (`SingleNode` — Erlang/OTP
5634    /// distributed-app takeover semantics per MESH-COMPOSITION §II.1;
5635    /// `Replicated` — active-active across every named cluster; `Sharded`
5636    /// — Akka-style hash-keyed entity distribution across the cluster pool
5637    /// per §II.4) that every downstream consumer of the Aplicacao's
5638    /// per-cluster fan-out shape keys off. Validated by
5639    /// [`AplicacaoSpec::validate_placement`] to be paired coherently with
5640    /// the sibling `:shard-key` axis (`shard_key.is_some() ==
5641    /// matches!(estrategia, Sharded)` — the cross-slot partition the
5642    /// [`Placement::shard_key`] accessor's docstring pins), and every
5643    /// downstream consumer that reads the strategy keys off this scalar
5644    /// (the [`AplicacaoSpec::validate_placement`]
5645    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier's
5646    /// `estrategia:` field, the [`AplicacaoSpec::validate_placement`]
5647    /// `Sharded ↔ non-Sharded` partition-dispatch `match` arm, the
5648    /// [`AplicacaoSpec::validate_placement`] non-`Sharded`-arm
5649    /// declared-but-inert refusal's
5650    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
5651    /// `estrategia:` field, the `feira app graph` per-Aplicacao strategy
5652    /// print line, the caixa-mesh per-Aplicacao `placement.estrategia`
5653    /// emit path the substrate operator's per-strategy fan-out reader
5654    /// consumes, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
5655    /// materializer's per-strategy admission-webhook resolver).
5656    ///
5657    /// Prior to this lift the `.estrategia` field was accessed inline at
5658    /// four sites — the [`AplicacaoSpec::validate_placement`]
5659    /// [`AplicacaoError::PlacementWithoutClusters`] error carrier at
5660    /// `estrategia: self.placement.estrategia`, the same method's
5661    /// `Sharded ↔ non-Sharded` `match self.placement.estrategia { … }`
5662    /// partition dispatch, the non-`Sharded`-arm
5663    /// [`AplicacaoError::ShardKeyOnNonSharded`] error carrier at
5664    /// `estrategia: self.placement.estrategia`, and the `feira app graph`
5665    /// per-Aplicacao strategy print line at
5666    /// `println!("… {} …", spec.placement.estrategia, …)`
5667    /// (caixa-feira/src/cmd/app.rs) — four open-coded field-accesses that
5668    /// expressed no compile-time link back to the typed slot. A future
5669    /// extension of the `:placement :estrategia` axis to a richer author
5670    /// surface (a per-cluster override the operator pins through a future
5671    /// `:placement :estrategia-overrides` slot the MESH-COMPOSITION §II.4
5672    /// roadmap acknowledges, a per-tenant strategy-alias table the M4 CR
5673    /// materializer resolves per-CR, a per-Aplicacao dynamic strategy
5674    /// derivation the future adaptive placement engine computes from
5675    /// `:affinity` + `:clusters` topology) would have had to be threaded
5676    /// through every open-coded copy in lockstep — one consumer reading
5677    /// the raw variant while a peer read the operator-resolved variant
5678    /// would silently split the `PlacementWithoutClusters` /
5679    /// `ShardKeyOnNonSharded` diagnostic quotes from the actual
5680    /// partition-dispatch input, a two-consumer split at the validator
5681    /// far from the source `caixa.lisp` with no field naming the
5682    /// strategy-drift root cause. Lifting the resolution rule to a typed
5683    /// method on the substrate primitive means every downstream consumer
5684    /// of the Aplicacao's per-`:placement` distribution-strategy surface
5685    /// reaches for exactly one typed dispatch — the resolver's accept-set
5686    /// migrates as a unit on any future axis addition.
5687    ///
5688    /// Peer of the sibling per-`:entrada` [`Entrada::port`] (9f9becd)
5689    /// `Copy`-return `u16` scalar accessor on the M3 mesh-slot family —
5690    /// same "one typed dispatch on the substrate primitive, thin
5691    /// projections at each consumer" discipline extended onto the
5692    /// per-`:placement` distribution-strategy `Copy`-composite-enum
5693    /// scalar axis. Second `Copy`-return accessor on the M3 mesh-slot
5694    /// family; first `Copy`-return accessor on the M3 mesh-slot
5695    /// `Placement` type — companion to the sibling per-`:placement`
5696    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5697    /// (74ec2d3) `Option<&str>` accessors on the sibling `Option<String>`
5698    /// optional-scalar axes, closing the last unlifted per-`:placement`
5699    /// scalar-value axis (the closed-set `PlacementStrategy`
5700    /// distribution-strategy discriminator) so every downstream
5701    /// per-`:placement` reader now routes through a typed dispatch on
5702    /// the substrate primitive. Named `estrategia()` to match the storage
5703    /// field's name; the accessor's identity name maps onto the
5704    /// canonical MESH-COMPOSITION §II.4 vocabulary the slot's docstring
5705    /// already carries. Declared `pub const fn` (matching the peer M3
5706    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
5707    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
5708    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
5709    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
5710    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
5711    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
5712    /// [`RateLimit`] — every one a `pub const fn`) so every future
5713    /// substrate-side `const`-context consumer of the resolved
5714    /// distribution-strategy variant (a `const _: () = assert!(…)`
5715    /// module-scope invariant pin on a per-fixture typed [`Placement`],
5716    /// a future M4 admission-webhook `const fn` resolver over a typed
5717    /// [`Placement`], any `const fn` composer that fans on the strategy
5718    /// at compile time) reaches through the same typed dispatch on the
5719    /// substrate primitive at const-eval time as at runtime. Pinned by
5720    /// [`placement_estrategia_accessor_is_const_fn`] which witnesses the
5721    /// const-eval posture at module scope via `const _:() = …` items so
5722    /// any future accidental downgrade to non-`const` trips at caixa-core
5723    /// build time.
5724    #[must_use]
5725    pub const fn estrategia(&self) -> PlacementStrategy {
5726        self.estrategia
5727    }
5728
5729    /// Substrate-canonical per-`:placement` `:clusters` MESH-COMPOSITION
5730    /// per-cluster distribution-target slice accessor every consumer that
5731    /// walks the Aplicacao's declared cluster-pool keys off — returns the
5732    /// author-declared `:placement :clusters` `Vec<String>` verbatim as a
5733    /// `&[String]` slice-view, borrowed from the typed slot's own
5734    /// `Vec<String>` storage (a zero-copy slice-view over the same
5735    /// backing buffer the `Serialize`/`Deserialize` derives round-trip
5736    /// through). Non-optional: the empty slice is the load-bearing
5737    /// pre-validation sentinel every downstream consumer of the paired
5738    /// [`AplicacaoError::PlacementWithoutClusters`] refusal cascade keys
5739    /// off — every strategy in the closed
5740    /// [`PlacementStrategy::{SingleNode, Replicated, Sharded}`] accept-set
5741    /// requires a non-empty list (`SingleNode` / `Replicated` use the
5742    /// list as hosting / takeover candidates per Erlang/OTP distributed-
5743    /// app convention, MESH-COMPOSITION §II.1; `Sharded` uses it as the
5744    /// shard pool per Akka cluster-sharding convention, §II.4), so the
5745    /// `.is_empty()` probe is the shared pre-condition every
5746    /// [`AplicacaoSpec::validate_placement`] arm heads on.
5747    ///
5748    /// The `:placement :clusters` slot carries the K8s-conformant DNS-
5749    /// 1123-label per-cluster distribution-target list — the same
5750    /// set-not-multiset shape the sibling `:membros :caixa` /
5751    /// `:children :caixa` axes carry (`validate_placement`'s per-entry
5752    /// [`validate_placement_cluster`] + [`insert_first_seen`] fan-out
5753    /// pins the shape). Every downstream consumer that fans on the list
5754    /// keys off this slice (the [`AplicacaoSpec::validate_placement`]
5755    /// pre-flight `.is_empty()` probe that trips
5756    /// [`AplicacaoError::PlacementWithoutClusters`], the same method's
5757    /// per-cluster value-shape + duplicate-detection fan-out loop, the
5758    /// caixa-mesh per-Aplicacao `placement.clusters` overlay emit path
5759    /// that materializes the list verbatim onto every
5760    /// programs.yaml entry the substrate operator's per-cluster
5761    /// `placement.clusters | contains .Values.cluster` filter reads,
5762    /// the `feira app graph` per-Aplicacao cluster print line, the
5763    /// future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
5764    /// per-cluster admission-webhook fan-out, the future M5 adaptive-
5765    /// placement engine's cluster-topology reader).
5766    ///
5767    /// Prior to this lift the `.clusters` `Vec<String>` was accessed
5768    /// inline at three production sites — the
5769    /// [`AplicacaoSpec::validate_placement`] pre-flight
5770    /// `self.placement.clusters.is_empty()` refusal probe, the same
5771    /// method's per-cluster validate loop's
5772    /// `for c in &self.placement.clusters` traversal head, and the
5773    /// `feira app graph` per-Aplicacao print line's
5774    /// `spec.placement.clusters` `{:?}` formatter argument
5775    /// (caixa-feira/src/cmd/app.rs) — three open-coded field-accesses
5776    /// that expressed no compile-time link back to the typed slot. A
5777    /// future extension of the `:placement :clusters` axis to a richer
5778    /// author surface (a per-tenant cluster-pool overlay the operator
5779    /// pins through a future `:placement :clusters-overrides` slot the
5780    /// MESH-COMPOSITION §V cross-cluster-federation roadmap
5781    /// acknowledges, a per-Aplicacao dynamic cluster-pool derivation
5782    /// the future M5 adaptive-placement engine computes from
5783    /// `:affinity` weights + live cluster-topology probes, a promotion
5784    /// of the plain `Vec<String>` to a richer `{static, dynamic}`
5785    /// partition once the substrate operator's cluster-membership
5786    /// reconciler comes into typed scope) would have had to be threaded
5787    /// through all three open-coded copies in lockstep or one consumer
5788    /// would silently disagree with the peers on which cluster-pool a
5789    /// given Aplicacao resolves to — the pre-flight `.is_empty()` probe
5790    /// reading the raw slot while the peer per-cluster validate loop
5791    /// read an operator-resolved slot would silently split the paired
5792    /// `PlacementWithoutClusters` / `PlacementClusterInvalid` /
5793    /// `PlacementClusterDuplicate` refusal cascade's actual traversal
5794    /// input from the pre-flight input, a three-consumer split at the
5795    /// validator and formatter far from the source `caixa.lisp` with
5796    /// no field naming the cluster-pool-drift root cause. Lifting the
5797    /// resolution rule to a typed method on the substrate primitive
5798    /// means every downstream consumer of the Aplicacao's
5799    /// per-`:placement` cluster-pool surface reaches for exactly one
5800    /// typed dispatch — the resolver's accept-set migrates as a unit
5801    /// on any future axis addition.
5802    ///
5803    /// Second slice-return (`&[T]`) accessor on any M2 or M3 typed
5804    /// slot — sibling to the seed M2
5805    /// [`crate::SupervisorSpec::children`] (bc92bce) `&[ChildSpec]`
5806    /// slice-return accessor on the peer per-`:supervisor` static-
5807    /// child-list `Vec`-carry axis, extended onto the first M3 mesh-
5808    /// slot `Vec`-carry axis. Same "one typed dispatch on the substrate
5809    /// primitive, thin projections at each consumer" discipline. The
5810    /// three peer `Vec`-carry axes still unlifted at the time of this
5811    /// lift — [`crate::AplicacaoSpec::membros`] (`Vec<Membro>`
5812    /// per-Aplicacao member list), [`crate::AplicacaoSpec::contratos`]
5813    /// (`Vec<WitContract>` per-Aplicacao WIT-typed edge list),
5814    /// [`crate::UpgradeFromEntry::instructions`]
5815    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
5816    /// — inherit this accessor's discipline as future compounding runs
5817    /// migrate their consumers onto the shared slice-return shape.
5818    /// Fourth (and final) accessor on the M3 mesh-slot `Placement`
5819    /// type, sibling to the two `Option<&str>`-return
5820    /// [`Placement::shard_key`] (7cd2a28) / [`Placement::affinity`]
5821    /// (74ec2d3) accessors and the `Copy`-return
5822    /// [`Placement::estrategia`] (921fe1b) accessor — closes the last
5823    /// unlifted per-`:placement` field axis (the `Vec<String>`
5824    /// distribution-target-list carrier) so every downstream
5825    /// per-`:placement` reader now routes through a typed dispatch on
5826    /// the substrate primitive. Named `clusters()` to match the storage
5827    /// field's name verbatim and the tatara-lisp author-surface term
5828    /// (`:clusters`) the field's own docstring already carries; the
5829    /// accessor's identity maps onto the canonical MESH-COMPOSITION
5830    /// §II.1 / §II.4 vocabulary the slot's docstring already reaches
5831    /// for. Returns `&[String]` (not `&Vec<String>`) because every
5832    /// downstream consumer of the cluster list treats it as a read-only
5833    /// sequence — the slice-view is the narrowest borrow that supports
5834    /// every present + roadmapped consumer (`.is_empty()`, `.iter()`,
5835    /// `.len()`) without leaking the backing `Vec`'s
5836    /// grow/push/reserve surface that no consumer of the typed view
5837    /// reaches for (the storage-side `Vec` remains reachable through
5838    /// the `pub clusters` field for the mutation-carrying serde
5839    /// round-trip and per-test fixture-mutation paths).
5840    #[must_use]
5841    pub const fn clusters(&self) -> &[String] {
5842        self.clusters.as_slice()
5843    }
5844}
5845
5846impl Default for Placement {
5847    fn default() -> Self {
5848        Self {
5849            // Route the struct-literal `estrategia` default arm through
5850            // the substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`]
5851            // typed `pub const` rather than the transitively-derived
5852            // [`PlacementStrategy::default`] route — one source of truth
5853            // for the M3-mesh-canonical [`PlacementStrategy::Replicated`]
5854            // active-active-across-every-named-cluster arm
5855            // (MESH-COMPOSITION §II.2) that both this struct-literal
5856            // altitude and the sibling [`Default for PlacementStrategy`]
5857            // impl already key off through the same substrate primitive.
5858            // Pinned by
5859            // `placement_default_estrategia_routes_through_lifted_default`.
5860            estrategia: PLACEMENT_ESTRATEGIA_DEFAULT,
5861            clusters: Vec::new(),
5862            affinity: None,
5863            shard_key: None,
5864        }
5865    }
5866}
5867
5868// ── external entry point ─────────────────────────────────────────────
5869
5870/// External entry point — what an outside caller sees. Renders to a
5871/// Gateway / Ingress + a route to the named member Servico.
5872#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
5873#[serde(rename_all = "camelCase")]
5874pub struct Entrada {
5875    /// Public hostname (e.g. `"checkout.quero.cloud"`).
5876    pub host: String,
5877
5878    /// Member Servico the gateway routes to. Must be in `:membros`.
5879    pub para: String,
5880
5881    /// Optional path filter — if set, only matching paths route to
5882    /// this Aplicacao (the rest fall through to other route rules).
5883    #[serde(default)]
5884    pub paths: Vec<String>,
5885
5886    /// Default port on the destination Servico (the trigger.service.port).
5887    #[serde(default = "default_port")]
5888    pub port: u16,
5889}
5890
5891impl Entrada {
5892    /// Substrate-canonical per-`:entrada` URL-path fallback resolver
5893    /// every HTTPRoute-aware renderer keys off — returns the author-
5894    /// declared `:entrada :paths` list verbatim when non-empty, and the
5895    /// singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] catch-
5896    /// all fallback otherwise (so an Aplicacao author who declares an
5897    /// external `:entrada` block but no per-path rule surface still
5898    /// gets a route whose sole `HTTPPathMatch` matches every incoming
5899    /// request under the paired
5900    /// [`crate::GATEWAY_API_PATH_MATCH_TYPE_PATH_PREFIX`] discriminator).
5901    ///
5902    /// Prior to this lift the "if `:entrada :paths` is empty use the
5903    /// substrate catch-all; else return each declared path verbatim"
5904    /// cascade lived inline at
5905    /// [`caixa_mesh::gateway_routes`]'s per-rule path-list resolver
5906    /// (caixa-mesh/src/lib.rs:2883 prior to this lift), the sole
5907    /// per-Aplicacao HTTPRoute per-rule path-list emit site the
5908    /// substrate ships today, with no typed method on the substrate
5909    /// primitive that named the rule. A future path-resolution axis
5910    /// addition — a per-cluster `:entrada :default-path` override the
5911    /// operator pins through a future `:placement`-scoped slot, an
5912    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
5913    /// admission-webhook floor that materializes the catch-all before
5914    /// the CR lands, a future per-`:entrada :paths` overlay from a
5915    /// per-cluster policy the future `feira app deploy` pipeline
5916    /// consumes — would have to be threaded through every renderer's
5917    /// inline copy of the cascade in lockstep or one consumer would
5918    /// silently disagree with the peers on which path list a given
5919    /// `:entrada` block resolves to. Lifting the rule to a typed
5920    /// method on the substrate primitive means every downstream
5921    /// HTTPRoute-aware consumer (the M4 CR materializer, the future
5922    /// per-cluster overlay resolver, every future per-Aplicacao
5923    /// snapshot renderer) reaches for exactly one typed dispatch —
5924    /// the resolver's accept-set moves as a unit on any future axis
5925    /// addition.
5926    ///
5927    /// Peer of the sibling [`crate::DEFAULT_SERVICO_PORT`] /
5928    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] lifts on the
5929    /// per-`:entrada` scalar-value axes — extends the "one typed
5930    /// dispatch on the substrate primitive, thin projections at each
5931    /// consumer" discipline onto the per-`:entrada` path-list
5932    /// resolution axis every HTTPRoute-aware renderer consumes. Same
5933    /// shape as the [`MeshPolicy::is_empty`] typed predicate on the
5934    /// sibling `:politicas` primitive — one typed method on the
5935    /// substrate primitive that names the cascade every renderer
5936    /// otherwise re-inlines.
5937    #[must_use]
5938    pub fn resolved_paths(&self) -> Vec<&str> {
5939        // Route the internal cascade-head + per-entry projection reads
5940        // through the lifted [`Self::paths`] slice accessor rather than
5941        // the raw `self.paths` field access — the substrate-primitive
5942        // per-`:entrada` path-list resolver's two internal reads now
5943        // key off the canonical raw-slot surface every downstream
5944        // per-`:entrada` path-list consumer (`AplicacaoSpec::validate`'s
5945        // per-entry value-shape gate, `feira app graph`'s per-Aplicacao
5946        // entrada summary line's `{:?}` Debug print) routes through, so
5947        // any future rebrand on the typed slot's raw-slot reader lands
5948        // at exactly one place. Same two-consumer coherence discipline
5949        // the sibling `Placement::clusters` (a6e18d7) accessor pins on
5950        // the peer M3 mesh-slot `Vec<String>`-carry axis.
5951        if self.paths().is_empty() {
5952            vec![crate::render::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH]
5953        } else {
5954            self.paths().iter().map(String::as_str).collect()
5955        }
5956    }
5957
5958    /// Substrate-canonical per-`:entrada` DNS-hostname singular
5959    /// accessor every Gateway-API `Listener.hostname` reader keys off
5960    /// — returns the author-declared `:entrada :host` byte-string
5961    /// verbatim as a `&str`, borrowed from the typed slot's own
5962    /// [`String`] storage.
5963    ///
5964    /// Named the "singular" half of the DNS-hostname resolver pair on
5965    /// the substrate primitive: the parent-Gateway per-listener
5966    /// `hostname:` axis of the K8s Gateway API v1.x is scalar-shaped
5967    /// (`Listener.hostname: Option<PreciseHostname>` — at most one
5968    /// hostname per listener), and this accessor is the typed dispatch
5969    /// the [`caixa_mesh::gateway_routes`] Gateway-listener emit site
5970    /// reaches for. Its plural sibling [`Entrada::hostnames`] carries
5971    /// the per-HTTPRoute `spec.hostnames[]` list axis the same
5972    /// per-Aplicacao ingress-hostname surface projects onto.
5973    ///
5974    /// Prior to this lift the `entrada.host.clone()` byte-string was
5975    /// accessed inline at two `caixa-mesh` sites — the parent-Gateway
5976    /// per-listener singular `hostname:` axis
5977    /// (`caixa-mesh/src/lib.rs:2775` prior to this lift) and the
5978    /// per-HTTPRoute plural `spec.hostnames[]` axis
5979    /// (`caixa-mesh/src/lib.rs:2969` prior to this lift). Both
5980    /// consumers read the same `entrada.host` field but the two-site
5981    /// duplication expressed no compile-time contract that the singular
5982    /// Gateway-listener filter and the plural `HTTPRoute` filter list
5983    /// stay in lockstep on future extensions of the `:entrada` slot to
5984    /// a multi-hostname author surface (an `:entrada :alt-hosts` list
5985    /// overlay, a per-cluster SNI fan-out the operator pins through a
5986    /// future `:placement :hosts` slot, an M4 `mesh.pleme.io/v1alpha1/
5987    /// Aplicacao` CR materializer's per-listener virtual-host filter
5988    /// admission-webhook overlay). Any such extension would have to be
5989    /// threaded through every renderer's inline copy of the resolution
5990    /// in lockstep or the Gateway listener's `hostname:` filter would
5991    /// silently disagree with the `HTTPRoute`'s `hostnames[]` filter list
5992    /// — a Gateway-API-conformance divergence whose apply-time symptom
5993    /// (the `HTTPRoute` `Accepted` condition flips to `False` with reason
5994    /// `NoMatchingParent` — the API server rejects the route because
5995    /// its `hostnames[]` filter doesn't intersect the parent listener's
5996    /// `hostname` filter) is far from the source `caixa.lisp` and never
5997    /// surfaces in the emitted YAML. Lifting the singular and plural
5998    /// resolvers to typed methods on the substrate primitive means
5999    /// every consumer of the Aplicacao's ingress-hostname surface
6000    /// reaches for exactly one typed dispatch, and the pair-invariant
6001    /// `hostnames() == vec![hostname()]` pinned by the sibling
6002    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`] test
6003    /// keeps the two axes in lockstep by construction.
6004    ///
6005    /// Peer of the sibling per-`:entrada` [`Entrada::resolved_paths`]
6006    /// (1449891) path-list resolver on the per-HTTPRoute per-rule
6007    /// `spec.rules[].matches[].path` axis. Same "one typed dispatch on
6008    /// the substrate primitive, thin projections at each consumer"
6009    /// discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6010    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6011    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6012    /// [`Entrada::resolved_paths`] lifts apply on the sibling per-
6013    /// `:entrada` scalar-value + list-value axes.
6014    #[must_use]
6015    pub const fn hostname(&self) -> &str {
6016        self.host.as_str()
6017    }
6018
6019    /// Substrate-canonical per-`:entrada` DNS-hostname plural
6020    /// accessor every Gateway-API `HTTPRoute.spec.hostnames[]` reader
6021    /// keys off — returns the singleton `[hostname()]` list under
6022    /// today's single-hostname-per-Aplicacao author surface, and the
6023    /// authoritative multi-hostname list under a future
6024    /// `:entrada :alt-hosts` / per-cluster SNI-fan-out extension.
6025    ///
6026    /// Plural half of the DNS-hostname resolver pair — see the
6027    /// companion [`Entrada::hostname`] docstring for the two-consumer
6028    /// lift + pair-invariant discipline (`hostnames() ==
6029    /// vec![hostname()]`, pinned load-bearing by the sibling
6030    /// [`tests::hostnames_returns_singleton_of_hostname_accessor`]
6031    /// test).
6032    ///
6033    /// Peer of the sibling [`Entrada::resolved_paths`] (1449891)
6034    /// per-`:entrada` plural-list resolver on the per-HTTPRoute
6035    /// per-rule path-list axis — same `Vec<&str>` shape, same
6036    /// substrate-primitive-owns-the-resolver discipline extended to
6037    /// the per-HTTPRoute virtual-host filter-list axis.
6038    #[must_use]
6039    pub fn hostnames(&self) -> Vec<&str> {
6040        vec![self.hostname()]
6041    }
6042
6043    /// Substrate-canonical per-`:entrada` destination-Servico scalar
6044    /// accessor every Gateway-API `HTTPRoute` reader keys off — returns
6045    /// the author-declared `:entrada :para` byte-string verbatim as a
6046    /// `&str`, borrowed from the typed slot's own [`String`] storage.
6047    ///
6048    /// The `:entrada :para` slot names the single member Servico the
6049    /// external Gateway routes to (validated by
6050    /// [`AplicacaoSpec::validate`] to be a
6051    /// [`Membro::caixa`] the Aplicacao declares — a stray
6052    /// `:para` that doesn't name a member is
6053    /// [`AplicacaoError::EntradaParaNotInMembros`], not a silent
6054    /// backend-attachment miss at cluster-apply time). Under today's
6055    /// single-destination author surface `:entrada :para` is the ingress
6056    /// apex Servico's canonical identity; under a hypothetical
6057    /// future multi-backend author surface (a `:entrada
6058    /// :split :backends` weighted-fan-out overlay for canary /
6059    /// blue-green traffic-split rollouts, per-path override for
6060    /// path-based per-Servico routing beyond the single-apex model,
6061    /// the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6062    /// per-CR admission-webhook that promotes the scalar to a
6063    /// weighted list) this accessor is the substrate primitive's typed
6064    /// dispatch every downstream `HTTPRoute`-aware consumer routes
6065    /// through, so the resolution shape migrates as a unit on one
6066    /// caixa-core edit rather than a coordinated rewrite across every
6067    /// renderer's inline field-access.
6068    ///
6069    /// Prior to this lift the `entrada.para` byte-string was accessed
6070    /// inline at two `caixa-mesh` sites — the per-Aplicacao HTTPRoute
6071    /// `metadata.name` composer's per-destination discriminator arg
6072    /// (`gateway_api_http_route_name(&caixa.nome, &entrada.para)`,
6073    /// `caixa-mesh/src/lib.rs:2845` prior to this lift) and the
6074    /// per-HTTPRoute per-rule `backendRefs[0].name` axis
6075    /// (`entrada.para.clone()`,
6076    /// `caixa-mesh/src/lib.rs:2975` prior to this lift). Both
6077    /// consumers read the same `entrada.para` field but the two-site
6078    /// duplication expressed no compile-time contract that the HTTPRoute
6079    /// name-discriminator and the per-rule backend name stay in
6080    /// lockstep on future extensions of the `:entrada` slot to a
6081    /// multi-destination author surface. Any such extension would have
6082    /// to be threaded through every renderer's inline copy of the
6083    /// destination projection in lockstep or the HTTPRoute
6084    /// `metadata.name` would silently reference a different destination
6085    /// than its own `backendRefs[]` — an operator-side
6086    /// `kubectl get httproute -n tatara-system <aplicacao>-<destination>`
6087    /// grep-by-name lookup would land on a route whose `backendRefs[]`
6088    /// silently point at a peer Servico, dropping every external
6089    /// `:entrada` flow at the gateway with the destination-drift root
6090    /// cause invisible in the emitted YAML.
6091    ///
6092    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] +
6093    /// [`Entrada::hostnames`] (11f3dfe) DNS-hostname resolver pair on
6094    /// the per-listener singular / per-HTTPRoute plural filter axes and
6095    /// [`Entrada::resolved_paths`] (1449891) per-`:entrada` path-list
6096    /// resolver on the per-HTTPRoute per-rule matches axis. Same "one
6097    /// typed dispatch on the substrate primitive, thin projections at
6098    /// each consumer" discipline the [`crate::DEFAULT_SERVICO_PORT`] +
6099    /// [`AplicacaoSpec::port_for_destination`] (9ca4896) /
6100    /// [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] +
6101    /// [`Entrada::resolved_paths`] (1449891) lifts apply on the
6102    /// sibling per-`:entrada` scalar-value + list-value axes — this
6103    /// accessor closes the last unlifted per-`:entrada` scalar axis
6104    /// (the destination-Servico byte-string) so every downstream
6105    /// per-`:entrada` reader now routes through a typed dispatch on
6106    /// the substrate primitive.
6107    #[must_use]
6108    pub const fn destination(&self) -> &str {
6109        self.para.as_str()
6110    }
6111
6112    /// Substrate-canonical per-`:entrada` L4-port scalar accessor every
6113    /// Gateway-API `HTTPRoute.backendRefs[0].port` / Cilium
6114    /// `CiliumNetworkPolicy.spec.ingress[].toPorts[0].ports[0].port`
6115    /// reader keys off — returns the author-declared `:entrada :port`
6116    /// value verbatim as a `u16`, `Copy`-projected from the typed slot's
6117    /// own `u16` storage (validated by [`AplicacaoSpec::validate`] to lie
6118    /// in [`SERVICO_PORT_MIN`]`..=u16::MAX` — a stray `:port 0` is
6119    /// [`AplicacaoError::EntradaPortZero`], not a silent
6120    /// admission-webhook rejection at cluster-apply time).
6121    ///
6122    /// The `:entrada :port` slot carries the destination Servico's
6123    /// canonical in-cluster L4 listener port (`trigger.service.port` on
6124    /// the `pleme-computeunit` library chart), and every downstream
6125    /// consumer that reads the port keys off this scalar (the
6126    /// [`AplicacaoSpec::validate`] entrada-block structural-floor gate,
6127    /// the [`AplicacaoSpec::port_for_destination`] typed-dispatch
6128    /// resolver `caixa-mesh` HTTPRoute / CNP L4-fallback renderers
6129    /// route through, the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6130    /// CR materializer's per-Aplicacao gateway port resolver).
6131    ///
6132    /// Prior to this lift the `.port` field was accessed inline at two
6133    /// caixa-core sites — the [`AplicacaoSpec::validate`] entrada-block
6134    /// structural-floor gate's `if e.port < SERVICO_PORT_MIN` check and
6135    /// the [`AplicacaoSpec::port_for_destination`] resolver's
6136    /// `.map_or(DEFAULT_SERVICO_PORT, |e| e.port)` cascade — two
6137    /// open-coded field-accesses that expressed no compile-time link
6138    /// back to the typed slot. A future extension of the `:entrada :port`
6139    /// axis to a richer author surface — a per-cluster override the
6140    /// operator pins through a future `:placement :default-port` slot the
6141    /// [`DEFAULT_SERVICO_PORT`] docstring acknowledges, an
6142    /// `Option<u16>`-shape migration once the substrate grows per-`:membros`
6143    /// heterogeneous listener ports, an M4
6144    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CR
6145    /// admission-webhook floor that promotes the scalar to a
6146    /// per-destination map — would have had to be threaded through both
6147    /// open-coded copies in lockstep or the structural-floor validator
6148    /// and the [`AplicacaoSpec::port_for_destination`] resolver would
6149    /// silently disagree on which port a given [`Entrada`] resolves to.
6150    /// Lifting the resolution rule to a typed method on the substrate
6151    /// primitive means every downstream consumer of the Aplicacao's
6152    /// per-`:entrada` L4-port surface reaches for exactly one typed
6153    /// dispatch — the resolver's accept-set migrates as a unit on any
6154    /// future axis addition.
6155    ///
6156    /// Peer of the sibling per-`:entrada` [`Entrada::hostname`] /
6157    /// [`Entrada::destination`] (11f3dfe, 6db982c) `&str` scalar
6158    /// accessors on the per-`:entrada` scalar-value axis — same "one
6159    /// typed dispatch on the substrate primitive, thin projections at
6160    /// each consumer" discipline extended onto the per-`:entrada`
6161    /// L4-port `u16` `Copy`-scalar axis. First `Copy`-return accessor on
6162    /// the M3 mesh-slot `Entrada` type — closes the last unlifted
6163    /// per-`:entrada` scalar-value axis (the `u16` L4 port); companion
6164    /// to the sibling per-`:politicas` `Option<Copy-T>` accessor family
6165    /// [`MeshPolicy::mtls_required`] / [`MeshPolicy::retries`] /
6166    /// [`MeshPolicy::timeout`] (c0110f1, bdfb399, 7073d0f) on the peer
6167    /// M3 mesh-slot Copy-scalar axis. Named `port()` to match the
6168    /// storage field's name; the accessor's identity name maps onto the
6169    /// canonical MESH-COMPOSITION §II.5 vocabulary the slot's docstring
6170    /// already carries. Declared `pub const fn` (matching the peer M3
6171    /// mesh-slot `Copy`-return accessor family — [`MeshPolicy::timeout`]
6172    /// / [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
6173    /// [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`] on
6174    /// the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`] /
6175    /// [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
6176    /// [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
6177    /// [`RateLimit`], and the sibling per-`:placement`
6178    /// [`Placement::estrategia`] on the peer M3 mesh-slot `Copy`-composite-
6179    /// enum scalar axis — every one a `pub const fn`) so every future
6180    /// substrate-side `const`-context consumer of the resolved
6181    /// per-`:entrada` L4-port scalar (a `const _: () = assert!(…)`
6182    /// module-scope pin on a per-fixture typed [`Entrada`] anchoring
6183    /// `entrada.port() >= SERVICO_PORT_MIN` at compile time, a future M4
6184    /// admission-webhook `const fn` per-CR gateway-port floor over a
6185    /// typed [`Entrada`], any `const fn` composer that fans on the port
6186    /// at compile time) reaches through the same typed dispatch on the
6187    /// substrate primitive at const-eval time as at runtime. Pinned by
6188    /// [`entrada_port_accessor_is_const_fn`] which witnesses the
6189    /// const-eval posture at module scope via `const _:() = …` items so
6190    /// any future accidental downgrade to non-`const` trips at caixa-core
6191    /// build time.
6192    #[must_use]
6193    pub const fn port(&self) -> u16 {
6194        self.port
6195    }
6196
6197    /// Substrate-canonical per-`:entrada` URL-path-list `&[String]`
6198    /// slice accessor every HTTPRoute-aware renderer keys off when it
6199    /// wants the raw author-declared path-list (not the fallback-
6200    /// applied projection [`Self::resolved_paths`] returns) — returns
6201    /// the author-declared `:entrada :paths` list verbatim as `&[String]`,
6202    /// borrowed from the typed slot's own [`Vec<String>`] storage.
6203    ///
6204    /// Named the "raw slot" half of the per-`:entrada` path-list resolver
6205    /// pair on the substrate primitive: the sibling [`Self::resolved_paths`]
6206    /// (1449891) closes the fallback-applying arm every per-Aplicacao
6207    /// HTTPRoute per-rule `matches[].path` emitter routes through (empty
6208    /// slot → single [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
6209    /// catch-all; non-empty slot → per-entry verbatim projection); this
6210    /// accessor closes the raw-slot arm every consumer that must see the
6211    /// author's declaration verbatim (the [`AplicacaoSpec::validate`]
6212    /// per-entry value-shape gate — empty `:paths` must be `Ok(())`,
6213    /// not `Err(EntradaPathEmpty)`, so it cannot route through the
6214    /// fallback-applying sibling; the `feira app graph` per-Aplicacao
6215    /// external-gateway summary line's `{:?}` Debug print — which must
6216    /// name the author's declaration, not the substrate's fallback, so
6217    /// an author reading their graph output can grep their caixa.lisp
6218    /// for the exact list they authored) routes through.
6219    ///
6220    /// Prior to this lift the `.paths` field was accessed inline at four
6221    /// production sites: the two internal reads in [`Self::resolved_paths`]
6222    /// (the `.is_empty()` cascade-head and the `.iter().map(String::as_str)`
6223    /// per-entry projection), the [`AplicacaoSpec::validate`] per-entry
6224    /// value-shape gate's `for p in &e.paths` traversal head, and the
6225    /// `feira app graph` per-Aplicacao entrada summary line's `{:?}`
6226    /// Debug print — four open-coded field-accesses that expressed no
6227    /// compile-time link back to the typed slot. A future extension of
6228    /// the `:entrada :paths` axis to a richer author surface — a
6229    /// per-path per-method HTTP-verb filter overlay (`(:paths ((:path
6230    /// "/api" :methods (:get :post))))` the Gateway API v1 HTTPRoute
6231    /// spec supports through `matches[].method`), a per-path per-header
6232    /// filter overlay (`matches[].headers[]`), a per-cluster override
6233    /// the operator pins through a future `:placement :path-overlay`
6234    /// slot, an M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
6235    /// per-CR admission-webhook that normalized the list at admission
6236    /// time — would have had to be threaded through every open-coded
6237    /// copy in lockstep or the validator's per-entry gate would silently
6238    /// disagree with the renderer's per-entry emit on which list a given
6239    /// `:entrada` block resolves to. Lifting the resolution to a typed
6240    /// method on the substrate primitive means every downstream consumer
6241    /// of the Aplicacao's per-`:entrada` path-list surface reaches for
6242    /// exactly one typed dispatch — the resolver's accept-set migrates
6243    /// as a unit on any future axis addition.
6244    ///
6245    /// Peer of the sibling [`crate::Placement::clusters`] (a6e18d7)
6246    /// `&[String]` slice accessor on the peer M3 mesh-slot `Vec<String>`-
6247    /// carry axis — same "one typed dispatch on the substrate primitive,
6248    /// thin projections at each consumer" discipline extended onto the
6249    /// per-`:entrada` `Vec<String>` slice-carry axis. Closes the last
6250    /// unlifted per-`:entrada` field axis (the `Vec<String>` path-list
6251    /// carrier) so every downstream per-`:entrada` reader now routes
6252    /// through a typed dispatch on the substrate primitive. Returns
6253    /// `&[String]` (not `&Vec<String>`) because every downstream consumer
6254    /// treats the list as a read-only sequence — the slice-view is the
6255    /// narrowest borrow that supports every present + roadmapped consumer
6256    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the backing
6257    /// `Vec`'s grow/push/reserve surface that no consumer of the typed
6258    /// view reaches for (the storage-side `Vec` remains reachable through
6259    /// the `pub paths` field for the mutation-carrying serde round-trip
6260    /// and per-test fixture-mutation paths).
6261    #[must_use]
6262    pub const fn paths(&self) -> &[String] {
6263        self.paths.as_slice()
6264    }
6265}
6266
6267/// Canonical default L4 port every typed Servico exposes on its
6268/// in-cluster K8s Service (the `trigger.service.port` axis the
6269/// `pleme-computeunit` library chart emits, the `:entrada :port` author
6270/// surface defaults to when the author omits the slot, and the
6271/// `caixa-mesh` `CiliumNetworkPolicy` L4-fallback substitutes when no
6272/// `:entrada` block matches the per-`:contratos` destination Servico).
6273/// The single source of truth all three typed-port consumers reach for:
6274///
6275///   - [`Entrada::port`]'s serde default (via the
6276///     [`default_port`] helper this constant feeds); the author surface
6277///     `(:entrada (:host … :para …))` without an explicit `:port` slot
6278///     reads back as a typed [`Entrada`] carrying this exact value;
6279///   - the
6280///     [`caixa_mesh::cilium_network_policies`][cm] `CiliumNetworkPolicy`
6281///     emitter's per-`(:de, :para)` L4 `toPorts[].ports[].port`
6282///     fallback, fired when the typed `:entrada` block doesn't name
6283///     the per-`:contratos` destination Servico — the typed
6284///     `:contratos` graph carries no per-destination port axis (the
6285///     destination port is the destination Servico's
6286///     `lareira-<nome>` chart's `trigger.service.port`, which the
6287///     Aplicacao-level renderer has no visibility into without a
6288///     resolver round-trip), so the renderer falls back to the
6289///     substrate's canonical Servico-port assumption — by
6290///     construction the same value the destination's own
6291///     `pleme-computeunit` chart emits, the same value the
6292///     destination's own typed `:entrada :port` slot defaults to;
6293///   - every future per-Servico renderer the absorption-roadmap
6294///     acknowledges (the future M4 `mesh.pleme.io/v1alpha1/Aplicacao`
6295///     CR materializer's per-edge port resolver, the future
6296///     per-`:politicas :rate-limit` `CiliumClusterwideEnvoyConfig`
6297///     emitter's per-route bucket key, the future caixa-otel
6298///     collector-pipeline emitter's per-Servico scrape port).
6299///
6300/// Until this lift landed the value `8080` lived at two production-code
6301/// call-sites: the [`default_port`] helper at
6302/// `caixa-core/src/aplicacao.rs:1712` (the typed slot's serde default)
6303/// and the `.unwrap_or(8080)` literal at
6304/// `caixa-mesh/src/lib.rs:344` (the L4-fallback in
6305/// [`caixa_mesh::cilium_network_policies`]'s per-`(:de, :para)` port
6306/// resolver). A future Servico-port rebrand — the substrate moving the
6307/// canonical port to `80` (HTTP's IANA-assigned port) once the cluster
6308/// gateway grows direct `:80` listeners, to `8443` once the substrate
6309/// moves to mTLS-by-default at the Servico boundary, to a per-cluster
6310/// override the operator pins through a future
6311/// `:placement :default-port` slot — without a coordinated edit on
6312/// both sides would silently emit Servicos listening on one port and
6313/// their Aplicacao's `CiliumNetworkPolicy` whitelisting a drifted one.
6314/// The CNP's apply-time symptom (the policy is admitted but every L4
6315/// flow on the destination Servico's actual port silently drops because
6316/// it doesn't match the whitelisted port) is far from the rebrand
6317/// commit's source, and Cilium's per-L4-drop diagnostic surfaces only
6318/// in hubble traces, not in `kubectl describe`. Lifting the literal to
6319/// a shared constant closes the drift footgun structurally — both
6320/// consumers read from the same `u16`, so any rebrand reaches both
6321/// sites by construction.
6322///
6323/// Mirrors the [`crate::DEFAULT_NAMESPACE`] lift (a085b26) on the peer
6324/// per-renderer canonical-K8s-axis constant — the namespace string
6325/// and the canonical Servico port both lived as duplicated literals
6326/// across caixa-core / caixa-mesh / caixa-flux before their respective
6327/// lifts. Same "the typed constant lives in one place" discipline the
6328/// [`crate::PLEME_LABEL_PREFIX`] / [`crate::LAREIRA_CHART_NAME_PREFIX`]
6329/// / [`crate::KUBE_KEY_API_VERSION`] lifts apply on the peer
6330/// shared-string axes.
6331///
6332/// [cm]: ../../caixa_mesh/fn.cilium_network_policies.html
6333pub const DEFAULT_SERVICO_PORT: u16 = 8080;
6334
6335/// Structural floor for the typed `:entrada :port` axis — every
6336/// validated [`Entrada::port`] past [`AplicacaoSpec::validate`] lies in
6337/// `SERVICO_PORT_MIN..=u16::MAX` (inclusive on both ends).
6338///
6339/// The IANA-registered TCP/UDP port space is `1..=65535` — port `0` is
6340/// the "any ephemeral" sentinel that the Berkeley-sockets `bind(0)` call
6341/// interprets as "let the kernel pick a free port at bind time", not a
6342/// well-defined destination the substrate's per-`:entrada` Gateway API
6343/// v1 `HTTPRoute.backendRefs[].port` axis can honor. A typed slot
6344/// carrying `port: 0` degenerates to a nominal-only routing target: the
6345/// K8s Gateway API v1 apiserver-side webhook rejects `port: 0` outright
6346/// (`spec.rules[].backendRefs[].port: Invalid value: 0` — the same
6347/// admission floor the peer `PolicyRetriesExceedsCap` cap-arm surfaces
6348/// at build time rather than at `kubectl apply` time), and the
6349/// substrate's per-`Entrada` `CiliumNetworkPolicy` L4-fallback resolver
6350/// (caixa-mesh/src/lib.rs:2657 through
6351/// [`DEFAULT_SERVICO_PORT`]) — the sole downstream reader of the
6352/// [`Entrada::port`] typed value — silently emits a policy whose
6353/// `toPorts[].ports[].port` scalar drifts off the destination Servico's
6354/// actual listener, dropping every L4 flow at the eBPF data plane far
6355/// from the source caixa.lisp with no field naming the port-zero-drift
6356/// root cause.
6357///
6358/// The typed field is `u16`, so `u16::MAX` (=65535) is the natural
6359/// structural ceiling — no `SERVICO_PORT_MAX` companion const is needed
6360/// on the top edge (unlike the peer capped-`u32` `:politicas` /
6361/// `:supervisor` / `:limits` axes where `POLICY_RETRIES_MAX` /
6362/// `SUPERVISOR_MAX_RESTARTS_MAX` / `LIMITS_CPU_MILLICORES_MAX` all sit
6363/// well below `u32::MAX` and therefore need explicit typed caps).
6364///
6365/// Pairs with [`DEFAULT_SERVICO_PORT`] on the same typed-port axis:
6366/// [`DEFAULT_SERVICO_PORT`] names the substrate's chosen default port
6367/// scalar every `(:entrada (:host … :para …))` slot without an explicit
6368/// `:port` inherits through the serde default hook; this constant names
6369/// the accept-set floor every declared port must satisfy. The pair is
6370/// invariantly ordered `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT` (the
6371/// substrate's default must satisfy its own accept-set floor by
6372/// construction) — a future rebrand that accidentally moved
6373/// [`DEFAULT_SERVICO_PORT`] below the floor (a hypothetical `0` /
6374/// negative-cast typo, a per-cluster override the operator pins through
6375/// a future `:placement :default-port` slot that lands out-of-range)
6376/// would silently invalidate the serde-default emission at every
6377/// author-side `(:entrada (:host … :para …))` slot — the compile-time
6378/// invariant pin
6379/// (`default_servico_port_satisfies_lifted_servico_port_min_floor`)
6380/// closes the drift footgun at caixa-core build time.
6381///
6382/// Lifted as a typed `pub const` (rather than an inline `0` literal at
6383/// the [`AplicacaoSpec::validate`] call site) so the accept-set floor
6384/// has exactly one source of truth — the future M4
6385/// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-Aplicacao
6386/// gateway resolver, the future per-Servico
6387/// `computeunit.trigger.service.port` renderer's per-CR port-value
6388/// validator, and every downstream test-fixture navigator asserting
6389/// the accept-set floor all read from one place. Same shape every
6390/// other typed bracket-floor / bracket-ceiling in this crate carries
6391/// ([`LIMITS_MEMORY_WASM32_PAGE_BYTES`], [`LIMITS_MEMORY_WASM32_MAX_BYTES`],
6392/// [`LIMITS_WALL_CLOCK_MAX`], [`LIMITS_CPU_MILLICORES_MAX`],
6393/// [`LIMITS_FUEL_MAX`], [`POLICY_TIMEOUT_MAX`], [`POLICY_RETRIES_MAX`],
6394/// [`POLICY_BREAKER_MAX_FAILURES_MAX`], [`POLICY_BREAKER_WINDOW_MAX`],
6395/// [`POLICY_RATE_LIMIT_MAX`]).
6396pub const SERVICO_PORT_MIN: u16 = 1;
6397
6398const fn default_port() -> u16 {
6399    DEFAULT_SERVICO_PORT
6400}
6401
6402// ── the typed view ───────────────────────────────────────────────────
6403
6404/// Typed composition view of the flat Aplicacao slots on
6405/// [`crate::Caixa`]. Built via [`crate::Caixa::aplicacao_view`] for
6406/// validation + downstream renderer consumption.
6407#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
6408#[serde(rename_all = "camelCase")]
6409pub struct AplicacaoSpec {
6410    pub membros: Vec<Membro>,
6411    pub contratos: Vec<WitContract>,
6412    pub politicas: MeshPolicy,
6413    pub placement: Placement,
6414    pub entrada: Option<Entrada>,
6415}
6416
6417impl AplicacaoSpec {
6418    /// Substrate-canonical per-`:membros` `Vec<Membro>` MESH-COMPOSITION
6419    /// per-Aplicacao member-list slice-return accessor every
6420    /// per-Aplicacao member-list reader keys off — returns the author-
6421    /// declared `:membros` list verbatim as a `&[Membro]` slice-view
6422    /// over the same backing buffer the raw `self.membros.as_slice()`
6423    /// field access borrows from.
6424    ///
6425    /// The `:membros` slot carries the M3 mesh-slot per-Aplicacao
6426    /// member list — the load-bearing identity of the application graph
6427    /// (MESH-COMPOSITION §III.1: the graph nodes are a set, not a
6428    /// multiset). Every per-`:membros` entry pairs a `:caixa` member-
6429    /// caixa name (through the lifted [`Membro::nome`] (4a32abf)
6430    /// accessor) with a `:versao` semver-requirement string (through
6431    /// the lifted [`Membro::versao_requirement`] (a40b0e3) accessor),
6432    /// and every downstream consumer that fans on the member-set keys
6433    /// off this slice (the [`AplicacaoSpec::validate`] `:contratos`
6434    /// membership-lookup `HashSet<&str>` seed's collect input, the
6435    /// [`AplicacaoSpec::validate_membros`] pre-flight `.is_empty()`
6436    /// [`AplicacaoError::NoMembros`] refusal probe, the same method's
6437    /// per-member DNS-1123 / semver-requirement / duplicate-detection
6438    /// fan-out loop, the [`AplicacaoSpec::detect_sync_cycles`]
6439    /// adjacency-list seed, the [`caixa_mesh::programs_for_aplicacao`]
6440    /// programs.yaml per-`:membros` fan-out emitter's per-entry
6441    /// mapping-composition loop, the `feira app graph` per-Aplicacao
6442    /// member-count print line and per-member tree traversal,
6443    /// every future wasm-operator (M4) per-Aplicacao CR materializer's
6444    /// per-member `ComputeUnit` fan-out, the future M5 adaptive-
6445    /// placement engine's per-member weight-topology reader).
6446    ///
6447    /// Prior to this lift the `.membros` `Vec<Membro>` was accessed
6448    /// inline at six production sites — the [`AplicacaoSpec::validate`]
6449    /// `self.membros.iter().map(Membro::nome).collect()` name-set seed,
6450    /// [`AplicacaoSpec::validate_membros`]'s pre-flight
6451    /// `self.membros.is_empty()` [`AplicacaoError::NoMembros`] refusal
6452    /// probe, the same method's per-member `for m in &self.membros`
6453    /// validate-loop traversal head, the
6454    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6455    /// `for m in &self.membros` adjacency-list seed, the
6456    /// [`caixa_mesh::programs_for_aplicacao`] emitter's
6457    /// `Vec::with_capacity(spec.membros.len())` output-buffer sizing
6458    /// paired with the peer `for m in &spec.membros` per-entry fan-out
6459    /// loop, and the `feira app graph` per-Aplicacao print line's
6460    /// `spec.membros.len()` count formatter argument paired with the
6461    /// peer `for m in &spec.membros` per-member tree traversal — six
6462    /// open-coded field-accesses that expressed no compile-time link
6463    /// back to the typed slot. A future extension of the `:membros`
6464    /// axis to a richer author surface (a per-cluster member-set
6465    /// overlay the operator pins through a future
6466    /// `:membros-overrides` slot the MESH-COMPOSITION §V federation
6467    /// roadmap acknowledges, a per-tenant member-alias table the M4
6468    /// `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer resolves per-
6469    /// CR at admission time, a per-Aplicacao dynamic member-set
6470    /// derivation the future adaptive-placement engine computes from
6471    /// weighted membership topology, a promotion of the plain
6472    /// `Vec<Membro>` to a richer `{static, dynamic}` partition once
6473    /// Orleans-style virtual-actor dynamic-membership comes into typed
6474    /// scope) would have had to be threaded through all six open-coded
6475    /// copies in lockstep or one consumer would silently disagree with
6476    /// the peers on which member-set a given Aplicacao resolves to —
6477    /// the `HashSet<&str>` name-set seed reading the raw slot while
6478    /// the peer `.is_empty()` refusal probe read an operator-resolved
6479    /// slot would silently split the `:contratos` membership-lookup
6480    /// input from the pre-flight-refusal input, a six-consumer split
6481    /// at the validator + programs.yaml emitter + graph printer far
6482    /// from the source `caixa.lisp` with no field naming the member-
6483    /// set-drift root cause. Lifting the resolution rule to a typed
6484    /// method on the substrate primitive means every downstream
6485    /// consumer of the Aplicacao's per-`:membros` member-list surface
6486    /// reaches for exactly one typed dispatch — the resolver's accept-
6487    /// set migrates as a unit on any future axis addition.
6488    ///
6489    /// Third slice-return (`&[T]`) accessor on any M2 or M3 typed slot
6490    /// — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6491    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6492    /// static-child-list `Vec`-carry axis, and to the M3
6493    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6494    /// on the peer per-`:placement` distribution-target-list `Vec`-
6495    /// carry axis. Same "one typed dispatch on the substrate primitive,
6496    /// thin projections at each consumer" discipline. The two peer
6497    /// `Vec`-carry axes still unlifted at the time of this lift —
6498    /// [`AplicacaoSpec::contratos`] (`Vec<WitContract>` per-Aplicacao
6499    /// WIT-typed edge list) and
6500    /// [`crate::UpgradeFromEntry::instructions`]
6501    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction list)
6502    /// — inherit this accessor's discipline as future compounding runs
6503    /// migrate their consumers onto the shared slice-return shape.
6504    /// First `&[T]`-return accessor on the top-level M3 mesh-slot
6505    /// `AplicacaoSpec` type itself, extending the discipline beyond
6506    /// the inner per-slot types ([`crate::Placement`],
6507    /// [`crate::SupervisorSpec`]) onto the outermost typed composition
6508    /// view every renderer consumes. Named `membros()` to match the
6509    /// storage field's name verbatim and the tatara-lisp author-
6510    /// surface term (`:membros`) the field's own docstring already
6511    /// carries; the accessor's identity maps onto the canonical
6512    /// MESH-COMPOSITION §III.1 vocabulary the slot's docstring already
6513    /// reaches for. Returns `&[Membro]` (not `&Vec<Membro>`) because
6514    /// every downstream consumer of the member list treats it as a
6515    /// read-only sequence — the slice-view is the narrowest borrow
6516    /// that supports every present + roadmapped consumer
6517    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6518    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6519    /// the typed view reaches for (the storage-side `Vec` remains
6520    /// reachable through the `pub membros` field for the mutation-
6521    /// carrying serde round-trip and per-test fixture-mutation paths).
6522    #[must_use]
6523    pub const fn membros(&self) -> &[Membro] {
6524        self.membros.as_slice()
6525    }
6526
6527    /// Substrate-canonical per-`:contratos` `Vec<WitContract>`
6528    /// MESH-COMPOSITION per-Aplicacao WIT-typed-edge-list slice-return
6529    /// accessor every per-Aplicacao contract-list reader keys off —
6530    /// returns the author-declared `:contratos` list verbatim as a
6531    /// `&[WitContract]` slice-view over the same backing buffer the raw
6532    /// `self.contratos.as_slice()` field access borrows from.
6533    ///
6534    /// The `:contratos` slot carries the M3 mesh-slot per-Aplicacao
6535    /// WIT-typed edge list — the load-bearing set of directed edges
6536    /// on the application graph whose nodes are the `:membros` entries
6537    /// (MESH-COMPOSITION §III.1: the graph edges are a set, not a
6538    /// multiset; the `(:de, :para, :wit, :endpoint, :subject, :slot)`
6539    /// six-tuple is the edge identity every downstream duplicate gate
6540    /// keys off). Every per-`:contratos` entry pairs a `:de` source-
6541    /// Servico caller name + a `:para` destination-Servico callee name
6542    /// (through the lifted [`WitContract::source`] +
6543    /// [`WitContract::destination`] (7f0fd43) accessor pair on the
6544    /// caller/callee-Servico axis) with a `:wit` world-reference
6545    /// (through the lifted [`WitContract::world_ref`] (0804823)
6546    /// accessor) and the target-shape-appropriate payload-carrier
6547    /// scalar (through the lifted [`WitContract::endpoint`] (7020470),
6548    /// [`WitContract::subject`] (90de675), or [`WitContract::slot`]
6549    /// (ed22b66) accessor on the per-target-shape payload-carrier
6550    /// axis). Every downstream consumer that fans on the edge-set
6551    /// keys off this slice (the [`AplicacaoSpec::validate`] per-edge
6552    /// name-set / self-edge / target-shape / dedup fan-out loop, the
6553    /// [`AplicacaoSpec::detect_sync_cycles`] per-edge sync-subgraph
6554    /// adjacency-list seed, the [`caixa_mesh::cilium_network_policies`]
6555    /// per-`(:de, :para)` `BTreeMap` group fan-out emitter's per-entry
6556    /// grouping loop, the `feira app graph` per-Aplicacao contract-
6557    /// count print line and per-contract tree traversal, every future
6558    /// wasm-operator (M4) per-Aplicacao CR materializer's per-edge
6559    /// `CiliumNetworkPolicy` fan-out, the future M5 per-edge
6560    /// mesh-policy overlay resolver's per-contract typed-edge weight
6561    /// reader).
6562    ///
6563    /// Prior to this lift the `.contratos` `Vec<WitContract>` was
6564    /// accessed inline at four production sites — the
6565    /// [`AplicacaoSpec::validate`]'s `for c in &self.contratos`
6566    /// per-edge validate-loop traversal head (which drives every
6567    /// per-edge name-set membership lookup, self-edge check,
6568    /// target-shape dispatch, and dedup `HashSet` insert), the
6569    /// [`AplicacaoSpec::detect_sync_cycles`]'s
6570    /// `for c in &self.contratos` adjacency-list seed head (which
6571    /// drives every per-edge sync-vs-pub-sub partition and per-edge
6572    /// adjacency insert), the [`caixa_mesh::cilium_network_policies`]
6573    /// emitter's `for c in &spec.contratos` per-`(:de, :para)`
6574    /// `BTreeMap` grouping loop head (which drives every per-CNP
6575    /// fan-out emit), and the `feira app graph` per-Aplicacao print
6576    /// line's `spec.contratos.len()` count formatter argument paired
6577    /// with the peer `for c in &spec.contratos` per-contract tree
6578    /// traversal — four open-coded field-accesses that expressed no
6579    /// compile-time link back to the typed slot. A future extension
6580    /// of the `:contratos` axis to a richer author surface (a
6581    /// per-cluster contract overlay the operator pins through a
6582    /// future `:contratos-overrides` slot the MESH-COMPOSITION §V
6583    /// federation roadmap acknowledges, a per-tenant edge-policy
6584    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
6585    /// materializer resolves per-CR at admission time, a per-edge
6586    /// weight scalar the future adaptive-placement engine reads to
6587    /// bias sync-subgraph routing, a promotion of the plain
6588    /// `Vec<WitContract>` to a richer `{static, dynamic}` partition
6589    /// once virtual-actor-style dynamic-edge composition comes into
6590    /// typed scope) would have had to be threaded through all four
6591    /// open-coded copies in lockstep or one consumer would silently
6592    /// disagree with the peers on which edge-set a given Aplicacao
6593    /// resolves to — the validator's per-edge dedup `HashSet` seed
6594    /// reading the raw slot while the peer sync-cycle adjacency-list
6595    /// seed read an operator-resolved slot would silently split the
6596    /// build-time edge-set gate from the runtime deadlock-detection
6597    /// gate, a four-consumer split at the validator, the cycle
6598    /// detector, the CNP emitter, and the graph printer far from
6599    /// the source `caixa.lisp` with no field naming the edge-set-
6600    /// drift root cause. Lifting the resolution rule to a typed method on the
6601    /// substrate primitive means every downstream consumer of the
6602    /// Aplicacao's per-`:contratos` edge-list surface reaches for
6603    /// exactly one typed dispatch — the resolver's accept-set
6604    /// migrates as a unit on any future axis addition.
6605    ///
6606    /// Fourth slice-return (`&[T]`) accessor on any M2 or M3 typed
6607    /// slot — sibling to the seed M2 [`crate::SupervisorSpec::children`]
6608    /// (bc92bce) `&[ChildSpec]` accessor on the peer per-`:supervisor`
6609    /// static-child-list `Vec`-carry axis, to the M3
6610    /// [`crate::Placement::clusters`] (a6e18d7) `&[String]` accessor
6611    /// on the peer per-`:placement` distribution-target-list `Vec`-
6612    /// carry axis, and to the immediately-adjacent sibling M3
6613    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` accessor on
6614    /// the peer per-`:membros` node-list `Vec`-carry axis — the
6615    /// per-`:contratos` edge-list accessor is the natural pair of
6616    /// the per-`:membros` node-list accessor (graph edges over graph
6617    /// nodes; every graph-shaped consumer reads both). Same "one
6618    /// typed dispatch on the substrate primitive, thin projections
6619    /// at each consumer" discipline. The last remaining `Vec`-carry
6620    /// axis still unlifted at the time of this lift —
6621    /// [`crate::UpgradeFromEntry::instructions`]
6622    /// (`Vec<UpgradeInstruction>` per-appup migration-instruction
6623    /// list) — inherits this accessor's discipline as future
6624    /// compounding runs migrate its consumers onto the shared slice-
6625    /// return shape. Second `&[T]`-return accessor on the top-level
6626    /// M3 mesh-slot `AplicacaoSpec` type itself, closing the last
6627    /// unlifted per-`AplicacaoSpec` `Vec`-carry axis (`:membros` +
6628    /// `:contratos` are the two `Vec` fields on the outer typed
6629    /// composition view — `:politicas`, `:placement`, `:entrada` are
6630    /// scalar/option-shaped and already route through their per-slot
6631    /// accessor families). Named `contratos()` to match the storage
6632    /// field's name verbatim and the tatara-lisp author-surface term
6633    /// (`:contratos`) the field's own docstring already carries; the
6634    /// accessor's identity maps onto the canonical MESH-COMPOSITION
6635    /// §III.1 vocabulary the slot's docstring already reaches for.
6636    /// Returns `&[WitContract]` (not `&Vec<WitContract>`) because
6637    /// every downstream consumer of the contract list treats it as a
6638    /// read-only sequence — the slice-view is the narrowest borrow
6639    /// that supports every present + roadmapped consumer
6640    /// (`.is_empty()`, `.iter()`, `.len()`) without leaking the
6641    /// backing `Vec`'s grow/push/reserve surface that no consumer of
6642    /// the typed view reaches for (the storage-side `Vec` remains
6643    /// reachable through the `pub contratos` field for the mutation-
6644    /// carrying serde round-trip and per-test fixture-mutation paths).
6645    #[must_use]
6646    pub const fn contratos(&self) -> &[WitContract] {
6647        self.contratos.as_slice()
6648    }
6649
6650    /// Substrate-canonical per-`:politicas` `MeshPolicy` MESH-COMPOSITION
6651    /// per-Aplicacao mesh-policy composite-reference accessor every
6652    /// per-Aplicacao policy-block reader keys off — returns the author-
6653    /// declared `:politicas` composite verbatim as a `&MeshPolicy`
6654    /// reference over the same backing storage the raw `&self.politicas`
6655    /// field access borrows from.
6656    ///
6657    /// The `:politicas` slot carries the M3 mesh-slot per-Aplicacao
6658    /// mesh-policy composite — the load-bearing container of every
6659    /// mesh-level operational-policy axis every downstream mesh-artifact
6660    /// emitter fans on (MESH-COMPOSITION §III.2 #3: the per-Aplicacao
6661    /// mesh-policy overlay is the single typed surface a
6662    /// `CiliumClusterwideEnvoyConfig` per-`:politicas` fan-out reads
6663    /// from). Every per-`:politicas` axis threads through a lifted
6664    /// per-slot accessor on the [`MeshPolicy`] type: the
6665    /// [`MeshPolicy::mtls_required`] (c0110f1) Cilium-mesh mTLS-
6666    /// enforcement-toggle scalar accessor, the [`MeshPolicy::retries`]
6667    /// (bdfb399) Gateway-API-mesh transient-failure-retry-budget scalar
6668    /// accessor, the [`MeshPolicy::timeout`] (7073d0f) Gateway-API-mesh
6669    /// per-call-deadline scalar accessor, the [`MeshPolicy::circuit_breaker`]
6670    /// (b0e741a) Envoy-outlier-detection consecutive-failure-ejection
6671    /// composite accessor, and the [`MeshPolicy::rate_limit`] (21a6c3b)
6672    /// Envoy-local-rate-limit-mesh token-bucket-declaration composite
6673    /// accessor. Every downstream consumer that reaches for a policy
6674    /// axis first passes through this outer accessor onto the composite
6675    /// and then dispatches onto the per-axis accessor — the two-level
6676    /// dispatch means every per-`:politicas` reader now routes through
6677    /// a typed dispatch on the substrate primitive at both altitudes.
6678    ///
6679    /// Prior to this lift the `.politicas` `MeshPolicy` composite was
6680    /// accessed inline at four production sites — the
6681    /// [`AplicacaoSpec::validate_politicas`] entry-side `let p =
6682    /// &self.politicas;` traversal seed (which drives every per-axis
6683    /// zero-floor + upper-cap + canonical-form bracket dispatch through
6684    /// `p.timeout()`, `p.retries()`, `p.circuit_breaker()`,
6685    /// `p.rate_limit()` on the axis-level lifted accessors), the
6686    /// [`caixa_mesh::cilium_network_policies`] per-CNP mTLS-mode-overlay
6687    /// emitter's `spec.politicas.mtls_required()` field-then-accessor
6688    /// chain (which drives every per-`(:de, :para)` CNP
6689    /// authentication-mode overlay onto the emitted `CiliumNetworkPolicy`),
6690    /// and the [`caixa_mesh::gateway_routes`] per-HTTPRoute per-request
6691    /// timeout + retry overlay emitter's paired
6692    /// `spec.politicas.timeout()` + `spec.politicas.retries()` field-then-
6693    /// accessor chain (which drives the per-Aplicacao Gateway-API-mesh
6694    /// deadline + budget overlay onto the emitted `HTTPRoute`) — four
6695    /// open-coded outer-field accesses that expressed no compile-time
6696    /// link back to the typed slot at the [`AplicacaoSpec`] altitude. A
6697    /// future extension of the `:politicas` outer axis to a richer
6698    /// author surface (a per-cluster policy overlay the operator pins
6699    /// through a future `:politicas-overrides` slot the MESH-COMPOSITION
6700    /// §V federation roadmap acknowledges, a per-tenant policy-alias
6701    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6702    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6703    /// policy-composite derivation the future adaptive-placement engine
6704    /// computes from a per-cluster load-topology reader, a promotion of
6705    /// the plain [`MeshPolicy`] to a richer `{static, dynamic}`
6706    /// partition once virtual-actor-style dynamic-mesh-policy
6707    /// composition comes into typed scope) would have had to be threaded
6708    /// through all four open-coded copies in lockstep or one consumer
6709    /// would silently disagree with the peers on which mesh-policy
6710    /// composite a given Aplicacao resolves to — the validator's
6711    /// per-axis bracket-dispatch seed reading the raw slot while the
6712    /// peer CNP mTLS-overlay emitter read an operator-resolved slot
6713    /// would silently split the build-time policy-shape gate from the
6714    /// runtime CNP-emission gate, a four-consumer split at the
6715    /// validator, the CNP emitter, and the `HTTPRoute` emitter far from
6716    /// the source `caixa.lisp` with no field naming the policy-drift
6717    /// root cause. Lifting the resolution rule to a typed method on the
6718    /// substrate primitive means every downstream consumer of the
6719    /// Aplicacao's per-`:politicas` mesh-policy composite surface
6720    /// reaches for exactly one typed dispatch — the resolver's accept-
6721    /// set migrates as a unit on any future axis addition.
6722    ///
6723    /// First `&Composite`-return accessor on the top-level M3 mesh-slot
6724    /// `AplicacaoSpec` type itself — sibling to the seed slice-return
6725    /// accessors [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6726    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that
6727    /// close the two `Vec`-carry axes on the outer typed composition
6728    /// view; the outer `:politicas` composite-reference axis is the
6729    /// natural pair to the paired outer `Vec`-carry accessors on the
6730    /// two peer M3 mesh slots — every whole-Aplicacao mesh-artifact
6731    /// emitter reads all four axes as one unit (graph nodes + graph
6732    /// edges + mesh policy + placement pool). Peer to the same
6733    /// [`crate::SupervisorSpec`] altitude on the sibling M2 supervisor-
6734    /// slot: every M2 `SupervisorSpec`-scoped composite reader
6735    /// ([`crate::SupervisorSpec::estrategia`], `max_restarts`,
6736    /// `restart_window`, `children`) already routes through the M2
6737    /// `SupervisorSpec` accessor family — this lift extends the same
6738    /// "one typed dispatch on the substrate primitive at the outer
6739    /// composition altitude" discipline to the M3 mesh-slot
6740    /// `AplicacaoSpec`-scoped `:politicas` composite axis. The two
6741    /// remaining peer outer-composite axes still unlifted at the time
6742    /// of this lift — [`AplicacaoSpec::placement`] (`Placement`
6743    /// per-Aplicacao distribution-composite) and [`AplicacaoSpec::entrada`]
6744    /// (`Option<Entrada>` per-Aplicacao external-gateway composite) —
6745    /// inherit this accessor's discipline as future compounding runs
6746    /// migrate their consumers onto the shared reference-return shape.
6747    /// Named `politicas()` to match the storage field's name verbatim
6748    /// and the tatara-lisp author-surface term (`:politicas`) the
6749    /// field's own docstring already carries; the accessor's identity
6750    /// maps onto the canonical MESH-COMPOSITION §III.2 vocabulary the
6751    /// slot's docstring already reaches for. Returns `&MeshPolicy`
6752    /// (not the owning composite by copy or clone) because every
6753    /// downstream consumer of the mesh-policy composite treats it as a
6754    /// read-only per-axis dispatch source — the reference-view is the
6755    /// narrowest borrow that supports every present + roadmapped
6756    /// consumer (per-axis accessor dispatch, [`MeshPolicy::is_empty`]
6757    /// emptiness probe) without cloning the composite through every
6758    /// consumer's fast path.
6759    #[must_use]
6760    pub const fn politicas(&self) -> &MeshPolicy {
6761        &self.politicas
6762    }
6763
6764    /// Substrate-canonical per-`:placement` `Placement` MESH-COMPOSITION
6765    /// per-Aplicacao distribution-composite composite-reference accessor
6766    /// every per-Aplicacao placement-block reader keys off — returns the
6767    /// author-declared `:placement` composite verbatim as a `&Placement`
6768    /// reference over the same backing storage the raw `&self.placement`
6769    /// field access borrows from.
6770    ///
6771    /// The `:placement` slot carries the M3 mesh-slot per-Aplicacao
6772    /// distribution composite — the load-bearing container of every
6773    /// where-does-this-Aplicacao-run axis every downstream cluster-artifact
6774    /// emitter fans on (MESH-COMPOSITION §II.1 for the `SingleNode` /
6775    /// `Replicated` Erlang/OTP distributed-app takeover axes, §II.4 for the
6776    /// `Sharded` Akka-cluster-sharding axis, §III.1 for the `:clusters`
6777    /// hosting-pool identity, §V for the `M3-Adaptive`-compression
6778    /// `:affinity` hint). Every per-`:placement` axis threads through a
6779    /// lifted per-slot accessor on the [`Placement`] type: the
6780    /// [`Placement::estrategia`] (921fe1b) MESH-COMPOSITION distribution-
6781    /// strategy scalar accessor, the [`Placement::clusters`] (a6e18d7)
6782    /// per-cluster distribution-target slice-return accessor, the
6783    /// [`Placement::affinity`] (74ec2d3) M3-Adaptive-compression-hint
6784    /// optional-scalar accessor, and the [`Placement::shard_key`]
6785    /// (7cd2a28) Akka-cluster-sharding-key optional-scalar accessor. Every
6786    /// downstream consumer that reaches for a placement axis first passes
6787    /// through this outer accessor onto the composite and then dispatches
6788    /// onto the per-axis accessor — the two-level dispatch means every
6789    /// per-`:placement` reader now routes through a typed dispatch on the
6790    /// substrate primitive at both altitudes.
6791    ///
6792    /// Prior to this lift the `.placement` `Placement` composite was
6793    /// accessed inline at three production sites — the
6794    /// [`AplicacaoSpec::validate_placement`] per-axis bracket-dispatch
6795    /// seed (six `self.placement.<axis>()` field-then-inner-accessor
6796    /// chains: the pre-flight `.clusters().is_empty()` refusal probe
6797    /// paired with the `.estrategia()` diagnostic-carry copy, the per-
6798    /// cluster `.clusters()` validate-loop traversal head, the per-
6799    /// hint `.affinity()` optional-scalar shape gate, and the `Sharded` ↔
6800    /// non-`Sharded` partition's `.estrategia()` match arm scrutinee
6801    /// paired with the shape-gate cascade's `.shard_key()` /
6802    /// `.estrategia()` diagnostic-carry pair), the
6803    /// [`caixa_mesh::programs_for_aplicacao`] per-Aplicacao programs.yaml
6804    /// per-entry placement-block emitter's outer
6805    /// `serde_yaml::to_value(&spec.placement)` composite-serialization
6806    /// seed (which fans onto every per-cluster `programs[]` entry as a
6807    /// self-describing distribution overlay the aggregator filters by),
6808    /// and the `feira app graph` per-Aplicacao print line's paired
6809    /// `spec.placement.estrategia()` + `spec.placement.clusters()` field-
6810    /// then-inner-accessor chains (which drive the human-readable
6811    /// distribution summary of the typed Aplicacao view) — three open-
6812    /// coded outer-field accesses that expressed no compile-time link
6813    /// back to the typed slot at the [`AplicacaoSpec`] altitude. A future
6814    /// extension of the `:placement` outer axis to a richer author surface
6815    /// (a per-cluster placement overlay the operator pins through a
6816    /// future `:placement-overrides` slot the MESH-COMPOSITION §V
6817    /// federation roadmap acknowledges, a per-tenant placement-alias
6818    /// table the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer
6819    /// resolves per-CR at admission time, a per-Aplicacao dynamic
6820    /// placement-composite derivation the future M5 adaptive-placement
6821    /// engine computes from a per-cluster load-topology reader, a
6822    /// promotion of the plain [`Placement`] to a richer `{static, dynamic}`
6823    /// partition once Orleans-style virtual-actor dynamic-placement comes
6824    /// into typed scope) would have had to be threaded through all three
6825    /// open-coded copies in lockstep or one consumer would silently
6826    /// disagree with the peers on which placement composite a given
6827    /// Aplicacao resolves to — the validator's per-axis bracket-dispatch
6828    /// seed reading the raw slot while the peer
6829    /// `programs_for_aplicacao` emitter read an operator-resolved slot
6830    /// would silently split the build-time distribution-shape gate from
6831    /// the runtime programs.yaml distribution-annotation gate, a three-
6832    /// consumer split at the validator, the programs.yaml emitter, and
6833    /// the `feira app graph` printer far from the source `caixa.lisp`
6834    /// with no field naming the placement-drift root cause. Lifting the
6835    /// resolution rule to a typed method on the substrate primitive
6836    /// means every downstream consumer of the Aplicacao's per-
6837    /// `:placement` distribution composite surface reaches for exactly
6838    /// one typed dispatch — the resolver's accept-set migrates as a unit
6839    /// on any future axis addition.
6840    ///
6841    /// Second `&Composite`-return accessor on the top-level M3 mesh-slot
6842    /// `AplicacaoSpec` type itself — sibling to the seed
6843    /// [`AplicacaoSpec::politicas`] (534dc21) `&MeshPolicy` mesh-policy
6844    /// composite-reference accessor on the peer per-`:politicas` outer-
6845    /// composite axis, and to the paired slice-return accessors
6846    /// [`AplicacaoSpec::membros`] (6c77e36) `&[Membro]` and
6847    /// [`AplicacaoSpec::contratos`] (0dcc926) `&[WitContract]` that close
6848    /// the two `Vec`-carry axes on the outer typed composition view; the
6849    /// outer `:placement` composite-reference axis is the natural pair
6850    /// to the peer `:politicas` composite-reference axis on the two
6851    /// operationally-symmetric M3 mesh slots (`:politicas` carries the
6852    /// how-to-run policy overlay, `:placement` carries the where-to-run
6853    /// distribution composite — every whole-Aplicacao mesh-artifact
6854    /// emitter reads both as one unit). Same "one typed dispatch on the
6855    /// substrate primitive, thin projections at each consumer"
6856    /// discipline the peer per-`:politicas` composite-reference axis
6857    /// already routes through. The one remaining outer-composite axis
6858    /// still unlifted at the time of this lift —
6859    /// [`AplicacaoSpec::entrada`] (`Option<Entrada>` per-Aplicacao
6860    /// external-gateway composite) — inherits this accessor's discipline
6861    /// as the next compounding run migrates its consumers onto the shared
6862    /// reference-return shape, closing the outer-composite altitude on
6863    /// every M3 mesh-slot axis. Named `placement()` to match the storage
6864    /// field's name verbatim and the tatara-lisp author-surface term
6865    /// (`:placement`) the field's own docstring already carries; the
6866    /// accessor's identity maps onto the canonical MESH-COMPOSITION §II
6867    /// vocabulary the slot's docstring already reaches for. Returns
6868    /// `&Placement` (not the owning composite by copy or clone) because
6869    /// every downstream consumer of the placement composite treats it as
6870    /// a read-only per-axis dispatch source — the reference-view is the
6871    /// narrowest borrow that supports every present + roadmapped consumer
6872    /// (per-axis accessor dispatch, serde composite-serialization) without
6873    /// cloning the composite through every consumer's fast path.
6874    #[must_use]
6875    pub const fn placement(&self) -> &Placement {
6876        &self.placement
6877    }
6878
6879    /// Substrate-canonical per-`:entrada` `Entrada` MESH-COMPOSITION
6880    /// per-Aplicacao external-gateway composite optional-composite-
6881    /// reference accessor every per-Aplicacao gateway-block reader
6882    /// keys off — returns the author-declared `:entrada` composite
6883    /// verbatim as an `Option<&Entrada>` reference over the same
6884    /// backing storage the raw `self.entrada.as_ref()` field access
6885    /// borrows from, with `None` naming the internal-only mesh shape
6886    /// (the author-omitted `:entrada` slot the K8s Gateway API v1
6887    /// gateway_routes emitter treats as "emit nothing" and the peer
6888    /// `feira app graph` printer treats as "internal-only mesh").
6889    ///
6890    /// The `:entrada` slot carries the M3 mesh-slot per-Aplicacao
6891    /// external-gateway composite — the load-bearing container of
6892    /// every does-this-Aplicacao-expose-a-public-endpoint axis every
6893    /// downstream cluster-artifact emitter fans on (MESH-COMPOSITION
6894    /// §III.4 for the `:host` K8s Gateway API v1 apiserver-validated
6895    /// hostname axis, §III.4 for the `:para` destination-Servico
6896    /// axis, §III.4 for the `:paths` HTTPRoute path-list axis, §III.4
6897    /// for the `:port` L4 backendRefs port axis). Every per-`:entrada`
6898    /// axis threads through a lifted per-slot accessor on the
6899    /// [`Entrada`] type: the [`Entrada::hostname`] (6db982c) K8s
6900    /// Gateway-API `Listener.hostname` scalar accessor, the paired
6901    /// [`Entrada::hostnames`] (`&HTTPRoute.spec.hostnames`)
6902    /// singleton-list resolver, the [`Entrada::destination`] (821a80e)
6903    /// backendRefs destination-Servico scalar accessor, the
6904    /// [`Entrada::resolved_paths`] path-fallback resolver, and the
6905    /// [`Entrada::port`] (9f9becd) Gateway-API-mesh L4 listener-port
6906    /// scalar accessor. Every downstream consumer that reaches for
6907    /// an entrada axis first passes through this outer accessor onto
6908    /// the composite and then dispatches onto the per-axis accessor
6909    /// — the two-level dispatch means every per-`:entrada` reader
6910    /// now routes through a typed dispatch on the substrate primitive
6911    /// at both altitudes.
6912    ///
6913    /// Prior to this lift the `.entrada` `Option<Entrada>` composite
6914    /// was accessed inline at four production sites — the
6915    /// [`AplicacaoSpec::validate`] per-`:entrada` shape-and-membership
6916    /// gate's `if let Some(e) = &self.entrada { … }` traversal head
6917    /// (which drives every per-axis refusal on the composite: the
6918    /// `validate_entrada_para` DNS-1123 shape gate on `e.para`, the
6919    /// `EntradaMemberMissing` membership lookup against the
6920    /// `:membros` accept-set, the `EmptyEntradaHost` refusal, the
6921    /// `validate_entrada_host` K8s Gateway API v1 apiserver-shape
6922    /// gate on `e.host`, and the `validate_entrada_path` HTTPRoute
6923    /// per-path shape gate on each entry of `e.paths`), the
6924    /// [`AplicacaoSpec::port_for_destination`] per-Aplicacao L4-port
6925    /// fallback resolver's `self.entrada.as_ref().filter(…).map_or(…)`
6926    /// composite-projection seed (which drives the destination-
6927    /// facing `Entrada::port` lookup every per-Aplicacao HTTPRoute
6928    /// backendRefs port emitter fans on), the
6929    /// [`caixa_mesh::gateway_routes`] per-Aplicacao K8s Gateway API
6930    /// v1 Gateway + HTTPRoute emitter's `spec.entrada.as_ref()`
6931    /// early-return seed (which drives the "no `:entrada` ⇒ no
6932    /// external artifacts" partition on the whole-Aplicacao Gateway-
6933    /// API emitter's fan-out), and the `feira app graph` per-
6934    /// Aplicacao print line's `if let Some(e) = &spec.entrada`
6935    /// external-gateway summary emitter (which drives the human-
6936    /// readable `entrada: host → para (paths=…, port=…)` /
6937    /// `entrada: (internal-only mesh)` partition on the typed
6938    /// Aplicacao view) — four open-coded outer-field accesses that
6939    /// expressed no compile-time link back to the typed slot at the
6940    /// [`AplicacaoSpec`] altitude. A future extension of the
6941    /// `:entrada` outer axis to a richer author surface (a
6942    /// multi-`:entrada` list the M4 CR materializer resolves per-CR
6943    /// at admission time so an Aplicacao can expose a public-web +
6944    /// admin-web pair, a per-cluster `:entrada-overrides` slot the
6945    /// MESH-COMPOSITION §V federation roadmap acknowledges so an
6946    /// operator can pin a per-cluster hostname override without
6947    /// re-authoring the `caixa.lisp`, a promotion of the plain
6948    /// `Option<Entrada>` to a richer `{single, multi}` partition once
6949    /// the multi-`:entrada` roadmap lands) would have had to be
6950    /// threaded through all four open-coded copies in lockstep or one
6951    /// consumer would silently disagree with the peers on which
6952    /// entrada composite a given Aplicacao resolves to — the
6953    /// validator's per-axis bracket-dispatch seed reading the raw
6954    /// slot while the peer `gateway_routes` emitter read an
6955    /// operator-resolved slot would silently split the build-time
6956    /// gateway-shape gate from the runtime Gateway + HTTPRoute
6957    /// emission gate, a four-consumer split at the validator, the
6958    /// `port_for_destination` L4-port resolver, the `gateway_routes`
6959    /// emitter, and the `feira app graph` printer far from the
6960    /// source `caixa.lisp` with no field naming the entrada-drift
6961    /// root cause. Lifting the resolution rule to a typed method on
6962    /// the substrate primitive means every downstream consumer of
6963    /// the Aplicacao's per-`:entrada` external-gateway composite
6964    /// surface reaches for exactly one typed dispatch — the
6965    /// resolver's accept-set migrates as a unit on any future axis
6966    /// addition.
6967    ///
6968    /// Third and final `&Composite`-return accessor on the top-level
6969    /// M3 mesh-slot `AplicacaoSpec` type itself — closes the last
6970    /// unlifted outer-composite axis on the outer typed composition
6971    /// view, sibling to the seed [`AplicacaoSpec::politicas`]
6972    /// (534dc21) `&MeshPolicy` mesh-policy composite-reference
6973    /// accessor on the per-`:politicas` outer-composite axis and to
6974    /// the [`AplicacaoSpec::placement`] (9abb8f0) `&Placement`
6975    /// distribution-composite composite-reference accessor on the
6976    /// per-`:placement` outer-composite axis; extends the outer-
6977    /// composite reference-return discipline the two peers already
6978    /// route through onto the last unlifted per-`AplicacaoSpec`
6979    /// outer-composite axis. The `:entrada` outer-composite axis is
6980    /// the natural pair to the two peer outer-composite axes on the
6981    /// three operationally-symmetric M3 mesh-slot outer composites
6982    /// (`:politicas` carries the how-to-run policy overlay,
6983    /// `:placement` carries the where-to-run distribution composite,
6984    /// `:entrada` carries the who-can-reach-it external-gateway
6985    /// composite — every whole-Aplicacao mesh-artifact emitter reads
6986    /// all three as one unit). Same "one typed dispatch on the
6987    /// substrate primitive, thin projections at each consumer"
6988    /// discipline the peer outer-composite axes already route through.
6989    /// Named `entrada()` to match the storage field's name verbatim
6990    /// and the tatara-lisp author-surface term (`:entrada`) the
6991    /// field's own docstring already carries; the accessor's
6992    /// identity maps onto the canonical MESH-COMPOSITION §III.4
6993    /// vocabulary the slot's docstring already reaches for. Returns
6994    /// `Option<&Entrada>` (not the owning composite by copy or
6995    /// clone) because every downstream consumer of the entrada
6996    /// composite treats it as a read-only per-axis dispatch source
6997    /// — the reference-view is the narrowest borrow that supports
6998    /// every present + roadmapped consumer (per-axis accessor
6999    /// dispatch, `.as_ref().filter(…).map_or(…)` per-destination
7000    /// port-fallback projection, early-return partition on the
7001    /// `None` arm) without cloning the composite through every
7002    /// consumer's fast path. The `Option` half of the return-type
7003    /// preserves the load-bearing "author-omitted `:entrada` ⇒
7004    /// internal-only mesh" partition (not a default composite the
7005    /// downstream must reject on emptiness) — the accessor projects
7006    /// the raw `Option<Entrada>` slot's presence bit through the
7007    /// reference-return unchanged.
7008    #[must_use]
7009    pub const fn entrada(&self) -> Option<&Entrada> {
7010        self.entrada.as_ref()
7011    }
7012
7013    /// Validate the typed shape:
7014    ///   - `:membros` is non-empty; every entry has a non-empty `:caixa`
7015    ///     and a non-empty `:versao`; no two entries share the same
7016    ///     `:caixa` (MESH-COMPOSITION §III.1 — the graph nodes are a set,
7017    ///     not a multiset)
7018    ///   - every `:contratos` :de + :para must be in `:membros`
7019    ///   - no `:contratos` edge is a self-edge (`:de == :para`) — a
7020    ///     contract is an inter-Servico edge, so a Servico contracting
7021    ///     with itself is a build error under every WIT shape
7022    ///     (MESH-COMPOSITION §III.1)
7023    ///   - no two `:contratos` entries agree on
7024    ///     `(de, para, wit, endpoint, subject, slot)` — the typed-graph
7025    ///     edges are a set, not a multiset (peer of the `:membros` /
7026    ///     `:placement :clusters` / `:entrada :paths` duplicate gates)
7027    ///   - `:entrada :para` must be in `:membros`
7028    ///   - `:placement Sharded` must declare `:shard-key` (non-empty);
7029    ///     `:placement Replicated`/`SingleNode` must NOT declare
7030    ///     `:shard-key` — only the hash-keyed Akka-cluster-sharding axis
7031    ///     consumes it (MESH-COMPOSITION §II.4), and the typed partition
7032    ///     between strategy and shard-key is symmetric: every validated
7033    ///     `Placement` has `shard_key.is_some()` iff `estrategia ==
7034    ///     Sharded`
7035    ///   - every `:placement` strategy must declare ≥1 `:clusters` entry —
7036    ///     `Replicated`/`SingleNode` need hosting clusters, `Sharded` needs
7037    ///     the shard pool (MESH-COMPOSITION §III.1)
7038    ///   - every `:clusters` entry is non-empty and unique
7039    ///   - `:placement :affinity`, when set, is non-empty
7040    ///   - the synchronous-`:contratos` subgraph is acyclic
7041    ///     (MESH-COMPOSITION §III.3)
7042    ///   - every declared `:politicas` value is operationally meaningful
7043    ///     (zero timeout, zero retries, zero breaker thresholds, zero rate
7044    ///     limit are all build errors — MESH-COMPOSITION §V CSE invariants;
7045    ///     omit the field instead to express "no policy on this axis")
7046    pub fn validate(&self) -> Result<(), AplicacaoError> {
7047        self.validate_membros()?;
7048        let names: std::collections::HashSet<&str> =
7049            self.membros().iter().map(Membro::nome).collect();
7050
7051        // Identity key for the typed-edge duplicate gate below: every
7052        // field that distinguishes one contract from another. Two
7053        // entries that agree on all six are *the same edge declared
7054        // twice*, the typed-graph analogue of duplicate `:membros` /
7055        // `:placement :clusters` / `:entrada :paths` entries (which
7056        // are already build errors at this layer). Rejecting it at the
7057        // validate gate closes a renderer-side footgun: caixa-mesh's
7058        // `cilium_network_policies` keys each emitted policy by
7059        // `<aplicacao>-<de>-to-<para>`, so two contracts with identical
7060        // (de, para) and identical payload would land as two K8s
7061        // objects with colliding `metadata.name`, rejected at apply
7062        // time far from the source caixa.lisp.
7063        let mut seen_contracts: std::collections::HashSet<ContratoIdentity<'_>> =
7064            std::collections::HashSet::new();
7065        for c in self.contratos() {
7066            // Per-axis value-shape gate on every `:contratos` name
7067            // reference, before any graph-membership lookup. Empty +
7068            // DNS-1123-malformed `:de`/`:para` values silently fell
7069            // through to `ContratoMemberMissing` at the lookup arm
7070            // because every `:membros :caixa` is shape-validated
7071            // (3f9d7a0), so the `names` set structurally cannot contain
7072            // an empty / malformed string and the membership-lookup
7073            // diagnostic always misframed the root cause as
7074            // "this caixa is not in `:membros`". The shape gate runs
7075            // ahead of the lookup so structurally-impossible-to-match
7076            // inputs route through the narrower self-locating
7077            // diagnostic, preserving the legitimate "well-shaped
7078            // phantom reference" arm. `:de` runs before `:para` per
7079            // the canonical edge-direction order the existing
7080            // membership lookup, self-edge check, target dispatch,
7081            // and diagnostic strings already use.
7082            // Route the per-`:contratos` per-arm DNS-1123 shape-gate arg
7083            // + the paired [`AplicacaoError::ContratoMemberMissing`]
7084            // diagnostic's `caixa:` carrier through the lifted
7085            // [`WitContract::source`] / [`WitContract::destination`]
7086            // scalar accessors rather than the raw `&c.de` / `&c.para`
7087            // `&String`-borrow arg site + the raw `c.de.clone()` /
7088            // `c.para.clone()` field-access `String`-carry sites — the
7089            // last unlifted per-`:contratos` raw-field-access sites in
7090            // the M3 mesh-slot validator's per-edge per-arm shape-gate
7091            // arg + phantom-name diagnostic wrap-envelope emit surface.
7092            // `c.source()` is byte-identical to `&c.de` (pinned by the
7093            // sibling `wit_contract_source_returns_de_byte_equal_across_permutations`
7094            // + `wit_contract_source_borrows_from_de_storage` accessor
7095            // tests) and `c.destination()` is byte-identical to `&c.para`
7096            // (pinned by the sibling
7097            // `wit_contract_destination_returns_para_byte_equal_across_permutations`
7098            // + `wit_contract_destination_borrows_from_para_storage`
7099            // accessor tests) — so a future rebrand of either underlying
7100            // storage flows through the accessor's one body without a
7101            // coordinated per-consumer rewrite across the M3 mesh
7102            // validator's per-edge shape-gate + phantom-name refusal
7103            // arms. Peer of the sibling per-`:contratos` self-loop
7104            // arm's `.source().to_string()` / `.world_ref().to_string()`
7105            // `String`-carry sites the earlier convergence lifted onto
7106            // the same accessor pair.
7107            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_DE, c.source())?;
7108            validate_contrato_caixa(crate::render::CONTRATO_AUTHOR_KEY_PARA, c.destination())?;
7109            if !names.contains(c.source()) {
7110                return Err(AplicacaoError::ContratoMemberMissing {
7111                    caixa: c.source().to_string(),
7112                });
7113            }
7114            if !names.contains(c.destination()) {
7115                return Err(AplicacaoError::ContratoMemberMissing {
7116                    caixa: c.destination().to_string(),
7117                });
7118            }
7119            // A `:contratos` entry is an *inter*-Servico contract
7120            // (MESH-COMPOSITION §III.1 — "Servico A calls Servico B"): a
7121            // typed edge between two distinct graph nodes. An edge whose
7122            // `:de` equals its `:para` is a Servico contracting with
7123            // itself — a degenerate edge under every WIT shape. The
7124            // synchronous shapes were caught only incidentally, and with
7125            // a misleading diagnostic: `detect_sync_cycles` reported
7126            // `cart → cart` as a `ContratoCycle` whose path is
7127            // `["cart", "cart"]` — framing a self-edge as a multi-node
7128            // deadlock. The pub-sub shape slipped through entirely
7129            // (`detect_sync_cycles` excludes `WitTarget::PubSub`, so a
7130            // `nats:pub-sub` edge from a member to itself silently
7131            // validated, then rendered a `CiliumNetworkPolicy` whose
7132            // endpointSelector and fromEndpoints both name the same
7133            // program — a self-allow rule that is a no-op, since
7134            // intra-pod traffic never traverses the mesh). A self-edge's
7135            // runtime meaning is an in-process call, which doesn't go
7136            // through the mesh at all, so no `:contratos` edge can carry
7137            // it. Firing the gate before the `:wit`/`target()` shape
7138            // checks means the structural "this edge can't exist" error
7139            // precedes the narrower payload-shape diagnostics, and shape-
7140            // agnostically covers all four `WitTarget` arms (HTTP / Store
7141            // / Capability / PubSub) at one point — closing the pub-sub
7142            // hole and replacing the misleading cycle diagnostic in one
7143            // gate. Peer of the duplicate-`:contratos` / duplicate-
7144            // `:membros` set gates: both reject a structurally
7145            // ill-formed graph at the typed surface, before the renderer
7146            // emits a K8s object that fails or no-ops far from the source
7147            // caixa.lisp.
7148            // Route the per-`:contratos` structural self-edge probe
7149            // through the lifted [`WitContract::is_self_loop`] typed
7150            // predicate rather than the raw `c.de == c.para` field-
7151            // equality check — the one production consumer of the per-
7152            // `:contratos` caller-equals-callee endpoint-equality axis
7153            // now keys off exactly one typed dispatch on the substrate
7154            // primitive, so any future rebrand of the axis (an M4-typed-
7155            // caller enum whose identity comparison rule the predicate
7156            // could route through, a per-cluster caller/callee-alias
7157            // table the M4 CR materializer resolves per-CR before the
7158            // equality probe) migrates as a single caixa-core edit
7159            // rather than a coordinated rewrite of the gate + every
7160            // downstream self-edge consumer. Peer of the sibling
7161            // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
7162            // [`WitContract::is_store`] shape-predicate routing on the
7163            // `:wit` world-ref axis, extended onto the per-edge
7164            // endpoint-equality axis.
7165            //
7166            // Route the paired [`AplicacaoError::ContratoSelfLoop`]
7167            // diagnostic's `caixa:` / `wit:` carriers through the
7168            // lifted [`WitContract::source`] / [`WitContract::world_ref`]
7169            // scalar accessors rather than the raw `c.de.clone()` /
7170            // `c.wit.clone()` field-access `String`-carry sites — the
7171            // last unlifted per-`:contratos` raw-field-access
7172            // `.clone()` sites in the M3 mesh-slot validator's self-
7173            // edge refusal arm. `.source().to_string()` is byte-
7174            // identical to `.de.clone()` (pinned by the sibling
7175            // `source_returns_de_byte_equal_across_permutations` accessor
7176            // test), and `.world_ref().to_string()` is byte-identical
7177            // to `.wit.clone()` (pinned by the sibling
7178            // `world_ref_returns_wit_byte_equal_across_permutations`
7179            // accessor test) — so a future rebrand of either underlying
7180            // storage flows through the accessor's one body without a
7181            // coordinated per-consumer rewrite across the M3 mesh
7182            // validator.
7183            if c.is_self_loop() {
7184                return Err(AplicacaoError::ContratoSelfLoop {
7185                    caixa: c.source().to_string(),
7186                    wit: c.world_ref().to_string(),
7187                });
7188            }
7189            if c.world_ref().is_empty() {
7190                let (de, para) = c.edge_pair();
7191                return Err(AplicacaoError::EmptyWit { de, para });
7192            }
7193            // Shape ↔ target consistency — surfaces "HTTP wit without
7194            // :endpoint", "NATS wit with :endpoint set", etc. as named
7195            // build errors instead of silent renderer drops. Threaded
7196            // through the duplicate-edge diagnostic below (via
7197            // [`WitTarget::label`]) so the "which typed target arm did
7198            // the duplicate carry" question is answered by the typed
7199            // enum's variant discriminator, not by re-probing the raw
7200            // `Option<String>` payload fields.
7201            let target_view = c.target()?;
7202            // Contract identity: (de, para, wit, endpoint, subject, slot).
7203            // Two contracts that match on all six are the same typed edge
7204            // declared twice — author error, not a legitimate variant of
7205            // "same caller-callee pair, different payload" (e.g.
7206            // cart→catalog at /products vs /search), which keeps distinct
7207            // identity keys via the differing endpoint payloads.
7208            //
7209            // Route the six-axis dedup key through the lifted
7210            // [`WitContract::identity`] composite-projection accessor
7211            // rather than the inline six-tuple builder — the two
7212            // substrate primitives on the per-`:contratos` identity axis
7213            // (the [`ContratoIdentity`] type alias's six axes, this
7214            // dedup-key's six tuple arms) now migrate as a unit on any
7215            // future axis addition. Peer of the sibling per-`:contratos`
7216            // composite-projection [`WitContract::edge_pair`] /
7217            // [`WitContract::edge_triple`] accessors on the
7218            // caller-callee / caller-callee-wit prefix axes; extends
7219            // the discipline onto the full-identity axis that carries
7220            // the three payload-shape arms too.
7221            let key = c.identity();
7222            crate::render::insert_first_seen(&mut seen_contracts, key, || {
7223                // Route the per-`:contratos` duplicate-gate diagnostic's
7224                // `(de, para, wit)` triple through the lifted
7225                // [`WitContract::edge_triple`] typed accessor rather
7226                // than pairing `edge_pair()` for the `(de, para)` prefix
7227                // with a raw `c.wit.clone()` for the `wit:` tail — the
7228                // paired-with-raw-field-access shape was the last
7229                // per-`:contratos` diagnostic constructor bypassing the
7230                // substrate-primitive composite projection, sibling to
7231                // the eight [`AplicacaoError::Contrato*`] triple-
7232                // carrying constructors [`WitContract::target`]'s edge
7233                // closure feeds through the same accessor.
7234                let (de, para, wit) = c.edge_triple();
7235                AplicacaoError::ContratoDuplicate {
7236                    de,
7237                    para,
7238                    wit,
7239                    target: target_view.label(),
7240                }
7241            })?;
7242        }
7243
7244        // Cycles in the synchronous-edge subgraph are build errors
7245        // (MESH-COMPOSITION §III.3). Pub-sub edges are excluded — they
7246        // are "acyclic by construction" because the publisher fires
7247        // and forgets, so no caller blocks on a downstream that loops
7248        // back to it.
7249        self.detect_sync_cycles()?;
7250
7251        if let Some(e) = self.entrada() {
7252            // Route the per-`:entrada` composite-reference read
7253            // through the lifted [`AplicacaoSpec::entrada`] accessor
7254            // rather than the raw `&self.entrada` field access — the
7255            // shape-and-membership gate's traversal head is now the
7256            // canonical read-side surface every per-Aplicacao entrada
7257            // consumer routes through, closing the fourth of four
7258            // open-coded outer-field accesses on the per-`:entrada`
7259            // outer-composite axis.
7260            //
7261            // Shape gate on `:entrada :para` runs ahead of the
7262            // membership lookup. Every `:membros :caixa` past
7263            // `validate_membro_caixa` is a valid DNS-1123 label
7264            // (3f9d7a0), so the `names` set structurally cannot
7265            // contain an empty / malformed string and the membership-
7266            // lookup diagnostic always misframed the root cause as
7267            // "this caixa is not in `:membros`". The shape gate
7268            // routes structurally-impossible-to-match inputs through
7269            // the narrower self-locating diagnostic, preserving the
7270            // legitimate "well-shaped phantom reference" arm — the
7271            // same trajectory the peer `:membros :caixa` (3f9d7a0),
7272            // `:placement :clusters` (6c8c00b), and `:contratos :de`
7273            // / `:para` (8d5af6b) axes already follow. This closes
7274            // the fourth and last Aplicacao-level Servico-name
7275            // reference axis on the canonical DNS-1123 floor.
7276            // Route the per-`:entrada :para` byte-string reads through
7277            // the lifted [`Entrada::destination`] accessor rather than
7278            // the raw `e.para` field access — the three
7279            // per-`AplicacaoSpec::validate` `:entrada :para` consumers
7280            // (shape-gate `validate_entrada_para` arg, membership
7281            // lookup, `EntradaMemberMissing` diagnostic carry) now key
7282            // off exactly one typed dispatch on the substrate
7283            // primitive, closing the last unlifted per-`:entrada :para`
7284            // raw-field-access axis on the M3 mesh-slot validator.
7285            // The `.destination().to_string()` at the diagnostic site
7286            // is byte-identical to `.para.clone()` — pinned by the
7287            // sibling `destination_returns_entrada_para_byte_equal` +
7288            // `destination_borrows_from_entrada_para_storage` accessor
7289            // tests — so a future rebrand of the underlying `:para`
7290            // storage (a lift from `String` to a typed
7291            // `ServicoName(String)` newtype, a per-Aplicacao interning
7292            // arena the M4 CR materializer authors, a
7293            // `smol_str::SmolStr` inline-buffer swap) flows through
7294            // the accessor's one body without a coordinated
7295            // per-consumer rewrite across the M3 mesh validator.
7296            validate_entrada_para(e.destination())?;
7297            if !names.contains(e.destination()) {
7298                return Err(AplicacaoError::EntradaMemberMissing {
7299                    para: e.destination().to_string(),
7300                });
7301            }
7302            // Route the per-`:entrada :host` byte-string reads through
7303            // the lifted [`Entrada::hostname`] accessor rather than
7304            // the raw `e.host` field access — the emptiness gate and
7305            // the shape-gate `validate_entrada_host` arg now key off
7306            // exactly one typed dispatch on the substrate primitive,
7307            // closing the last unlifted per-`:entrada :host` raw-
7308            // field-access axis on the M3 mesh-slot validator. Peer
7309            // of the sibling per-`:entrada :para` convergence above
7310            // and pinned by the existing
7311            // `hostname_returns_entrada_host_byte_equal` +
7312            // `hostnames_returns_singleton_of_hostname_accessor`
7313            // accessor tests, so any future
7314            // Gateway-API-shaped host renormalization (a wildcard-
7315            // label lift, a trailing-`.` FQDN substitution, an IDNA
7316            // Punycode round-trip the SNI fan-out overlay authors)
7317            // flows through the accessor's one body without a
7318            // coordinated per-consumer rewrite across the M3 mesh
7319            // validator.
7320            if e.hostname().is_empty() {
7321                return Err(AplicacaoError::EmptyEntradaHost);
7322            }
7323            // The `:host` lands verbatim as a K8s Gateway API v1
7324            // `Listener.hostname` *and* `HTTPRoute.spec.hostnames[0]` —
7325            // both apiserver-validated against the same restrictive
7326            // pattern: lowercase RFC 1123 DNS subdomain, optional
7327            // single leading wildcard label (`*.`), max length 253,
7328            // per-label max length 63, no IP literals, no scheme,
7329            // no port. Until this gate landed `validate()` only
7330            // refused the empty string (`EmptyEntradaHost`); a
7331            // structurally invalid hostname (`"https://example.com"`,
7332            // `"checkout.quero.cloud:8080"`, `"1.2.3.4"`,
7333            // `"_underscored.example.com"`, `"FOO.example.com"`,
7334            // `"checkout.quero.cloud."`) silently passed validate
7335            // and the apiserver `field is invalid` error surfaced at
7336            // `kubectl apply` time, far from the source caixa.lisp.
7337            // Lifting the gate to caixa-build time mirrors the
7338            // `:entrada :paths` value-shape trajectory (eb3456d) and
7339            // closes the last unstructured `:entrada` axis.
7340            validate_entrada_host(e.hostname())?;
7341            // Structural-floor gate on `:entrada :port`: every
7342            // validated `Entrada::port` past this gate lies in
7343            // `SERVICO_PORT_MIN..=u16::MAX` (the `u16` field's natural
7344            // type-inferred ceiling closes the top edge, so no companion
7345            // upper-cap arm is needed here — unlike the peer capped-
7346            // `u32` `:politicas` / `:supervisor` / `:limits` axes whose
7347            // `require_positive_bounded_u32` bracket covers both edges).
7348            // Routes through the lifted [`SERVICO_PORT_MIN`] canonical
7349            // accept-set-floor const rather than the prior inline
7350            // `if e.port == 0` byte-check so a future rebrand of the
7351            // accept-set floor (a hypothetical unprivileged-only
7352            // migration lifting the floor to `1024`, a per-cluster
7353            // scoping the operator pins through a future
7354            // `:placement :port-floor` slot as the M4 typed-slot
7355            // trajectory adds it, the future
7356            // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7357            // per-Aplicacao gateway resolver reaching for the same
7358            // floor) is a one-line edit on the canonical
7359            // [`SERVICO_PORT_MIN`] declaration, not a coordinated
7360            // rewrite across the emit site + the pin test + every
7361            // future per-target renderer the substrate adds.
7362            if e.port() < SERVICO_PORT_MIN {
7363                return Err(AplicacaoError::EntradaPortZero);
7364            }
7365            // Each `:entrada :paths` entry becomes a K8s Gateway API
7366            // HTTPRoute `matches[].path.value`. The Gateway API rejects
7367            // values that don't start with `/` for `type: PathPrefix`,
7368            // and an empty value is meaningless. Surface those as build
7369            // errors (MESH-COMPOSITION §III.3) rather than apply-time
7370            // failures. Empty `:paths` itself is fine — caixa-mesh
7371            // falls back to a single `/` catch-all.
7372            let mut seen = std::collections::HashSet::new();
7373            // Route the per-entry value-shape gate's traversal head
7374            // through the lifted [`Entrada::paths`] slice accessor
7375            // rather than the raw `&e.paths` field access — the
7376            // per-Aplicacao `:entrada :paths` validate loop now keys
7377            // off the canonical raw-slot surface every downstream
7378            // per-`:entrada` path-list consumer (the sibling
7379            // [`Entrada::resolved_paths`] fallback-applying resolver
7380            // internal reads, `feira app graph`'s per-Aplicacao entrada
7381            // summary line's `{:?}` Debug print) routes through, so any
7382            // future rebrand on the typed slot's raw-slot reader lands
7383            // at exactly one place. Same convergence discipline as the
7384            // sibling [`Placement::clusters`] (a6e18d7) reader-site
7385            // convergences on the peer M3 mesh-slot `Vec<String>`-carry
7386            // axis.
7387            for p in e.paths() {
7388                if p.is_empty() {
7389                    return Err(AplicacaoError::EntradaPathEmpty);
7390                }
7391                if !p.starts_with('/') {
7392                    return Err(AplicacaoError::EntradaPathNotAbsolute { path: p.clone() });
7393                }
7394                // Per-entry value-shape gate: the path lands verbatim
7395                // as a K8s Gateway API HTTPRoute `matches[].path.value`
7396                // (caixa-mesh/src/lib.rs:498), apiserver-validated
7397                // against `maxLength: 1024` + the Gateway API webhook's
7398                // path-grammar rules (no `//`, no `/./`, no `/../`, no
7399                // query/fragment separators, no whitespace, no control
7400                // characters, no non-ASCII bytes). Until this gate
7401                // landed `validate` only refused the empty string and
7402                // missing-leading-slash (eb3456d); a structurally
7403                // invalid path (`"/api?q=1"`, `"/api#frag"`,
7404                // `"/api bar"`, `"/api/../etc"`, `"/api//cart"`, a
7405                // 1025-byte URL-shaped slug) silently passed validate
7406                // and the failure surfaced at `kubectl apply` time as
7407                // a Gateway API webhook rejection, far from the source
7408                // caixa.lisp, with no field naming the offending
7409                // `:paths` entry. Lifting the gate to caixa-build time
7410                // mirrors the `:entrada :host` value-shape trajectory
7411                // (c7d05ec) on the sibling axis — every author surface
7412                // that emits a Gateway API field now matches the
7413                // apiserver's accepted set at validate time.
7414                validate_entrada_path(p)?;
7415                crate::render::insert_first_seen(&mut seen, p.as_str(), || {
7416                    AplicacaoError::EntradaPathDuplicate { path: p.clone() }
7417                })?;
7418            }
7419        }
7420
7421        self.validate_placement()?;
7422
7423        self.validate_politicas()?;
7424
7425        Ok(())
7426    }
7427
7428    /// Reject `:membros` values that are operationally meaningless. The
7429    /// `:membros` slot is the graph node set (MESH-COMPOSITION §III.1):
7430    /// every entry names a Servico that participates in the Aplicacao,
7431    /// and the rendered programs.yaml fan-out emits one entry per
7432    /// `:membros`. Three authoring footguns are closed here:
7433    ///
7434    ///   - `:caixa ""` — caixa-mesh's `programs_for_aplicacao` would emit
7435    ///     a `programs:` entry whose `name:` is the empty string, which
7436    ///     downstream `lareira-fleet-programs` rejects at template time
7437    ///     with a non-localized error;
7438    ///   - `:versao ""` — caixa-resolver's lacre pipeline can't resolve
7439    ///     an empty semver constraint, so the failure surfaces far from
7440    ///     the source caixa.lisp;
7441    ///   - duplicate `:caixa` names — two entries with the same name
7442    ///     produce duplicate programs.yaml entries (one silently
7443    ///     overwrites the other in the cluster's HelmRelease values), and
7444    ///     contract membership lookups against `:contratos` collapse the
7445    ///     two onto one node, masking authoring mistakes.
7446    ///
7447    /// Same value-shape discipline as `:placement :clusters` (where empty
7448    /// + duplicate cluster names are rejected) and `:entrada :paths`
7449    /// (where empty + duplicate path entries are rejected). Lifting these
7450    /// invariants to the typed surface mirrors the MESH-COMPOSITION
7451    /// §III.3 promise that the `:membros` set — the load-bearing identity
7452    /// of the application graph — is well-formed by construction.
7453    fn validate_membros(&self) -> Result<(), AplicacaoError> {
7454        if self.membros().is_empty() {
7455            return Err(AplicacaoError::NoMembros);
7456        }
7457        let mut seen = std::collections::HashSet::new();
7458        for m in self.membros() {
7459            // Route the `MembroCaixaEmpty` refusal-arm's per-member
7460            // empty-`:caixa` shape-gate through the typed
7461            // [`Membro::nome`] accessor rather than the raw `.caixa`
7462            // field access — the last un-lifted `.caixa` production-
7463            // code read site on the per-`:membros` member-caixa `:nome`
7464            // axis, sibling to the six caixa-core validator read sites
7465            // (member-set collector, per-member value-shape gate,
7466            // duplicate dedup key, cycle-detector adjacency-map seed,
7467            // self-loop gate) the 4a32abf lift already routed through
7468            // the accessor and the peer 54bf2f3 caixa-mesh emit-side
7469            // per-`programs[]` entry-`name:` `String`-carry converge.
7470            // Prior to this converge the `MembroCaixaEmpty` refusal
7471            // arm was the solitary consumer bypassing the typed
7472            // dispatch — the same-loop iteration's very next call
7473            // `validate_membro_caixa(m.nome())` already routed through
7474            // the accessor, so an author landing an empty-`:caixa`
7475            // entry hit the accessor on the shape-gate line but
7476            // bypassed it on the emptiness line one line above. A
7477            // future extension of the `:membros :caixa` axis to a
7478            // richer author surface (a per-cluster alias table pinned
7479            // through a future `:placement`-scoped slot, a namespace-
7480            // qualified rewrite the M4 CR materializer applies per-CR,
7481            // a per-member overlay from the future `:membros
7482            // :nome-suffix` slot MESH-COMPOSITION §III.2 acknowledges)
7483            // that lands on the accessor would silently disagree
7484            // between the emptiness gate and every peer consumer —
7485            // an author-declared `:caixa "checkout"` value the
7486            // accessor rewrote to `""` under a future alias arm would
7487            // pass the raw `.is_empty()` gate here while the peer
7488            // `validate_membro_caixa(m.nome())` call one line below
7489            // (and every downstream emit-side consumer routing through
7490            // the accessor) tripped on the empty-value shape far from
7491            // this diagnostic. Pinned by the drift-detection test
7492            // [`validate_membros_empty_gate_routes_through_nome_accessor`]
7493            // below.
7494            if m.nome().is_empty() {
7495                return Err(AplicacaoError::MembroCaixaEmpty);
7496            }
7497            // Every emitted cluster artifact's `metadata.name` derives
7498            // from a `:membros :caixa` value verbatim — the rendered
7499            // programs.yaml entry's `name:` (caixa-mesh/src/lib.rs:133),
7500            // the [`crate::LABEL_PROGRAM`] label value on every CNP
7501            // endpointSelector / fromEndpoints (caixa-mesh/src/lib.rs:263,
7502            // 272), the composed `CiliumNetworkPolicy` `metadata.name`
7503            // (caixa-mesh/src/lib.rs:250), and the Gateway API HTTPRoute
7504            // `metadata.name` when the member is the `:entrada :para`
7505            // target (caixa-mesh/src/lib.rs:423). Each apiserver-side
7506            // schema enforces the DNS-1123 label rule on admission;
7507            // a structurally invalid member name (`"Cart"`, `"my_cart"`,
7508            // `"my.cart"`, `"-cart"`, `"cart-"`, the >63-byte UUID-shaped
7509            // mistaken-identity slug) silently passes the prior empty-/
7510            // duplicate-only gate and the failure surfaces at `kubectl
7511            // apply` time as a `metadata.name: Invalid value` rejection,
7512            // far from the source caixa.lisp, with no field naming the
7513            // offending `:membros` entry. Lifting the gate to caixa-build
7514            // time mirrors the `:entrada :host` value-shape trajectory
7515            // (c7d05ec) on the peer axis — every author surface that
7516            // emits a K8s name now matches the apiserver's accepted set
7517            // at validate time.
7518            validate_membro_caixa(m.nome())?;
7519            // The author surface for `:versao` is the same Cargo-shaped
7520            // semver requirement string (`"^0.1"`, `"~0.1.2"`, `"0.1.0"`,
7521            // `"*"`) every `:deps` entry carries — and the lacre pipeline
7522            // resolves both axes through the same
7523            // [`crate::version::parse_requirement`] entry-point. The
7524            // shared [`crate::render::require_valid_versao_requirement`]
7525            // helper brackets the empty-first + parse cascade both peer
7526            // axes ([`crate::dep::Dep::validate`] on `:deps :versao`,
7527            // [`crate::SupervisorSpec::validate`] on `:children :versao`)
7528            // route through, so drift between the three axes' accepted
7529            // requirement sets is structurally impossible and the parse-
7530            // side no-op the empty-first arm closes (semver's empty
7531            // parse yields an implicit `*`) lives in exactly one
7532            // predicate.
7533            crate::render::require_valid_versao_requirement(
7534                m.versao_requirement(),
7535                || AplicacaoError::MembroVersaoEmpty {
7536                    caixa: m.nome().to_string(),
7537                },
7538                |reason| AplicacaoError::MembroVersaoInvalid {
7539                    caixa: m.nome().to_string(),
7540                    versao: m.versao_requirement().to_string(),
7541                    reason,
7542                },
7543            )?;
7544            crate::render::insert_first_seen(&mut seen, m.nome(), || {
7545                AplicacaoError::MembroDuplicate {
7546                    caixa: m.nome().to_string(),
7547                }
7548            })?;
7549        }
7550        Ok(())
7551    }
7552
7553    /// Reject `:placement` values that are operationally meaningless or
7554    /// internally contradictory. Each strategy variant has the same
7555    /// invariants on `:clusters` (non-empty list, non-empty unique
7556    /// entries) — the §III.1 author surface is uniform on this axis,
7557    /// even though the *meaning* of the list differs by strategy
7558    /// (`Replicated`/`SingleNode` host the app; `Sharded` defines the
7559    /// shard pool).
7560    ///
7561    /// Empty cluster names or a `Some("")` `:shard-key`/`:affinity`
7562    /// are the same authoring footgun closed for `:politicas` zero
7563    /// values and `:entrada` empty paths: the field is *declared* but
7564    /// carries no meaning, so downstream renderers either skip it
7565    /// silently (cluster-fanout drops the empty entry, no diagnostic)
7566    /// or apply it literally and fail at admission time. Lifting both
7567    /// to build errors mirrors MESH-COMPOSITION §III.3's "placement
7568    /// violation is a build error" promise.
7569    ///
7570    /// `:shard-key` and `:estrategia` are typed-partitioned: the slot
7571    /// is required exactly when `:estrategia Sharded` (hash-keyed
7572    /// distribution, Akka cluster-sharding convention, §II.4) and
7573    /// refused on `:estrategia Replicated`/`SingleNode` (where no
7574    /// hash-keyed routing axis consumes it). The partition closes the
7575    /// "I think I configured sharding" footgun where an author writes
7576    /// `:placement (:estrategia Replicated :shard-key "tenantId")` and
7577    /// the typed slot's value silently vanishes at the renderer layer
7578    /// — every validated `Placement` past this call satisfies
7579    /// `shard_key.is_some() == matches!(estrategia, Sharded)`.
7580    fn validate_placement(&self) -> Result<(), AplicacaoError> {
7581        // Every strategy needs at least one named cluster: `Replicated`
7582        // and `SingleNode` use the list as hosting/takeover candidates
7583        // (Erlang/OTP distributed-app convention — see MESH-COMPOSITION
7584        // §II.1), while `Sharded` uses it as the shard pool
7585        // (Akka cluster-sharding convention — §II.4). An empty list is
7586        // meaningless under any of the three.
7587        //
7588        // Route the paired pre-flight `.is_empty()` refusal probe and
7589        // the per-cluster validate loop's traversal head through the
7590        // lifted [`Placement::clusters`] slice-return accessor rather
7591        // than the raw `self.placement.clusters` field access — the
7592        // two production consumers of the per-`:placement` cluster-
7593        // pool `Vec`-carry now key off exactly one typed dispatch on
7594        // the substrate primitive, so any future rebrand on the axis
7595        // (a per-tenant cluster-pool overlay the operator pins through
7596        // a future `:placement :clusters-overrides` slot, a per-
7597        // Aplicacao dynamic cluster-pool derivation the future M5
7598        // adaptive-placement engine computes from `:affinity` weights)
7599        // migrates as a single caixa-core edit rather than a
7600        // coordinated rewrite of the paired arms — sibling of the
7601        // peer M2 [`crate::SupervisorSpec::children`] (bc92bce) two-
7602        // arm migration on the per-`:supervisor` static-child-list
7603        // `Vec`-carry axis.
7604        //
7605        // Route the per-`:placement` outer-composite reference read
7606        // through the lifted [`AplicacaoSpec::placement`] outer accessor
7607        // rather than the raw `&self.placement` field access — the
7608        // per-axis bracket-dispatch fan-out below (`p.clusters()`,
7609        // `p.estrategia()`, `p.affinity()`, `p.shard_key()` on the
7610        // axis-level lifted accessor family) now routes through the
7611        // substrate-primitive typed dispatch at the outer composition
7612        // altitude, the same shape the peer caixa-mesh
7613        // `programs_for_aplicacao` per-Aplicacao programs.yaml emitter
7614        // and the sibling `feira app graph` per-Aplicacao print line
7615        // now key off after this accessor lift.
7616        let p = self.placement();
7617        if p.clusters().is_empty() {
7618            return Err(AplicacaoError::PlacementWithoutClusters {
7619                estrategia: p.estrategia(),
7620            });
7621        }
7622        let mut seen = std::collections::HashSet::new();
7623        for c in p.clusters() {
7624            // Per-entry value-shape gate: the cluster name lands in
7625            // every K8s context / `lareira-fleet-programs` aggregator
7626            // filter / future M4 CR materializer's per-cluster axis
7627            // a validated `:clusters` entry passes through, each
7628            // enforcing the DNS-1123 label rule on admission. Same
7629            // typed-shape trajectory as `:membros :caixa` (3f9d7a0)
7630            // on the peer name axis — both axes' validated values
7631            // are guaranteed-accepted by the apiserver without
7632            // re-validation at any downstream renderer or admission
7633            // layer.
7634            validate_placement_cluster(c)?;
7635            crate::render::insert_first_seen(&mut seen, c.as_str(), || {
7636                AplicacaoError::PlacementClusterDuplicate { cluster: c.clone() }
7637            })?;
7638        }
7639        // Route the per-`:placement :affinity` per-hint value-shape
7640        // gate through the typed [`Placement::affinity`] accessor rather
7641        // than the raw `&self.placement.affinity` field access — the
7642        // sole open-coded field-access site on the per-`:placement`
7643        // M3-Adaptive-compression-hint axis the accessor lift now owns.
7644        // The `Some(a)`-bound `a` narrows from `&String` to `&str` under
7645        // the accessor's `Option<&str>` return type;
7646        // [`validate_placement_affinity`]'s `&str` parameter accepts
7647        // the narrower borrow without a re-allocation, so the routing
7648        // change is byte-for-byte in the pass arm and remains
7649        // byte-for-byte in every failure diagnostic
7650        // ([`AplicacaoError::PlacementAffinityInvalid`]'s `affinity:
7651        // String` field is populated inside
7652        // [`validate_placement_affinity`] via the peer `.to_string()`
7653        // path on the same borrowed slice). Peer of the sibling
7654        // `PlacementStrategy::Sharded`-arm `:shard-key` shape-gate
7655        // routing through [`Placement::shard_key`] at the caixa-core
7656        // site above — extends the "read `:placement` optional-scalars
7657        // through the typed accessor" discipline to the second
7658        // `Option<String>`-shape slot on the M3 mesh-slot family.
7659        //
7660        // Per-hint value-shape gate: the `:affinity` value lands
7661        // verbatim in the M3 Adaptive compression overlay
7662        // (caixa-mesh's `placement.affinity` emission) and every
7663        // future M4 placement-engine routing axis keying off the
7664        // hint as a K8s `app.pleme.io/affinity-hint=<value>` label
7665        // selector — each enforces the DNS-1123 label rule on
7666        // admission. Same typed-shape trajectory as `:placement
7667        // :clusters` (6c8c00b) on the sibling slot and the four
7668        // Servico-name reference axes (`:membros :caixa` 3f9d7a0,
7669        // `:placement :clusters` 6c8c00b, `:contratos :de`/`:para`
7670        // 8d5af6b, `:entrada :para` b0e8748) — the fifth typed slot
7671        // on the Aplicacao surface to land on the canonical
7672        // [`crate::render::is_dns_1123_label`] floor.
7673        if let Some(a) = p.affinity() {
7674            validate_placement_affinity(a)?;
7675        }
7676        match p.estrategia() {
7677            // Route the `Sharded`-arm shape-gate cascade through the
7678            // typed [`Placement::shard_key`] accessor rather than the
7679            // raw `&self.placement.shard_key` field access — one of the
7680            // two open-coded field-access sites on the per-`:placement`
7681            // Akka-cluster-sharding-key axis the accessor lift now
7682            // owns. The `Some(k)`-bound `k` narrows from `&String` to
7683            // `&str` under the accessor's `Option<&str>` return type;
7684            // `str::is_empty` and [`validate_placement_shard_key`]'s
7685            // `&str` parameter both accept the narrower borrow without
7686            // a re-allocation.
7687            PlacementStrategy::Sharded => match p.shard_key() {
7688                None => return Err(AplicacaoError::ShardedWithoutKey),
7689                Some(k) if k.is_empty() => return Err(AplicacaoError::ShardedKeyEmpty),
7690                // Per-axis value-shape gate on the Akka-cluster-sharding
7691                // `:shard-key` extractor expression. The shape gate runs
7692                // after the more self-locating `ShardedKeyEmpty` arm so
7693                // a `:shard-key ""` surfaces the narrower empty
7694                // diagnostic first; every non-empty `:shard-key` past
7695                // this call is guaranteed to be a printable-ASCII
7696                // single-token reference the future M4 Akka-style
7697                // cluster-sharding reconciler can hash without
7698                // re-validating at the runtime layer. Mirrors the
7699                // payload-axis shape gates on the peer `:contratos`
7700                // `:endpoint`/`:subject`/`:slot` axes (4f0390b /
7701                // 63e18a0 / c4213a4) — each lifts the runtime parser's
7702                // intersection-floor to a caixa-build-time gate.
7703                Some(k) => validate_placement_shard_key(k)?,
7704            },
7705            // `:shard-key` is the Akka-cluster-sharding axis
7706            // (MESH-COMPOSITION §II.4) — hash-keyed entity distribution
7707            // across the cluster pool. `Replicated` (active-active across
7708            // every named cluster) and `SingleNode` (Erlang/OTP
7709            // distributed-app takeover/failover, §II.1) have no hash-keyed
7710            // routing axis to consume the slot; downstream renderers
7711            // (caixa-mesh's `placement.shardKey` overlay at
7712            // caixa-mesh/src/lib.rs:909, the future M4 Akka-style cluster-
7713            // sharding reconciler) ignore `:shard-key` outside the
7714            // `Sharded` arm by construction. Until this gate landed an
7715            // author who wrote `:placement (:estrategia Replicated
7716            // :shard-key "tenantId")` (an off-by-one strategy typo, a
7717            // copy-paste from a Sharded sibling caixa, the "I think I
7718            // configured sharding" footgun) silently passed validate and
7719            // the typed slot's value vanished at the renderer layer with
7720            // no diagnostic — the canonical "declared-but-inert" footgun
7721            // the empty-:affinity / empty-shard-key / zero-:politicas /
7722            // empty-:contratos-target gates already close on every other
7723            // declare-but-no-opinion axis (2d71a9a / 5dbcfaf / c7c7799).
7724            // Lifting the rejection to a build-time gate closes the
7725            // Sharded ↔ non-Sharded partition over the typed
7726            // `:placement` slot: every validated `Placement` past this
7727            // call has `shard_key.is_some()` iff `estrategia ==
7728            // Sharded`, structurally — the future Akka reconciler can
7729            // reach for `placement.shard_key` knowing it's `Some` exactly
7730            // when the strategy consumes it, without re-deriving the
7731            // partition from inline strategy probes.
7732            PlacementStrategy::Replicated | PlacementStrategy::SingleNode => {
7733                // Route the non-`Sharded`-arm declared-but-inert refusal
7734                // through the typed [`Placement::shard_key`] accessor —
7735                // the second of the two open-coded field-access sites the
7736                // accessor lift now owns. The `Some(k)`-bound `k` narrows
7737                // from `&String` to `&str`; the `AplicacaoError::
7738                // ShardKeyOnNonSharded { shard_key: String }` diagnostic
7739                // materializes the owned `String` via `k.to_string()`
7740                // (peer to the sibling per-Membro `String`-carry sites
7741                // 4127bb6 routed through `m.nome().to_string()` /
7742                // `m.versao_requirement().to_string()`), so the whole
7743                // `Sharded` ↔ non-`Sharded` partition on the
7744                // `:shard-key` axis now flows through the same typed
7745                // dispatch as the sibling `Sharded`-arm shape gate.
7746                if let Some(k) = p.shard_key() {
7747                    return Err(AplicacaoError::ShardKeyOnNonSharded {
7748                        estrategia: p.estrategia(),
7749                        shard_key: k.to_string(),
7750                    });
7751                }
7752            }
7753        }
7754        Ok(())
7755    }
7756
7757    /// Reject `:politicas` values that are operationally meaningless.
7758    /// Each axis is optional — omitting it expresses "no policy on this
7759    /// axis". Carrying a *zero* value for a declared axis is the bug
7760    /// this function rejects: zero is either
7761    ///
7762    ///   - re-interpreted as "infinite" by downstream proxies (Envoy's
7763    ///     `RouteAction.timeout = 0s` disables the timeout entirely),
7764    ///     directly contradicting MESH-COMPOSITION §V CSE invariant
7765    ///     "every Aplicacao declares :politicas :timeout (no infinite
7766    ///     blocking)", or
7767    ///   - a renderer footgun (a 0-failure circuit breaker trips on the
7768    ///     first call; a 0-rate rate-limit denies every request).
7769    ///
7770    /// Lifting these "0 means the opposite of what you think" idioms to
7771    /// the typed Aplicacao surface as build errors mirrors the §III.3
7772    /// promise that contract drift, capability leaks, and cycles are all
7773    /// build errors — not runtime surprises.
7774    fn validate_politicas(&self) -> Result<(), AplicacaoError> {
7775        // Route the per-`:politicas` composite-reference read through
7776        // the lifted [`AplicacaoSpec::politicas`] outer accessor rather
7777        // than the raw `&self.politicas` field access — the per-axis
7778        // bracket-dispatch fan-out below (`p.timeout()`, `p.retries()`,
7779        // `p.circuit_breaker()`, `p.rate_limit()`) now routes through
7780        // the substrate-primitive typed dispatch at the outer
7781        // composition altitude AND at every per-axis altitude, matching
7782        // the peer caixa-mesh CNP mTLS-overlay + HTTPRoute
7783        // timeout/retry-overlay emitters that already key off the same
7784        // per-axis accessor family. The four-axis fan-out is now
7785        // uniformly `p.<axis>()` — the last two raw `p.timeout` /
7786        // `p.retries` field-access sites (co-resident with the peer
7787        // `p.circuit_breaker()` / `p.rate_limit()` accessor sites that
7788        // b0e741a / 21a6c3b already lifted) now route through
7789        // [`MeshPolicy::timeout`] / [`MeshPolicy::retries`], closing
7790        // the per-`:politicas` bracket-dispatch fan-out's raw-field-
7791        // access axis on the M3 mesh-slot family.
7792        let p = self.politicas();
7793        if let Some(t) = p.timeout() {
7794            // Zero-floor + integer-millisecond canonical-form +
7795            // upper-cap bracket on the typed `:timeout` axis. See
7796            // [`crate::render::require_positive_canonical_bounded_duration`]
7797            // for the full three-arm ordering discipline (zero-floor
7798            // strictly precedes the canonical-form arm so
7799            // `Duration::ZERO` surfaces the self-locating
7800            // `PolicyTimeoutZero` diagnostic naming the omit-axis
7801            // remediation; canonical-form strictly precedes the cap
7802            // arm so a sub-millisecond above-cap `Duration` surfaces
7803            // the more fundamental round-trip-shape diagnostic first)
7804            // and the four peer typed-`Duration` sites that now share
7805            // this canonical bracket. Every validated value lies in
7806            // `1ms..=POLICY_TIMEOUT_MAX` (1ms..=1h), integer-millisecond
7807            // granularity — the same top-and-bottom-edge discipline
7808            // [`POLICY_RETRIES_MAX`] and
7809            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] apply on the sibling
7810            // capped-`u32` `:politicas` axes.
7811            crate::render::require_positive_canonical_bounded_duration(
7812                t,
7813                POLICY_TIMEOUT_MAX,
7814                || AplicacaoError::PolicyTimeoutZero,
7815                |timeout| AplicacaoError::PolicyTimeoutNotCanonical { timeout },
7816                |timeout| AplicacaoError::PolicyTimeoutExceedsCap { timeout },
7817            )?;
7818        }
7819        if let Some(r) = p.retries() {
7820            // Zero-floor + upper-cap bracket on the typed `:retries`
7821            // axis. See [`crate::render::require_positive_bounded_u32`]
7822            // for the ordering discipline (zero-floor arm strictly
7823            // precedes cap arm so `Some(0)` surfaces the self-locating
7824            // `PolicyRetriesZero` diagnostic with its omit-axis
7825            // remediation directly named, not the misleading
7826            // `0 > POLICY_RETRIES_MAX == false` cap-arm miss). Until
7827            // this bracket landed the top edge ran all the way to
7828            // `u32::MAX` and a struct-literal `MeshPolicy { retries:
7829            // Some(100_000), .. }` (or the equivalent author-surface
7830            // `(:retries 100000)` / `(:retries 4294967295)` typo
7831            // landing in the slot) silently passed validate. The
7832            // runtime substrate consuming the value (Envoy's
7833            // `retry_policy.num_retries`, the future
7834            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7835            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7836            // policy into a thundering-herd amplification vector —
7837            // the caller's one request fans out to `retries`
7838            // server-side calls per edge per traversal, multiplying
7839            // load by `(retries+1)^depth` across the
7840            // synchronous-`:contratos` subgraph at the precise moment
7841            // the substrate is already failing (transient failure is
7842            // the trigger), exactly the failure mode AWS App Mesh's
7843            // explicit `maxRetries ≤ 10` schema cap exists to prevent.
7844            // The bracket set is `1..=POLICY_RETRIES_MAX`. Peer with
7845            // the sibling capped-`u32` `:politicas` axes
7846            // (`max_failures`, `rate_limit.rate`) and the peer capped-
7847            // `u32` axes in `:supervisor :max-restarts` +
7848            // `:limits :cpu`; all five now route through the same
7849            // canonical bracket helper.
7850            crate::render::require_positive_bounded_u32(
7851                r,
7852                POLICY_RETRIES_MAX,
7853                || AplicacaoError::PolicyRetriesZero,
7854                |retries| AplicacaoError::PolicyRetriesExceedsCap { retries },
7855            )?;
7856        }
7857        if let Some(cb) = p.circuit_breaker() {
7858            // Zero-floor + upper-cap bracket on the typed
7859            // `:max-failures` axis. See
7860            // [`crate::render::require_positive_bounded_u32`] for the
7861            // ordering discipline (zero-floor arm strictly precedes
7862            // cap arm so `max_failures == 0` surfaces the
7863            // self-locating `PolicyBreakerZeroFailures` diagnostic
7864            // with its omit-axis remediation directly named, not the
7865            // misleading `0 > POLICY_BREAKER_MAX_FAILURES_MAX ==
7866            // false` cap-arm miss). Until this bracket landed the top
7867            // edge ran all the way to `u32::MAX` and a struct-literal
7868            // `CircuitBreaker { max_failures: 100_000, .. }` (or the
7869            // equivalent author-surface `(:max-failures 100000)` /
7870            // `(:max-failures 4294967295)` typo landing in the slot)
7871            // silently passed validate. The runtime substrate
7872            // consuming the value (Envoy's
7873            // `outlier_detection.consecutive_5xx`, the future
7874            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7875            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7876            // breaker policy into a no-op — the trip threshold is
7877            // structurally so high that no realistic
7878            // failures-per-`:window` traffic shape can reach it, the
7879            // breaker never trips, and every typed-slot consumer
7880            // emits an Envoy / Cilium L7 overlay carrying a
7881            // protection that is structurally never enforced. The
7882            // bracket set is `1..=POLICY_BREAKER_MAX_FAILURES_MAX`;
7883            // peer with `retries` and `rate_limit.rate` on the same
7884            // helper.
7885            crate::render::require_positive_bounded_u32(
7886                cb.max_failures(),
7887                POLICY_BREAKER_MAX_FAILURES_MAX,
7888                || AplicacaoError::PolicyBreakerZeroFailures,
7889                |max_failures| AplicacaoError::PolicyBreakerMaxFailuresExceedsCap { max_failures },
7890            )?;
7891            // Zero-floor + integer-millisecond canonical-form +
7892            // upper-cap bracket on the typed `:window` axis. See
7893            // [`crate::render::require_positive_canonical_bounded_duration`]
7894            // for the full three-arm ordering discipline (peer to the
7895            // `:timeout` site immediately above); every validated
7896            // value lies in `1ms..=POLICY_BREAKER_WINDOW_MAX`
7897            // (1ms..=1h), integer-millisecond granularity — the same
7898            // top-and-bottom-edge discipline
7899            // [`POLICY_TIMEOUT_MAX`] applies on the sibling
7900            // duration-typed `:politicas :timeout` axis.
7901            crate::render::require_positive_canonical_bounded_duration(
7902                cb.window(),
7903                POLICY_BREAKER_WINDOW_MAX,
7904                || AplicacaoError::PolicyBreakerZeroWindow,
7905                |window| AplicacaoError::PolicyBreakerWindowNotCanonical { window },
7906                |window| AplicacaoError::PolicyBreakerWindowExceedsCap { window },
7907            )?;
7908        }
7909        if let Some(rl) = p.rate_limit() {
7910            // Zero-floor + upper-cap bracket on the typed
7911            // `:rate-limit` rate axis. See
7912            // [`crate::render::require_positive_bounded_u32`] for the
7913            // ordering discipline (zero-floor arm strictly precedes
7914            // cap arm so `rl.rate == 0` surfaces the self-locating
7915            // `PolicyRateLimitZero` diagnostic with its omit-axis
7916            // remediation directly named, not the misleading
7917            // `0 > POLICY_RATE_LIMIT_MAX == false` cap-arm miss).
7918            // Until this bracket landed the top edge ran all the way
7919            // to `u32::MAX` and a struct-literal
7920            // `RateLimit { rate: u32::MAX, .. }` (or the equivalent
7921            // author-surface `(:rate-limit "4294967295/s")` /
7922            // `(:rate-limit "100000000/m")` typo landing in the slot)
7923            // silently passed validate. The runtime substrate
7924            // consuming the value (Envoy's
7925            // `local_rate_limit.token_bucket.max_tokens`, the future
7926            // `CiliumClusterwideEnvoyConfig` per-`:politicas` overlay
7927            // MESH-COMPOSITION §III.2 #3 names) then turned a typed
7928            // rate-limit policy into a no-op limiter: the bucket
7929            // capacity is structurally so high that no realistic
7930            // per-edge traffic shape can drain it, the limiter never
7931            // trips, and every typed-slot consumer emits a "rate
7932            // declared" L7 overlay carrying enforcement that is
7933            // structurally never reached — the canonical
7934            // declared-but-inert footgun the sibling
7935            // [`POLICY_BREAKER_MAX_FAILURES_MAX`] cap arm closes on
7936            // the peer no-op-breaker shape. The bracket set is
7937            // `1..=POLICY_RATE_LIMIT_MAX`; peer with `retries` and
7938            // `max_failures` on the same helper. The rate bracket
7939            // strictly precedes the window-canonical gate so a
7940            // structurally absurd rate magnitude surfaces the more
7941            // fundamental amplification-shape diagnostic before the
7942            // narrower codec-round-trip-shape diagnostic on `:window`.
7943            crate::render::require_positive_bounded_u32(
7944                rl.rate(),
7945                POLICY_RATE_LIMIT_MAX,
7946                || AplicacaoError::PolicyRateLimitZero,
7947                |rate| AplicacaoError::PolicyRateLimitExceedsCap { rate },
7948            )?;
7949            // The `:rate-limit` author surface is the canonical
7950            // `"<n>/<s|m|h>"` form, and the [`rate_limit_codec`] parser
7951            // accepts exactly the three-unit set (1s/60s/3600s) the
7952            // [`rate_limit_codec::render`] formatter emits the canonical
7953            // unit suffix for. A `RateLimit` whose `:window` is anything
7954            // else (zero, 30s, 45s, 120s, 86400s, …) is constructible
7955            // programmatically (struct literals in Rust + the typed
7956            // `Duration` field) but renders to a `<n>/<k>s` fragment
7957            // (the codec's fall-through) the parser then rejects on
7958            // round-trip — silently breaking the THEORY.md §V.2.7
7959            // render-determinism contract for any consumer that
7960            // serializes-then-deserializes the typed slot. Lifting the
7961            // canonical-window invariant to a build-time gate at
7962            // `validate_politicas` makes the codec's round-trip property
7963            // a structural property of the validated typed value:
7964            // every `RateLimit` past `AplicacaoSpec::validate` has a
7965            // window the codec round-trips losslessly, so the next
7966            // typed-slot wiring (the future `CiliumClusterwideEnvoyConfig`
7967            // emitter for `:politicas :rate-limit`, MESH-COMPOSITION
7968            // §III.2 #3) reaches for `rate_limit.window` knowing the
7969            // value is in the codec's accepted set without re-validating
7970            // at the renderer layer. Same trajectory as c4213a4 (typed
7971            // WitContract endpoint/subject/slot value-shape gates) and
7972            // the b0c8389 :behavior + :upgrade-from script-path lifts:
7973            // the typed slot's valid set matches its codec's accepted
7974            // set, structurally.
7975            // Route the canonical-window shape-gate through the substrate
7976            // primitive [`RateLimit::canonical_unit`] rather than the free
7977            // module-private [`is_canonical_rate_limit_window`] predicate:
7978            // both projections resolve `Duration → Option<RateLimitUnit>`
7979            // through [`RateLimitUnit::from_window`] (the sole `Duration → Self`
7980            // arm on the closed-set typed enum), but the accessor is the
7981            // typed method every downstream consumer of the validated slot
7982            // ([`rate_limit_codec::render`]'s canonical arm above, the
7983            // future M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
7984            // per-`:politicas :rate-limit` admission webhook, the future
7985            // per-`:contratos`-edge rate-limit-override overlay
7986            // MESH-COMPOSITION §III.2 #3 acknowledges) already reads. Two
7987            // production consumers of the canonical-unit axis (the codec
7988            // render and this validate gate) now key off exactly one typed
7989            // dispatch on the substrate primitive, so any future extension
7990            // to `canonical_unit` (a per-cluster canonical-window overlay
7991            // the operator pins through a future `:contratos :rate-limit
7992            // -unit-overrides` slot, a per-tenant unit-alias table the M4
7993            // CR materializer resolves per-CR) reaches both consumers by
7994            // construction rather than a coordinated rewrite of every
7995            // free-helper call site.
7996            if rl.canonical_unit().is_none() {
7997                return Err(AplicacaoError::PolicyRateLimitWindowNotCanonical {
7998                    window: rl.window(),
7999                });
8000            }
8001        }
8002        Ok(())
8003    }
8004
8005    /// Detect cycles in the synchronous-edge subgraph of `:contratos`.
8006    /// A synchronous edge is any contract whose typed [`WitTarget`] is
8007    /// `Http`, `Store`, or `Capability` — the caller blocks on the
8008    /// callee, so a cycle would deadlock at runtime. Pub-sub edges
8009    /// (`WitTarget::PubSub`) are skipped: an event publisher does not
8010    /// block on its subscribers, so they can never close a sync loop.
8011    ///
8012    /// Iterative DFS with three-coloring; the reported cycle is the
8013    /// path of caixa names traversed from the back-edge target around
8014    /// to itself, in declaration order. Adjacency lists and DFS roots
8015    /// are visited in `BTreeMap` key order so the diagnostic is
8016    /// deterministic across runs.
8017    fn detect_sync_cycles(&self) -> Result<(), AplicacaoError> {
8018        use std::collections::{BTreeMap, BTreeSet};
8019
8020        #[derive(Clone, Copy, PartialEq, Eq)]
8021        enum Mark {
8022            White,
8023            Gray,
8024            Black,
8025        }
8026
8027        let mut adj: BTreeMap<&str, BTreeSet<&str>> = BTreeMap::new();
8028        for m in self.membros() {
8029            adj.entry(m.nome()).or_default();
8030        }
8031        for c in self.contratos() {
8032            // target() was already called by validate(); re-running here
8033            // keeps detect_sync_cycles self-contained for callers that
8034            // reuse it (M4 per-edge policy resolver) without revalidating.
8035            //
8036            // The pub-sub-arm check routes through the lifted
8037            // [`WitTarget::is_pubsub`] `gen_platform::IsVariant`-derived
8038            // arm-discriminator predicate rather than a raw `matches!(…,
8039            // WitTarget::PubSub { .. })` on the variant so a future
8040            // rebrand on the axis (an M4 per-edge WIT registry split of
8041            // [`WitTarget::PubSub`] into shape-specific peers, a
8042            // per-consumer rename that the accept-set already carries)
8043            // reaches this call site through the derive rather than a
8044            // scattered per-arm `matches!` rewrite — same
8045            // `IsVariant`-derived-arm-discriminator discipline the
8046            // peer closed-set typed enums ([`crate::CaixaKind`] via
8047            // f5bba80, [`PlacementStrategy`] via 766ec63,
8048            // [`crate::supervisor::RestartStrategy`] +
8049            // [`crate::supervisor::RestartPolicy`],
8050            // [`crate::upgrade::UpgradeInstruction`] via 915a934)
8051            // already route through on the substrate's other typed-enum
8052            // arm-discriminator axes.
8053            if c.target()?.is_pubsub() {
8054                continue;
8055            }
8056            adj.entry(c.source()).or_default().insert(c.destination());
8057        }
8058
8059        let mut color: BTreeMap<&str, Mark> = adj.keys().map(|k| (*k, Mark::White)).collect();
8060        let mut parent: BTreeMap<&str, &str> = BTreeMap::new();
8061
8062        // Stable DFS root order — BTreeMap iteration is sorted by key.
8063        let roots: Vec<&str> = adj.keys().copied().collect();
8064
8065        // Frame: (node, sorted-neighbours snapshot, next-edge index).
8066        for root in roots {
8067            if color.get(root).copied().unwrap_or(Mark::White) != Mark::White {
8068                continue;
8069            }
8070            let root_neighbors: Vec<&str> = adj
8071                .get(root)
8072                .map(|s| s.iter().copied().collect())
8073                .unwrap_or_default();
8074            let mut stack: Vec<(&str, Vec<&str>, usize)> = vec![(root, root_neighbors, 0)];
8075            color.insert(root, Mark::Gray);
8076
8077            loop {
8078                // Read+advance the top frame in one borrow scope so we
8079                // can later mutate the stack (push/pop) without holding
8080                // a borrow across.
8081                let step: Option<(&str, Option<&str>)> = stack.last_mut().map(|top| {
8082                    let node = top.0;
8083                    if top.2 >= top.1.len() {
8084                        (node, None)
8085                    } else {
8086                        let nxt = top.1[top.2];
8087                        top.2 += 1;
8088                        (node, Some(nxt))
8089                    }
8090                });
8091                let Some((node, nxt_opt)) = step else { break };
8092                let Some(nxt) = nxt_opt else {
8093                    color.insert(node, Mark::Black);
8094                    stack.pop();
8095                    continue;
8096                };
8097                let nxt_color = color.get(nxt).copied().unwrap_or(Mark::White);
8098                match nxt_color {
8099                    Mark::Gray => {
8100                        // Reconstruct the cycle from `node` back through
8101                        // the parent chain to `nxt`, then close.
8102                        let mut cycle = Vec::new();
8103                        let mut cur = node;
8104                        cycle.push(cur.to_string());
8105                        while cur != nxt {
8106                            match parent.get(cur).copied() {
8107                                Some(p) => {
8108                                    cur = p;
8109                                    cycle.push(cur.to_string());
8110                                }
8111                                None => break,
8112                            }
8113                        }
8114                        cycle.reverse();
8115                        cycle.push(nxt.to_string());
8116                        return Err(AplicacaoError::ContratoCycle { cycle });
8117                    }
8118                    Mark::White => {
8119                        parent.insert(nxt, node);
8120                        color.insert(nxt, Mark::Gray);
8121                        let nxt_neighbors: Vec<&str> = adj
8122                            .get(nxt)
8123                            .map(|s| s.iter().copied().collect())
8124                            .unwrap_or_default();
8125                        stack.push((nxt, nxt_neighbors, 0));
8126                    }
8127                    Mark::Black => {}
8128                }
8129            }
8130        }
8131        Ok(())
8132    }
8133
8134    /// Substrate-canonical destination-facing TCP port every emitted
8135    /// per-Aplicacao artifact must key `destination`-shaped port axes
8136    /// off. Returns the typed `:entrada :port` scalar when this
8137    /// Aplicacao's `:entrada` block names `destination` under its
8138    /// `:para` axis (the destination Servico *is* the ingress apex, so
8139    /// the substrate honors the author-declared listener port
8140    /// verbatim), and the lifted [`DEFAULT_SERVICO_PORT`] canonical
8141    /// fallback otherwise (every non-apex destination — the internal
8142    /// mesh Servicos `:contratos` reach across, the future per-edge
8143    /// policy resolver's per-destination probe targets, the
8144    /// M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's per-CNP
8145    /// L4 port resolver — reads the same substrate-canonical port floor
8146    /// by construction).
8147    ///
8148    /// Prior to this lift the "if :entrada matches this destination use
8149    /// its :port, else fall back to `DEFAULT_SERVICO_PORT`" cascade
8150    /// lived inline at [`caixa_mesh::cilium_network_policies`]'s per-
8151    /// `(:de, :para)` L4-port resolution site (caixa-mesh/src/lib.rs:2652
8152    /// prior to this lift), with no typed method on the substrate primitive
8153    /// that named the rule. A future per-destination port axis addition
8154    /// — a per-`:contratos` explicit `:port` slot the M4 typed-edge
8155    /// registry adds, a per-`:membros` `:port` overlay once heterogeneous
8156    /// per-Servico listener ports land, a per-cluster override the operator
8157    /// pins through a future `:placement :default-port` slot — would have
8158    /// to be threaded through every renderer's inline cascade in lockstep
8159    /// or one consumer would silently disagree on which port a given
8160    /// destination Servico's ingress lands at. Lifting the rule to a
8161    /// typed method on the substrate primitive means the M4 CR
8162    /// materializer, the future per-edge policy resolver, and every
8163    /// downstream test-fixture navigator reach for exactly one typed
8164    /// dispatch — the resolver's accept-set moves as a unit on any
8165    /// future axis addition.
8166    ///
8167    /// Peer of the [`WitTarget::payload_pair`] (6788ed6) /
8168    /// [`RATE_LIMIT_UNIT_TABLE`] (808017c) canonical "one dispatch on
8169    /// the typed primitive, thin projections at each consumer"
8170    /// discipline lifts on the sibling `:contratos` payload / `:politicas
8171    /// :rate-limit` unit-suffix axes; extends the discipline onto the
8172    /// destination-facing port-resolution axis every per-Aplicacao
8173    /// L4-fallback renderer consumes.
8174    #[must_use]
8175    pub fn port_for_destination(&self, destination: &str) -> u16 {
8176        // Route the per-`:entrada` composite-reference read through
8177        // the lifted [`AplicacaoSpec::entrada`] accessor rather than
8178        // the raw `self.entrada.as_ref()` field access — the
8179        // per-destination L4-port fallback resolver's composite-
8180        // projection seed is now the canonical read-side surface
8181        // every per-Aplicacao entrada consumer routes through, peer
8182        // of the sibling `validate` per-`:entrada` shape-and-
8183        // membership gate migration on the same outer-composite
8184        // axis.
8185        // Route the per-`:entrada` apex-destination membership probe
8186        // through the lifted [`Entrada::destination`] accessor rather
8187        // than the raw `e.para == destination` field access — the last
8188        // un-lifted `.para` production-code read site on the per-
8189        // `:entrada` `:para` axis, sibling to the four caixa-core
8190        // consumer sites the peer 15ddd8c converge already routed
8191        // through the accessor (the three
8192        // `AplicacaoSpec::validate`-side per-`:entrada` shape-and-
8193        // membership gate sites: the `validate_entrada_para` DNS-1123
8194        // shape gate, the per-`:membros` membership lookup, and the
8195        // `EntradaTargetMissing` diagnostic-carry `String`-clone) and
8196        // the peer emit-side per-Aplicacao `HTTPRoute` per-parent-refs
8197        // `entrada.para`-projection converge at
8198        // caixa-core/src/render.rs (the `gateway_api_http_route_name`
8199        // route-name projection site). Prior to this converge the
8200        // `port_for_destination` resolver was the solitary consumer
8201        // bypassing the typed dispatch on the `.para` axis — the two
8202        // `caixa-mesh` per-`(HTTPRoute, CNP)` emit sites at
8203        // caixa-mesh/src/lib.rs:3173 (`entrada.destination()`) and
8204        // caixa-mesh/src/lib.rs:2739 (`c.destination()`) that already
8205        // reach through the same accessor family compose with this
8206        // resolver at the emit boundary via the apex-identity
8207        // invariant `spec.port_for_destination(entrada.destination())
8208        // == entrada.port` the sibling
8209        // [`port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`]
8210        // pin pins across four permutations. A future extension of the
8211        // `:entrada :para` axis to a richer author surface (a per-
8212        // cluster alias overlay the operator pins through a future
8213        // `:placement`-scoped slot, a namespace-qualified rewrite the
8214        // M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
8215        // per-CR, a `:entrada :para-aliases` overlay MESH-COMPOSITION
8216        // §III.2 acknowledges) that lands on the accessor would silently
8217        // disagree between this resolver and the two `caixa-mesh` emit
8218        // sites — an author-declared `:para "cart"` value the accessor
8219        // rewrote to `"cart-v2"` under a future canary arm would leave
8220        // the resolver's membership arm falling through to
8221        // `DEFAULT_SERVICO_PORT` (matching against the raw un-aliased
8222        // `.para`) while the peer emit-site consumers landed on the
8223        // accessor-projected value at `caixa-mesh/src/lib.rs:3173` and
8224        // silently disagreed on which destination port a given typed
8225        // `:entrada` resolves to at cluster-apply time. Pinned by the
8226        // drift-detection test
8227        // [`port_for_destination_apex_arm_routes_through_destination_accessor`]
8228        // below.
8229        self.entrada()
8230            .filter(|e| e.destination() == destination)
8231            .map_or(DEFAULT_SERVICO_PORT, Entrada::port)
8232    }
8233}
8234
8235/// Cross-slot coherence gate on the Aplicacao graph: no `:membros :caixa`
8236/// entry may name the Aplicacao's own `:nome`.
8237///
8238/// An Aplicacao that lists itself as a member is a degenerate self-edge in
8239/// the typed graph — the application graph is a DAG rooted at the Aplicacao
8240/// (MESH-COMPOSITION §III.1 names `:membros` as the set of *constituent*
8241/// Servicos that compose the app; an Aplicacao is never its own constituent),
8242/// and the lacre pipeline's closure-resolution would otherwise be handed a
8243/// node that is its own parent: a one-node cycle it either rejects far from
8244/// the source `caixa.lisp` (the resolver detecting infinite recursion on the
8245/// closure walk) or, worse, recurses on until it exhausts the lacre stack.
8246/// Because every `:nome` is a globally-unique substrate identity (DNS-1123
8247/// label + lacre closure root), a member whose `:caixa` equals the
8248/// Aplicacao's `:nome` *is* the Aplicacao itself, not a coincidentally-named
8249/// peer.
8250///
8251/// Lives outside [`AplicacaoSpec::validate`] because the typed view carries
8252/// the membros but not the parent `:nome`; mirrors the cross-slot precedence
8253/// gate `validate_upgrade_from_against_versao` and the supervision-tree
8254/// self-parent gate `crate::supervisor::validate_no_self_supervision`
8255/// (ad4abf1) — the same "an edge from a graph node to itself is structurally
8256/// not a tree/mesh edge" discipline, here on the second typed-graph axis
8257/// (the Aplicacao :membros set; the supervision-tree :children list was the
8258/// first). Closes the kind ↔ self-edge coverage on both typed-graph kinds:
8259/// every validated Supervisor's children are distinct from its `:nome`,
8260/// every validated Aplicacao's membros are distinct from its `:nome`. The
8261/// transitive consequence is that `:entrada :para` and `:contratos`
8262/// `:de`/`:para` — already gated to be members of `:membros` — also cannot
8263/// name the Aplicacao itself, without re-deriving the partition.
8264pub fn validate_no_self_membership(
8265    membros: &[Membro],
8266    parent_nome: &str,
8267) -> Result<(), AplicacaoError> {
8268    for m in membros {
8269        if m.nome() == parent_nome {
8270            return Err(AplicacaoError::MembroIsSelfAplicacao {
8271                caixa: parent_nome.to_string(),
8272            });
8273        }
8274    }
8275    Ok(())
8276}
8277
8278#[derive(Debug, Error, PartialEq, Eq)]
8279pub enum AplicacaoError {
8280    #[error("Aplicacao must declare at least one :membros entry")]
8281    NoMembros,
8282    #[error(
8283        ":membros entry has empty :caixa (every member must name a Servico; \
8284         omit the entry instead of carrying an empty name)"
8285    )]
8286    MembroCaixaEmpty,
8287    #[error(
8288        ":membros entry :caixa {caixa:?} is not a valid DNS-1123 label: {reason} \
8289         (the K8s apiserver enforces this rule on every `metadata.name` / Service \
8290         name / label value the member name lands in; use a lowercase \
8291         alphanumeric + hyphen identifier like `\"checkout\"` or `\"cart-v2\"`)"
8292    )]
8293    MembroCaixaInvalid { caixa: String, reason: String },
8294    #[error(
8295        ":membros entry {caixa:?} has empty :versao (every member must pin a \
8296         semver constraint that resolves through the lacre pipeline)"
8297    )]
8298    MembroVersaoEmpty { caixa: String },
8299    #[error(
8300        ":membros entry {caixa:?} :versao {versao:?} is not a valid semver \
8301         requirement: {reason} (use Cargo-shaped forms like `\"^0.1\"`, \
8302         `\"~0.1.2\"`, `\"0.1.0\"`, or `\"*\"` — the same shape `:deps :versao` \
8303         carries; the lacre pipeline resolves both through the same parser)"
8304    )]
8305    MembroVersaoInvalid {
8306        caixa: String,
8307        versao: String,
8308        reason: String,
8309    },
8310    #[error(
8311        ":membros entry {caixa:?} appears more than once (the graph node set \
8312         is a set, not a multiset; duplicate members produce duplicate \
8313         programs.yaml entries and ambiguous :contratos membership lookups)"
8314    )]
8315    MembroDuplicate { caixa: String },
8316    #[error(
8317        "aplicacao {caixa:?} lists itself as a :membros entry — an Aplicacao is \
8318         never its own constituent Servico (the application graph is a DAG rooted \
8319         at the Aplicacao; :membros names the *other* caixas that compose the \
8320         app, not the app itself). Since every :nome is a globally-unique \
8321         substrate identity, a member naming the Aplicacao's own :nome is a \
8322         one-node lacre-closure recursion, not a coincidentally-named peer; \
8323         drop the self-referential :membros entry or rename it to the actual \
8324         constituent caixa."
8325    )]
8326    MembroIsSelfAplicacao { caixa: String },
8327    #[error(
8328        "contrato {slot} is empty (every :contratos entry's :de and :para must name a \
8329         caixa declared in :membros; omit the contract or fill the {slot} field with a \
8330         member name)"
8331    )]
8332    ContratoCaixaEmpty { slot: &'static str },
8333    #[error(
8334        "contrato {slot} {caixa:?} is not a valid DNS-1123 label: {reason} (every \
8335         :contratos {slot} value names a member of :membros, which is itself a \
8336         DNS-1123 label per the K8s apiserver's `metadata.name` rule on every \
8337         object the member name lands in — Service, Pod, identity-based Cilium \
8338         selector; use a lowercase alphanumeric + hyphen identifier like \
8339         `\"checkout\"` or `\"cart-v2\"`)"
8340    )]
8341    ContratoCaixaInvalid {
8342        slot: &'static str,
8343        caixa: String,
8344        reason: String,
8345    },
8346    #[error("contrato references caixa {caixa:?} not declared in :membros")]
8347    ContratoMemberMissing { caixa: String },
8348    #[error(
8349        "contrato {caixa:?} → {caixa:?} (:wit {wit:?}) is a self-edge — a :contratos \
8350         entry is an inter-Servico contract whose :de and :para must name distinct \
8351         :membros; a Servico's calls to itself are in-process, not mesh edges (drop \
8352         the contract, or point :para at the member it actually calls)"
8353    )]
8354    ContratoSelfLoop { caixa: String, wit: String },
8355    #[error("contrato {de:?} → {para:?} has empty :wit")]
8356    EmptyWit { de: String, para: String },
8357    #[error(
8358        "contrato {de:?} → {para:?} :wit {wit:?} is not a valid WIT world reference: \
8359         {reason} (the substrate dispatches `:wit` values on the canonical \
8360         lowercase `<namespace>:<package>(/<interface>)?(@<version>)?` shape — \
8361         `wasi:http/proxy`, `nats:pub-sub`, `wasi:keyvalue/store` — and silently \
8362         demotes unmatched shapes to a capability-only L4 edge; use a lowercase \
8363         kebab-case identifier per segment)"
8364    )]
8365    ContratoWitInvalid {
8366        de: String,
8367        para: String,
8368        wit: String,
8369        reason: String,
8370    },
8371    #[error(
8372        ":entrada :para is empty (every :entrada must route to a caixa declared in \
8373         :membros; fill the :para field with a member name)"
8374    )]
8375    EntradaParaEmpty,
8376    #[error(
8377        ":entrada :para {para:?} is not a valid DNS-1123 label: {reason} (every \
8378         :entrada :para value names a member of :membros, which is itself a DNS-1123 \
8379         label per the K8s apiserver's `metadata.name` rule on every object the \
8380         member name lands in — Service backendRefs, HTTPRoute spec, identity-based \
8381         Cilium selector; use a lowercase alphanumeric + hyphen identifier like \
8382         `\"checkout\"` or `\"cart-v2\"`)"
8383    )]
8384    EntradaParaInvalid { para: String, reason: String },
8385    #[error(":entrada routes to caixa {para:?} not declared in :membros")]
8386    EntradaMemberMissing { para: String },
8387    #[error(":entrada must declare a non-empty :host")]
8388    EmptyEntradaHost,
8389    #[error(
8390        ":entrada :host {host:?} is not a valid Gateway API v1 Hostname: {reason} \
8391         (the K8s apiserver enforces the same shape on Gateway `Listener.hostname` and \
8392         `HTTPRoute.spec.hostnames` at admission time; use a lowercase RFC 1123 DNS name \
8393         like `\"checkout.quero.cloud\"` or `\"*.quero.cloud\"`)"
8394    )]
8395    EntradaHostInvalid { host: String, reason: String },
8396    #[error(":entrada :port must be in 1..=65535, got 0")]
8397    EntradaPortZero,
8398    #[error(":entrada :paths entry is empty (use the empty list to match all)")]
8399    EntradaPathEmpty,
8400    #[error(
8401        ":entrada :paths entry {path:?} must start with `/` (Gateway API PathPrefix invariant)"
8402    )]
8403    EntradaPathNotAbsolute { path: String },
8404    #[error(
8405        ":entrada :paths entry {path:?} is not a valid Gateway API v1 HTTPPathMatch \
8406         value: {reason} (the K8s apiserver enforces the same shape on \
8407         `HTTPRoute.spec.rules[].matches[].path.value` at admission time; use a \
8408         single-`/`-prefixed printable-ASCII path like `\"/api/cart\"` — RFC 3986 \
8409         requires percent-encoding `%XX` for non-ASCII and whitespace)"
8410    )]
8411    EntradaPathInvalid { path: String, reason: String },
8412    #[error(":entrada :paths entry {path:?} appears more than once")]
8413    EntradaPathDuplicate { path: String },
8414    #[error(
8415        ":placement {estrategia} requires at least one :clusters entry \
8416         (Replicated/SingleNode: hosting/takeover candidates; Sharded: shard pool)"
8417    )]
8418    PlacementWithoutClusters { estrategia: PlacementStrategy },
8419    #[error(":placement :clusters entry is empty (cluster names must be non-empty)")]
8420    PlacementClusterEmpty,
8421    #[error(
8422        ":placement :clusters entry {cluster:?} is not a valid DNS-1123 label: {reason} \
8423         (cluster names land in the K8s context keying every per-cluster `kubeconfig`, \
8424         in the `lareira-fleet-programs` aggregator's `clusters[]` filter, and in the \
8425         future M4 cross-cluster fan-out's per-entry namespace prefix / cluster identity \
8426         — each enforces the DNS-1123 label rule; use a lowercase alphanumeric + hyphen \
8427         identifier like `\"rio\"` or `\"mar-east\"`)"
8428    )]
8429    PlacementClusterInvalid { cluster: String, reason: String },
8430    #[error(":placement :clusters entry {cluster:?} appears more than once")]
8431    PlacementClusterDuplicate { cluster: String },
8432    #[error(
8433        ":placement :affinity must be non-empty when set (omit :affinity to express \
8434         `no placement hint`)"
8435    )]
8436    PlacementAffinityEmpty,
8437    #[error(
8438        ":placement :affinity {affinity:?} is not a valid DNS-1123 label: {reason} \
8439         (placement hints land verbatim in the M3 Adaptive compression overlay's \
8440         `placement.affinity` field and in every future M4 placement-engine routing \
8441         axis keying off the hint as a K8s `app.pleme.io/affinity-hint=<value>` label \
8442         selector — both enforce the DNS-1123 label rule on admission; use a \
8443         lowercase alphanumeric + hyphen hint like `\"data-locality\"`, \
8444         `\"low-latency\"`, or `\"anti-affinity\"`)"
8445    )]
8446    PlacementAffinityInvalid { affinity: String, reason: String },
8447    #[error(":placement Sharded requires :shard-key")]
8448    ShardedWithoutKey,
8449    #[error(
8450        ":placement Sharded :shard-key must be non-empty (a `Some(\"\")` shard key \
8451         hashes every entity onto the same shard, defeating sharding entirely)"
8452    )]
8453    ShardedKeyEmpty,
8454    #[error(
8455        ":placement Sharded :shard-key {shard_key:?} is not a valid Akka-style \
8456         entity-id extractor expression: {reason} (the future M4 Akka-style \
8457         cluster-sharding reconciler — MESH-COMPOSITION §II.4 — reads `:shard-key` \
8458         as a single-token property reference and hashes the extracted entity ID \
8459         to compute shard placement; use a printable-ASCII extractor expression \
8460         like `\"tenantId\"`, `\"$tenantId\"`, `\"metadata.tenantId\"`, or \
8461         `\"${{tenant}}\"`)"
8462    )]
8463    ShardKeyInvalid { shard_key: String, reason: String },
8464    #[error(
8465        ":placement {estrategia} carries :shard-key {shard_key:?} — only :estrategia \
8466         Sharded consumes :shard-key (hash-keyed entity distribution, Akka cluster-sharding \
8467         convention); :estrategia Replicated runs every cluster active-active and \
8468         :estrategia SingleNode takes over a single cluster at a time (Erlang/OTP \
8469         distributed-app convention) — both ignore the slot. Drop :shard-key, or switch \
8470         to :estrategia Sharded if hash-keyed routing is the intent"
8471    )]
8472    ShardKeyOnNonSharded {
8473        estrategia: PlacementStrategy,
8474        shard_key: String,
8475    },
8476    #[error("contrato {de:?} → {para:?} (:wit {wit:?}) is missing required `:{expected}` field")]
8477    ContratoMissingTarget {
8478        de: String,
8479        para: String,
8480        wit: String,
8481        expected: &'static str,
8482    },
8483    #[error(
8484        "contrato {de:?} → {para:?} (:wit {wit:?}) carries the wrong target field — \
8485         expected `:{expected}` only"
8486    )]
8487    ContratoWrongTarget {
8488        de: String,
8489        para: String,
8490        wit: String,
8491        expected: &'static str,
8492    },
8493    #[error(
8494        "HTTP contrato {de:?} → {para:?} :endpoint is empty (use a non-empty path \
8495         like `/charge`; an empty endpoint renders as a `path: \"\"` Cilium L7 rule \
8496         that matches no traffic and silently drops every request)"
8497    )]
8498    ContratoEndpointEmpty { de: String, para: String },
8499    #[error(
8500        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} must start with `/` \
8501         (Cilium L7 :path + Gateway API PathPrefix invariant — same shape required of \
8502         :entrada :paths)"
8503    )]
8504    ContratoEndpointNotAbsolute {
8505        de: String,
8506        para: String,
8507        endpoint: String,
8508    },
8509    #[error(
8510        "HTTP contrato {de:?} → {para:?} :endpoint {endpoint:?} is not a valid \
8511         Cilium L7 `path:` / Gateway API v1 HTTPPathMatch value: {reason} (caixa-mesh \
8512         emits the :endpoint verbatim as the Cilium L7 `path:` rule at \
8513         caixa-mesh/src/lib.rs:311; the K8s apiserver enforces the same HTTPPathMatch \
8514         shape on `:entrada :paths`. Use a single-`/`-prefixed printable-ASCII path \
8515         like `\"/charge\"` — RFC 3986 requires percent-encoding `%XX` for non-ASCII \
8516         and whitespace)"
8517    )]
8518    ContratoEndpointInvalid {
8519        de: String,
8520        para: String,
8521        endpoint: String,
8522        reason: String,
8523    },
8524    #[error(
8525        "pub-sub contrato {de:?} → {para:?} :subject is empty (publish without a \
8526         subject is a no-op subscribe; omit :subject only if the WIT world is not \
8527         pub-sub-shaped)"
8528    )]
8529    ContratoSubjectEmpty { de: String, para: String },
8530    #[error(
8531        "pub-sub contrato {de:?} → {para:?} :subject {subject:?} is not a valid \
8532         NATS subject: {reason} (the NATS server's subject parser enforces the \
8533         same shape — `.`-separated tokens of `[A-Za-z0-9_-]`, with the `*` \
8534         single-token and `>` multi-token wildcards — at publish/subscribe time; \
8535         use a token-by-token form like `\"checkout.events.charge.failed\"` or \
8536         `\"orders.*.completed\"` — a malformed subject silently drops every \
8537         message at runtime far from the source caixa.lisp)"
8538    )]
8539    ContratoSubjectInvalid {
8540        de: String,
8541        para: String,
8542        subject: String,
8543        reason: String,
8544    },
8545    #[error(
8546        "store contrato {de:?} → {para:?} :slot is empty (an empty slot template \
8547         addresses the bucket root, defeating the per-key isolation the slot exists \
8548         for; omit :slot only if the WIT world is not store-shaped)"
8549    )]
8550    ContratoSlotEmpty { de: String, para: String },
8551    #[error(
8552        "store contrato {de:?} → {para:?} :slot {slot:?} is not a valid \
8553         WASI keyvalue store slot template: {reason} (the substrate enforces \
8554         the printable-ASCII intersection-floor every kv backend admits — \
8555         use a single-token path / template expression like `\"checkout/$orderId\"`, \
8556         `\"users:{{tenant}}/{{id}}\"`, or `\"session.tokens.<sid>\"`; RFC 3986 requires \
8557         percent-encoding `%XX` for non-ASCII and whitespace — a malformed \
8558         slot either gets rejected on write by strict backends or silently \
8559         corrupts the next read on permissive ones, far from the source caixa.lisp)"
8560    )]
8561    ContratoSlotInvalid {
8562        de: String,
8563        para: String,
8564        slot: String,
8565        reason: String,
8566    },
8567    #[error(
8568        "synchronous :contratos form a cycle ({}); break with a NATS pub-sub edge \
8569         or an event-sourced indirection (MESH-COMPOSITION §III.3)",
8570        cycle.join(" → ")
8571    )]
8572    ContratoCycle { cycle: Vec<String> },
8573    #[error(
8574        ":contratos entry {de:?} → {para:?} (:wit {wit:?} {target}) appears more \
8575         than once (the typed graph edges are a set, not a multiset; duplicate \
8576         contracts would render as colliding `CiliumNetworkPolicy` `metadata.name` \
8577         values that K8s admission rejects far from the source caixa.lisp)"
8578    )]
8579    ContratoDuplicate {
8580        de: String,
8581        para: String,
8582        wit: String,
8583        target: String,
8584    },
8585    #[error(
8586        ":politicas :timeout must be > 0 (Envoy interprets a zero timeout as `infinite`, \
8587         contradicting MESH-COMPOSITION §V `no infinite blocking`); omit :timeout to \
8588         express `no per-call deadline on this axis`"
8589    )]
8590    PolicyTimeoutZero,
8591    #[error(
8592        ":politicas :retries must be > 0 when set; omit :retries to express \
8593         `no retries on transient failure`"
8594    )]
8595    PolicyRetriesZero,
8596    #[error(
8597        ":politicas :retries ({retries}) exceeds the mesh-policy ceiling \
8598         (POLICY_RETRIES_MAX = 10) — a value above this cap turns the typed \
8599         retry policy into a thundering-herd amplification vector on transient \
8600         failure (one caller request fans out to `(retries+1)^depth` server-side \
8601         calls across the synchronous-:contratos subgraph), exactly the failure \
8602         mode AWS App Mesh's `maxRetries ≤ 10` schema cap exists to prevent. \
8603         Pin a value in 1..=10 (Envoy / Istio production playbooks recommend ≤ 5) \
8604         or omit :retries to disable retries entirely"
8605    )]
8606    PolicyRetriesExceedsCap { retries: u32 },
8607    #[error(
8608        ":politicas :circuit-breaker :max-failures must be > 0 (a zero-threshold \
8609         breaker trips on the first call); omit :circuit-breaker to disable it"
8610    )]
8611    PolicyBreakerZeroFailures,
8612    #[error(
8613        ":politicas :circuit-breaker :max-failures ({max_failures}) exceeds the \
8614         mesh-policy ceiling (POLICY_BREAKER_MAX_FAILURES_MAX = 1000) — a value \
8615         above this cap turns the typed breaker policy into a no-op: the trip \
8616         threshold is structurally so high that no realistic failures-per-:window \
8617         traffic shape can reach it, so the breaker never trips and every typed-slot \
8618         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, \
8619         Envoy's outlier_detection.consecutive_5xx) emits a protection that is \
8620         structurally never enforced. Pin a value in 1..=1000 (Hystrix / Istio / \
8621         Envoy / Polly / Resilience4j production playbooks recommend 5..=50) or \
8622         omit :circuit-breaker to disable the breaker entirely"
8623    )]
8624    PolicyBreakerMaxFailuresExceedsCap { max_failures: u32 },
8625    #[error(
8626        ":politicas :circuit-breaker :window must be > 0 (a zero-window breaker \
8627         tracks no failures); omit :circuit-breaker to disable it"
8628    )]
8629    PolicyBreakerZeroWindow,
8630    #[error(
8631        ":politicas :rate-limit rate must be > 0 (a zero-rate limit denies every \
8632         request); omit :rate-limit to disable rate limiting"
8633    )]
8634    PolicyRateLimitZero,
8635    #[error(
8636        ":politicas :rate-limit rate ({rate}) exceeds the mesh-policy ceiling \
8637         (POLICY_RATE_LIMIT_MAX = 1000000) — a value above this cap turns the typed \
8638         rate-limit policy into a no-op limiter: the token-bucket capacity is \
8639         structurally so high that no realistic per-edge traffic shape can drain it, \
8640         so the limiter never trips and every typed-slot consumer (the future \
8641         CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8642         local_rate_limit.token_bucket.max_tokens) emits a rate-limit declaration \
8643         that is structurally never enforced. Pin a value in 1..=1000000 (Envoy / \
8644         Istio / Kong / NGINX production playbooks recommend 10..=10000 RPS; \
8645         Cloudflare / AWS API Gateway typical 10000..=100000 per-minute; \
8646         Cloudflare Enterprise rate-plans run to ~1M per-hour) or omit :rate-limit \
8647         to disable rate limiting entirely"
8648    )]
8649    PolicyRateLimitExceedsCap { rate: u32 },
8650    #[error(
8651        ":politicas :rate-limit :window must be exactly 1s, 1m (60s), or 1h (3600s) — \
8652         the canonical authoring forms `\"<n>/s\"`, `\"<n>/m\"`, `\"<n>/h\"` the \
8653         rate-limit codec round-trips losslessly; got {window:?} which renders to a \
8654         non-round-trippable form (omit :rate-limit to disable, or pick one of the \
8655         three canonical windows)"
8656    )]
8657    PolicyRateLimitWindowNotCanonical { window: Duration },
8658    #[error(
8659        ":politicas :timeout must be an integer number of milliseconds — the canonical \
8660         authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} the shared \
8661         duration codec round-trips losslessly; got {timeout:?} which carries a \
8662         sub-millisecond residue that either truncates to a different `Duration` on \
8663         re-parse (e.g. `Duration::from_micros(1500)` → renders `\"1ms\"` → parses back \
8664         to 1ms, not 1.5ms) or renders as `\"0s\"` (sub-millisecond magnitude) the \
8665         zero-floor gate rejects on re-validate. Pick an integer-millisecond magnitude \
8666         (e.g. `\"30s\"`, `\"1500ms\"`, `\"2m\"`, `\"1h\"`)"
8667    )]
8668    PolicyTimeoutNotCanonical { timeout: Duration },
8669    #[error(
8670        ":politicas :timeout ({timeout:?}) exceeds the mesh-policy ceiling \
8671         (POLICY_TIMEOUT_MAX = 1h = 3600s) — a value above this cap turns the typed \
8672         per-call deadline into a nominal-only contract (Envoy / Cilium L7 timeout \
8673         overlays carry a deadline so long no realistic synchronous-:contratos \
8674         traversal can reach it), and the MESH-COMPOSITION §V \"no infinite blocking\" \
8675         CSE invariant degenerates to enforcement only at the per-Servico \
8676         `:limits :wall-clock` layer — far above the per-edge granularity the typed \
8677         `:politicas :timeout` slot is meant to express. Pin a value in 1ms..=1h \
8678         (Envoy / Istio / Linkerd / AWS App Mesh production playbooks all recommend \
8679         ≤ 60s; the Kubernetes ingress-nginx documented `proxy_read_timeout` band \
8680         maxes out at the same `3600s` ceiling) or omit :timeout to express \
8681         `no per-call deadline on this axis` (the synchronous-call deadline then \
8682         relies entirely on the per-Servico `:limits :wall-clock` axis)"
8683    )]
8684    PolicyTimeoutExceedsCap { timeout: Duration },
8685    #[error(
8686        ":politicas :circuit-breaker :window must be an integer number of milliseconds — \
8687         the canonical authoring form `\"<integer><unit>\"` for unit ∈ {{`ms`,`s`,`m`,`h`}} \
8688         the shared duration codec round-trips losslessly; got {window:?} which carries a \
8689         sub-millisecond residue that either truncates to a different `Duration` on \
8690         re-parse or renders as `\"0s\"` the zero-floor gate rejects on re-validate. \
8691         Pick an integer-millisecond magnitude (e.g. `\"60s\"`, `\"500ms\"`, `\"2m\"`)"
8692    )]
8693    PolicyBreakerWindowNotCanonical { window: Duration },
8694    #[error(
8695        ":politicas :circuit-breaker :window ({window:?}) exceeds the mesh-policy ceiling \
8696         (POLICY_BREAKER_WINDOW_MAX = 1h = 3600s) — a value above this cap turns the typed \
8697         rolling-window breaker into a lifetime-counter breaker: the failure-counting window \
8698         is structurally so long that transient failures are never forgotten, the breaker \
8699         trips once and stays tripped for the lifetime of the component, and every typed-slot \
8700         consumer (the future CiliumClusterwideEnvoyConfig per-:politicas overlay, Envoy's \
8701         outlier_detection.interval) emits a \"rolling\" window that exists only nominally. \
8702         Pin a value in 1ms..=1h (Hystrix / resilience4j / Istio / Envoy production playbooks \
8703         default to 10s; AWS App Mesh maxes out at ~5m) or omit :circuit-breaker to disable \
8704         the breaker entirely"
8705    )]
8706    PolicyBreakerWindowExceedsCap { window: Duration },
8707}
8708
8709#[cfg(test)]
8710mod tests {
8711    use super::*;
8712
8713    fn membro(name: &str, ver: &str) -> Membro {
8714        Membro {
8715            caixa: name.into(),
8716            versao: ver.into(),
8717        }
8718    }
8719
8720    fn contract_http(de: &str, para: &str, ep: &str) -> WitContract {
8721        WitContract {
8722            de: de.into(),
8723            para: para.into(),
8724            wit: "wasi:http/proxy".into(),
8725            endpoint: Some(ep.into()),
8726            subject: None,
8727            slot: None,
8728        }
8729    }
8730
8731    fn three_member_spec() -> AplicacaoSpec {
8732        AplicacaoSpec {
8733            membros: vec![
8734                membro("catalog", "^0.1"),
8735                membro("cart", "^0.1"),
8736                membro("payment", "^0.2"),
8737            ],
8738            contratos: vec![
8739                contract_http("cart", "catalog", "/products/:id"),
8740                contract_http("cart", "payment", "/charge"),
8741            ],
8742            politicas: MeshPolicy {
8743                timeout: Some(Duration::from_secs(30)),
8744                retries: Some(3),
8745                mtls_required: Some(true),
8746                ..Default::default()
8747            },
8748            placement: Placement {
8749                estrategia: PlacementStrategy::Replicated,
8750                clusters: vec!["rio".into(), "mar".into()],
8751                affinity: Some("data-locality".into()),
8752                shard_key: None,
8753            },
8754            entrada: Some(Entrada {
8755                host: "checkout.quero.cloud".into(),
8756                para: "cart".into(),
8757                paths: vec!["/api/cart".into(), "/api/products".into()],
8758                port: 8080,
8759            }),
8760        }
8761    }
8762
8763    #[test]
8764    fn happy_path_validates() {
8765        three_member_spec().validate().unwrap();
8766    }
8767
8768    #[test]
8769    fn rejects_empty_membros() {
8770        let mut s = three_member_spec();
8771        s.membros = vec![];
8772        assert_eq!(s.validate().unwrap_err(), AplicacaoError::NoMembros);
8773    }
8774
8775    #[test]
8776    fn rejects_empty_membro_caixa() {
8777        // A `:caixa ""` entry has no name to render into programs.yaml
8778        // and no caixa.lisp to resolve at lacre time.
8779        let mut s = three_member_spec();
8780        s.membros[1].caixa = String::new();
8781        assert_eq!(s.validate().unwrap_err(), AplicacaoError::MembroCaixaEmpty);
8782    }
8783
8784    #[test]
8785    fn rejects_empty_membro_versao() {
8786        // A `:versao ""` entry can't pin a semver constraint, so the
8787        // lacre pipeline fails far from the source.
8788        let mut s = three_member_spec();
8789        s.membros[2].versao = String::new();
8790        let err = s.validate().unwrap_err();
8791        assert!(
8792            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "payment"),
8793            "got {err:?}"
8794        );
8795    }
8796
8797    #[test]
8798    fn rejects_duplicate_membro_caixa() {
8799        // Two `:membros` entries with the same `:caixa` collapse to one
8800        // node in the membership HashSet, which masks `:contratos`
8801        // membership errors and produces duplicate programs.yaml entries.
8802        let mut s = three_member_spec();
8803        s.membros.push(membro("cart", "^0.2"));
8804        let err = s.validate().unwrap_err();
8805        assert!(
8806            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
8807            "got {err:?}"
8808        );
8809    }
8810
8811    #[test]
8812    fn rejects_invalid_membro_versao_requirement() {
8813        // The fail-before-pass-after pin: a non-empty but malformed
8814        // semver requirement (`"^bad-version"`) silently passed
8815        // `validate()` on every pre-gate codebase because the prior
8816        // shape only refused the empty string. The parse failure
8817        // surfaced far downstream at lacre-resolve time with a
8818        // `semver::Error` that didn't name which `:membros` entry
8819        // carried the typo. The new gate moves the check to caixa-build
8820        // time at the source caixa.lisp.
8821        let mut s = three_member_spec();
8822        s.membros[2].versao = "^bad-version".into();
8823        let err = s.validate().unwrap_err();
8824        assert!(
8825            matches!(
8826                err,
8827                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8828                    if caixa == "payment" && versao == "^bad-version"
8829            ),
8830            "got {err:?}"
8831        );
8832    }
8833
8834    #[test]
8835    fn rejects_membro_versao_with_double_caret_typo() {
8836        // `"^^0.1"` is the canonical doubled-caret typo — looks like a
8837        // Cargo-shaped requirement on first glance but fails the parser
8838        // because semver doesn't accept stacked operators. Pin this
8839        // adjacent-shape footgun explicitly so a future relaxation that
8840        // accepts "looks-canonical-but-isn't" forms surfaces here.
8841        let mut s = three_member_spec();
8842        s.membros[0].versao = "^^0.1".into();
8843        let err = s.validate().unwrap_err();
8844        assert!(
8845            matches!(
8846                err,
8847                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8848                    if caixa == "catalog" && versao == "^^0.1"
8849            ),
8850            "got {err:?}"
8851        );
8852    }
8853
8854    #[test]
8855    fn rejects_membro_versao_with_v_prefixed_tag() {
8856        // `"v0.1"` is the canonical "git-tag-shape leaking into the
8857        // semver requirement slot" typo — an author copies the
8858        // publish-side git-tag string verbatim into `:versao`, but
8859        // Cargo's semver parser rejects the leading `v` (only digits +
8860        // canonical operators are valid in the major-version
8861        // position). The gate's diagnostic names which member entry
8862        // carried the v-prefix so the fix is one edit, not a grep
8863        // through every member's `:versao`. (Note: bare `x`-glob
8864        // shorthands like `^0.1.x` are *accepted* by the semver crate
8865        // as an `*` wildcard on the patch axis — they're a Cargo-side
8866        // valid shape, not a typo, so the gate intentionally lets them
8867        // through.)
8868        let mut s = three_member_spec();
8869        s.membros[1].versao = "v0.1".into();
8870        let err = s.validate().unwrap_err();
8871        assert!(
8872            matches!(
8873                err,
8874                AplicacaoError::MembroVersaoInvalid { ref caixa, ref versao, .. }
8875                    if caixa == "cart" && versao == "v0.1"
8876            ),
8877            "got {err:?}"
8878        );
8879    }
8880
8881    #[test]
8882    fn accepts_canonical_membro_versao_forms() {
8883        // The four Cargo-shaped requirement forms `:deps :versao`
8884        // already accepts via `crate::parse_requirement` must pass the
8885        // membros gate without re-validating at the resolver layer.
8886        // Pin every leg so a future tightening of the canonical set
8887        // surfaces here as a test failure.
8888        for form in [
8889            "^0.1",      // caret — minor-range pin (the most common shape)
8890            "~0.1.2",    // tilde — patch-range pin
8891            "0.1.0",     // exact — single-version pin
8892            "*",         // wildcard — explicitly any-version (semver::VersionReq::STAR)
8893            ">=0.1, <2", // multi-range — comma-separated comparators
8894        ] {
8895            let mut s = three_member_spec();
8896            for m in &mut s.membros {
8897                m.versao = form.into();
8898            }
8899            s.validate()
8900                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
8901        }
8902    }
8903
8904    #[test]
8905    fn membro_versao_empty_takes_precedence_over_invalid() {
8906        // Order pin: the existing `MembroVersaoEmpty` diagnostic
8907        // (which doesn't try to parse) fires before the new
8908        // `MembroVersaoInvalid` parse-side diagnostic, so an empty
8909        // `:versao` keeps its narrower error message — `parse_requirement`
8910        // would also reject `""`, but the empty-string arm is the more
8911        // self-locating diagnostic for the author.
8912        let mut s = three_member_spec();
8913        s.membros[1].versao = String::new();
8914        let err = s.validate().unwrap_err();
8915        assert!(
8916            matches!(err, AplicacaoError::MembroVersaoEmpty { ref caixa } if caixa == "cart"),
8917            "got {err:?}"
8918        );
8919    }
8920
8921    #[test]
8922    fn membro_versao_invalid_fires_before_duplicate_check() {
8923        // Order pin: a malformed requirement on a non-duplicate entry
8924        // surfaces *its own* diagnostic (which names the offending
8925        // `:versao` string), even when a later entry would otherwise
8926        // collapse onto an earlier name. The per-entry shape gate runs
8927        // inline before the duplicate-key insert, parallel to
8928        // `membros_validation_runs_before_contratos_membership_check`
8929        // and `duplicate_contrato_gate_runs_after_target_shape_check`.
8930        let mut s = three_member_spec();
8931        s.membros[0].versao = "^bad".into();
8932        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
8933        let err = s.validate().unwrap_err();
8934        assert!(
8935            matches!(
8936                err,
8937                AplicacaoError::MembroVersaoInvalid { ref caixa, .. } if caixa == "catalog"
8938            ),
8939            "got {err:?}"
8940        );
8941    }
8942
8943    #[test]
8944    fn membro_versao_invalid_diagnostic_carries_offending_versao() {
8945        // The diagnostic-shape pin: the error names the offending
8946        // `:versao` value verbatim so the author can grep their
8947        // caixa.lisp without re-running the build, and carries a
8948        // non-empty `reason` from `semver::VersionReq::parse` so the
8949        // parser's own wording flows through to the diagnostic.
8950        let mut s = three_member_spec();
8951        s.membros[2].versao = "not-a-req".into();
8952        let err = s.validate().unwrap_err();
8953        let AplicacaoError::MembroVersaoInvalid {
8954            caixa,
8955            versao,
8956            reason,
8957        } = err
8958        else {
8959            panic!("expected MembroVersaoInvalid, got other variant");
8960        };
8961        assert_eq!(caixa, "payment");
8962        assert_eq!(versao, "not-a-req");
8963        assert!(
8964            !reason.is_empty(),
8965            "MembroVersaoInvalid `reason` must carry the parser's wording verbatim"
8966        );
8967    }
8968
8969    #[test]
8970    fn membro_versao_invalid_runs_before_contratos_check() {
8971        // A malformed `:versao` on any member must surface its own
8972        // diagnostic (which names *which* member to fix) before any
8973        // `:contratos` membership lookup raises `ContratoMemberMissing`.
8974        // The `:contratos` gate runs after `validate_membros`, so this
8975        // is structurally guaranteed — pin it explicitly so a future
8976        // refactor that reorders the gates surfaces here.
8977        let mut s = three_member_spec();
8978        s.membros[1].versao = "^^0.1".into();
8979        // Add a contrato whose `:para` doesn't exist — would normally
8980        // raise ContratoMemberMissing at the membership lookup, but
8981        // the membros gate must fire first.
8982        s.contratos
8983            .push(contract_http("cart", "phantom", "/never-reached"));
8984        let err = s.validate().unwrap_err();
8985        assert!(
8986            matches!(err, AplicacaoError::MembroVersaoInvalid { .. }),
8987            "expected MembroVersaoInvalid to fire before ContratoMemberMissing, got {err:?}"
8988        );
8989    }
8990
8991    #[test]
8992    fn membros_validation_runs_before_contratos_membership_check() {
8993        // If `:membros` carries a duplicate, the membership-collapse
8994        // would silently accept a `:contratos :para "phantom"` so long
8995        // as some entry hashes to "phantom". Pinning order: the
8996        // duplicate-membros error fires first, regardless of whether
8997        // contratos reference real members.
8998        let mut s = three_member_spec();
8999        s.membros = vec![
9000            membro("cart", "^0.1"),
9001            membro("cart", "^0.2"),
9002            membro("catalog", "^0.1"),
9003            membro("payment", "^0.1"),
9004        ];
9005        let err = s.validate().unwrap_err();
9006        assert!(
9007            matches!(err, AplicacaoError::MembroDuplicate { ref caixa } if caixa == "cart"),
9008            "got {err:?}"
9009        );
9010    }
9011
9012    #[test]
9013    fn distinct_membros_validate() {
9014        // Pin the happy-path: every `:membros` entry has a non-empty
9015        // `:caixa`, a non-empty `:versao`, and the set is duplicate-free.
9016        // The fixture already satisfies this; this test makes the
9017        // invariant explicit so a future refactor of the fixture can't
9018        // silently break the guarantee.
9019        three_member_spec().validate().unwrap();
9020    }
9021
9022    // ── :membros :caixa DNS-1123 label value-shape gate ───────────────────
9023
9024    #[test]
9025    fn rejects_membro_caixa_with_uppercase() {
9026        // The canonical "I copied the Servico's display name verbatim"
9027        // typo — caixa names are lowercase per K8s DNS-1123 label rule,
9028        // but author tools often round-trip a TitleCase or CamelCase
9029        // identifier from an ADR or a sketch. Pin the diagnostic names
9030        // the offending name and suggests the lower-cased fix in one
9031        // edit, mirroring the `rejects_entrada_host_with_uppercase`
9032        // gate's shape (c7d05ec).
9033        let mut s = three_member_spec();
9034        s.membros[1].caixa = "Cart".into();
9035        let err = s.validate().unwrap_err();
9036        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9037            panic!("expected MembroCaixaInvalid, got other variant");
9038        };
9039        assert_eq!(caixa, "Cart");
9040        assert!(
9041            reason.contains("uppercase"),
9042            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9043        );
9044        assert!(
9045            reason.contains("\"cart\""),
9046            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
9047        );
9048    }
9049
9050    #[test]
9051    fn rejects_membro_caixa_with_underscore() {
9052        // The canonical "I'm thinking of a Python module / Postgres
9053        // table" leak — `_` is forbidden by every DNS-1123 / DNS-1035
9054        // label schema. K8s rejects `metadata.name: my_cart` at admission
9055        // time with an opaque `field is invalid` (no source-citing
9056        // diagnostic). The gate moves it to caixa-build time.
9057        let mut s = three_member_spec();
9058        s.membros[0].caixa = "my_cart".into();
9059        let err = s.validate().unwrap_err();
9060        assert!(
9061            matches!(
9062                err,
9063                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9064                    if caixa == "my_cart" && reason.contains('_')
9065            ),
9066            "got {err:?}"
9067        );
9068    }
9069
9070    #[test]
9071    fn rejects_membro_caixa_with_dot() {
9072        // A `:membros :caixa` entry is a single DNS-1123 *label*, not a
9073        // subdomain — even though K8s `metadata.name` itself accepts
9074        // dots (DNS-1123 subdomain rule), this string also lands as a
9075        // K8s Service name (DNS-1035 label — no dots) and as a label
9076        // value on identity-based Cilium selectors. The strictest floor
9077        // among the use sites wins. The "I want to namespace my member
9078        // names with `.`" intent is expressed via `-` (e.g. `cart-v2`).
9079        let mut s = three_member_spec();
9080        s.membros[2].caixa = "team.cart".into();
9081        let err = s.validate().unwrap_err();
9082        assert!(
9083            matches!(
9084                err,
9085                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9086                    if caixa == "team.cart" && reason.contains('.')
9087            ),
9088            "got {err:?}"
9089        );
9090    }
9091
9092    #[test]
9093    fn rejects_membro_caixa_with_leading_hyphen() {
9094        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
9095        // with an alphanumeric. The K8s apiserver rejects `-cart`
9096        // outright; the renderer would emit a `metadata.name: "-cart"`
9097        // that fails admission far from the source caixa.lisp.
9098        let mut s = three_member_spec();
9099        s.membros[0].caixa = "-cart".into();
9100        let err = s.validate().unwrap_err();
9101        assert!(
9102            matches!(
9103                err,
9104                AplicacaoError::MembroCaixaInvalid { ref caixa, ref reason }
9105                    if caixa == "-cart" && reason.contains("start and end")
9106            ),
9107            "got {err:?}"
9108        );
9109    }
9110
9111    #[test]
9112    fn rejects_membro_caixa_with_trailing_hyphen() {
9113        // The symmetric arm of the boundary rule. Pin separately so
9114        // both ends of the label are covered against a future relaxation
9115        // that only checks one boundary.
9116        let mut s = three_member_spec();
9117        s.membros[1].caixa = "cart-".into();
9118        let err = s.validate().unwrap_err();
9119        assert!(
9120            matches!(
9121                err,
9122                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9123                    if caixa == "cart-"
9124            ),
9125            "got {err:?}"
9126        );
9127    }
9128
9129    #[test]
9130    fn rejects_membro_caixa_with_unicode() {
9131        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9132        // (`xn--…`) by the author before it reaches K8s. The byte-by-
9133        // byte ASCII validity check rejects multi-byte UTF-8 sequences
9134        // by the first byte that fails the `[a-z0-9-]` predicate.
9135        let mut s = three_member_spec();
9136        s.membros[2].caixa = "café".into();
9137        let err = s.validate().unwrap_err();
9138        assert!(
9139            matches!(
9140                err,
9141                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9142                    if caixa == "café"
9143            ),
9144            "got {err:?}"
9145        );
9146    }
9147
9148    #[test]
9149    fn rejects_membro_caixa_with_whitespace() {
9150        // Whitespace is the canonical "I pasted from a sketch / doc"
9151        // footgun. The apiserver rejects every `metadata.name` value
9152        // carrying whitespace; pin the gate fires at the right boundary.
9153        let mut s = three_member_spec();
9154        s.membros[0].caixa = "my cart".into();
9155        let err = s.validate().unwrap_err();
9156        assert!(
9157            matches!(
9158                err,
9159                AplicacaoError::MembroCaixaInvalid { ref caixa, .. }
9160                    if caixa == "my cart"
9161            ),
9162            "got {err:?}"
9163        );
9164    }
9165
9166    #[test]
9167    fn rejects_membro_caixa_too_long() {
9168        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
9169        // pin. K8s Service name + DNS-1123 label both cap at 63 bytes
9170        // exactly. The gate's reason names both the cap and the actual
9171        // length so the author can shorten in one edit.
9172        let mut s = three_member_spec();
9173        let too_long = "a".repeat(64);
9174        s.membros[1].caixa = too_long.clone();
9175        let err = s.validate().unwrap_err();
9176        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9177            panic!("expected MembroCaixaInvalid");
9178        };
9179        assert_eq!(caixa, too_long);
9180        assert!(
9181            reason.contains("63") && reason.contains("64"),
9182            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
9183        );
9184    }
9185
9186    #[test]
9187    fn membro_caixa_max_length_validates() {
9188        // 63 bytes exactly — the K8s DNS-1123 label cap. Pin the boundary
9189        // so a future tightening (e.g. dropping to 62) surfaces here as
9190        // a regression, mirroring `entrada_host_max_length_validates`
9191        // (c7d05ec).
9192        let mut s = three_member_spec();
9193        s.membros[2].caixa = "a".repeat(63);
9194        s.entrada.as_mut().unwrap().para = "a".repeat(63);
9195        // remove contratos referencing the renamed member; they'd
9196        // raise ContratoMemberMissing otherwise
9197        s.contratos
9198            .retain(|c| c.de != "payment" && c.para != "payment");
9199        s.validate().unwrap();
9200    }
9201
9202    #[test]
9203    fn accepts_canonical_membro_caixa_forms() {
9204        // The DNS-1123 label shapes a caixa author is realistically
9205        // going to write: single-word lowercase, hyphen-joined, ending
9206        // in a digit-suffixed version (`cart-v2`), starting with a
9207        // digit (`3rd-party-shim` — DNS-1123 allows this, unlike
9208        // DNS-1035 which requires a letter at position 0), single-
9209        // character (`a` — boundary). Pin every leg so a future
9210        // tightening that bans (e.g.) digit-start identifiers surfaces
9211        // here.
9212        for form in [
9213            "checkout",
9214            "cart",
9215            "cart-v2",
9216            "a",
9217            "c0",
9218            "3rd-party-shim",
9219            "x-1-2-3-4",
9220        ] {
9221            let mut s = three_member_spec();
9222            // Renaming a member also requires updating downstream refs;
9223            // drop everything else and rebuild a minimal spec around
9224            // just the one renamed member.
9225            s.membros = vec![membro(form, "^0.1")];
9226            s.contratos = vec![];
9227            s.entrada = None;
9228            s.validate()
9229                .unwrap_or_else(|e| panic!("canonical form {form:?} must validate, got {e:?}"));
9230        }
9231    }
9232
9233    #[test]
9234    fn membro_caixa_empty_takes_precedence_over_invalid() {
9235        // Order pin: the existing `MembroCaixaEmpty` diagnostic
9236        // (which doesn't try to parse) fires before the new
9237        // `MembroCaixaInvalid` parse-side diagnostic, so an empty
9238        // `:caixa` keeps its narrower error message — the new gate
9239        // would also reject `""`, but the empty-string arm is the more
9240        // self-locating diagnostic for the author. Mirrors the
9241        // `entrada_host_empty_takes_precedence_over_invalid` pin
9242        // (c7d05ec).
9243        let mut s = three_member_spec();
9244        s.membros[1].caixa = String::new();
9245        let err = s.validate().unwrap_err();
9246        assert_eq!(err, AplicacaoError::MembroCaixaEmpty);
9247    }
9248
9249    #[test]
9250    fn membro_caixa_invalid_fires_before_versao_check() {
9251        // Order pin: an invalid-shape `:caixa` surfaces *its own*
9252        // diagnostic (which names the offending caixa name), even when
9253        // the same entry's `:versao` is also empty/invalid. The shape
9254        // gate runs first because the diagnostic is more self-locating —
9255        // an empty/invalid `:versao` on an invalid-shape caixa name is
9256        // a downstream-fix-after-the-caixa-rename concern.
9257        let mut s = three_member_spec();
9258        s.membros[1].caixa = "Cart".into();
9259        s.membros[1].versao = String::new(); // would otherwise raise MembroVersaoEmpty
9260        let err = s.validate().unwrap_err();
9261        assert!(
9262            matches!(
9263                err,
9264                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Cart"
9265            ),
9266            "got {err:?}"
9267        );
9268    }
9269
9270    #[test]
9271    fn membro_caixa_invalid_fires_before_duplicate_check() {
9272        // Order pin: a malformed-shape `:caixa` on an earlier entry
9273        // surfaces *its own* diagnostic, even when a later entry would
9274        // otherwise collapse onto a duplicate name. The per-entry shape
9275        // gate runs inline before the duplicate-key insert, parallel
9276        // to `membro_versao_invalid_fires_before_duplicate_check`.
9277        let mut s = three_member_spec();
9278        s.membros[0].caixa = "Catalog".into();
9279        s.membros.push(membro("cart", "^0.2")); // would otherwise raise MembroDuplicate
9280        let err = s.validate().unwrap_err();
9281        assert!(
9282            matches!(
9283                err,
9284                AplicacaoError::MembroCaixaInvalid { ref caixa, .. } if caixa == "Catalog"
9285            ),
9286            "got {err:?}"
9287        );
9288    }
9289
9290    #[test]
9291    fn membro_caixa_invalid_diagnostic_carries_offending_caixa() {
9292        // The diagnostic-shape pin: the error names the offending
9293        // `:caixa` value verbatim so the author can grep their
9294        // caixa.lisp without re-running the build, and carries a
9295        // non-empty `reason` naming the specific violation. Same
9296        // shape every typed-shape gate enshrines (c7d05ec's
9297        // `entrada_host_diagnostic_carries_offending_host`,
9298        // 9888b13's `membro_versao_invalid_diagnostic_carries_offending_versao`).
9299        let mut s = three_member_spec();
9300        s.membros[2].caixa = "BAD_NAME".into();
9301        let err = s.validate().unwrap_err();
9302        let AplicacaoError::MembroCaixaInvalid { caixa, reason } = err else {
9303            panic!("expected MembroCaixaInvalid");
9304        };
9305        assert_eq!(caixa, "BAD_NAME");
9306        assert!(
9307            !reason.is_empty(),
9308            "MembroCaixaInvalid `reason` must carry a parser-shaped wording"
9309        );
9310    }
9311
9312    #[test]
9313    fn rejects_contrato_with_unknown_de() {
9314        let mut s = three_member_spec();
9315        s.contratos.push(contract_http("phantom", "catalog", "/x"));
9316        let err = s.validate().unwrap_err();
9317        assert!(
9318            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9319        );
9320    }
9321
9322    #[test]
9323    fn rejects_contrato_with_unknown_para() {
9324        let mut s = three_member_spec();
9325        s.contratos.push(contract_http("cart", "phantom", "/x"));
9326        let err = s.validate().unwrap_err();
9327        assert!(
9328            matches!(err, AplicacaoError::ContratoMemberMissing { caixa } if caixa == "phantom")
9329        );
9330    }
9331
9332    #[test]
9333    fn contrato_unknown_de_diagnostic_routes_caixa_field_through_source_accessor() {
9334        // The read-path pin: the phantom-`:de` refusal arm's
9335        // `ContratoMemberMissing.caixa` carrier must be observed through
9336        // the lifted [`WitContract::source`] accessor, not the raw
9337        // `.de.clone()` field-access `String`-carry. Peer of the sibling
9338        // per-`:contratos` self-loop arm's `.source().to_string()` /
9339        // `.world_ref().to_string()` `String`-carry sites the earlier
9340        // convergence lifted onto the same accessor pair. A future
9341        // silent detour that reintroduced the raw `.de.clone()` at the
9342        // wrap envelope while the shape-gate and membership lookup
9343        // routed through the accessor would surface here as a byte-equal
9344        // miss between the fired diagnostic's `caixa:` field and the
9345        // offending edge's `.source()` — pinning the accessor as the
9346        // sole read path across the phantom-name refusal arm's arg +
9347        // wrap-envelope emit surface.
9348        let mut s = three_member_spec();
9349        let phantom = contract_http("phantom", "catalog", "/x");
9350        s.contratos.push(phantom.clone());
9351        let err = s.validate().unwrap_err();
9352        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9353            panic!("expected ContratoMemberMissing on phantom :de, got {err:?}");
9354        };
9355        assert_eq!(
9356            caixa,
9357            phantom.source(),
9358            "ContratoMemberMissing.caixa on the phantom-:de arm must \
9359             byte-equal WitContract::source — the wrap envelope must \
9360             route through the lifted accessor rather than the raw \
9361             .de.clone() field-access String-carry"
9362        );
9363    }
9364
9365    #[test]
9366    fn contrato_unknown_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9367        // The symmetric read-path pin on the `:para` phantom-name
9368        // refusal arm — same shape as the sibling `:de` pin above but
9369        // on the callee-Servico axis. Pins the wrap envelope's
9370        // `caixa:` field is observed through the lifted
9371        // [`WitContract::destination`] accessor, not the raw
9372        // `.para.clone()` field-access `String`-carry.
9373        let mut s = three_member_spec();
9374        let phantom = contract_http("cart", "phantom", "/x");
9375        s.contratos.push(phantom.clone());
9376        let err = s.validate().unwrap_err();
9377        let AplicacaoError::ContratoMemberMissing { caixa } = err else {
9378            panic!("expected ContratoMemberMissing on phantom :para, got {err:?}");
9379        };
9380        assert_eq!(
9381            caixa,
9382            phantom.destination(),
9383            "ContratoMemberMissing.caixa on the phantom-:para arm must \
9384             byte-equal WitContract::destination — the wrap envelope \
9385             must route through the lifted accessor rather than the raw \
9386             .para.clone() field-access String-carry"
9387        );
9388    }
9389
9390    #[test]
9391    fn contrato_malformed_de_diagnostic_routes_caixa_field_through_source_accessor() {
9392        // The read-path pin on the `:de` DNS-1123-malformed shape-gate
9393        // refusal arm — the `validate_contrato_caixa` arg must be
9394        // observed through the lifted [`WitContract::source`] accessor,
9395        // not the raw `&c.de` `&String`-borrow. A `BAD_NAME` `:de`
9396        // value routes through the shared
9397        // [`crate::render::require_valid_dns_1123_label`] floor with the
9398        // accessor-projected value; the fired
9399        // `AplicacaoError::ContratoCaixaInvalid.caixa` carrier byte-equals
9400        // the offending edge's `.source()`, pinning that the arg + the
9401        // downstream `caixa: caixa.to_string()` wrap route through the
9402        // same accessor's read path.
9403        let mut s = three_member_spec();
9404        let malformed = contract_http("BAD_NAME", "catalog", "/x");
9405        s.contratos.push(malformed.clone());
9406        let err = s.validate().unwrap_err();
9407        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9408            panic!("expected ContratoCaixaInvalid on malformed :de, got {err:?}");
9409        };
9410        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9411        assert_eq!(
9412            caixa,
9413            malformed.source(),
9414            "ContratoCaixaInvalid.caixa on the malformed-:de arm must \
9415             byte-equal WitContract::source — the shape-gate arg + wrap \
9416             envelope must route through the lifted accessor rather \
9417             than the raw &c.de &String-borrow"
9418        );
9419    }
9420
9421    #[test]
9422    fn contrato_malformed_para_diagnostic_routes_caixa_field_through_destination_accessor() {
9423        // Symmetric arm to the sibling `:de` malformed-shape pin above,
9424        // on the `:para` axis. Pins the shape-gate arg + wrap envelope
9425        // route through the lifted [`WitContract::destination`]
9426        // accessor. `:para` runs after the `:de` shape gate in the
9427        // canonical edge-direction order, so the `:de` value must be
9428        // well-shaped for the `:para` gate to fire — the `cart` :de is
9429        // canonical.
9430        let mut s = three_member_spec();
9431        let malformed = contract_http("cart", "BAD_NAME", "/x");
9432        s.contratos.push(malformed.clone());
9433        let err = s.validate().unwrap_err();
9434        let AplicacaoError::ContratoCaixaInvalid { slot, caixa, .. } = err else {
9435            panic!("expected ContratoCaixaInvalid on malformed :para, got {err:?}");
9436        };
9437        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9438        assert_eq!(
9439            caixa,
9440            malformed.destination(),
9441            "ContratoCaixaInvalid.caixa on the malformed-:para arm must \
9442             byte-equal WitContract::destination — the shape-gate arg + \
9443             wrap envelope must route through the lifted accessor \
9444             rather than the raw &c.para &String-borrow"
9445        );
9446    }
9447
9448    // ── :contratos :de / :para DNS-1123 label value-shape gate ──────────
9449
9450    #[test]
9451    fn rejects_contrato_de_empty() {
9452        // `:de ""` previously fell through to `ContratoMemberMissing`
9453        // (with `caixa: ""`) because the validated `:membros :caixa`
9454        // set never contains the empty string. The narrower
9455        // `ContratoCaixaEmpty { slot: ":de" }` diagnostic now names
9456        // the offending slot.
9457        let mut s = three_member_spec();
9458        s.contratos.push(contract_http("", "catalog", "/x"));
9459        let err = s.validate().unwrap_err();
9460        assert_eq!(
9461            err,
9462            AplicacaoError::ContratoCaixaEmpty {
9463                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9464            },
9465            "got {err:?}"
9466        );
9467    }
9468
9469    #[test]
9470    fn rejects_contrato_para_empty() {
9471        // Symmetric arm to `:de ""` — `:para ""` previously fell
9472        // through to `ContratoMemberMissing { caixa: "" }`.
9473        let mut s = three_member_spec();
9474        s.contratos.push(contract_http("cart", "", "/x"));
9475        let err = s.validate().unwrap_err();
9476        assert_eq!(
9477            err,
9478            AplicacaoError::ContratoCaixaEmpty {
9479                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9480            },
9481            "got {err:?}"
9482        );
9483    }
9484
9485    #[test]
9486    fn rejects_contrato_de_with_uppercase() {
9487        // The canonical "I copied the Servico's TitleCase display
9488        // name from an ADR" typo. Until this gate landed `:de "Cart"`
9489        // surfaced `ContratoMemberMissing { caixa: "Cart" }` — framed
9490        // as "this caixa isn't in `:membros`" when the root cause is
9491        // "this `:de` value's shape can never legitimately match a
9492        // validated member (DNS-1123 labels are lowercase)". The
9493        // narrower diagnostic names the offending slot, the value
9494        // verbatim, and the parser-shaped reason.
9495        let mut s = three_member_spec();
9496        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9497        let err = s.validate().unwrap_err();
9498        let AplicacaoError::ContratoCaixaInvalid {
9499            slot,
9500            caixa,
9501            reason,
9502        } = err
9503        else {
9504            panic!("expected ContratoCaixaInvalid, got other variant");
9505        };
9506        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_DE);
9507        assert_eq!(caixa, "Cart");
9508        assert!(
9509            reason.contains("uppercase"),
9510            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9511        );
9512    }
9513
9514    #[test]
9515    fn rejects_contrato_para_with_underscore() {
9516        // The canonical "I'm thinking of a Python module" leak —
9517        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9518        // Pin the `:para` axis surfaces the same diagnostic shape as
9519        // the `:de` axis on the underscore violation.
9520        let mut s = three_member_spec();
9521        s.contratos.push(contract_http("cart", "my_catalog", "/x"));
9522        let err = s.validate().unwrap_err();
9523        assert!(
9524            matches!(
9525                err,
9526                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9527                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "my_catalog" && reason.contains('_')
9528            ),
9529            "got {err:?}"
9530        );
9531    }
9532
9533    #[test]
9534    fn rejects_contrato_de_with_dot() {
9535        // A `:contratos :de` value is a single DNS-1123 *label*, not
9536        // a subdomain — mirroring the `:membros :caixa` floor. The
9537        // strictest floor among the use sites wins.
9538        let mut s = three_member_spec();
9539        s.contratos
9540            .push(contract_http("team.cart", "catalog", "/x"));
9541        let err = s.validate().unwrap_err();
9542        assert!(
9543            matches!(
9544                err,
9545                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9546                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "team.cart" && reason.contains('.')
9547            ),
9548            "got {err:?}"
9549        );
9550    }
9551
9552    #[test]
9553    fn rejects_contrato_para_with_unicode() {
9554        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9555        // (`xn--…`) before it reaches K8s. The byte-by-byte ASCII
9556        // validity check rejects multi-byte UTF-8 by the first
9557        // non-`[a-z0-9-]` byte.
9558        let mut s = three_member_spec();
9559        s.contratos.push(contract_http("cart", "café", "/x"));
9560        let err = s.validate().unwrap_err();
9561        assert!(
9562            matches!(
9563                err,
9564                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9565                    if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA && caixa == "café"
9566            ),
9567            "got {err:?}"
9568        );
9569    }
9570
9571    #[test]
9572    fn rejects_contrato_de_with_leading_hyphen() {
9573        // DNS-1123 boundary rule: labels must start and end with an
9574        // alphanumeric. K8s rejects `-cart` outright; the narrower
9575        // shape diagnostic now names the violation at caixa-build
9576        // time rather than the misframed membership-lookup arm.
9577        let mut s = three_member_spec();
9578        s.contratos.push(contract_http("-cart", "catalog", "/x"));
9579        let err = s.validate().unwrap_err();
9580        assert!(
9581            matches!(
9582                err,
9583                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, ref reason }
9584                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "-cart" && reason.contains("start and end")
9585            ),
9586            "got {err:?}"
9587        );
9588    }
9589
9590    #[test]
9591    fn contrato_de_empty_takes_precedence_over_invalid() {
9592        // Order pin: the `ContratoCaixaEmpty` arm fires before the
9593        // `ContratoCaixaInvalid` parse-side arm — same empty-first
9594        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9595        // / `validate_entrada_host` already establish on their peer
9596        // name axes. The empty string is a structurally distinct
9597        // authoring footgun (the author left the field blank, vs.
9598        // typed a malformed value), so it gets its own diagnostic.
9599        let mut s = three_member_spec();
9600        s.contratos.push(contract_http("", "catalog", "/x"));
9601        let err = s.validate().unwrap_err();
9602        assert_eq!(
9603            err,
9604            AplicacaoError::ContratoCaixaEmpty {
9605                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9606            }
9607        );
9608    }
9609
9610    #[test]
9611    fn contrato_de_shape_fires_before_para_shape() {
9612        // Per-axis order pin: within one `:contratos` entry, the `:de`
9613        // shape gate fires before the `:para` shape gate — same
9614        // edge-direction order the existing `ContratoMemberMissing` /
9615        // `ContratoSelfLoop` / target-dispatch checks use, so the
9616        // diagnostic for a contract with both `:de` and `:para`
9617        // malformed is stable. Authors fixing the surfaced `:de`
9618        // first will see `:para`'s diagnostic on re-run.
9619        let mut s = three_member_spec();
9620        s.contratos.push(contract_http("Cart", "Catalog", "/x"));
9621        let err = s.validate().unwrap_err();
9622        assert!(
9623            matches!(
9624                err,
9625                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9626                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9627            ),
9628            "got {err:?}"
9629        );
9630    }
9631
9632    #[test]
9633    fn contrato_shape_fires_before_membership_lookup() {
9634        // The load-bearing pin: an invalid-shape `:de` surfaces its
9635        // *own* diagnostic, not the misframed `ContratoMemberMissing`.
9636        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
9637        // an invalid-shape `:de` could never legitimately match any
9638        // member — the prior `ContratoMemberMissing` diagnostic was
9639        // a structural impossibility framed as a graph-membership
9640        // failure. The shape gate now routes every such input through
9641        // the narrower self-locating diagnostic.
9642        let mut s = three_member_spec();
9643        s.contratos.push(contract_http("Cart", "catalog", "/x"));
9644        let err = s.validate().unwrap_err();
9645        assert!(
9646            matches!(
9647                err,
9648                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_DE
9649            ),
9650            "got {err:?}"
9651        );
9652        // And the symmetric case: an invalid-shape `:para` surfaces
9653        // its own diagnostic too, even when `:de` is well-shaped.
9654        let mut s = three_member_spec();
9655        s.contratos.push(contract_http("cart", "Catalog", "/x"));
9656        let err = s.validate().unwrap_err();
9657        assert!(
9658            matches!(
9659                err,
9660                AplicacaoError::ContratoCaixaInvalid { slot, .. } if slot == crate::render::CONTRATO_AUTHOR_KEY_PARA
9661            ),
9662            "got {err:?}"
9663        );
9664    }
9665
9666    #[test]
9667    fn contrato_shape_fires_before_self_edge_check() {
9668        // A `:de "Cart" :para "Cart"` entry is two distinct authoring
9669        // bugs: the shape violation (uppercase) and the self-edge
9670        // violation. The narrower per-axis shape diagnostic surfaces
9671        // first because fixing the shape may reveal that the author
9672        // also meant to point `:para` at a different member — the
9673        // self-edge framing is only useful once both endpoints have
9674        // valid shape.
9675        let mut s = three_member_spec();
9676        s.contratos.push(contract_http("Cart", "Cart", "/x"));
9677        let err = s.validate().unwrap_err();
9678        assert!(
9679            matches!(
9680                err,
9681                AplicacaoError::ContratoCaixaInvalid { slot, ref caixa, .. }
9682                    if slot == crate::render::CONTRATO_AUTHOR_KEY_DE && caixa == "Cart"
9683            ),
9684            "got {err:?}"
9685        );
9686    }
9687
9688    #[test]
9689    fn contrato_well_shaped_phantom_still_raises_member_missing() {
9690        // Strict-improvement pin: a well-shaped `:de` that simply
9691        // isn't in `:membros` (a phantom reference — author meant
9692        // to add the member but didn't, or renamed and missed an
9693        // update) still surfaces `ContratoMemberMissing`, unchanged.
9694        // The shape gate only intercepts inputs that could never
9695        // legitimately match a validated member; legitimately-shaped
9696        // phantom references remain on the graph-membership axis.
9697        let mut s = three_member_spec();
9698        s.contratos
9699            .push(contract_http("phantom-shim", "catalog", "/x"));
9700        let err = s.validate().unwrap_err();
9701        assert!(
9702            matches!(
9703                err,
9704                AplicacaoError::ContratoMemberMissing { ref caixa }
9705                    if caixa == "phantom-shim"
9706            ),
9707            "got {err:?}"
9708        );
9709    }
9710
9711    #[test]
9712    fn contrato_caixa_invalid_diagnostic_carries_offending_slot_and_value() {
9713        // The diagnostic-shape pin: the error names the offending
9714        // slot (`:de` or `:para`) verbatim and the offending value
9715        // verbatim plus a non-empty parser-shaped reason, so the
9716        // author can grep their caixa.lisp for `:de "<name>"` /
9717        // `:para "<name>"` and fix it in one edit. Same diagnostic
9718        // shape as `MembroCaixaInvalid` (3f9d7a0) and
9719        // `PlacementClusterInvalid` (6c8c00b).
9720        let mut s = three_member_spec();
9721        s.contratos.push(contract_http("cart", "BAD_NAME", "/x"));
9722        let err = s.validate().unwrap_err();
9723        let AplicacaoError::ContratoCaixaInvalid {
9724            slot,
9725            caixa,
9726            reason,
9727        } = err
9728        else {
9729            panic!("expected ContratoCaixaInvalid, got {err:?}");
9730        };
9731        assert_eq!(slot, crate::render::CONTRATO_AUTHOR_KEY_PARA);
9732        assert_eq!(caixa, "BAD_NAME");
9733        assert!(
9734            !reason.is_empty(),
9735            "ContratoCaixaInvalid `reason` must carry a parser-shaped wording"
9736        );
9737    }
9738
9739    #[test]
9740    fn contrato_author_key_consts_pin_canonical_kebab_case_labels() {
9741        // Scalar-value pin: the two author-facing kebab-case labels the
9742        // `(:contratos ((:de "<caixa>" :para "<caixa>" …) …))` surface
9743        // admits on the `:contratos` per-entry endpoint-shape axis,
9744        // one arm per typed sub-slot. Mirrors the peer scalar-value
9745        // pin the sibling top-level M2 / M3 / Supervisor
9746        // author-facing-label consts carry
9747        // (`m3_top_level_author_key_consts_pin_canonical_kebab_case_labels`
9748        // for the parent [`crate::render::M3_AUTHOR_KEY_CONTRATOS`]
9749        // slot itself), so every altitude of the typed-slot algebra
9750        // shares the same "one canonical byte-string per arm"
9751        // discipline. A future rebrand (`:de` → `:from` matching the
9752        // OTP `appup` [`crate::render::M2_UPGRADE_FROM_KEY_FROM`]
9753        // sibling, `:para` → `:to` matching the same, or
9754        // `:de`/`:para` → `:source`/`:target` matching the WIT
9755        // world's `import`/`export` half-vocabulary) lands as an
9756        // edit to exactly one const, and every consumer that reaches
9757        // for the label picks it up at build time rather than at
9758        // runtime as a downstream `ContratoCaixaEmpty` /
9759        // `ContratoCaixaInvalid` `slot: <stale-kebab-case>`
9760        // diagnostic mismatch far from the rename's commit.
9761        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_DE, ":de");
9762        assert_eq!(crate::render::CONTRATO_AUTHOR_KEY_PARA, ":para");
9763    }
9764
9765    #[test]
9766    fn contrato_shape_gate_routes_through_lifted_contrato_author_key_consts() {
9767        // Production-through-const pin: the two per-axis labels the
9768        // per-`:contratos` entry endpoint-shape gate at
9769        // [`AplicacaoSpec::validate`] passes as the `slot: &'static str`
9770        // argument to [`validate_contrato_caixa`] route through the
9771        // lifted [`crate::render::CONTRATO_AUTHOR_KEY_DE`] /
9772        // [`crate::render::CONTRATO_AUTHOR_KEY_PARA`] consts, so a
9773        // future rebrand that reaches the const but not the gate (or
9774        // vice versa) surfaces here at build time rather than at
9775        // runtime as a downstream [`AplicacaoError::ContratoCaixaEmpty`]
9776        // `slot: <stale-kebab-case>` diagnostic far from the rename's
9777        // commit. Mirror of the peer
9778        // [`manifest::declared_mesh_slots_route_through_lifted_m3_author_key_consts`]
9779        // pin (882f498) on the sibling M3 top-level slot axis.
9780        let mut s = three_member_spec();
9781        s.contratos.push(contract_http("", "catalog", "/x"));
9782        assert_eq!(
9783            s.validate().unwrap_err(),
9784            AplicacaoError::ContratoCaixaEmpty {
9785                slot: crate::render::CONTRATO_AUTHOR_KEY_DE
9786            }
9787        );
9788        let mut s = three_member_spec();
9789        s.contratos.push(contract_http("cart", "", "/x"));
9790        assert_eq!(
9791            s.validate().unwrap_err(),
9792            AplicacaoError::ContratoCaixaEmpty {
9793                slot: crate::render::CONTRATO_AUTHOR_KEY_PARA
9794            }
9795        );
9796    }
9797
9798    #[test]
9799    fn accepts_canonical_contrato_caixa_forms() {
9800        // The DNS-1123 label shapes a caixa author is realistically
9801        // going to write on a `:contratos :de` / `:para`. Pin every
9802        // leg so a future tightening that bans (e.g.) digit-start
9803        // identifiers surfaces here, mirroring
9804        // `accepts_canonical_membro_caixa_forms` on the peer name
9805        // axis.
9806        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
9807            let mut s = three_member_spec();
9808            s.membros = vec![membro("checkout", "^0.1"), membro(form, "^0.1")];
9809            s.contratos = vec![contract_http("checkout", form, "/x")];
9810            s.entrada = None;
9811            s.validate().unwrap_or_else(|e| {
9812                panic!("canonical form {form:?} must validate on `:para`, got {e:?}")
9813            });
9814
9815            let mut s = three_member_spec();
9816            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
9817            s.contratos = vec![contract_http(form, "catalog", "/x")];
9818            s.entrada = None;
9819            s.validate().unwrap_or_else(|e| {
9820                panic!("canonical form {form:?} must validate on `:de`, got {e:?}")
9821            });
9822        }
9823    }
9824
9825    #[test]
9826    fn rejects_empty_wit() {
9827        let mut s = three_member_spec();
9828        s.contratos.push(WitContract {
9829            de: "cart".into(),
9830            para: "catalog".into(),
9831            wit: String::new(),
9832            endpoint: None,
9833            subject: None,
9834            slot: None,
9835        });
9836        let err = s.validate().unwrap_err();
9837        assert!(matches!(err, AplicacaoError::EmptyWit { .. }));
9838    }
9839
9840    #[test]
9841    fn rejects_entrada_to_unknown_member() {
9842        let mut s = three_member_spec();
9843        s.entrada.as_mut().unwrap().para = "phantom".into();
9844        assert!(matches!(
9845            s.validate().unwrap_err(),
9846            AplicacaoError::EntradaMemberMissing { .. }
9847        ));
9848    }
9849
9850    // ── :entrada :para DNS-1123 label value-shape gate ───────────────────
9851
9852    #[test]
9853    fn rejects_entrada_para_empty() {
9854        // `:para ""` previously fell through to
9855        // `EntradaMemberMissing { para: "" }` because the validated
9856        // `:membros :caixa` set never contains the empty string. The
9857        // narrower `EntradaParaEmpty` diagnostic now names the
9858        // offending slot directly — same empty-first cascade
9859        // `MembroCaixaEmpty` / `PlacementClusterEmpty` /
9860        // `ContratoCaixaEmpty` establish on the peer name axes.
9861        let mut s = three_member_spec();
9862        s.entrada.as_mut().unwrap().para = String::new();
9863        let err = s.validate().unwrap_err();
9864        assert_eq!(err, AplicacaoError::EntradaParaEmpty, "got {err:?}");
9865    }
9866
9867    #[test]
9868    fn rejects_entrada_para_with_uppercase() {
9869        // The canonical "I copied the Servico's TitleCase display
9870        // name from an ADR" typo. Until this gate landed `:para "Cart"`
9871        // surfaced `EntradaMemberMissing { para: "Cart" }` — framed
9872        // as "this caixa isn't in `:membros`" when the root cause is
9873        // "this `:para` value's shape can never legitimately match a
9874        // validated member (DNS-1123 labels are lowercase)". The
9875        // narrower diagnostic names the value verbatim plus the
9876        // parser-shaped reason.
9877        let mut s = three_member_spec();
9878        s.entrada.as_mut().unwrap().para = "Cart".into();
9879        let err = s.validate().unwrap_err();
9880        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
9881            panic!("expected EntradaParaInvalid, got other variant");
9882        };
9883        assert_eq!(para, "Cart");
9884        assert!(
9885            reason.contains("uppercase"),
9886            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
9887        );
9888    }
9889
9890    #[test]
9891    fn rejects_entrada_para_with_underscore() {
9892        // The canonical "I'm thinking of a Python module" leak —
9893        // `_` is forbidden by every DNS-1123 / DNS-1035 label schema.
9894        let mut s = three_member_spec();
9895        s.entrada.as_mut().unwrap().para = "my_cart".into();
9896        let err = s.validate().unwrap_err();
9897        assert!(
9898            matches!(
9899                err,
9900                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9901                    if para == "my_cart" && reason.contains('_')
9902            ),
9903            "got {err:?}"
9904        );
9905    }
9906
9907    #[test]
9908    fn rejects_entrada_para_with_dot() {
9909        // An `:entrada :para` value is a single DNS-1123 *label*, not
9910        // a subdomain — mirroring the `:membros :caixa` floor. The
9911        // strictest floor among the use sites wins.
9912        let mut s = three_member_spec();
9913        s.entrada.as_mut().unwrap().para = "team.cart".into();
9914        let err = s.validate().unwrap_err();
9915        assert!(
9916            matches!(
9917                err,
9918                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9919                    if para == "team.cart" && reason.contains('.')
9920            ),
9921            "got {err:?}"
9922        );
9923    }
9924
9925    #[test]
9926    fn rejects_entrada_para_with_unicode() {
9927        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
9928        // (`xn--…`) before it reaches K8s.
9929        let mut s = three_member_spec();
9930        s.entrada.as_mut().unwrap().para = "café".into();
9931        let err = s.validate().unwrap_err();
9932        assert!(
9933            matches!(
9934                err,
9935                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "café"
9936            ),
9937            "got {err:?}"
9938        );
9939    }
9940
9941    #[test]
9942    fn rejects_entrada_para_with_leading_hyphen() {
9943        // DNS-1123 boundary rule: labels must start and end with an
9944        // alphanumeric. K8s rejects `-cart` outright.
9945        let mut s = three_member_spec();
9946        s.entrada.as_mut().unwrap().para = "-cart".into();
9947        let err = s.validate().unwrap_err();
9948        assert!(
9949            matches!(
9950                err,
9951                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9952                    if para == "-cart" && reason.contains("start and end")
9953            ),
9954            "got {err:?}"
9955        );
9956    }
9957
9958    #[test]
9959    fn rejects_entrada_para_with_trailing_hyphen() {
9960        // Symmetric boundary arm.
9961        let mut s = three_member_spec();
9962        s.entrada.as_mut().unwrap().para = "cart-".into();
9963        let err = s.validate().unwrap_err();
9964        assert!(
9965            matches!(
9966                err,
9967                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9968                    if para == "cart-" && reason.contains("start and end")
9969            ),
9970            "got {err:?}"
9971        );
9972    }
9973
9974    #[test]
9975    fn rejects_entrada_para_too_long() {
9976        // 64-byte over-cap slug — the DNS-1123 label rule caps at 63
9977        // bytes per label. K8s rejects longer names at admission on
9978        // every `metadata.name` axis.
9979        let mut s = three_member_spec();
9980        s.entrada.as_mut().unwrap().para = "a".repeat(64);
9981        let err = s.validate().unwrap_err();
9982        assert!(
9983            matches!(
9984                err,
9985                AplicacaoError::EntradaParaInvalid { ref para, ref reason }
9986                    if para.len() == 64 && reason.contains("max length")
9987            ),
9988            "got {err:?}"
9989        );
9990    }
9991
9992    #[test]
9993    fn entrada_para_empty_takes_precedence_over_invalid() {
9994        // Order pin: the `EntradaParaEmpty` arm fires before the
9995        // `EntradaParaInvalid` parse-side arm — same empty-first
9996        // cascade `validate_membro_caixa` / `validate_placement_cluster`
9997        // / `validate_contrato_caixa` already establish.
9998        let mut s = three_member_spec();
9999        s.entrada.as_mut().unwrap().para = String::new();
10000        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaParaEmpty);
10001    }
10002
10003    #[test]
10004    fn entrada_para_shape_fires_before_membership_lookup() {
10005        // The load-bearing pin: an invalid-shape `:para` surfaces its
10006        // *own* diagnostic, not the misframed `EntradaMemberMissing`.
10007        // Because every `:membros :caixa` is shape-validated (3f9d7a0),
10008        // an invalid-shape `:para` could never legitimately match any
10009        // member — the prior `EntradaMemberMissing` diagnostic framed
10010        // a structural impossibility as a graph-membership failure.
10011        let mut s = three_member_spec();
10012        s.entrada.as_mut().unwrap().para = "Cart".into();
10013        let err = s.validate().unwrap_err();
10014        assert!(
10015            matches!(
10016                err,
10017                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
10018            ),
10019            "got {err:?}"
10020        );
10021    }
10022
10023    #[test]
10024    fn entrada_para_shape_fires_before_host_gate() {
10025        // Per-`:entrada` order pin: the `:para` shape gate fires
10026        // before the `:host` gate, mirroring the existing
10027        // `entrada_host_member_missing_takes_precedence_over_host_invalid`
10028        // ordering where the member-lookup arm preceded the host gate.
10029        // The shape gate slots ahead of that, so a malformed `:para`
10030        // surfaces its own diagnostic even when `:host` is also wrong.
10031        let mut s = three_member_spec();
10032        let e = s.entrada.as_mut().unwrap();
10033        e.para = "Cart".into();
10034        e.host = "BAD HOST".into();
10035        let err = s.validate().unwrap_err();
10036        assert!(
10037            matches!(
10038                err,
10039                AplicacaoError::EntradaParaInvalid { ref para, .. } if para == "Cart"
10040            ),
10041            "got {err:?}"
10042        );
10043    }
10044
10045    #[test]
10046    fn entrada_para_well_shaped_phantom_still_raises_member_missing() {
10047        // Strict-improvement pin: a well-shaped `:para` that simply
10048        // isn't in `:membros` (a phantom reference — author meant to
10049        // add the member but didn't, or renamed and missed an
10050        // update) still surfaces `EntradaMemberMissing`, unchanged.
10051        // The shape gate only intercepts inputs that could never
10052        // legitimately match a validated member.
10053        let mut s = three_member_spec();
10054        s.entrada.as_mut().unwrap().para = "phantom-shim".into();
10055        let err = s.validate().unwrap_err();
10056        assert!(
10057            matches!(
10058                err,
10059                AplicacaoError::EntradaMemberMissing { ref para }
10060                    if para == "phantom-shim"
10061            ),
10062            "got {err:?}"
10063        );
10064    }
10065
10066    #[test]
10067    fn entrada_para_invalid_diagnostic_carries_offending_para() {
10068        // The diagnostic-shape pin: the error names the offending
10069        // `:para` value verbatim plus a non-empty parser-shaped
10070        // reason, so the author can grep their caixa.lisp for
10071        // `:para "<name>"` and fix it in one edit. Same diagnostic
10072        // shape as `MembroCaixaInvalid` (3f9d7a0),
10073        // `PlacementClusterInvalid` (6c8c00b), and
10074        // `ContratoCaixaInvalid` (8d5af6b).
10075        let mut s = three_member_spec();
10076        s.entrada.as_mut().unwrap().para = "BAD_NAME".into();
10077        let err = s.validate().unwrap_err();
10078        let AplicacaoError::EntradaParaInvalid { para, reason } = err else {
10079            panic!("expected EntradaParaInvalid, got {err:?}");
10080        };
10081        assert_eq!(para, "BAD_NAME");
10082        assert!(
10083            !reason.is_empty(),
10084            "EntradaParaInvalid `reason` must carry a parser-shaped wording"
10085        );
10086    }
10087
10088    #[test]
10089    fn accepts_canonical_entrada_para_forms() {
10090        // Positive-control sweep covering the DNS-1123 label shapes a
10091        // caixa author is realistically going to write on `:entrada
10092        // :para`. Pin every leg so a future tightening that bans
10093        // (e.g.) digit-start identifiers surfaces here, mirroring
10094        // `accepts_canonical_membro_caixa_forms` and
10095        // `accepts_canonical_contrato_caixa_forms` on the peer name
10096        // axes.
10097        for form in ["cart", "cart-v2", "a", "c0", "3rd-party-shim", "x-1-2-3-4"] {
10098            let mut s = three_member_spec();
10099            s.membros = vec![membro(form, "^0.1"), membro("catalog", "^0.1")];
10100            s.contratos = vec![contract_http(form, "catalog", "/x")];
10101            s.entrada = Some(Entrada {
10102                host: "checkout.quero.cloud".into(),
10103                para: form.into(),
10104                paths: vec!["/api".into()],
10105                port: 8080,
10106            });
10107            s.validate().unwrap_or_else(|e| {
10108                panic!("canonical form {form:?} must validate on `:entrada :para`, got {e:?}")
10109            });
10110        }
10111    }
10112
10113    #[test]
10114    fn rejects_replicated_without_clusters() {
10115        let mut s = three_member_spec();
10116        s.placement.clusters = vec![];
10117        assert!(matches!(
10118            s.validate().unwrap_err(),
10119            AplicacaoError::PlacementWithoutClusters { .. }
10120        ));
10121    }
10122
10123    #[test]
10124    fn rejects_sharded_without_key() {
10125        let mut s = three_member_spec();
10126        s.placement.estrategia = PlacementStrategy::Sharded;
10127        s.placement.shard_key = None;
10128        s.placement.clusters = vec!["rio".into()];
10129        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedWithoutKey);
10130    }
10131
10132    #[test]
10133    fn sharded_with_key_validates() {
10134        let mut s = three_member_spec();
10135        s.placement.estrategia = PlacementStrategy::Sharded;
10136        s.placement.shard_key = Some("$tenantId".into());
10137        s.validate().unwrap();
10138    }
10139
10140    #[test]
10141    fn round_trip_via_json_preserves_shape() {
10142        let s = three_member_spec();
10143        let json = serde_json::to_string(&s.membros).unwrap();
10144        let back: Vec<Membro> = serde_json::from_str(&json).unwrap();
10145        assert_eq!(back, s.membros);
10146
10147        let json = serde_json::to_string(&s.contratos).unwrap();
10148        let back: Vec<WitContract> = serde_json::from_str(&json).unwrap();
10149        assert_eq!(back, s.contratos);
10150
10151        let json = serde_json::to_string(&s.placement).unwrap();
10152        let back: Placement = serde_json::from_str(&json).unwrap();
10153        assert_eq!(back, s.placement);
10154
10155        let json = serde_json::to_string(&s.entrada).unwrap();
10156        let back: Option<Entrada> = serde_json::from_str(&json).unwrap();
10157        assert_eq!(back, s.entrada);
10158    }
10159
10160    #[test]
10161    fn rate_limit_round_trip_seconds() {
10162        let policy = MeshPolicy {
10163            rate_limit: Some(RateLimit {
10164                rate: 100,
10165                window: Duration::from_secs(1),
10166            }),
10167            ..Default::default()
10168        };
10169        let json = serde_json::to_string(&policy).unwrap();
10170        assert!(json.contains("\"100/s\""));
10171        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10172        assert_eq!(back.rate_limit.unwrap().rate, 100);
10173        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(1));
10174    }
10175
10176    #[test]
10177    fn rate_limit_round_trip_minutes() {
10178        let policy = MeshPolicy {
10179            rate_limit: Some(RateLimit {
10180                rate: 5000,
10181                window: Duration::from_secs(60),
10182            }),
10183            ..Default::default()
10184        };
10185        let json = serde_json::to_string(&policy).unwrap();
10186        assert!(json.contains("\"5000/m\""));
10187    }
10188
10189    #[test]
10190    fn circuit_breaker_round_trip() {
10191        let policy = MeshPolicy {
10192            circuit_breaker: Some(CircuitBreaker {
10193                max_failures: 5,
10194                window: Duration::from_secs(60),
10195            }),
10196            ..Default::default()
10197        };
10198        let json = serde_json::to_string(&policy).unwrap();
10199        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
10200        assert_eq!(back.circuit_breaker.unwrap().max_failures, 5);
10201        assert_eq!(
10202            back.circuit_breaker.unwrap().window,
10203            Duration::from_secs(60)
10204        );
10205    }
10206
10207    #[test]
10208    fn rejects_http_contrato_without_endpoint() {
10209        let mut s = three_member_spec();
10210        s.contratos.push(WitContract {
10211            de: "cart".into(),
10212            para: "catalog".into(),
10213            wit: "wasi:http/proxy".into(),
10214            endpoint: None,
10215            subject: None,
10216            slot: None,
10217        });
10218        let err = s.validate().unwrap_err();
10219        assert!(matches!(
10220            err,
10221            AplicacaoError::ContratoMissingTarget {
10222                expected: WitTarget::HTTP_FIELD_NAME,
10223                ..
10224            }
10225        ));
10226    }
10227
10228    #[test]
10229    fn rejects_http_contrato_with_subject() {
10230        let mut s = three_member_spec();
10231        s.contratos.push(WitContract {
10232            de: "cart".into(),
10233            para: "catalog".into(),
10234            wit: "wasi:http/proxy".into(),
10235            endpoint: Some("/x".into()),
10236            subject: Some("not.allowed.here".into()),
10237            slot: None,
10238        });
10239        let err = s.validate().unwrap_err();
10240        assert!(matches!(
10241            err,
10242            AplicacaoError::ContratoWrongTarget {
10243                expected: WitTarget::HTTP_FIELD_NAME,
10244                ..
10245            }
10246        ));
10247    }
10248
10249    #[test]
10250    fn rejects_pubsub_contrato_without_subject() {
10251        let mut s = three_member_spec();
10252        s.contratos.push(WitContract {
10253            de: "cart".into(),
10254            para: "catalog".into(),
10255            wit: "nats:pub-sub".into(),
10256            endpoint: None,
10257            subject: None,
10258            slot: None,
10259        });
10260        let err = s.validate().unwrap_err();
10261        assert!(matches!(
10262            err,
10263            AplicacaoError::ContratoMissingTarget {
10264                expected: WitTarget::PUBSUB_FIELD_NAME,
10265                ..
10266            }
10267        ));
10268    }
10269
10270    #[test]
10271    fn rejects_pubsub_contrato_with_endpoint() {
10272        let mut s = three_member_spec();
10273        s.contratos.push(WitContract {
10274            de: "cart".into(),
10275            para: "catalog".into(),
10276            wit: "kafka:topic".into(),
10277            endpoint: Some("/wrong".into()),
10278            subject: Some("topic.x".into()),
10279            slot: None,
10280        });
10281        let err = s.validate().unwrap_err();
10282        assert!(matches!(
10283            err,
10284            AplicacaoError::ContratoWrongTarget {
10285                expected: WitTarget::PUBSUB_FIELD_NAME,
10286                ..
10287            }
10288        ));
10289    }
10290
10291    #[test]
10292    fn rejects_store_contrato_without_slot() {
10293        let mut s = three_member_spec();
10294        s.contratos.push(WitContract {
10295            de: "cart".into(),
10296            para: "catalog".into(),
10297            wit: "wasi:keyvalue/store".into(),
10298            endpoint: None,
10299            subject: None,
10300            slot: None,
10301        });
10302        let err = s.validate().unwrap_err();
10303        assert!(matches!(
10304            err,
10305            AplicacaoError::ContratoMissingTarget {
10306                expected: WitTarget::STORE_FIELD_NAME,
10307                ..
10308            }
10309        ));
10310    }
10311
10312    // ── value-shape on WitTarget payload (endpoint / subject / slot) ──────
10313
10314    #[test]
10315    fn rejects_http_contrato_with_empty_endpoint() {
10316        // `Some("")` for an HTTP endpoint passes the presence check
10317        // (target() previously returned WitTarget::Http { endpoint: "" })
10318        // but renders as a `path: ""` Cilium L7 rule that matches no
10319        // traffic. Same value-shape footgun closed for :entrada :paths
10320        // entries (eb3456d).
10321        let mut s = three_member_spec();
10322        s.contratos.push(WitContract {
10323            de: "cart".into(),
10324            para: "catalog".into(),
10325            wit: "wasi:http/proxy".into(),
10326            endpoint: Some(String::new()),
10327            subject: None,
10328            slot: None,
10329        });
10330        let err = s.validate().unwrap_err();
10331        assert!(
10332            matches!(err, AplicacaoError::ContratoEndpointEmpty { ref de, ref para }
10333                if de == "cart" && para == "catalog"),
10334            "got {err:?}"
10335        );
10336    }
10337
10338    #[test]
10339    fn rejects_http_contrato_with_relative_endpoint() {
10340        // Cilium L7 :path + Gateway API PathPrefix both require a
10341        // leading `/`. Same shape required of :entrada :paths
10342        // (eb3456d). Lifted into target() so every consumer of the
10343        // typed WitTarget view inherits the guarantee.
10344        let mut s = three_member_spec();
10345        s.contratos.push(WitContract {
10346            de: "cart".into(),
10347            para: "catalog".into(),
10348            wit: "wasi:http/proxy".into(),
10349            endpoint: Some("products/:id".into()),
10350            subject: None,
10351            slot: None,
10352        });
10353        let err = s.validate().unwrap_err();
10354        assert!(
10355            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10356                if endpoint == "products/:id"),
10357            "got {err:?}"
10358        );
10359    }
10360
10361    #[test]
10362    fn rejects_pubsub_contrato_with_empty_subject() {
10363        // NATS / Kafka publish without a subject is a no-op subscribe;
10364        // never the author's intent. Same empty-string rejection as
10365        // :membros :caixa, :placement :clusters entries, :entrada
10366        // :paths entries — every value carried by every typed slot is
10367        // value-shape-checked at validate().
10368        let mut s = three_member_spec();
10369        s.contratos.push(WitContract {
10370            de: "cart".into(),
10371            para: "catalog".into(),
10372            wit: "nats:pub-sub".into(),
10373            endpoint: None,
10374            subject: Some(String::new()),
10375            slot: None,
10376        });
10377        let err = s.validate().unwrap_err();
10378        assert!(
10379            matches!(err, AplicacaoError::ContratoSubjectEmpty { ref de, ref para }
10380                if de == "cart" && para == "catalog"),
10381            "got {err:?}"
10382        );
10383    }
10384
10385    #[test]
10386    fn rejects_store_contrato_with_empty_slot() {
10387        // An empty slot template addresses the bucket root, defeating
10388        // the per-key isolation the slot exists for — a footgun on
10389        // `wasi:keyvalue/store` whose closest analog is the empty
10390        // shard-key rejected on :placement Sharded (c7c7799).
10391        let mut s = three_member_spec();
10392        s.contratos.push(WitContract {
10393            de: "cart".into(),
10394            para: "catalog".into(),
10395            wit: "wasi:keyvalue/store".into(),
10396            endpoint: None,
10397            subject: None,
10398            slot: Some(String::new()),
10399        });
10400        let err = s.validate().unwrap_err();
10401        assert!(
10402            matches!(err, AplicacaoError::ContratoSlotEmpty { ref de, ref para }
10403                if de == "cart" && para == "catalog"),
10404            "got {err:?}"
10405        );
10406    }
10407
10408    #[test]
10409    fn http_contrato_root_endpoint_validates() {
10410        // Pin the boundary case: a single-`/` endpoint is the catch-all
10411        // form the Gateway HTTPRoute renderer falls back to when
10412        // :entrada :paths is empty (caixa-mesh::gateway_routes), so it
10413        // must remain a valid contrato endpoint too.
10414        let mut s = three_member_spec();
10415        s.contratos.push(contract_http("cart", "catalog", "/"));
10416        s.validate().unwrap();
10417    }
10418
10419    // ── :contratos :endpoint value-shape gate ────────────────────────────
10420    //
10421    // Mirrors the `:entrada :paths` value-shape suite on the peer
10422    // HTTP-path axis. Until this gate landed `WitContract::target()`
10423    // only refused the empty string + the missing-leading-`/` form
10424    // (c4213a4); a structurally invalid endpoint passed validate and
10425    // landed verbatim as a Cilium L7 `path:` rule
10426    // (caixa-mesh/src/lib.rs:311) that either silently dropped all
10427    // traffic or was rejected at apply time by Cilium policy admission.
10428    // Every authoring footgun the K8s Gateway API webhook / Cilium
10429    // policy validator would catch on admission now becomes a caixa-
10430    // build-time `ContratoEndpointInvalid` with the offending
10431    // `:endpoint` + `:de` + `:para` named verbatim. Same diagnostic
10432    // shape as `EntradaPathInvalid` on the sibling axis; same shared
10433    // predicate (`crate::render::is_gateway_api_http_path`) ensures
10434    // drift between the two axes' rule enforcement is a build error
10435    // at the predicate.
10436
10437    fn contrato_endpoint_err(ep: &str) -> AplicacaoError {
10438        // Fresh spec per call so the would-be-duplicate edge
10439        // `(cart, catalog, wasi:http/proxy, ep)` doesn't collide with
10440        // `three_member_spec`'s pre-existing
10441        // `(cart, catalog, …, /products/:id)` entry — only the
10442        // endpoint payload differs.
10443        let mut s = three_member_spec();
10444        s.contratos.push(contract_http("cart", "catalog", ep));
10445        s.validate().unwrap_err()
10446    }
10447
10448    #[test]
10449    fn rejects_http_contrato_endpoint_with_query() {
10450        // Fail-before-pass-after pin — pre-gate the `?token=X` suffix
10451        // silently rendered as a Cilium L7 `path: "/charge?token=X"`
10452        // rule the L7 matcher would never satisfy.
10453        let err = contrato_endpoint_err("/charge?token=X");
10454        assert!(
10455            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10456                if endpoint == "/charge?token=X" && reason.contains("must not contain `?`")),
10457            "got {err:?}"
10458        );
10459    }
10460
10461    #[test]
10462    fn rejects_http_contrato_endpoint_with_fragment() {
10463        let err = contrato_endpoint_err("/charge#frag");
10464        assert!(
10465            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10466                if endpoint == "/charge#frag" && reason.contains("must not contain `#`")),
10467            "got {err:?}"
10468        );
10469    }
10470
10471    #[test]
10472    fn rejects_http_contrato_endpoint_with_whitespace() {
10473        let err = contrato_endpoint_err("/foo bar");
10474        assert!(
10475            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10476                if endpoint == "/foo bar" && reason.contains("whitespace")),
10477            "got {err:?}"
10478        );
10479    }
10480
10481    #[test]
10482    fn rejects_http_contrato_endpoint_with_control_char() {
10483        let err = contrato_endpoint_err("/api/\x01bar");
10484        assert!(
10485            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10486                if endpoint == "/api/\x01bar" && reason.contains("control character")),
10487            "got {err:?}"
10488        );
10489    }
10490
10491    #[test]
10492    fn rejects_http_contrato_endpoint_with_non_ascii() {
10493        let err = contrato_endpoint_err("/api/café");
10494        assert!(
10495            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10496                if endpoint == "/api/café" && reason.contains("non-ASCII")),
10497            "got {err:?}"
10498        );
10499    }
10500
10501    #[test]
10502    fn rejects_http_contrato_endpoint_with_consecutive_slashes() {
10503        let err = contrato_endpoint_err("/api//cart");
10504        assert!(
10505            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10506                if endpoint == "/api//cart" && reason.contains("consecutive `/`")),
10507            "got {err:?}"
10508        );
10509    }
10510
10511    #[test]
10512    fn rejects_http_contrato_endpoint_with_dot_segment() {
10513        let err = contrato_endpoint_err("/api/./cart");
10514        assert!(
10515            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10516                if endpoint == "/api/./cart" && reason.contains("`.` segment")),
10517            "got {err:?}"
10518        );
10519    }
10520
10521    #[test]
10522    fn rejects_http_contrato_endpoint_with_parent_segment() {
10523        // Path-traversal in a contrato endpoint is the canonical
10524        // "L7 rule that the workload's HTTP server's path-resolution
10525        // logic interprets differently than the policy enforcer"
10526        // footgun. Rejected outright at validate time.
10527        let err = contrato_endpoint_err("/api/../etc");
10528        assert!(
10529            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10530                if endpoint == "/api/../etc" && reason.contains("`..` parent-segment")),
10531            "got {err:?}"
10532        );
10533    }
10534
10535    #[test]
10536    fn rejects_http_contrato_endpoint_too_long() {
10537        // 1025-byte endpoint — one over the Gateway API
10538        // HTTPPathMatch.value `maxLength: 1024` cap. The Cilium L7
10539        // path matcher has no inherent length limit but the policy
10540        // CR itself rides through the K8s apiserver, which enforces
10541        // ConfigMap-shaped limits; sharing the Gateway API cap is the
10542        // conservative floor.
10543        let big = format!("/api/{}", "a".repeat(1020));
10544        assert_eq!(big.len(), 1025);
10545        let err = contrato_endpoint_err(&big);
10546        assert!(
10547            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
10548                if endpoint == &big && reason.contains("max length of 1024")),
10549            "got {err:?}"
10550        );
10551    }
10552
10553    #[test]
10554    fn http_contrato_endpoint_max_length_validates() {
10555        // 1024-byte endpoint — exactly the cap. Boundary pin: drift
10556        // in the cap surfaces here and at
10557        // `rejects_http_contrato_endpoint_too_long` simultaneously,
10558        // mirroring `entrada_path_max_length_validates` on the peer
10559        // axis.
10560        let big = format!("/api/{}", "a".repeat(1019));
10561        assert_eq!(big.len(), 1024);
10562        let mut s = three_member_spec();
10563        s.contratos.push(contract_http("cart", "catalog", &big));
10564        s.validate().unwrap();
10565    }
10566
10567    #[test]
10568    fn http_contrato_endpoint_accepts_canonical_forms() {
10569        // Positive-set sweep: every canonical HTTP-path shape the
10570        // sibling `:entrada :paths` axis accepts (the bare-root `/`,
10571        // plain paths, hidden-file-style `.config` segments distinct
10572        // from the `.` segment, digit-bearing segments, the canonical
10573        // route-template `:param` form, trailing-slash form,
10574        // percent-encoded segments, the `/foo..bar` interior-`..`-
10575        // substring forms that are NOT `..` segments) must remain a
10576        // valid contrato endpoint too. Drift between this list and
10577        // the entrada path positive sweep surfaces at the shared
10578        // `is_gateway_api_http_path` substrate-side suite — one
10579        // source of truth. Uses a fresh `(payment, catalog)` edge so
10580        // none of the swept endpoints collide with the pre-existing
10581        // `(cart, catalog, /products/:id)` / `(cart, payment,
10582        // /charge)` entries in `three_member_spec`.
10583        for ep in [
10584            "/",
10585            "/charge",
10586            "/v1/charge",
10587            "/api/.config",
10588            "/products/:id",
10589            "/api/cart/",
10590            "/api/caf%C3%A9",
10591            "/foo..bar",
10592            "/...",
10593        ] {
10594            let mut s = three_member_spec();
10595            s.contratos.push(contract_http("payment", "catalog", ep));
10596            s.validate()
10597                .unwrap_or_else(|e| panic!("expected {ep:?} to validate, got {e:?}"));
10598        }
10599    }
10600
10601    #[test]
10602    fn contrato_endpoint_empty_takes_precedence_over_invalid() {
10603        // Ordering pin: `ContratoEndpointEmpty` is the more self-
10604        // locating diagnostic on `""` and must lead — the value-
10605        // shape gate is only reached after the empty-check fires.
10606        // Mirrors `entrada_path_empty_takes_precedence_over_invalid`
10607        // on the peer axis.
10608        let mut s = three_member_spec();
10609        s.contratos.push(WitContract {
10610            de: "cart".into(),
10611            para: "catalog".into(),
10612            wit: "wasi:http/proxy".into(),
10613            endpoint: Some(String::new()),
10614            subject: None,
10615            slot: None,
10616        });
10617        let err = s.validate().unwrap_err();
10618        assert!(
10619            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
10620            "got {err:?}"
10621        );
10622    }
10623
10624    #[test]
10625    fn contrato_endpoint_not_absolute_takes_precedence_over_invalid() {
10626        // Ordering pin: an endpoint without a leading `/` surfaces the
10627        // narrower `ContratoEndpointNotAbsolute` diagnostic first; the
10628        // value-shape gate is only consulted on endpoints that already
10629        // satisfy the absolute-prefix invariant. Mirrors
10630        // `entrada_path_not_absolute_takes_precedence_over_invalid`.
10631        let err = contrato_endpoint_err("bad path");
10632        assert!(
10633            matches!(err, AplicacaoError::ContratoEndpointNotAbsolute { ref endpoint, .. }
10634                if endpoint == "bad path"),
10635            "got {err:?}"
10636        );
10637    }
10638
10639    #[test]
10640    fn contrato_endpoint_invalid_diagnostic_carries_offending_endpoint() {
10641        // Diagnostic-shape pin — the offending `:endpoint` + `:de` +
10642        // `:para` + a non-empty reason flow through verbatim so the
10643        // author can grep their caixa.lisp for the offending contrato
10644        // block and fix it in one edit. Same shape as
10645        // `entrada_path_diagnostic_carries_offending_path`.
10646        let err = contrato_endpoint_err("/api?q=1");
10647        match err {
10648            AplicacaoError::ContratoEndpointInvalid {
10649                de,
10650                para,
10651                endpoint,
10652                reason,
10653            } => {
10654                assert_eq!(de, "cart");
10655                assert_eq!(para, "catalog");
10656                assert_eq!(endpoint, "/api?q=1");
10657                assert!(!reason.is_empty(), "reason field must be non-empty");
10658            }
10659            other => panic!("expected ContratoEndpointInvalid, got {other:?}"),
10660        }
10661    }
10662
10663    #[test]
10664    fn target_view_payload_is_guaranteed_nonempty_after_target_call() {
10665        // The compounding theorem: every &str inside a WitTarget
10666        // returned by target() is non-empty (and absolute, for Http).
10667        // Renderers downstream of typed_view() can rely on this
10668        // without re-checking — the type system carries the proof.
10669        let http = contract_http("cart", "catalog", "/x");
10670        match http.target().unwrap() {
10671            WitTarget::Http { endpoint } => {
10672                assert!(!endpoint.is_empty());
10673                assert!(endpoint.starts_with('/'));
10674            }
10675            other => panic!("expected Http, got {other:?}"),
10676        }
10677        let nats = WitContract {
10678            de: "a".into(),
10679            para: "b".into(),
10680            wit: "nats:pub-sub".into(),
10681            endpoint: None,
10682            subject: Some("topic.x".into()),
10683            slot: None,
10684        };
10685        match nats.target().unwrap() {
10686            WitTarget::PubSub { subject } => assert!(!subject.is_empty()),
10687            other => panic!("expected PubSub, got {other:?}"),
10688        }
10689        let kv = WitContract {
10690            de: "a".into(),
10691            para: "b".into(),
10692            wit: "wasi:keyvalue/store".into(),
10693            endpoint: None,
10694            subject: None,
10695            slot: Some("checkout/$orderId".into()),
10696        };
10697        match kv.target().unwrap() {
10698            WitTarget::Store { slot } => assert!(!slot.is_empty()),
10699            other => panic!("expected Store, got {other:?}"),
10700        }
10701    }
10702
10703    #[test]
10704    fn target_diagnostic_names_offending_endpoint_value() {
10705        // When the malformed endpoint string is non-trivial, the
10706        // diagnostic carries the actual value back to the author —
10707        // not a generic "endpoint malformed" error.
10708        let bad = WitContract {
10709            de: "src".into(),
10710            para: "dst".into(),
10711            wit: "wasi:http/proxy".into(),
10712            endpoint: Some("api/v1/charge".into()),
10713            subject: None,
10714            slot: None,
10715        };
10716        match bad.target().unwrap_err() {
10717            AplicacaoError::ContratoEndpointNotAbsolute { de, para, endpoint } => {
10718                assert_eq!(de, "src");
10719                assert_eq!(para, "dst");
10720                assert_eq!(endpoint, "api/v1/charge");
10721            }
10722            other => panic!("expected ContratoEndpointNotAbsolute, got {other:?}"),
10723        }
10724    }
10725
10726    #[test]
10727    fn rejects_unknown_wit_with_target_set() {
10728        let mut s = three_member_spec();
10729        s.contratos.push(WitContract {
10730            de: "cart".into(),
10731            para: "catalog".into(),
10732            wit: "custom:exchange".into(),
10733            endpoint: Some("/leaked".into()),
10734            subject: None,
10735            slot: None,
10736        });
10737        let err = s.validate().unwrap_err();
10738        assert!(matches!(
10739            err,
10740            AplicacaoError::ContratoWrongTarget {
10741                expected: WitTarget::CAPABILITY_EXPECTED,
10742                ..
10743            }
10744        ));
10745    }
10746
10747    #[test]
10748    fn wit_target_capability_expected_pins_wrong_target_diagnostic_scalar() {
10749        // Pin the Capability-arm `ContratoWrongTarget::expected` scalar
10750        // single-sourced onto [`WitTarget::CAPABILITY_EXPECTED`] — the
10751        // fourth arm of the same "which payload field name goes in the
10752        // diagnostic" dispatch the payload-arm [`WitTarget::HTTP_FIELD_NAME`]
10753        // / [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
10754        // consts cover on the peer HTTP / PubSub / Store arms
10755        // (`wit_target_field_name_pins_per_variant`). Until this lift
10756        // landed the byte-string sat twice — once inline in the
10757        // [`WitContract::target`] Capability-arm rejection at the
10758        // production dispatch, once in `rejects_unknown_wit_with_target_set`
10759        // pinning against the same literal — with no compile-time link
10760        // between them. Same "one canonical declaration, next to the
10761        // variant" trajectory the peer [`WitTarget::CAPABILITY_LABEL`]
10762        // lift established for the payload-less arm's human-readable
10763        // label axis; this test is the shape peer of
10764        // `wit_target_label_pins_per_variant`'s Capability-arm assertion
10765        // pair (routes-through-const + scalar-value pin) on the
10766        // wrong-target diagnostic-scalar axis.
10767        //
10768        // Fail-before-pass-after was verified locally by mutating the
10769        // const declaration to `"capability"` — the scalar-value pin
10770        // below fires (`"capability" != "none"`) and the routes-through
10771        // assertion below still holds (production and const walk in
10772        // lockstep), which is the correct behavior: a rename on the
10773        // const drifts here first, not at a downstream consumer.
10774        assert_eq!(WitTarget::CAPABILITY_EXPECTED, "none");
10775
10776        let mut s = three_member_spec();
10777        s.contratos.push(WitContract {
10778            de: "cart".into(),
10779            para: "catalog".into(),
10780            wit: "custom:exchange".into(),
10781            endpoint: Some("/leaked".into()),
10782            subject: None,
10783            slot: None,
10784        });
10785        match s.validate().unwrap_err() {
10786            AplicacaoError::ContratoWrongTarget { expected, .. } => {
10787                assert_eq!(expected, WitTarget::CAPABILITY_EXPECTED);
10788            }
10789            other => panic!("expected ContratoWrongTarget, got {other:?}"),
10790        }
10791    }
10792
10793    #[test]
10794    fn unknown_wit_capability_only_validates() {
10795        let mut s = three_member_spec();
10796        s.contratos.push(WitContract {
10797            de: "cart".into(),
10798            para: "catalog".into(),
10799            // A WIT world we haven't yet shaped — accept it as a typed
10800            // capability edge so authors aren't blocked while the WIT
10801            // registry catches up. No payload field may be carried.
10802            wit: "custom:exchange".into(),
10803            endpoint: None,
10804            subject: None,
10805            slot: None,
10806        });
10807        s.validate().unwrap();
10808        let added = s.contratos.last().unwrap();
10809        assert_eq!(added.target().unwrap(), WitTarget::Capability);
10810    }
10811
10812    #[test]
10813    fn target_typed_view_round_trips_each_shape() {
10814        let http = contract_http("cart", "catalog", "/products/:id");
10815        assert_eq!(
10816            http.target().unwrap(),
10817            WitTarget::Http {
10818                endpoint: "/products/:id"
10819            }
10820        );
10821        let nats = WitContract {
10822            de: "a".into(),
10823            para: "b".into(),
10824            wit: "nats:pub-sub".into(),
10825            endpoint: None,
10826            subject: Some("topic.x".into()),
10827            slot: None,
10828        };
10829        assert_eq!(
10830            nats.target().unwrap(),
10831            WitTarget::PubSub { subject: "topic.x" }
10832        );
10833        let kv = WitContract {
10834            de: "a".into(),
10835            para: "b".into(),
10836            wit: "wasi:keyvalue/store".into(),
10837            endpoint: None,
10838            subject: None,
10839            slot: Some("checkout/$orderId".into()),
10840        };
10841        assert_eq!(
10842            kv.target().unwrap(),
10843            WitTarget::Store {
10844                slot: "checkout/$orderId"
10845            }
10846        );
10847    }
10848
10849    #[test]
10850    fn wit_contract_kind_predicates() {
10851        let http = contract_http("a", "b", "/x");
10852        assert!(http.is_http());
10853        assert!(!http.is_pubsub());
10854        assert!(!http.is_store());
10855        assert!(!http.is_capability());
10856
10857        let nats = WitContract {
10858            de: "a".into(),
10859            para: "b".into(),
10860            wit: "nats:pub-sub".into(),
10861            endpoint: None,
10862            subject: Some("topic.x".into()),
10863            slot: None,
10864        };
10865        assert!(nats.is_pubsub());
10866        assert!(!nats.is_http());
10867        assert!(!nats.is_capability());
10868
10869        let kv = WitContract {
10870            de: "a".into(),
10871            para: "b".into(),
10872            wit: "wasi:keyvalue/store".into(),
10873            endpoint: None,
10874            subject: None,
10875            slot: Some("checkout/$orderId".into()),
10876        };
10877        assert!(kv.is_store());
10878        assert!(!kv.is_http());
10879        assert!(!kv.is_capability());
10880
10881        // Fourth arm on the paired closed-set predicate family: the
10882        // payload-less capability edge that projects to the payload-
10883        // less [`WitTarget::Capability`] arm under [`WitContract::target`].
10884        // Extends the 3-arm predicate sweep this test opened to cover
10885        // the closed 4-way partition [`WitContract::is_capability`]
10886        // closes on the pre-projection WIT-shape axis, matched with the
10887        // sibling post-projection [`WitTarget`]-side `IsVariant`-derived
10888        // 4-arm predicate set.
10889        let cap = WitContract {
10890            de: "a".into(),
10891            para: "b".into(),
10892            wit: "custom:capability-only".into(),
10893            endpoint: None,
10894            subject: None,
10895            slot: None,
10896        };
10897        assert!(cap.is_capability());
10898        assert!(!cap.is_http());
10899        assert!(!cap.is_pubsub());
10900        assert!(!cap.is_store());
10901    }
10902
10903    // ── :contratos :wit value-shape gate ─────────────────────────────────
10904    //
10905    // Mirrors the `:contratos :endpoint` value-shape suite on the peer
10906    // dispatch-discriminator axis. Until this gate landed
10907    // `WitContract::target()` accepted any non-empty string and
10908    // silently demoted unrecognized shapes to a capability-only L4
10909    // edge — the canonical "I thought I had L7 HTTP routing, got
10910    // L4-only" footgun. Every authoring footgun the WIT registry's
10911    // own grammar rejects (uppercase, hyphen-for-colon typo,
10912    // whitespace, empty package, doubled `@`, …) now becomes a
10913    // caixa-build-time `ContratoWitInvalid` with the offending
10914    // `:wit` + `:de` + `:para` named verbatim. Same diagnostic shape
10915    // as `ContratoEndpointInvalid` on the sibling axis; same shared
10916    // predicate (`crate::render::is_wit_world_ref`) ensures drift
10917    // between any two axes' rule enforcement is a build error at the
10918    // predicate, not piecemeal across renderers.
10919
10920    fn contrato_wit_err(wit: &str) -> AplicacaoError {
10921        // Fresh spec per call so the new contract doesn't collide on
10922        // identity with `three_member_spec`'s pre-existing entries.
10923        // The new edge uses `(payment, catalog)` — a pair the fixture
10924        // doesn't already declare — with no payload field set, so the
10925        // wit-shape gate fires before any payload-shape arm.
10926        let mut s = three_member_spec();
10927        s.contratos.push(WitContract {
10928            de: "payment".into(),
10929            para: "catalog".into(),
10930            wit: wit.into(),
10931            endpoint: None,
10932            subject: None,
10933            slot: None,
10934        });
10935        s.validate().unwrap_err()
10936    }
10937
10938    #[test]
10939    fn rejects_wit_with_uppercase_namespace() {
10940        // Fail-before-pass-after pin — pre-gate `:wit "WASI:http/proxy"`
10941        // didn't match the lowercase `wasi:http/` prefix is_http() keys
10942        // off, so the dispatch fell through to the capability arm and
10943        // the contract silently rendered as an L4-only Cilium edge.
10944        // The new gate surfaces the uppercase typo at validate time
10945        // with the offending `:wit` named.
10946        let err = contrato_wit_err("WASI:http/proxy");
10947        assert!(
10948            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10949                if wit == "WASI:http/proxy" && reason.contains("lowercase")),
10950            "got {err:?}"
10951        );
10952    }
10953
10954    #[test]
10955    fn rejects_wit_with_hyphen_for_colon_typo() {
10956        // The canonical "I forgot the `:` separator" typo — pre-gate
10957        // this passed as Capability silently, so the renderer emitted
10958        // an L4-only policy where the author expected L7 HTTP rules.
10959        let err = contrato_wit_err("wasi-http/proxy");
10960        assert!(
10961            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10962                if wit == "wasi-http/proxy" && reason.contains("must contain a `:`")),
10963            "got {err:?}"
10964        );
10965    }
10966
10967    #[test]
10968    fn rejects_wit_with_multiple_colons() {
10969        // Doubled `:` — the namespace/package split has nowhere to
10970        // anchor, so the dispatch silently demotes to Capability.
10971        let err = contrato_wit_err("wasi:http:proxy");
10972        assert!(
10973            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10974                if wit == "wasi:http:proxy" && reason.contains("exactly one `:`")),
10975            "got {err:?}"
10976        );
10977    }
10978
10979    #[test]
10980    fn rejects_wit_with_empty_package() {
10981        // `wasi:` — namespace alone with no package. Pre-gate this
10982        // failed neither the is_http nor is_pubsub nor is_store
10983        // prefix check (none of `wasi:http/`, `wasi:keyvalue/` match
10984        // a bare `wasi:`), so it silently demoted to Capability.
10985        let err = contrato_wit_err("wasi:");
10986        assert!(
10987            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
10988                if wit == "wasi:" && reason.contains("package") && reason.contains("must not be empty")),
10989            "got {err:?}"
10990        );
10991    }
10992
10993    #[test]
10994    fn rejects_wit_with_underscore() {
10995        // Underscore — WIT identifiers are kebab-case, same rule
10996        // DNS-1123 enforces on its peer axes. The diagnostic carries
10997        // the explicit "use `-` instead" remediation.
10998        let err = contrato_wit_err("wasi:http_proxy");
10999        assert!(
11000            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11001                if wit == "wasi:http_proxy" && reason.contains('_')),
11002            "got {err:?}"
11003        );
11004    }
11005
11006    #[test]
11007    fn rejects_wit_with_whitespace() {
11008        // Whitespace mid-token — the prefix check matches but the
11009        // package-and-onward parse silently demoted to Capability.
11010        let err = contrato_wit_err("wasi:http proxy");
11011        assert!(
11012            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11013                if wit == "wasi:http proxy" && reason.contains("whitespace")),
11014            "got {err:?}"
11015        );
11016    }
11017
11018    #[test]
11019    fn rejects_wit_with_non_ascii() {
11020        // Un-percent-encoded non-ASCII byte — the canonical "I copied
11021        // the package name from a doc with smart quotes / accented
11022        // characters" footgun.
11023        let err = contrato_wit_err("wasi:caf\u{e9}/proxy");
11024        assert!(
11025            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11026                if wit == "wasi:caf\u{e9}/proxy" && reason.contains("non-ASCII")),
11027            "got {err:?}"
11028        );
11029    }
11030
11031    #[test]
11032    fn rejects_wit_with_consecutive_hyphens() {
11033        // `pub--sub` — WIT identifiers join words with single hyphens.
11034        let err = contrato_wit_err("nats:pub--sub");
11035        assert!(
11036            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11037                if wit == "nats:pub--sub" && reason.contains("consecutive `-`")),
11038            "got {err:?}"
11039        );
11040    }
11041
11042    #[test]
11043    fn rejects_wit_with_trailing_at_no_version() {
11044        // `wasi:http/proxy@` — the version-suffix author started to
11045        // type `@0.2.0` and stopped, leaving a stray `@`. The WIT
11046        // parser would reject this; surface it at validate time.
11047        let err = contrato_wit_err("wasi:http/proxy@");
11048        assert!(
11049            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11050                if wit == "wasi:http/proxy@" && reason.contains("trailing `@`")),
11051            "got {err:?}"
11052        );
11053    }
11054
11055    #[test]
11056    fn rejects_wit_too_long() {
11057        // 129-byte WIT reference — one over the WIT_IDENT_MAX_LEN cap.
11058        // The legitimate-shape arms all pass (lowercase, single `:`,
11059        // kebab-case identifiers); only the cap arm fires. Surfaces
11060        // the paste-from-binary / accidental-multi-line-blob landing
11061        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
11062        // on the peer axis.
11063        let big = format!("wasi:{}", "a".repeat(124));
11064        assert_eq!(big.len(), 129);
11065        let err = contrato_wit_err(&big);
11066        assert!(
11067            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, ref reason, .. }
11068                if wit == &big && reason.contains("max length of 128")),
11069            "got {err:?}"
11070        );
11071    }
11072
11073    #[test]
11074    fn wit_max_length_validates() {
11075        // 128-byte WIT reference — exactly the cap. Boundary pin:
11076        // drift in the cap surfaces here and at `rejects_wit_too_long`
11077        // simultaneously, mirroring
11078        // `http_contrato_endpoint_max_length_validates` on the peer
11079        // axis.
11080        let big = format!("wasi:{}", "a".repeat(123));
11081        assert_eq!(big.len(), 128);
11082        let mut s = three_member_spec();
11083        s.contratos.push(WitContract {
11084            de: "payment".into(),
11085            para: "catalog".into(),
11086            wit: big,
11087            endpoint: None,
11088            subject: None,
11089            slot: None,
11090        });
11091        s.validate().unwrap();
11092    }
11093
11094    #[test]
11095    fn wit_accepts_canonical_forms_at_aplicacao_layer() {
11096        // Positive-set sweep through the AplicacaoSpec::validate
11097        // surface (rather than the substrate-side predicate directly)
11098        // — pins every shape the existing test fixtures + the
11099        // checkout-aplicacao example carry, so the gate's accept-set
11100        // matches the substrate's emit-set. Drift between this list
11101        // and `render::tests::wit_world_ref_accepts_canonical_forms`
11102        // surfaces at the substrate layer's positive sweep — one
11103        // source of truth for the rule.
11104        for wit in [
11105            "wasi:http/proxy",
11106            "wasi:keyvalue/store",
11107            "nats:pub-sub",
11108            "kafka:topic",
11109            "custom:exchange",
11110            "pleme:cap/audit",
11111            "wasi:http/proxy@0.2.0",
11112        ] {
11113            // Payload field paired to the dispatched WIT shape so the
11114            // shape-↔-target arm doesn't fire instead of the wit-shape
11115            // arm we're exercising. Routes off the same
11116            // `wit_shape_is_http` / `wit_shape_is_pubsub` /
11117            // `wit_shape_is_store` free functions the production
11118            // `WitContract::is_http` / `is_pubsub` / `is_store`
11119            // methods delegate to (both consult the lifted
11120            // `WIT_HTTP_SHAPE_PREFIXES` / `WIT_PUBSUB_SHAPE_PREFIXES`
11121            // / `WIT_STORE_SHAPE_PREFIXES` prefix sets), so any
11122            // future prefix addition to the routing accept-set
11123            // reaches this test's payload-dispatch arm by
11124            // construction — no per-test-site drift can hide a
11125            // shape-→-target-slot mismatch that would silently
11126            // demote a canonical `:wit` value to the
11127            // `(None, None, None)` capability-only arm and let the
11128            // `AplicacaoSpec::validate` positive sweep pass on a
11129            // shape it should exercise as HTTP / pub-sub / store.
11130            let (endpoint, subject, slot) = if wit_shape_is_http(wit) {
11131                (Some("/x".into()), None, None)
11132            } else if wit_shape_is_pubsub(wit) {
11133                (None, Some("topic.x".into()), None)
11134            } else if wit_shape_is_store(wit) {
11135                (None, None, Some("bucket/$key".into()))
11136            } else {
11137                (None, None, None)
11138            };
11139            let mut s = three_member_spec();
11140            s.contratos.push(WitContract {
11141                de: "payment".into(),
11142                para: "catalog".into(),
11143                wit: wit.into(),
11144                endpoint,
11145                subject,
11146                slot,
11147            });
11148            s.validate()
11149                .unwrap_or_else(|e| panic!("canonical WIT {wit:?} must validate, got {e:?}"));
11150        }
11151    }
11152
11153    #[test]
11154    fn wit_shape_predicates_accept_canonical_prefix_set() {
11155        // Positive-set sweep pinning every prefix in
11156        // WIT_HTTP_SHAPE_PREFIXES / WIT_PUBSUB_SHAPE_PREFIXES /
11157        // WIT_STORE_SHAPE_PREFIXES against the three free-function
11158        // dispatch predicates. The six prefixes are the load-bearing
11159        // routing keys the substrate's WIT-shape dispatch consults
11160        // (L7-HTTP-vs-L4, pub-sub-cycle exclusion,
11161        // key/value-store-slot admission); any drift between the
11162        // free-function accept-set and this list surfaces here
11163        // rather than at apply time as a silent
11164        // shape-→-capability-only demotion.
11165        assert!(wit_shape_is_http("wasi:http/proxy"));
11166        assert!(wit_shape_is_http("wasi:http/proxy@0.2.0"));
11167        assert!(wit_shape_is_http("http:incoming"));
11168
11169        assert!(wit_shape_is_pubsub("nats:pub-sub"));
11170        assert!(wit_shape_is_pubsub("kafka:topic"));
11171
11172        assert!(wit_shape_is_store("wasi:keyvalue/store"));
11173        assert!(wit_shape_is_store("kv:cache/session"));
11174    }
11175
11176    #[test]
11177    fn wit_shape_predicates_reject_uncanonical_forms() {
11178        // Negative-set pin: the six canonical prefixes are
11179        // lowercase-only (mirrors the `is_wit_world_ref` substrate
11180        // predicate's lowercase invariant — see its docstring on the
11181        // "I thought I had L7 HTTP routing, got L4-only" footgun).
11182        // The empty string, an uppercase-prefixed form, a hyphen-
11183        // instead-of-colon typo, and a bare kebab identifier all miss
11184        // every shape arm — reachable-by-construction only via the
11185        // `is_wit_world_ref` gate that admission-checks the `:wit`
11186        // value first, but pinned here so any future
11187        // free-function change (e.g. a case-insensitive
11188        // `wit.to_ascii_lowercase().starts_with(p)` slip) surfaces at
11189        // this unit level.
11190        for wit in ["", "WASI:HTTP/proxy", "wasi-http/proxy", "custom-shape"] {
11191            assert!(!wit_shape_is_http(wit), "{wit:?} must not be HTTP");
11192            assert!(!wit_shape_is_pubsub(wit), "{wit:?} must not be pubsub");
11193            assert!(!wit_shape_is_store(wit), "{wit:?} must not be store");
11194        }
11195    }
11196
11197    #[test]
11198    fn wit_shape_predicates_partition_canonical_set() {
11199        // Every canonical prefix routes to exactly one shape arm —
11200        // the three prefix sets are pairwise disjoint. Pins the
11201        // routing property [`WitContract::target`] relies on: an
11202        // `is_http()` return of `true` guarantees `is_pubsub()` and
11203        // `is_store()` return `false`, so the shape-→-target-slot
11204        // dispatch (endpoint vs subject vs slot) is unambiguous.
11205        // Drift (e.g. a future `"kv:"` moved into the HTTP set
11206        // without removal from the store set) would silently route
11207        // one prefix to two arms and the first-matching-arm order
11208        // becomes load-bearing — this pin surfaces it as a build
11209        // error instead.
11210        for prefix in WIT_HTTP_SHAPE_PREFIXES {
11211            let sample = format!("{prefix}x");
11212            assert!(wit_shape_is_http(&sample));
11213            assert!(!wit_shape_is_pubsub(&sample));
11214            assert!(!wit_shape_is_store(&sample));
11215        }
11216        for prefix in WIT_PUBSUB_SHAPE_PREFIXES {
11217            let sample = format!("{prefix}x");
11218            assert!(!wit_shape_is_http(&sample));
11219            assert!(wit_shape_is_pubsub(&sample));
11220            assert!(!wit_shape_is_store(&sample));
11221        }
11222        for prefix in WIT_STORE_SHAPE_PREFIXES {
11223            let sample = format!("{prefix}x");
11224            assert!(!wit_shape_is_http(&sample));
11225            assert!(!wit_shape_is_pubsub(&sample));
11226            assert!(wit_shape_is_store(&sample));
11227        }
11228    }
11229
11230    #[test]
11231    fn wit_shape_matches_scans_prefix_set_with_starts_with_semantics() {
11232        // Positive pin: [`wit_shape_matches`] is exactly the
11233        // `PREFIXES.iter().any(|p| wit.starts_with(p))` combinator,
11234        // parameterized on the accept-set. Two-prefix accept-set,
11235        // one-prefix accept-set, and empty accept-set (which must
11236        // reject everything, including the empty string — an empty
11237        // `any()` fold returns `false`) all pinned so a future
11238        // reimplementation that swaps `starts_with` for `contains`,
11239        // `==`, or a case-folded comparator surfaces at unit-test
11240        // time.
11241        let two = &["wasi:http/", "http:"];
11242        assert!(wit_shape_matches("wasi:http/proxy", two));
11243        assert!(wit_shape_matches("http:incoming", two));
11244        assert!(!wit_shape_matches("wasi:keyvalue/store", two));
11245
11246        let one = &["nats:"];
11247        assert!(wit_shape_matches("nats:pub-sub", one));
11248        assert!(!wit_shape_matches("kafka:topic", one));
11249
11250        // Empty accept-set matches nothing — the identity element
11251        // for the disjunctive `any()` fold across the prefix set.
11252        // Reachable via a future `wit_shape_is_<name>` const paired
11253        // to a still-empty prefix table on a nascent shape-arm draft.
11254        let empty: &[&str] = &[];
11255        assert!(!wit_shape_matches("wasi:http/proxy", empty));
11256        assert!(!wit_shape_matches("", empty));
11257
11258        // starts_with, not contains: a prefix embedded mid-string
11259        // never matches. Pins the routing invariant [`WitContract::target`]
11260        // relies on (an authored `:wit "custom:wasi:http/"` string
11261        // does not silently route through the HTTP arm just because
11262        // it happens to contain the canonical HTTP prefix).
11263        assert!(!wit_shape_matches("custom:wasi:http/proxy", two));
11264    }
11265
11266    #[test]
11267    fn wit_shape_predicates_delegate_to_wit_shape_matches() {
11268        // Equivalence pin: each per-shape predicate is exactly
11269        // `wit_shape_matches(wit, WIT_<SHAPE>_SHAPE_PREFIXES)`. Sweeps
11270        // every canonical prefix + the empty string + one negative
11271        // sample against every peer so a future predicate that grew
11272        // its own inline `iter().any(starts_with)` (rather than
11273        // delegating through the lifted combinator) drifts loudly here
11274        // — the peer-const table's contents must agree with the
11275        // predicate's accept-set by construction.
11276        let samples = [
11277            String::new(),
11278            "wasi:http/proxy".to_string(),
11279            "http:incoming".to_string(),
11280            "nats:pub-sub".to_string(),
11281            "kafka:topic".to_string(),
11282            "wasi:keyvalue/store".to_string(),
11283            "kv:cache/session".to_string(),
11284            "custom-shape".to_string(),
11285            "WASI:HTTP/proxy".to_string(),
11286        ];
11287        for wit in &samples {
11288            assert_eq!(
11289                wit_shape_is_http(wit),
11290                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11291                "wit_shape_is_http drifted from combinator on {wit:?}",
11292            );
11293            assert_eq!(
11294                wit_shape_is_pubsub(wit),
11295                wit_shape_matches(wit, WIT_PUBSUB_SHAPE_PREFIXES),
11296                "wit_shape_is_pubsub drifted from combinator on {wit:?}",
11297            );
11298            assert_eq!(
11299                wit_shape_is_store(wit),
11300                wit_shape_matches(wit, WIT_STORE_SHAPE_PREFIXES),
11301                "wit_shape_is_store drifted from combinator on {wit:?}",
11302            );
11303        }
11304    }
11305
11306    #[test]
11307    fn wit_contract_shape_methods_delegate_to_free_functions() {
11308        // Equivalence pin: `WitContract::is_http` / `is_pubsub` /
11309        // `is_store` are `&self` conveniences on top of the free
11310        // functions — for every canonical prefix the method's return
11311        // matches its free-function peer. Sweeps the union of the
11312        // three prefix sets so a future method that grew its own
11313        // inline prefix logic (rather than delegating) drifts loudly
11314        // here on the first prefix the free function accepts and the
11315        // method doesn't.
11316        for shape_set in [
11317            WIT_HTTP_SHAPE_PREFIXES,
11318            WIT_PUBSUB_SHAPE_PREFIXES,
11319            WIT_STORE_SHAPE_PREFIXES,
11320        ] {
11321            for prefix in shape_set {
11322                let c = WitContract {
11323                    de: "cart".into(),
11324                    para: "catalog".into(),
11325                    wit: format!("{prefix}x"),
11326                    endpoint: None,
11327                    subject: None,
11328                    slot: None,
11329                };
11330                assert_eq!(c.is_http(), wit_shape_is_http(&c.wit));
11331                assert_eq!(c.is_pubsub(), wit_shape_is_pubsub(&c.wit));
11332                assert_eq!(c.is_store(), wit_shape_is_store(&c.wit));
11333                assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11334            }
11335        }
11336        // Capability-arm delegation sweep: two representative
11337        // Capability-shaped `:wit` values (a bare non-prefix-matching
11338        // WIT world, the deliberately-shaped empty string
11339        // [`WitContract::is_capability`]'s docstring calls out as
11340        // syntactically Capability). Extends the free-function
11341        // delegation pin onto the fourth arm so a future
11342        // [`WitContract::is_capability`] rewrite that grew an inline
11343        // prefix-set scan (rather than delegating through
11344        // [`wit_shape_is_capability`]) drifts loudly here on the first
11345        // Capability-shaped sample.
11346        for wit in ["custom:capability-only", ""] {
11347            let c = WitContract {
11348                de: "cart".into(),
11349                para: "catalog".into(),
11350                wit: wit.into(),
11351                endpoint: None,
11352                subject: None,
11353                slot: None,
11354            };
11355            assert_eq!(c.is_capability(), wit_shape_is_capability(&c.wit));
11356        }
11357    }
11358
11359    #[test]
11360    fn wit_shape_is_capability_partitions_the_wit_shape_space_on_the_raw_str_axis() {
11361        // 4-way partition-witness pin on the raw `&str` axis: for every
11362        // canonical prefix in the three payload-arm accept-sets,
11363        // exactly one of the four [`wit_shape_is_http`] /
11364        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11365        // [`wit_shape_is_capability`] free functions returns `true` and
11366        // the other three return `false` — the four-arm partition
11367        // witness that locks the free-function WIT-shape-classifier
11368        // family into a partition of the `:contratos :wit` axis
11369        // load-bearing. Peer of the sibling [`WitContract`]-surface
11370        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
11371        // partition pin — extends the discipline onto the raw `&str`
11372        // axis so any future arm addition (a hypothetical
11373        // `wasi:sockets/*` transport-layer shape, an `oci:*`
11374        // capability-import carrier per the sibling
11375        // [`wit_shape_matches`] docstring's trajectory bullet) that
11376        // landed on one of the payload-arm free functions without
11377        // shrinking [`wit_shape_is_capability`]'s accept-set surfaces
11378        // here as two arms returning `true` simultaneously at
11379        // caixa-core build time rather than a silent per-consumer
11380        // misclassification at renderer emit time.
11381        for shape_set in [
11382            WIT_HTTP_SHAPE_PREFIXES,
11383            WIT_PUBSUB_SHAPE_PREFIXES,
11384            WIT_STORE_SHAPE_PREFIXES,
11385        ] {
11386            for prefix in shape_set {
11387                let wit = format!("{prefix}x");
11388                let hits = [
11389                    wit_shape_is_http(&wit),
11390                    wit_shape_is_pubsub(&wit),
11391                    wit_shape_is_store(&wit),
11392                    wit_shape_is_capability(&wit),
11393                ]
11394                .iter()
11395                .filter(|&&b| b)
11396                .count();
11397                assert_eq!(
11398                    hits,
11399                    1,
11400                    "raw-&str WIT-shape 4-way predicate partition must \
11401                     admit exactly one arm per canonical prefix; got {hits} \
11402                     hits at wit={wit:?} (is_http={}, is_pubsub={}, is_store={}, \
11403                     is_capability={})",
11404                    wit_shape_is_http(&wit),
11405                    wit_shape_is_pubsub(&wit),
11406                    wit_shape_is_store(&wit),
11407                    wit_shape_is_capability(&wit),
11408                );
11409            }
11410        }
11411        // Capability-arm sweep on the raw `&str` axis: two
11412        // representative Capability-shaped `:wit` values (a bare non-
11413        // prefix-matching WIT world, the deliberately-shaped empty
11414        // string the pure classifier still admits per
11415        // [`wit_shape_is_capability`]'s docstring). Both must land on
11416        // the fourth arm exclusively so the partition witness holds
11417        // across the full 4-arm closure on the raw `&str` axis.
11418        for wit in ["custom:capability-only", ""] {
11419            let hits = [
11420                wit_shape_is_http(wit),
11421                wit_shape_is_pubsub(wit),
11422                wit_shape_is_store(wit),
11423                wit_shape_is_capability(wit),
11424            ]
11425            .iter()
11426            .filter(|&&b| b)
11427            .count();
11428            assert_eq!(
11429                hits, 1,
11430                "raw-&str WIT-shape 4-way predicate partition must \
11431                 admit exactly one arm on Capability-shaped wit={wit:?}"
11432            );
11433            assert!(
11434                wit_shape_is_capability(wit),
11435                "wit={wit:?} must project onto the Capability arm on the raw-&str axis"
11436            );
11437        }
11438    }
11439
11440    #[test]
11441    fn wit_shape_is_capability_composes_through_payload_arm_predicate_negation() {
11442        // Composition-witness pin: [`wit_shape_is_capability`] is the
11443        // exact-inverse disjunction of the sibling payload-arm free-
11444        // function trio [`wit_shape_is_http`] / [`wit_shape_is_pubsub`]
11445        // / [`wit_shape_is_store`]. A future reimplementation that
11446        // grew its own prefix-set scan (e.g. inlining a fourth
11447        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does
11448        // not own today) rather than delegating to the sibling trio
11449        // would drift loudly here — the composition contract binds the
11450        // fourth-arm free-function predicate to the exact-inverse of
11451        // the three payload-arm free-function predicates, so any
11452        // rebrand of any prefix-set const flows through
11453        // [`wit_shape_is_capability`] by construction without a
11454        // coordinated per-consumer rewrite. Peer of the sibling
11455        // [`WitContract`]-surface
11456        // [`wit_contract_is_capability_composes_through_shape_predicate_negation`]
11457        // composition pin — extends the discipline onto the raw
11458        // `&str` axis.
11459        let mut cases: Vec<String> = Vec::new();
11460        for shape_set in [
11461            WIT_HTTP_SHAPE_PREFIXES,
11462            WIT_PUBSUB_SHAPE_PREFIXES,
11463            WIT_STORE_SHAPE_PREFIXES,
11464        ] {
11465            for prefix in shape_set {
11466                cases.push(format!("{prefix}x"));
11467            }
11468        }
11469        cases.push("custom:capability-only".to_string());
11470        cases.push(String::new());
11471        for wit in cases {
11472            assert_eq!(
11473                wit_shape_is_capability(&wit),
11474                !wit_shape_is_http(&wit) && !wit_shape_is_pubsub(&wit) && !wit_shape_is_store(&wit),
11475                "wit_shape_is_capability must equal \
11476                 !wit_shape_is_http() && !wit_shape_is_pubsub() && !wit_shape_is_store() \
11477                 at wit={wit:?}"
11478            );
11479        }
11480    }
11481
11482    #[test]
11483    fn wit_shape_classifier_family_is_const_fn() {
11484        // Fail-before-pass-after pin on the 4-arm free-function WIT-
11485        // shape classifier family's `const`-eval posture. Each of the
11486        // four peer classifiers ([`wit_shape_is_http`] /
11487        // [`wit_shape_is_pubsub`] / [`wit_shape_is_store`] /
11488        // [`wit_shape_is_capability`]) and the underlying combinator
11489        // [`wit_shape_matches`] must be `pub const fn` — any future
11490        // accidental downgrade to non-`const` fails the `const fn`
11491        // wrappers below at caixa-core build time with E0015
11492        // (`cannot call non-const function`), strictly stronger than
11493        // a runtime `assert!` and strictly stronger than the module-
11494        // scope `const _: () = assert!(…)` pins immediately after the
11495        // classifier declarations (those anchor specific accept-set
11496        // truth-table entries; this pin anchors the `const` posture
11497        // itself via `const fn` wrappers that are only well-formed
11498        // when the callee is itself `const fn`).
11499        //
11500        // Verified fail-before-pass-after by locally reverting
11501        // `pub const fn` → `pub fn` on each classifier and observing
11502        // E0015 at every corresponding wrapper call site (build
11503        // error, no test-time surface), then restoring `pub const fn`
11504        // and observing the pin pass at test time. Peer of the
11505        // sibling M3
11506        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11507        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11508        // M2
11509        // [`child_spec_restart_accessor_is_const_fn`] /
11510        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11511        // and M3
11512        // [`placement_estrategia_accessor_is_const_fn`] /
11513        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11514        // sibling `const`-eval-surface-pass axes.
11515        const fn matches_via_const_fn(wit: &str, prefixes: &[&str]) -> bool {
11516            wit_shape_matches(wit, prefixes)
11517        }
11518        const fn http_via_const_fn(wit: &str) -> bool {
11519            wit_shape_is_http(wit)
11520        }
11521        const fn pubsub_via_const_fn(wit: &str) -> bool {
11522            wit_shape_is_pubsub(wit)
11523        }
11524        const fn store_via_const_fn(wit: &str) -> bool {
11525            wit_shape_is_store(wit)
11526        }
11527        const fn capability_via_const_fn(wit: &str) -> bool {
11528            wit_shape_is_capability(wit)
11529        }
11530        // Sweep one canonical accept-set sample per arm plus the
11531        // payload-less/empty capability samples, asserting the
11532        // wrapper and direct dispatches agree byte-for-byte across
11533        // the closed 4-arm partition.
11534        let cases: [(&str, bool, bool, bool, bool); 6] = [
11535            ("wasi:http/proxy", true, false, false, false),
11536            ("http:incoming", true, false, false, false),
11537            ("nats:events", false, true, false, false),
11538            ("kafka:topic", false, true, false, false),
11539            ("wasi:keyvalue/store", false, false, true, false),
11540            ("kv:cache", false, false, true, false),
11541        ];
11542        for (wit, is_http, is_pubsub, is_store, _is_capability) in cases {
11543            assert_eq!(
11544                matches_via_const_fn(wit, WIT_HTTP_SHAPE_PREFIXES),
11545                wit_shape_matches(wit, WIT_HTTP_SHAPE_PREFIXES),
11546                "wit_shape_matches const fn wrapper disagrees at wit={wit:?}",
11547            );
11548            assert_eq!(http_via_const_fn(wit), wit_shape_is_http(wit));
11549            assert_eq!(pubsub_via_const_fn(wit), wit_shape_is_pubsub(wit));
11550            assert_eq!(store_via_const_fn(wit), wit_shape_is_store(wit));
11551            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11552            assert_eq!(wit_shape_is_http(wit), is_http);
11553            assert_eq!(wit_shape_is_pubsub(wit), is_pubsub);
11554            assert_eq!(wit_shape_is_store(wit), is_store);
11555        }
11556        // Payload-less capability arm (the 4th partition arm).
11557        let capability_samples: [&str; 3] =
11558            ["wasi:filesystem/preopens", "custom:capability-only", ""];
11559        for wit in capability_samples {
11560            assert_eq!(capability_via_const_fn(wit), wit_shape_is_capability(wit));
11561            assert!(wit_shape_is_capability(wit));
11562            assert!(!wit_shape_is_http(wit));
11563            assert!(!wit_shape_is_pubsub(wit));
11564            assert!(!wit_shape_is_store(wit));
11565        }
11566    }
11567
11568    #[test]
11569    fn wit_shape_matches_composes_through_bytes_starts_with_across_boundary_lengths() {
11570        // Composition-witness pin: [`wit_shape_matches`] agrees with
11571        // the reference `prefixes.iter().any(|p| wit.starts_with(p))`
11572        // dispatch (the prior non-`const` implementation) across
11573        // boundary lengths — empty `wit`, empty prefix, one-byte
11574        // slack, prefix longer than `wit`, one-byte trailing slack.
11575        // The rewrite to a byte-level manual starts_with loop (the
11576        // enabler for the `pub const fn` posture) must not change any
11577        // truth-table entry on the canonical accept-set — this pin
11578        // sweeps a targeted boundary corpus and asserts byte-for-byte
11579        // agreement, locking the const-fn rewrite's semantics against
11580        // the prior iterator body by construction.
11581        let prefixes = &["wasi:http/", "http:"][..];
11582        let cases: [(&str, bool); 12] = [
11583            ("wasi:http/proxy", true),
11584            ("wasi:http/", true), // exact-length match on prefix
11585            ("wasi:http", false), // one byte short
11586            ("http:", true),
11587            ("http:incoming", true),
11588            ("http", false), // one byte short
11589            ("", false),
11590            ("wasi:https/proxy", false),
11591            ("nats:events", false),
11592            ("HTTPS:", false), // uppercase — no case-fold in classifier
11593            ("wasi:HTTP/proxy", false),
11594            ("wasi:http", false),
11595        ];
11596        for (wit, expected) in cases {
11597            assert_eq!(
11598                wit_shape_matches(wit, prefixes),
11599                expected,
11600                "wit_shape_matches disagrees with reference at wit={wit:?}",
11601            );
11602            // Byte-equal to the iterator body it replaced.
11603            let via_iter = prefixes.iter().any(|p| wit.starts_with(p));
11604            assert_eq!(
11605                wit_shape_matches(wit, prefixes),
11606                via_iter,
11607                "wit_shape_matches must byte-equal iter().any(starts_with) at wit={wit:?}",
11608            );
11609        }
11610        // Empty prefix set → always false regardless of `wit`.
11611        let empty: &[&str] = &[];
11612        assert!(!wit_shape_matches("", empty));
11613        assert!(!wit_shape_matches("wasi:http/proxy", empty));
11614        // Empty prefix inside a non-empty set → always true (every
11615        // string starts with the empty string, matching the
11616        // iterator body's semantics on `str::starts_with("")`).
11617        let contains_empty: &[&str] = &["nats:", ""];
11618        assert!(wit_shape_matches("", contains_empty));
11619        assert!(wit_shape_matches("wasi:http/proxy", contains_empty));
11620    }
11621
11622    #[test]
11623    fn wit_contract_is_capability_partitions_the_wit_shape_space() {
11624        // 4-way partition-witness pin: for every canonical prefix in
11625        // the payload-arm accept-sets, exactly one of the four
11626        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11627        // [`WitContract::is_store`] / [`WitContract::is_capability`]
11628        // predicates returns `true` and the other three return `false`
11629        // — the four-arm partition witness that locks the substrate's
11630        // WIT-shape-space closure on the pre-projection axis load-
11631        // bearing. A future arm addition (a hypothetical fourth
11632        // payload-shape prefix set, a `wasi:sockets/*` transport-layer
11633        // shape) that landed on one of the payload-arm predicates
11634        // without shrinking [`WitContract::is_capability`]'s accept-set
11635        // would surface here as two arms returning `true` simultaneously
11636        // — a partition-witness break the pin catches at caixa-core
11637        // build time rather than a silent per-consumer misclassification
11638        // at renderer emit time. Peer of the sibling `WitTarget`-side
11639        // [`tests::wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set`]
11640        // partition-witness pin on the post-projection payload-scalar
11641        // arm-set — extends the discipline onto the pre-projection
11642        // 4-arm shape-space.
11643        for shape_set in [
11644            WIT_HTTP_SHAPE_PREFIXES,
11645            WIT_PUBSUB_SHAPE_PREFIXES,
11646            WIT_STORE_SHAPE_PREFIXES,
11647        ] {
11648            for prefix in shape_set {
11649                let c = WitContract {
11650                    de: "cart".into(),
11651                    para: "catalog".into(),
11652                    wit: format!("{prefix}x"),
11653                    endpoint: None,
11654                    subject: None,
11655                    slot: None,
11656                };
11657                let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11658                    .iter()
11659                    .filter(|&&b| b)
11660                    .count();
11661                assert_eq!(
11662                    hits,
11663                    1,
11664                    "WitContract WIT-shape 4-way predicate partition must \
11665                     admit exactly one arm per canonical prefix; got {hits} \
11666                     hits at wit={:?} (is_http={}, is_pubsub={}, is_store={}, \
11667                     is_capability={})",
11668                    c.wit,
11669                    c.is_http(),
11670                    c.is_pubsub(),
11671                    c.is_store(),
11672                    c.is_capability(),
11673                );
11674            }
11675        }
11676        // Capability-arm sweep: two representative capability shapes
11677        // (a bare WIT world outside the three payload-arm prefix sets,
11678        // and the deliberately-shaped empty string that
11679        // [`crate::render::is_wit_world_ref`] rejects at
11680        // [`WitContract::target`] time but which the pure classifier
11681        // still admits — see the method docstring's "purely syntactic
11682        // classification" note). Both must land on the fourth arm
11683        // exclusively, so the partition witness holds across the full
11684        // 4-arm closure.
11685        for wit in ["custom:capability-only", ""] {
11686            let c = WitContract {
11687                de: "cart".into(),
11688                para: "catalog".into(),
11689                wit: wit.into(),
11690                endpoint: None,
11691                subject: None,
11692                slot: None,
11693            };
11694            let hits = [c.is_http(), c.is_pubsub(), c.is_store(), c.is_capability()]
11695                .iter()
11696                .filter(|&&b| b)
11697                .count();
11698            assert_eq!(
11699                hits, 1,
11700                "WitContract WIT-shape 4-way predicate partition must \
11701                 admit exactly one arm on Capability-shaped wit={wit:?}"
11702            );
11703            assert!(
11704                c.is_capability(),
11705                "wit={wit:?} must project onto the Capability arm"
11706            );
11707        }
11708    }
11709
11710    #[test]
11711    fn wit_contract_is_capability_composes_through_shape_predicate_negation() {
11712        // Composition-witness pin: [`WitContract::is_capability`] is the
11713        // exact-inverse disjunction of the sibling payload-arm predicate
11714        // trio [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
11715        // [`WitContract::is_store`]. A future reimplementation that
11716        // grew its own prefix-set scan (e.g. inlining a fourth
11717        // [`WIT_CAPABILITY_SHAPE_PREFIXES`] const the substrate does not
11718        // own today) rather than delegating to the sibling trio would
11719        // drift loudly here — the composition contract binds the
11720        // fourth-arm predicate to the exact-inverse of the three
11721        // payload-arm predicates, so any rebrand of any prefix-set const
11722        // flows through this method by construction without a
11723        // coordinated per-consumer rewrite. Sweeps the union of the
11724        // three payload-arm prefix sets plus two Capability-shaped
11725        // shapes (a bare non-prefix-matching WIT world, the deliberately-
11726        // empty string the pure classifier still admits per the method
11727        // docstring's "purely syntactic classification" note).
11728        let mut cases: Vec<String> = Vec::new();
11729        for shape_set in [
11730            WIT_HTTP_SHAPE_PREFIXES,
11731            WIT_PUBSUB_SHAPE_PREFIXES,
11732            WIT_STORE_SHAPE_PREFIXES,
11733        ] {
11734            for prefix in shape_set {
11735                cases.push(format!("{prefix}x"));
11736            }
11737        }
11738        cases.push("custom:capability-only".to_string());
11739        cases.push(String::new());
11740        for wit in cases {
11741            let c = WitContract {
11742                de: "cart".into(),
11743                para: "catalog".into(),
11744                wit: wit.clone(),
11745                endpoint: None,
11746                subject: None,
11747                slot: None,
11748            };
11749            assert_eq!(
11750                c.is_capability(),
11751                !c.is_http() && !c.is_pubsub() && !c.is_store(),
11752                "WitContract::is_capability must equal \
11753                 !is_http() && !is_pubsub() && !is_store() at wit={wit:?}"
11754            );
11755        }
11756    }
11757
11758    #[test]
11759    fn wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant() {
11760        // Cross-projection-witness pin: whenever [`WitContract::target`]
11761        // succeeds, the pre-projection [`WitContract::is_capability`]
11762        // classification agrees with the post-projection
11763        // [`WitTarget::is_capability`] `gen_platform::IsVariant`-derived
11764        // predicate — the 4-arm typed partition on the substrate's
11765        // typed-view surface (7f6aa98 IsVariant lift) and the peer 4-arm
11766        // partition on the pre-projection axis line up by construction.
11767        // A future divergence between the two axes (a peer
11768        // [`WitTarget`] variant addition that landed on the typed-view
11769        // surface without a peer prefix-set + [`WitContract`] predicate
11770        // extension, or vice versa) would surface here at caixa-core
11771        // build time rather than a silent per-consumer split at renderer
11772        // emit time. Peer of the sibling pre-/post-projection
11773        // agreement pins the payload-carrier trio
11774        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
11775        // [`WitContract::slot`] on pre-projection; [`WitTarget::http_endpoint`]
11776        // / [`WitTarget::pubsub_subject`] / [`WitTarget::store_slot`] on
11777        // post-projection — b11bb49 trio lift) already carry across the
11778        // three payload arms — this pin closes the pair on the fourth
11779        // payload-less arm.
11780        let http = WitContract {
11781            de: "cart".into(),
11782            para: "catalog".into(),
11783            wit: "wasi:http/proxy".into(),
11784            endpoint: Some("/x".into()),
11785            subject: None,
11786            slot: None,
11787        };
11788        assert!(!http.is_capability());
11789        assert!(!http.target().unwrap().is_capability());
11790
11791        let nats = WitContract {
11792            de: "cart".into(),
11793            para: "catalog".into(),
11794            wit: "nats:pub-sub".into(),
11795            endpoint: None,
11796            subject: Some("events.x".into()),
11797            slot: None,
11798        };
11799        assert!(!nats.is_capability());
11800        assert!(!nats.target().unwrap().is_capability());
11801
11802        let kv = WitContract {
11803            de: "cart".into(),
11804            para: "catalog".into(),
11805            wit: "wasi:keyvalue/store".into(),
11806            endpoint: None,
11807            subject: None,
11808            slot: Some("checkout/$orderId".into()),
11809        };
11810        assert!(!kv.is_capability());
11811        assert!(!kv.target().unwrap().is_capability());
11812
11813        let cap = WitContract {
11814            de: "cart".into(),
11815            para: "catalog".into(),
11816            wit: "custom:capability-only".into(),
11817            endpoint: None,
11818            subject: None,
11819            slot: None,
11820        };
11821        assert!(cap.is_capability());
11822        assert!(cap.target().unwrap().is_capability());
11823    }
11824
11825    #[test]
11826    fn wit_contract_pre_projection_accessor_family_is_const_fn() {
11827        // Fail-before-pass-after pin on the [`WitContract`] pre-
11828        // projection accessor family's `const`-eval-surface posture.
11829        // Each of the three per-`:contratos` byte-string scalar
11830        // accessors ([`WitContract::source`] / [`WitContract::destination`]
11831        // / [`WitContract::world_ref`], each projecting through
11832        // `String::as_str` — const-stable since Rust 1.87, well within
11833        // the workspace MSRV) and each of the four peer WIT-shape
11834        // predicates ([`WitContract::is_http`] /
11835        // [`WitContract::is_pubsub`] / [`WitContract::is_store`] /
11836        // [`WitContract::is_capability`], each composing
11837        // `wit_shape_is_<arm>(self.world_ref())` on the `pub const fn`
11838        // free-function classifier family the sibling
11839        // [`wit_shape_classifier_family_is_const_fn`] pin already
11840        // anchors on the raw `&str → bool` axis) must be `pub const fn`
11841        // — any future accidental downgrade to non-`const` fails the
11842        // `const fn` wrappers below at caixa-core build time with E0015
11843        // (`cannot call non-const function`), strictly stronger than a
11844        // runtime `assert!` and strictly stronger than a
11845        // module-scope `const _: () = assert!(…)` pin (which cannot be
11846        // formed on a `&WitContract` fixture because the type's
11847        // `String` / `Option<String>` carriers rule out `const`-context
11848        // construction; the `const fn` wrapper is the load-bearing
11849        // shape that side-steps the destructor-in-const restriction on
11850        // the value axis while still pinning the `const`-fn posture on
11851        // the callee).
11852        //
11853        // Peer of the sibling free-function classifier pin
11854        // [`wit_shape_classifier_family_is_const_fn`] (d46420c) on the
11855        // raw `&str → bool` axis — this pin extends the same
11856        // `const`-eval-surface discipline onto the peer method surface
11857        // that composes through those free-function classifiers, and
11858        // simultaneously onto the underlying per-`:contratos`
11859        // byte-string scalar-accessor trio each predicate reads
11860        // through. Sibling of the peer M3
11861        // [`rate_limit_unit_from_window_accessor_is_const_fn`] /
11862        // [`rate_limit_canonical_unit_accessor_is_const_fn`] (974bbd8),
11863        // M2
11864        // [`child_spec_restart_accessor_is_const_fn`] /
11865        // [`supervisor_spec_estrategia_accessor_is_const_fn`] (152c868),
11866        // and M3
11867        // [`placement_estrategia_accessor_is_const_fn`] /
11868        // [`entrada_port_accessor_is_const_fn`] (bafa004) pins on the
11869        // sibling `const`-eval-surface-pass axes.
11870        const fn source_via_const_fn(c: &WitContract) -> &str {
11871            c.source()
11872        }
11873        const fn destination_via_const_fn(c: &WitContract) -> &str {
11874            c.destination()
11875        }
11876        const fn world_ref_via_const_fn(c: &WitContract) -> &str {
11877            c.world_ref()
11878        }
11879        const fn is_http_via_const_fn(c: &WitContract) -> bool {
11880            c.is_http()
11881        }
11882        const fn is_pubsub_via_const_fn(c: &WitContract) -> bool {
11883            c.is_pubsub()
11884        }
11885        const fn is_store_via_const_fn(c: &WitContract) -> bool {
11886            c.is_store()
11887        }
11888        const fn is_capability_via_const_fn(c: &WitContract) -> bool {
11889            c.is_capability()
11890        }
11891        // Sweep one canonical accept-set sample per WIT-shape arm plus
11892        // a payload-less capability sample, asserting the wrapper and
11893        // direct dispatches agree byte-for-byte across the closed
11894        // 4-arm partition on both the scalar-accessor trio and the
11895        // WIT-shape-predicate family.
11896        for (wit, is_http, is_pubsub, is_store, is_capability) in [
11897            ("wasi:http/proxy", true, false, false, false),
11898            ("http:incoming", true, false, false, false),
11899            ("nats:events", false, true, false, false),
11900            ("kafka:topic", false, true, false, false),
11901            ("wasi:keyvalue/store", false, false, true, false),
11902            ("kv:cache", false, false, true, false),
11903            ("custom:capability-only", false, false, false, true),
11904            ("", false, false, false, true),
11905        ] {
11906            let c = WitContract {
11907                de: "cart".into(),
11908                para: "catalog".into(),
11909                wit: wit.into(),
11910                endpoint: None,
11911                subject: None,
11912                slot: None,
11913            };
11914            assert_eq!(source_via_const_fn(&c), c.source());
11915            assert_eq!(destination_via_const_fn(&c), c.destination());
11916            assert_eq!(world_ref_via_const_fn(&c), c.world_ref());
11917            assert_eq!(is_http_via_const_fn(&c), c.is_http());
11918            assert_eq!(is_pubsub_via_const_fn(&c), c.is_pubsub());
11919            assert_eq!(is_store_via_const_fn(&c), c.is_store());
11920            assert_eq!(is_capability_via_const_fn(&c), c.is_capability());
11921            assert_eq!(c.source(), "cart");
11922            assert_eq!(c.destination(), "catalog");
11923            assert_eq!(c.world_ref(), wit);
11924            assert_eq!(c.is_http(), is_http);
11925            assert_eq!(c.is_pubsub(), is_pubsub);
11926            assert_eq!(c.is_store(), is_store);
11927            assert_eq!(c.is_capability(), is_capability);
11928        }
11929    }
11930
11931    #[test]
11932    fn wit_contract_identity_projection_accessor_is_const_fn() {
11933        // Fail-before-pass-after pin on the [`WitContract::identity`]
11934        // six-arm composite-projection accessor's `const`-eval-surface
11935        // posture. The accessor projects the typed edge's six identity
11936        // arms (`:de` / `:para` / `:wit` / `:endpoint` / `:subject` /
11937        // `:slot`) as a borrowed [`ContratoIdentity<'_>`] six-tuple —
11938        // every callee is itself `pub const fn` ([`WitContract::source`]
11939        // / [`WitContract::destination`] / [`WitContract::world_ref`]
11940        // through `String::as_str`, const-stable since Rust 1.87;
11941        // [`WitContract::endpoint`] / [`WitContract::subject`] /
11942        // [`WitContract::slot`] through the sibling `match &self
11943        // .<field> { Some(s) => Some(s.as_str()), None => None }` shape
11944        // 0650f64 closed the const-eval surface on) and the tuple
11945        // constructor from borrowed-reference / `Option`-of-borrowed-
11946        // reference arms is trivially const. Any future accidental
11947        // downgrade fails the `identity_via_const_fn` wrapper at
11948        // caixa-core build time with E0015 (`cannot call non-const
11949        // method`), strictly stronger than a runtime `assert!` and
11950        // strictly stronger than a module-scope `const _: () =
11951        // assert!(…)` pin (which cannot be formed on a `&WitContract`
11952        // fixture because the type's `String` / `Option<String>`
11953        // carriers rule out `const`-context value construction; the
11954        // `const fn` wrapper is the load-bearing shape that side-steps
11955        // the destructor-in-const restriction on the value axis while
11956        // still pinning the `const`-fn posture on the callee — mirror
11957        // of the sibling
11958        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
11959        // pin's discipline verbatim on the peer scalar-accessor
11960        // surface).
11961        //
11962        // Peer of the sibling
11963        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
11964        // (279823b) pin on the six per-`:contratos` scalar-accessor
11965        // callees this composite-projection reads through — where that
11966        // pin anchors the const-eval surface at the six individual
11967        // scalar-accessor arms, this pin extends the same posture onto
11968        // the composite six-tuple projection every consumer that dedups
11969        // typed edges on the [`ContratoIdentity`] axis keys off (the
11970        // [`AplicacaoSpec::validate`]-side duplicate-`:contratos`
11971        // scanner + its BTreeMap dedup key; a future per-Aplicacao CR
11972        // materializer's per-edge identity-based admission webhook; a
11973        // future L7 policy-emitter that shards CNPs by identity-tuple
11974        // rather than by name). Same fail-before-pass-after wrapper
11975        // discipline as the peer M2 / M3 accessor-family pins on the
11976        // sibling `const`-eval-surface passes.
11977        const fn identity_via_const_fn(c: &WitContract) -> ContratoIdentity<'_> {
11978            c.identity()
11979        }
11980        // Sweep one canonical WIT-shape sample per payload-carrier arm
11981        // plus a payload-less capability sample so the pin exercises
11982        // both `Some(_)`-carrying and `None`-carrying arms on all three
11983        // `Option<String>` payload-carrier axes (`:endpoint` / `:subject`
11984        // / `:slot`) — every wrapper dispatch must agree byte-for-byte
11985        // with the direct method call on every arm of the closed WIT-
11986        // shape partition.
11987        for (wit, endpoint, subject, slot) in [
11988            ("wasi:http/proxy", Some("/checkout"), None, None),
11989            ("http:incoming", Some("/api"), None, None),
11990            ("nats:events", None, Some("orders.placed"), None),
11991            ("kafka:topic", None, Some("orders.stream"), None),
11992            ("wasi:keyvalue/store", None, None, Some("carts/{id}")),
11993            ("kv:cache", None, None, Some("session/{token}")),
11994            ("custom:capability-only", None, None, None),
11995        ] {
11996            let c = WitContract {
11997                de: "cart".into(),
11998                para: "catalog".into(),
11999                wit: wit.into(),
12000                endpoint: endpoint.map(str::to_string),
12001                subject: subject.map(str::to_string),
12002                slot: slot.map(str::to_string),
12003            };
12004            assert_eq!(identity_via_const_fn(&c), c.identity());
12005            assert_eq!(
12006                c.identity(),
12007                ("cart", "catalog", wit, endpoint, subject, slot,),
12008            );
12009        }
12010    }
12011
12012    #[test]
12013    fn m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn() {
12014        // Fail-before-pass-after pin on the four M3 mesh-slot
12015        // `String → &str` scalar accessors ([`Membro::nome`] /
12016        // [`Membro::versao_requirement`] on the per-`:membros` axis,
12017        // [`Entrada::hostname`] / [`Entrada::destination`] on the
12018        // per-`:entrada` axis) — each projects the typed slot's
12019        // [`String`] storage through the `pub const fn`
12020        // [`String::as_str`] (const-stable since Rust 1.87, well
12021        // within the workspace MSRV) and any future accidental
12022        // downgrade to non-`const` fails the corresponding
12023        // `<name>_via_const_fn` wrapper at caixa-core build time with
12024        // E0015 (`cannot call non-const method`), strictly stronger
12025        // than a runtime `assert!` and strictly stronger than a
12026        // module-scope `const _: () = assert!(…)` pin (which cannot
12027        // be formed on `&Membro` / `&Entrada` fixtures because the
12028        // types' `String` carriers rule out `const`-context value
12029        // construction; the `const fn` wrapper is the load-bearing
12030        // shape that side-steps the destructor-in-const restriction
12031        // on the value axis while still pinning the `const`-fn
12032        // posture on the callee — mirror of the sibling
12033        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
12034        // (279823b) pin on the per-`:contratos` axis). Peer of the
12035        // sibling per-M2/M3/universal-axis `String → &str` accessor
12036        // family pins on the sibling `const`-eval-surface passes
12037        // ([`crate::Caixa::nome`] / [`crate::Caixa::versao`] at the
12038        // top-level manifest, [`crate::CaixaVersion::as_str`] at the
12039        // typed-newtype wrapper,
12040        // [`crate::supervisor::ChildSpec::nome`] /
12041        // [`crate::supervisor::ChildSpec::versao_requirement`] at the
12042        // M2 supervisor-tree axis,
12043        // [`crate::upgrade::UpgradeFromEntry::prior_versao`] at the
12044        // M2 upgrade axis, [`crate::dep::Dep::nome`] /
12045        // [`crate::dep::Dep::versao_requirement`] at the dep-graph
12046        // axis, and the sibling per-`:contratos`
12047        // [`WitContract::source`] / [`WitContract::destination`] /
12048        // [`WitContract::world_ref`] trio at 279823b).
12049        const fn membro_nome_via_const_fn(m: &Membro) -> &str {
12050            m.nome()
12051        }
12052        const fn membro_versao_via_const_fn(m: &Membro) -> &str {
12053            m.versao_requirement()
12054        }
12055        const fn entrada_hostname_via_const_fn(e: &Entrada) -> &str {
12056            e.hostname()
12057        }
12058        const fn entrada_destination_via_const_fn(e: &Entrada) -> &str {
12059            e.destination()
12060        }
12061        for (caixa, versao) in [
12062            ("cart", "^0.1"),
12063            ("catalog-v2", "~0.2.3"),
12064            ("checkout", "*"),
12065        ] {
12066            let m = Membro {
12067                caixa: caixa.into(),
12068                versao: versao.into(),
12069            };
12070            assert_eq!(membro_nome_via_const_fn(&m), m.nome());
12071            assert_eq!(membro_versao_via_const_fn(&m), m.versao_requirement());
12072            assert_eq!(m.nome(), caixa);
12073            assert_eq!(m.versao_requirement(), versao);
12074        }
12075        for (host, para) in [
12076            ("cart.example.com", "cart"),
12077            ("api.checkout.io", "checkout"),
12078        ] {
12079            let e = Entrada {
12080                host: host.into(),
12081                para: para.into(),
12082                paths: vec![],
12083                port: DEFAULT_SERVICO_PORT,
12084            };
12085            assert_eq!(entrada_hostname_via_const_fn(&e), e.hostname());
12086            assert_eq!(entrada_destination_via_const_fn(&e), e.destination());
12087            assert_eq!(e.hostname(), host);
12088            assert_eq!(e.destination(), para);
12089        }
12090    }
12091
12092    #[test]
12093    fn m3_option_string_scalar_accessor_family_is_const_fn() {
12094        // Fail-before-pass-after pin on the five M3 mesh-slot
12095        // `Option<String> → Option<&str>` scalar accessors
12096        // ([`WitContract::endpoint`] / [`WitContract::subject`] /
12097        // [`WitContract::slot`] on the per-`:contratos` HTTP /
12098        // pub-sub / key-value payload-carrier trio,
12099        // [`Placement::shard_key`] / [`Placement::affinity`] on the
12100        // per-`:placement` Akka-sharding-key + Adaptive-compression-
12101        // hint pair). Each accessor destructures the typed slot's
12102        // `Option<String>` storage through the `match &self.<field> {
12103        // Some(s) => Some(s.as_str()), None => None }` shape —
12104        // routing through [`String::as_str`] (const-stable since Rust
12105        // 1.87, well within the workspace MSRV) rather than the
12106        // non-const [`Option::as_deref`] the pre-lift bodies carried
12107        // — and any future accidental downgrade to non-`const` fails
12108        // the corresponding `<name>_via_const_fn` wrapper at
12109        // caixa-core build time with E0015 (`cannot call non-const
12110        // method`), strictly stronger than a runtime `assert!` and
12111        // strictly stronger than a module-scope `const _: () =
12112        // assert!(…)` pin (which cannot be formed on `&WitContract`
12113        // / `&Placement` fixtures because the types' `String` /
12114        // `Option<String>` carriers rule out `const`-context value
12115        // construction; the `const fn` wrapper is the load-bearing
12116        // shape that side-steps the destructor-in-const restriction
12117        // on the value axis while still pinning the `const`-fn
12118        // posture on the callee — mirror of the sibling
12119        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
12120        // (279823b) and
12121        // [`m3_membros_and_entrada_string_scalar_accessor_family_is_const_fn`]
12122        // (29c5d7e) pins on the peer `String → &str` axes at the same
12123        // structs).
12124        //
12125        // Peer of the sibling per-`Caixa` `Option<String> →
12126        // Option<&str>` accessor family pin
12127        // [`crate::manifest::tests::caixa_option_string_scalar_accessor_family_is_const_fn`]
12128        // on the top-level manifest's optional universal-axis surface
12129        // (`:licenca` / `:repositorio` / `:descricao` / `:edicao` /
12130        // `:restart-window`).
12131        const fn wit_endpoint_via_const_fn(w: &WitContract) -> Option<&str> {
12132            w.endpoint()
12133        }
12134        const fn wit_subject_via_const_fn(w: &WitContract) -> Option<&str> {
12135            w.subject()
12136        }
12137        const fn wit_slot_via_const_fn(w: &WitContract) -> Option<&str> {
12138            w.slot()
12139        }
12140        const fn placement_shard_key_via_const_fn(p: &Placement) -> Option<&str> {
12141            p.shard_key()
12142        }
12143        const fn placement_affinity_via_const_fn(p: &Placement) -> Option<&str> {
12144            p.affinity()
12145        }
12146        // Sweep every closed shape-arm partition on the
12147        // per-`:contratos` payload-carrier trio: HTTP (`:endpoint`
12148        // Some, sibling pair None), pub-sub (`:subject` Some, sibling
12149        // pair None), key-value (`:slot` Some, sibling pair None),
12150        // and Capability (all three None) so each accessor's
12151        // Some/None arm carries a pin through the const dispatch.
12152        for (wit, endpoint, subject, slot) in [
12153            ("wasi:http/proxy", Some("/api"), None, None),
12154            ("nats:pub-sub", None, Some("orders.paid"), None),
12155            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
12156            ("custom:capability-only", None, None, None),
12157        ] {
12158            let c = WitContract {
12159                de: "cart".into(),
12160                para: "catalog".into(),
12161                wit: wit.into(),
12162                endpoint: endpoint.map(str::to_string),
12163                subject: subject.map(str::to_string),
12164                slot: slot.map(str::to_string),
12165            };
12166            assert_eq!(wit_endpoint_via_const_fn(&c), c.endpoint());
12167            assert_eq!(wit_subject_via_const_fn(&c), c.subject());
12168            assert_eq!(wit_slot_via_const_fn(&c), c.slot());
12169            assert_eq!(c.endpoint(), endpoint);
12170            assert_eq!(c.subject(), subject);
12171            assert_eq!(c.slot(), slot);
12172        }
12173        // Sweep both `Some`/`None` arms on each per-`:placement`
12174        // optional-scalar so the shard-key + affinity pair carries a
12175        // const-dispatch pin on both arms.
12176        for (shard_key, affinity) in [
12177            (Some("tenantId"), Some("data-locality")),
12178            (Some("$tenantId"), None),
12179            (None, Some("low-latency")),
12180            (None, None),
12181        ] {
12182            let p = Placement {
12183                estrategia: PlacementStrategy::default(),
12184                clusters: vec![],
12185                affinity: affinity.map(str::to_string),
12186                shard_key: shard_key.map(str::to_string),
12187            };
12188            assert_eq!(placement_shard_key_via_const_fn(&p), p.shard_key());
12189            assert_eq!(placement_affinity_via_const_fn(&p), p.affinity());
12190            assert_eq!(p.shard_key(), shard_key);
12191            assert_eq!(p.affinity(), affinity);
12192        }
12193    }
12194
12195    #[test]
12196    fn m3_placement_entrada_slice_return_accessor_pair_is_const_fn() {
12197        // Fail-before-pass-after pin on the two M3-mesh-slot inner-
12198        // composite `Vec → &[String]` slice-return accessors on
12199        // [`Placement::clusters`] and [`Entrada::paths`]. Each
12200        // destructures the typed slot's `Vec<String>` storage through
12201        // the `pub const fn` [`Vec::as_slice`] (const-stable since Rust
12202        // 1.66, well within the workspace MSRV) — any future accidental
12203        // downgrade to non-`const` fails the corresponding
12204        // `<name>_via_const_fn` wrapper at caixa-core build time with
12205        // E0015 (`cannot call non-const method`), strictly stronger
12206        // than a runtime `assert!`. Sibling of the peer
12207        // [`m3_aplicacao_spec_reference_return_accessor_family_is_const_fn`]
12208        // pin on the outer-`AplicacaoSpec` reference-return family
12209        // (`:membros` / `:contratos` slice-return + `:politicas` /
12210        // `:placement` / `:entrada` composite-reference), and of the
12211        // peer M2 slice-return axis pins
12212        // [`crate::supervisor::tests::supervisor_children_slice_return_accessor_is_const_fn`]
12213        // (on `SupervisorSpec::children`) and
12214        // [`crate::upgrade::tests::upgrade_from_entry_instructions_slice_return_accessor_is_const_fn`]
12215        // (on `UpgradeFromEntry::instructions`). Together the four
12216        // pins close the last unlifted reference-return accessor
12217        // family across the substrate primitive.
12218        const fn placement_clusters_via_const_fn(p: &Placement) -> &[String] {
12219            p.clusters()
12220        }
12221        const fn entrada_paths_via_const_fn(e: &Entrada) -> &[String] {
12222            e.paths()
12223        }
12224        // Sweep both the empty-Vec (no author-declared entries) and
12225        // the populated-Vec arms on every slice-return accessor so
12226        // each carries a const-dispatch pin on both arms.
12227        let p_empty = Placement {
12228            estrategia: PlacementStrategy::default(),
12229            clusters: vec![],
12230            affinity: None,
12231            shard_key: None,
12232        };
12233        let p_full = Placement {
12234            estrategia: PlacementStrategy::default(),
12235            clusters: vec!["prod-a".into(), "prod-b".into()],
12236            affinity: None,
12237            shard_key: None,
12238        };
12239        assert_eq!(
12240            placement_clusters_via_const_fn(&p_empty),
12241            p_empty.clusters()
12242        );
12243        assert_eq!(placement_clusters_via_const_fn(&p_full), p_full.clusters());
12244        assert!(p_empty.clusters().is_empty());
12245        assert_eq!(p_full.clusters(), &["prod-a", "prod-b"]);
12246        let e_empty = Entrada {
12247            host: "web.example.com".into(),
12248            para: "web".into(),
12249            paths: vec![],
12250            port: DEFAULT_SERVICO_PORT,
12251        };
12252        let e_full = Entrada {
12253            host: "web.example.com".into(),
12254            para: "web".into(),
12255            paths: vec!["/api".into(), "/health".into()],
12256            port: DEFAULT_SERVICO_PORT,
12257        };
12258        assert_eq!(entrada_paths_via_const_fn(&e_empty), e_empty.paths());
12259        assert_eq!(entrada_paths_via_const_fn(&e_full), e_full.paths());
12260        assert!(e_empty.paths().is_empty());
12261        assert_eq!(e_full.paths(), &["/api", "/health"]);
12262    }
12263
12264    #[test]
12265    fn m3_aplicacao_spec_reference_return_accessor_family_is_const_fn() {
12266        // Fail-before-pass-after pin on the five outer-`AplicacaoSpec`
12267        // reference-return accessors — the two `Vec → &[T]` slice-
12268        // return accessors on [`AplicacaoSpec::membros`] and
12269        // [`AplicacaoSpec::contratos`] (each routes through the
12270        // `pub const fn` [`Vec::as_slice`], const-stable since Rust
12271        // 1.66), the two `&Composite` composite-reference accessors
12272        // on [`AplicacaoSpec::politicas`] and
12273        // [`AplicacaoSpec::placement`] (each routes through a raw
12274        // `&self.<field>` borrow, trivially const), and the one
12275        // `Option<&Composite>` optional-composite-reference accessor
12276        // on [`AplicacaoSpec::entrada`] (routes through the
12277        // `pub const fn` [`Option::as_ref`], const-stable since Rust
12278        // 1.83). Any future accidental downgrade to non-`const` fails
12279        // the corresponding `<name>_via_const_fn` wrapper at caixa-
12280        // core build time with E0015 (`cannot call non-const
12281        // method`), strictly stronger than a runtime `assert!`.
12282        // Sibling of the peer inner-composite pin
12283        // [`m3_placement_entrada_slice_return_accessor_pair_is_const_fn`]
12284        // on the `Placement::clusters` + `Entrada::paths` slice-
12285        // return pair, and of the peer M2 axis pins on
12286        // [`crate::supervisor::SupervisorSpec::children`] and
12287        // [`crate::upgrade::UpgradeFromEntry::instructions`].
12288        const fn aplicacao_membros_via_const_fn(s: &AplicacaoSpec) -> &[Membro] {
12289            s.membros()
12290        }
12291        const fn aplicacao_contratos_via_const_fn(s: &AplicacaoSpec) -> &[WitContract] {
12292            s.contratos()
12293        }
12294        const fn aplicacao_politicas_via_const_fn(s: &AplicacaoSpec) -> &MeshPolicy {
12295            s.politicas()
12296        }
12297        const fn aplicacao_placement_via_const_fn(s: &AplicacaoSpec) -> &Placement {
12298            s.placement()
12299        }
12300        const fn aplicacao_entrada_via_const_fn(s: &AplicacaoSpec) -> Option<&Entrada> {
12301            s.entrada()
12302        }
12303        // Construct both a minimal "no :entrada" (internal-only
12304        // mesh) and a full "with :entrada" (external-gateway)
12305        // fixture so the family pins both the `None`-arm (author-
12306        // omitted `:entrada`) and the `Some`-arm (author-declared
12307        // `:entrada`) on the optional-composite axis.
12308        let membro = Membro {
12309            caixa: "web".into(),
12310            versao: "^0.1".into(),
12311        };
12312        let entrada_full = Entrada {
12313            host: "web.example.com".into(),
12314            para: "web".into(),
12315            paths: vec!["/api".into()],
12316            port: DEFAULT_SERVICO_PORT,
12317        };
12318        let internal_only = AplicacaoSpec {
12319            membros: vec![membro.clone()],
12320            contratos: vec![],
12321            politicas: MeshPolicy::default(),
12322            placement: Placement::default(),
12323            entrada: None,
12324        };
12325        let with_entrada = AplicacaoSpec {
12326            membros: vec![membro],
12327            contratos: vec![],
12328            politicas: MeshPolicy::default(),
12329            placement: Placement::default(),
12330            entrada: Some(entrada_full),
12331        };
12332        assert_eq!(
12333            aplicacao_membros_via_const_fn(&internal_only),
12334            internal_only.membros()
12335        );
12336        assert_eq!(
12337            aplicacao_membros_via_const_fn(&with_entrada),
12338            with_entrada.membros()
12339        );
12340        assert_eq!(
12341            aplicacao_contratos_via_const_fn(&internal_only),
12342            internal_only.contratos()
12343        );
12344        assert!(std::ptr::eq(
12345            aplicacao_politicas_via_const_fn(&internal_only),
12346            internal_only.politicas(),
12347        ));
12348        assert!(std::ptr::eq(
12349            aplicacao_placement_via_const_fn(&internal_only),
12350            internal_only.placement(),
12351        ));
12352        assert!(aplicacao_entrada_via_const_fn(&internal_only).is_none());
12353        match (
12354            aplicacao_entrada_via_const_fn(&with_entrada),
12355            with_entrada.entrada(),
12356        ) {
12357            (Some(a), Some(b)) => assert!(std::ptr::eq(a, b)),
12358            _ => panic!(
12359                "aplicacao_entrada_via_const_fn must agree with \
12360                 AplicacaoSpec::entrada on the Some-arm reference"
12361            ),
12362        }
12363    }
12364
12365    #[test]
12366    fn target_projected_returns_byte_equal_typed_view_across_all_four_arms() {
12367        // Load-bearing contract pin: on every canonical
12368        // `(:wit, :endpoint/:subject/:slot)` shape the substrate admits,
12369        // [`WitContract::target_projected`] returns byte-equal to
12370        // [`WitContract::target`]`().unwrap()` — the post-validation
12371        // projection accessor is a thin panicking wrapper over the
12372        // pre-validation validator, no extra work in the projection
12373        // path. Any future divergence (a validator-side normalization
12374        // the projection doesn't route through, an accessor-side
12375        // caching layer the validator doesn't populate) would surface
12376        // here at caixa-core build time rather than a silent per-consumer
12377        // split at renderer emit time. Sweeps the closed 4-arm
12378        // [`WitTarget`] partition ([`WitTarget::Http`] /
12379        // [`WitTarget::PubSub`] / [`WitTarget::Store`] /
12380        // [`WitTarget::Capability`]) so every arm carries a byte-equality
12381        // pin on the two-accessor pair.
12382        for (wit, endpoint, subject, slot) in [
12383            ("wasi:http/proxy", Some("/x"), None, None),
12384            ("nats:pub-sub", None, Some("events.x"), None),
12385            ("wasi:keyvalue/store", None, None, Some("checkout/$orderId")),
12386            ("custom:capability-only", None, None, None),
12387        ] {
12388            let c = WitContract {
12389                de: "cart".into(),
12390                para: "catalog".into(),
12391                wit: wit.into(),
12392                endpoint: endpoint.map(str::to_string),
12393                subject: subject.map(str::to_string),
12394                slot: slot.map(str::to_string),
12395            };
12396            assert_eq!(
12397                c.target_projected(),
12398                c.target().unwrap(),
12399                "target_projected must return byte-equal to target().unwrap() at wit={wit:?}"
12400            );
12401        }
12402    }
12403
12404    #[test]
12405    #[should_panic(expected = "validated by typed_view")]
12406    fn target_projected_panics_with_canonical_message_on_unvalidated_contract() {
12407        // Panic-path pin: [`WitContract::target_projected`] threads the
12408        // canonical [`WitContract::PROJECTED_INVARIANT_MSG`] byte-string
12409        // through its expect-panic when called on a contract whose
12410        // (`:wit`, payload) shape has not been crossed by
12411        // [`AplicacaoSpec::validate`] — a contract with a structurally-
12412        // invalid `:wit` (hyphen-for-colon typo) that would surface
12413        // [`AplicacaoError::ContratoWitInvalid`] at the validator gate.
12414        // A future rebrand on the panic-message axis would land at one
12415        // caixa-core edit on [`WitContract::PROJECTED_INVARIANT_MSG`]
12416        // and this pin's [`should_panic(expected = …)`] literal would
12417        // migrate alongside — the pin catches drift between the const
12418        // and the accessor's `expect(…)` call by construction.
12419        let c = WitContract {
12420            de: "cart".into(),
12421            para: "catalog".into(),
12422            // Hyphen-for-colon typo: `WitContract::target` returns
12423            // [`AplicacaoError::ContratoWitInvalid`] on this shape,
12424            // driving the [`WitContract::target_projected`] expect-panic.
12425            wit: "wasi-http/proxy".into(),
12426            endpoint: Some("/x".into()),
12427            subject: None,
12428            slot: None,
12429        };
12430        let _ = c.target_projected();
12431    }
12432
12433    #[test]
12434    fn target_projected_invariant_msg_matches_prior_inline_call_site_literal() {
12435        // Byte-equivalence pin: [`WitContract::PROJECTED_INVARIANT_MSG`]
12436        // carries the exact byte-string the two prior open-coded
12437        // `.target().expect("validated by typed_view")` production
12438        // consumers threaded through inline before this lift converged
12439        // them onto [`WitContract::target_projected`] — the caixa-mesh
12440        // per-`(:de, :para)` CNP L7 introspection branch at
12441        // `caixa-mesh/src/lib.rs:2825` and the caixa-feira `feira app
12442        // graph` per-`:contratos` payload-column printer at
12443        // `caixa-feira/src/cmd/app.rs:110`. Locks the panic-message
12444        // byte-string load-bearing so a well-meaning const-side rebrand
12445        // that didn't carry a matched pin migration would surface here
12446        // at caixa-core build time rather than a silent per-consumer
12447        // panic-message drift at cluster-apply time. Peer of the
12448        // sibling [`WitTarget::CAPABILITY_LABEL`] /
12449        // [`WitTarget::CAPABILITY_EXPECTED`] /
12450        // [`WitTarget::CAPABILITY_GRAPH_LABEL`] byte-equivalence pins on
12451        // the paired payload-less-arm scalar-const family.
12452        assert_eq!(
12453            WitContract::PROJECTED_INVARIANT_MSG,
12454            "validated by typed_view"
12455        );
12456    }
12457
12458    #[test]
12459    fn empty_wit_takes_precedence_over_invalid() {
12460        // Ordering pin: `EmptyWit` is the more self-locating
12461        // diagnostic on `""` and must lead — the value-shape gate is
12462        // only reached after the empty-check fires. Mirrors
12463        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12464        // the peer payload axis.
12465        let mut s = three_member_spec();
12466        s.contratos.push(WitContract {
12467            de: "payment".into(),
12468            para: "catalog".into(),
12469            wit: String::new(),
12470            endpoint: None,
12471            subject: None,
12472            slot: None,
12473        });
12474        let err = s.validate().unwrap_err();
12475        assert!(
12476            matches!(err, AplicacaoError::EmptyWit { .. }),
12477            "got {err:?}"
12478        );
12479    }
12480
12481    #[test]
12482    fn wit_invalid_fires_before_payload_shape_arm() {
12483        // Ordering pin: a malformed `:wit` surfaces *its own*
12484        // diagnostic (which names the offending wit verbatim) before
12485        // any payload-field check — a contrato whose wit is
12486        // structurally invalid AND carries a wrong target field
12487        // returns `ContratoWitInvalid`, not `ContratoWrongTarget`,
12488        // because the dispatch on the wit is what decides which
12489        // payload field is "right" in the first place. Without this
12490        // ordering, the author would see "wrong target field" for a
12491        // wit that hasn't even been parsed, which doesn't name the
12492        // root cause.
12493        let mut s = three_member_spec();
12494        s.contratos.push(WitContract {
12495            de: "payment".into(),
12496            para: "catalog".into(),
12497            // Hyphen-for-colon typo + endpoint set: pre-gate this
12498            // raised `ContratoWrongTarget { expected: "none" }` (the
12499            // Capability arm rejecting the endpoint), masking the
12500            // real authoring mistake (the wit isn't `wasi:http/proxy`).
12501            wit: "wasi-http/proxy".into(),
12502            endpoint: Some("/x".into()),
12503            subject: None,
12504            slot: None,
12505        });
12506        let err = s.validate().unwrap_err();
12507        assert!(
12508            matches!(err, AplicacaoError::ContratoWitInvalid { ref wit, .. }
12509                if wit == "wasi-http/proxy"),
12510            "got {err:?}"
12511        );
12512    }
12513
12514    #[test]
12515    fn wit_invalid_diagnostic_carries_offending_wit() {
12516        // Diagnostic-shape pin — the offending `:wit` + `:de` +
12517        // `:para` + a non-empty reason flow through verbatim so the
12518        // author can grep their caixa.lisp for the offending contrato
12519        // block and fix it in one edit. Same shape as
12520        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`.
12521        let err = contrato_wit_err("WASI:HTTP/proxy");
12522        match err {
12523            AplicacaoError::ContratoWitInvalid {
12524                de,
12525                para,
12526                wit,
12527                reason,
12528            } => {
12529                assert_eq!(de, "payment");
12530                assert_eq!(para, "catalog");
12531                assert_eq!(wit, "WASI:HTTP/proxy");
12532                assert!(!reason.is_empty(), "reason field must be non-empty");
12533            }
12534            other => panic!("expected ContratoWitInvalid, got {other:?}"),
12535        }
12536    }
12537
12538    // ── :contratos :subject value-shape gate ─────────────────────────────
12539    //
12540    // Mirrors the `:contratos :endpoint` / `:contratos :wit` value-shape
12541    // suites on the peer payload axes. Until this gate landed
12542    // `WitContract::target()` only refused the empty string; a
12543    // structurally invalid subject silently passed validate and the
12544    // failure surfaced at runtime as a NATS server-side `-ERR 'Invalid
12545    // Subject'` on publish / subscribe, or as a silent message drop,
12546    // far from the source caixa.lisp. Every authoring footgun the
12547    // NATS server's subject parser would catch on admission now
12548    // becomes a caixa-build-time `ContratoSubjectInvalid` with the
12549    // offending `:subject` + `:de` + `:para` named verbatim. Same
12550    // diagnostic shape as `ContratoEndpointInvalid` /
12551    // `ContratoWitInvalid` on the peer payload axes; same shared
12552    // predicate (`crate::render::is_nats_subject`) ensures drift
12553    // between any two axes' rule enforcement is a build error at the
12554    // predicate, not piecemeal across renderers.
12555
12556    fn contrato_subject_err(subject: &str) -> AplicacaoError {
12557        // Fresh spec per call so the new contract doesn't collide on
12558        // identity with `three_member_spec`'s pre-existing entries.
12559        // The new edge uses `(payment, catalog)` — a pair the fixture
12560        // doesn't already declare — with `:wit "nats:pub-sub"` and the
12561        // varying `:subject`, so the subject-shape gate fires cleanly
12562        // after the wit-shape gate (which `"nats:pub-sub"` passes).
12563        let mut s = three_member_spec();
12564        s.contratos.push(WitContract {
12565            de: "payment".into(),
12566            para: "catalog".into(),
12567            wit: "nats:pub-sub".into(),
12568            endpoint: None,
12569            subject: Some(subject.into()),
12570            slot: None,
12571        });
12572        s.validate().unwrap_err()
12573    }
12574
12575    #[test]
12576    fn rejects_pubsub_contrato_subject_with_whitespace() {
12577        // Fail-before-pass-after pin — pre-gate `"foo bar"` silently
12578        // landed at the NATS server as a malformed subject the parser
12579        // rejects with `-ERR 'Invalid Subject'`. Now caught at the
12580        // source caixa.lisp.
12581        let err = contrato_subject_err("foo bar");
12582        assert!(
12583            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12584                if subject == "foo bar" && reason.contains("whitespace")),
12585            "got {err:?}"
12586        );
12587    }
12588
12589    #[test]
12590    fn rejects_pubsub_contrato_subject_with_control_char() {
12591        let err = contrato_subject_err("foo\x01bar");
12592        assert!(
12593            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12594                if subject == "foo\x01bar" && reason.contains("control character")),
12595            "got {err:?}"
12596        );
12597    }
12598
12599    #[test]
12600    fn rejects_pubsub_contrato_subject_with_non_ascii() {
12601        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12602        // the subject from a doc with smart quotes / accented
12603        // characters" footgun.
12604        let err = contrato_subject_err("foo.caf\u{e9}");
12605        assert!(
12606            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12607                if subject == "foo.caf\u{e9}" && reason.contains("non-ASCII")),
12608            "got {err:?}"
12609        );
12610    }
12611
12612    #[test]
12613    fn rejects_pubsub_contrato_subject_with_leading_dot() {
12614        // Empty leading token — NATS rejects.
12615        let err = contrato_subject_err(".foo");
12616        assert!(
12617            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12618                if subject == ".foo" && reason.contains("must not start with `.`")),
12619            "got {err:?}"
12620        );
12621    }
12622
12623    #[test]
12624    fn rejects_pubsub_contrato_subject_with_trailing_dot() {
12625        // Empty trailing token — NATS rejects. The remediation
12626        // (use `>` instead) is in the reason string.
12627        let err = contrato_subject_err("foo.");
12628        assert!(
12629            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12630                if subject == "foo." && reason.contains("must not end with `.`")),
12631            "got {err:?}"
12632        );
12633    }
12634
12635    #[test]
12636    fn rejects_pubsub_contrato_subject_with_consecutive_dots() {
12637        // The canonical "I forgot to fill in the middle segment"
12638        // typo — `"foo..bar"`. NATS rejects empty tokens.
12639        let err = contrato_subject_err("foo..bar");
12640        assert!(
12641            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12642                if subject == "foo..bar" && reason.contains("consecutive `.`")),
12643            "got {err:?}"
12644        );
12645    }
12646
12647    #[test]
12648    fn rejects_pubsub_contrato_subject_with_non_trailing_multi_wildcard() {
12649        // `foo.>.bar` — `>` is the multi-token wildcard, only allowed
12650        // as the final segment. Pre-gate this passed as a typed edge
12651        // and surfaced at runtime as a NATS subscribe rejection.
12652        let err = contrato_subject_err("foo.>.bar");
12653        assert!(
12654            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12655                if subject == "foo.>.bar" && reason.contains("only allowed as the final segment")),
12656            "got {err:?}"
12657        );
12658    }
12659
12660    #[test]
12661    fn rejects_pubsub_contrato_subject_with_mid_segment_star() {
12662        // `foo*.bar` — NATS wildcards are standalone tokens. The
12663        // remediation is in the reason string.
12664        let err = contrato_subject_err("foo*.bar");
12665        assert!(
12666            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12667                if subject == "foo*.bar" && reason.contains("`*` mid-segment")),
12668            "got {err:?}"
12669        );
12670    }
12671
12672    #[test]
12673    fn rejects_pubsub_contrato_subject_with_invalid_char() {
12674        // `foo,bar` — comma is not a valid NATS subject character.
12675        // Pinned separately from the wildcard arms so the invalid-
12676        // character diagnostic is in force.
12677        let err = contrato_subject_err("foo,bar");
12678        assert!(
12679            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12680                if subject == "foo,bar" && reason.contains("invalid character")),
12681            "got {err:?}"
12682        );
12683    }
12684
12685    #[test]
12686    fn rejects_pubsub_contrato_subject_too_long() {
12687        // 257-byte subject — one over the NATS_SUBJECT_MAX_LEN cap.
12688        // The legitimate-shape arms all pass (one all-`a` token, no
12689        // `.`, no wildcards); only the cap arm fires. Surfaces the
12690        // paste-from-binary / accidental-multi-line-blob landing
12691        // footgun. Mirrors `rejects_http_contrato_endpoint_too_long`
12692        // on the peer axis.
12693        let big = "a".repeat(257);
12694        assert_eq!(big.len(), 257);
12695        let err = contrato_subject_err(&big);
12696        assert!(
12697            matches!(err, AplicacaoError::ContratoSubjectInvalid { ref subject, ref reason, .. }
12698                if subject == &big && reason.contains("max length of 256")),
12699            "got {err:?}"
12700        );
12701    }
12702
12703    #[test]
12704    fn pubsub_contrato_subject_max_length_validates() {
12705        // 256-byte subject — exactly the cap. Boundary pin: drift in
12706        // the cap surfaces here and at
12707        // `rejects_pubsub_contrato_subject_too_long` simultaneously,
12708        // mirroring `http_contrato_endpoint_max_length_validates` and
12709        // `wit_max_length_validates` on the peer axes.
12710        let big = "a".repeat(256);
12711        assert_eq!(big.len(), 256);
12712        let mut s = three_member_spec();
12713        s.contratos.push(WitContract {
12714            de: "payment".into(),
12715            para: "catalog".into(),
12716            wit: "nats:pub-sub".into(),
12717            endpoint: None,
12718            subject: Some(big),
12719            slot: None,
12720        });
12721        s.validate().unwrap();
12722    }
12723
12724    #[test]
12725    fn pubsub_contrato_subject_accepts_canonical_forms() {
12726        // Positive-set sweep: every canonical NATS subject shape the
12727        // substrate-side `is_nats_subject` predicate accepts (the
12728        // multi-dot `events.order.charged`, the snake_case / kebab-
12729        // case / mixed-case tokens, the digit-bearing tokens, the
12730        // single-token wildcard `*` at every segment position, and
12731        // the trailing `>` multi-token wildcard) must remain a valid
12732        // contrato subject too. Drift between this list and the
12733        // substrate-side `nats_subject_accepts_canonical_forms` sweep
12734        // surfaces at the shared predicate — one source of truth.
12735        // Uses a fresh `(payment, catalog)` edge so none of the swept
12736        // subjects collide with the pre-existing entries in
12737        // `three_member_spec`.
12738        for subject in [
12739            "checkout.events.charge.failed",
12740            "rio.events.order.charged",
12741            "orders",
12742            "orders.123",
12743            "snake_case.token",
12744            "kebab-case.token",
12745            "MixedCase.Token",
12746            "orders.*.charged",
12747            "*.events.*",
12748            "orders.>",
12749        ] {
12750            let mut s = three_member_spec();
12751            s.contratos.push(WitContract {
12752                de: "payment".into(),
12753                para: "catalog".into(),
12754                wit: "nats:pub-sub".into(),
12755                endpoint: None,
12756                subject: Some(subject.into()),
12757                slot: None,
12758            });
12759            s.validate()
12760                .unwrap_or_else(|e| panic!("expected {subject:?} to validate, got {e:?}"));
12761        }
12762    }
12763
12764    #[test]
12765    fn contrato_subject_empty_takes_precedence_over_invalid() {
12766        // Ordering pin: `ContratoSubjectEmpty` is the more self-
12767        // locating diagnostic on `""` and must lead — the value-shape
12768        // gate is only reached after the empty-check fires. Mirrors
12769        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
12770        // the peer payload axis.
12771        let mut s = three_member_spec();
12772        s.contratos.push(WitContract {
12773            de: "payment".into(),
12774            para: "catalog".into(),
12775            wit: "nats:pub-sub".into(),
12776            endpoint: None,
12777            subject: Some(String::new()),
12778            slot: None,
12779        });
12780        let err = s.validate().unwrap_err();
12781        assert!(
12782            matches!(err, AplicacaoError::ContratoSubjectEmpty { .. }),
12783            "got {err:?}"
12784        );
12785    }
12786
12787    #[test]
12788    fn contrato_subject_invalid_diagnostic_carries_offending_subject() {
12789        // Diagnostic-shape pin — the offending `:subject` + `:de` +
12790        // `:para` + a non-empty reason flow through verbatim so the
12791        // author can grep their caixa.lisp for the offending contrato
12792        // block and fix it in one edit. Same shape as
12793        // `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
12794        // and `wit_invalid_diagnostic_carries_offending_wit`.
12795        let err = contrato_subject_err("foo..bar");
12796        match err {
12797            AplicacaoError::ContratoSubjectInvalid {
12798                de,
12799                para,
12800                subject,
12801                reason,
12802            } => {
12803                assert_eq!(de, "payment");
12804                assert_eq!(para, "catalog");
12805                assert_eq!(subject, "foo..bar");
12806                assert!(!reason.is_empty(), "reason field must be non-empty");
12807            }
12808            other => panic!("expected ContratoSubjectInvalid, got {other:?}"),
12809        }
12810    }
12811
12812    #[test]
12813    fn target_view_pubsub_subject_passes_through_to_typed_view() {
12814        // The compounding theorem on the pub-sub axis: every
12815        // `WitTarget::PubSub { subject }` returned by `target()` carries
12816        // a NATS-server-accepted subject. Renderers downstream of
12817        // `typed_view()` (caixa-mesh's CNP L4 emitter, the future
12818        // NATS Stream/Consumer CR emitter, the future `feira app graph`
12819        // view's subject labeller) can rely on this without re-checking
12820        // — the type system carries the proof. Mirrors
12821        // `target_view_payload_is_guaranteed_nonempty_after_target_call`
12822        // on the peer axes.
12823        let nats = WitContract {
12824            de: "a".into(),
12825            para: "b".into(),
12826            wit: "nats:pub-sub".into(),
12827            endpoint: None,
12828            subject: Some("orders.events.*.charged".into()),
12829            slot: None,
12830        };
12831        match nats.target().unwrap() {
12832            WitTarget::PubSub { subject } => {
12833                assert_eq!(subject, "orders.events.*.charged");
12834            }
12835            other => panic!("expected PubSub, got {other:?}"),
12836        }
12837    }
12838
12839    // ── :contratos :slot value-shape gate ────────────────────────────────
12840    //
12841    // Mirrors the `:contratos :endpoint` (4f0390b) + `:contratos :subject`
12842    // (63e18a0) value-shape suites on the peer payload axes. Until this
12843    // gate landed `WitContract::target()` only refused the empty string
12844    // for the Store arm; a structurally invalid slot (raw whitespace,
12845    // control character, non-ASCII byte, paste-from-binary multi-line
12846    // blob) silently passed validate and surfaced at runtime as a
12847    // per-backend kv write rejection or a silent next-read corruption,
12848    // far from the source caixa.lisp with no field naming which
12849    // `:contratos` edge carried the typo. Every authoring footgun the
12850    // kv backend intersection-floor would catch on write now becomes a
12851    // caixa-build-time `ContratoSlotInvalid` with the offending
12852    // `:slot` + `:de` + `:para` named verbatim. Same diagnostic shape
12853    // as `ContratoEndpointInvalid` / `ContratoSubjectInvalid` on the
12854    // peer payload axes; same shared predicate
12855    // (`crate::render::is_wasi_keyvalue_slot`) ensures drift between
12856    // any two axes' rule enforcement is a build error at the
12857    // predicate, not piecemeal across renderers. Closes the typed
12858    // payload-axis value-shape trajectory across all three legs of the
12859    // four `WitTarget` arms (HTTP / PubSub / Store / Capability).
12860
12861    fn contrato_slot_err(slot: &str) -> AplicacaoError {
12862        // Fresh spec per call so the new contract doesn't collide on
12863        // identity with `three_member_spec`'s pre-existing entries
12864        // and doesn't close a synchronous cycle the cycle detector
12865        // would reject before the slot-shape gate fires. The new edge
12866        // uses `(payment, catalog)` — a pair the fixture doesn't
12867        // already declare in either direction (the fixture carries
12868        // `cart -> catalog` and `cart -> payment`, so `payment ->
12869        // catalog` doesn't form a cycle on the sync subgraph) — with
12870        // `:wit "wasi:keyvalue/store"` and the varying `:slot`, so the
12871        // slot-shape gate fires cleanly after the wit-shape gate
12872        // (which `"wasi:keyvalue/store"` passes). Same edge pair the
12873        // peer `contrato_subject_err` helper uses (63e18a0).
12874        let mut s = three_member_spec();
12875        s.contratos.push(WitContract {
12876            de: "payment".into(),
12877            para: "catalog".into(),
12878            wit: "wasi:keyvalue/store".into(),
12879            endpoint: None,
12880            subject: None,
12881            slot: Some(slot.into()),
12882        });
12883        s.validate().unwrap_err()
12884    }
12885
12886    #[test]
12887    fn rejects_store_contrato_slot_with_whitespace() {
12888        // Fail-before-pass-after pin — pre-gate `"check out/$order"`
12889        // silently landed at the kv backend with whitespace whose
12890        // runtime behavior varies unpredictably across backends (etcd
12891        // accepts, Redis accepts then breaks on next CLI op, DynamoDB
12892        // rejects on write). Now caught at the source caixa.lisp.
12893        let err = contrato_slot_err("check out/$order");
12894        assert!(
12895            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12896                if slot == "check out/$order" && reason.contains("whitespace")),
12897            "got {err:?}"
12898        );
12899    }
12900
12901    #[test]
12902    fn rejects_store_contrato_slot_with_tab() {
12903        // Tab byte arm-pinned separately from the space arm so a
12904        // future relaxation that admits one but not the other surfaces
12905        // here.
12906        let err = contrato_slot_err("check\tout");
12907        assert!(
12908            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12909                if slot == "check\tout" && reason.contains("whitespace")),
12910            "got {err:?}"
12911        );
12912    }
12913
12914    #[test]
12915    fn rejects_store_contrato_slot_with_control_char() {
12916        // SOH (0x01) — distinct from the whitespace arm. Redis admits
12917        // and corrupts on RESP protocol framing; DynamoDB rejects on
12918        // write.
12919        let err = contrato_slot_err("checkout/\x01order");
12920        assert!(
12921            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12922                if slot == "checkout/\x01order" && reason.contains("control character")),
12923            "got {err:?}"
12924        );
12925    }
12926
12927    #[test]
12928    fn rejects_store_contrato_slot_with_newline() {
12929        // Embedded newline — the canonical "the paste-from-binary slug
12930        // spans multiple lines" footgun. Distinct from the whitespace
12931        // arm because `\n` is a control character (0x0A).
12932        let err = contrato_slot_err("checkout\norder");
12933        assert!(
12934            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12935                if slot == "checkout\norder" && reason.contains("control character")),
12936            "got {err:?}"
12937        );
12938    }
12939
12940    #[test]
12941    fn rejects_store_contrato_slot_with_non_ascii() {
12942        // Un-percent-encoded non-ASCII byte — the canonical "I copied
12943        // the slot from a doc with accented characters" footgun. Each
12944        // kv backend re-encodes non-ASCII differently (etcd preserves
12945        // bytes verbatim; Redis-via-RESP3 may re-encode; DynamoDB
12946        // rejects), so the typed slot's value set is the intersection-
12947        // floor every backend admits identically (printable ASCII).
12948        let err = contrato_slot_err("ch\u{e9}ckout/$order");
12949        assert!(
12950            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12951                if slot == "ch\u{e9}ckout/$order" && reason.contains("non-ASCII")),
12952            "got {err:?}"
12953        );
12954    }
12955
12956    #[test]
12957    fn rejects_store_contrato_slot_too_long() {
12958        // 513-byte slot — one over the WASI_KV_SLOT_MAX_LEN cap. The
12959        // legitimate-shape arms all pass (a single all-`a` token, no
12960        // separators); only the cap arm fires. Surfaces the paste-
12961        // from-binary / accidental-multi-line-blob landing footgun.
12962        // Mirrors `rejects_pubsub_contrato_subject_too_long` and
12963        // `rejects_http_contrato_endpoint_too_long` on the peer
12964        // payload axes.
12965        let big = "a".repeat(513);
12966        assert_eq!(big.len(), 513);
12967        let err = contrato_slot_err(&big);
12968        assert!(
12969            matches!(err, AplicacaoError::ContratoSlotInvalid { ref slot, ref reason, .. }
12970                if slot == &big && reason.contains("max length of 512")),
12971            "got {err:?}"
12972        );
12973    }
12974
12975    #[test]
12976    fn store_contrato_slot_max_length_validates() {
12977        // 512-byte slot — exactly the cap. Boundary pin: drift in the
12978        // cap surfaces here and at `rejects_store_contrato_slot_too_long`
12979        // simultaneously, mirroring
12980        // `pubsub_contrato_subject_max_length_validates` and
12981        // `http_contrato_endpoint_max_length_validates` on the peer
12982        // payload axes.
12983        let big = "a".repeat(512);
12984        assert_eq!(big.len(), 512);
12985        let mut s = three_member_spec();
12986        s.contratos.push(WitContract {
12987            de: "payment".into(),
12988            para: "catalog".into(),
12989            wit: "wasi:keyvalue/store".into(),
12990            endpoint: None,
12991            subject: None,
12992            slot: Some(big),
12993        });
12994        s.validate().unwrap();
12995    }
12996
12997    #[test]
12998    fn store_contrato_slot_accepts_canonical_forms() {
12999        // Positive-set sweep: every canonical kv slot template the
13000        // substrate-side `is_wasi_keyvalue_slot` predicate accepts
13001        // (single-token identifiers, path-namespaced `$`-templates,
13002        // colon-namespaced `{}`-templates, dot-namespaced `<>`-templates,
13003        // snake_case / kebab-case / MixedCase tokens, digit-bearing
13004        // tokens, percent-encoded fragments) must remain valid
13005        // contrato slots too. Drift between this list and the
13006        // substrate-side `wasi_kv_slot_accepts_canonical_forms` sweep
13007        // surfaces at the shared predicate — one source of truth.
13008        // Uses a fresh `(payment, catalog)` edge so none of the swept
13009        // slots collide with the pre-existing entries in
13010        // `three_member_spec`.
13011        for slot in [
13012            "checkout",
13013            "checkout/$orderId",
13014            "users:{tenant}/{id}",
13015            "session.<sid>",
13016            "session.tokens.<sid>",
13017            "snake_case_key",
13018            "kebab-case-key",
13019            "MixedCase",
13020            "shard0",
13021            "v2/key",
13022            "users/caf%C3%A9",
13023        ] {
13024            let mut s = three_member_spec();
13025            s.contratos.push(WitContract {
13026                de: "payment".into(),
13027                para: "catalog".into(),
13028                wit: "wasi:keyvalue/store".into(),
13029                endpoint: None,
13030                subject: None,
13031                slot: Some(slot.into()),
13032            });
13033            s.validate()
13034                .unwrap_or_else(|e| panic!("expected slot {slot:?} to validate, got {e:?}"));
13035        }
13036    }
13037
13038    #[test]
13039    fn contrato_slot_empty_takes_precedence_over_invalid() {
13040        // Ordering pin: `ContratoSlotEmpty` is the more self-locating
13041        // diagnostic on `""` and must lead — the value-shape gate is
13042        // only reached after the empty-check fires. Mirrors
13043        // `contrato_subject_empty_takes_precedence_over_invalid` and
13044        // `contrato_endpoint_empty_takes_precedence_over_invalid` on
13045        // the peer payload axes.
13046        let mut s = three_member_spec();
13047        s.contratos.push(WitContract {
13048            de: "payment".into(),
13049            para: "catalog".into(),
13050            wit: "wasi:keyvalue/store".into(),
13051            endpoint: None,
13052            subject: None,
13053            slot: Some(String::new()),
13054        });
13055        let err = s.validate().unwrap_err();
13056        assert!(
13057            matches!(err, AplicacaoError::ContratoSlotEmpty { .. }),
13058            "got {err:?}"
13059        );
13060    }
13061
13062    #[test]
13063    fn contrato_slot_invalid_diagnostic_carries_offending_slot() {
13064        // Diagnostic-shape pin — the offending `:slot` + `:de` +
13065        // `:para` + a non-empty reason flow through verbatim so the
13066        // author can grep their caixa.lisp for the offending contrato
13067        // block and fix it in one edit. Same shape as
13068        // `contrato_subject_invalid_diagnostic_carries_offending_subject`
13069        // and `contrato_endpoint_invalid_diagnostic_carries_offending_endpoint`
13070        // on the peer payload axes.
13071        let err = contrato_slot_err("check out/$order");
13072        match err {
13073            AplicacaoError::ContratoSlotInvalid {
13074                de,
13075                para,
13076                slot,
13077                reason,
13078            } => {
13079                assert_eq!(de, "payment");
13080                assert_eq!(para, "catalog");
13081                assert_eq!(slot, "check out/$order");
13082                assert!(!reason.is_empty(), "reason field must be non-empty");
13083            }
13084            other => panic!("expected ContratoSlotInvalid, got {other:?}"),
13085        }
13086    }
13087
13088    #[test]
13089    fn target_view_store_slot_passes_through_to_typed_view() {
13090        // The compounding theorem on the store axis: every
13091        // `WitTarget::Store { slot }` returned by `target()` carries a
13092        // kv-backend-accepted slot template. Renderers downstream of
13093        // `typed_view()` (the future per-Servico `:capabilities
13094        // wasi:keyvalue/store` axis emitter, the future `feira app
13095        // graph` view's slot labeller, the future kv-provider CR
13096        // materializer) can rely on this without re-checking — the
13097        // type system carries the proof. Mirrors
13098        // `target_view_pubsub_subject_passes_through_to_typed_view` on
13099        // the peer payload axis.
13100        let store = WitContract {
13101            de: "a".into(),
13102            para: "b".into(),
13103            wit: "wasi:keyvalue/store".into(),
13104            endpoint: None,
13105            subject: None,
13106            slot: Some("checkout/$orderId".into()),
13107        };
13108        match store.target().unwrap() {
13109            WitTarget::Store { slot } => {
13110                assert_eq!(slot, "checkout/$orderId");
13111            }
13112            other => panic!("expected Store, got {other:?}"),
13113        }
13114    }
13115
13116    #[test]
13117    fn rejects_self_loop_in_synchronous_contratos() {
13118        // A synchronous self-edge (`cart → cart` over HTTP) is now
13119        // rejected by the dedicated `ContratoSelfLoop` gate — a precise
13120        // "this edge is degenerate" diagnostic — rather than incidentally
13121        // by the cycle detector framing it as a `["cart", "cart"]`
13122        // multi-node deadlock.
13123        let mut s = three_member_spec();
13124        s.contratos.push(contract_http("cart", "cart", "/loop"));
13125        let err = s.validate().unwrap_err();
13126        match err {
13127            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
13128                assert_eq!(caixa, "cart");
13129                assert_eq!(wit, "wasi:http/proxy");
13130            }
13131            other => panic!("expected ContratoSelfLoop, got {other:?}"),
13132        }
13133    }
13134
13135    #[test]
13136    fn rejects_self_loop_in_pubsub_contratos() {
13137        // The cycle detector excludes pub-sub edges (acyclic by
13138        // construction), so before the explicit gate a `nats:pub-sub`
13139        // self-edge silently validated and rendered a self-allow CNP.
13140        // The shape-agnostic `ContratoSelfLoop` gate closes that hole.
13141        let mut s = three_member_spec();
13142        s.contratos.push(WitContract {
13143            de: "payment".into(),
13144            para: "payment".into(),
13145            wit: "nats:pub-sub".into(),
13146            endpoint: None,
13147            subject: Some("rio.events.payment".into()),
13148            slot: None,
13149        });
13150        let err = s.validate().unwrap_err();
13151        match err {
13152            AplicacaoError::ContratoSelfLoop { caixa, wit } => {
13153                assert_eq!(caixa, "payment");
13154                assert_eq!(wit, "nats:pub-sub");
13155            }
13156            other => panic!("expected ContratoSelfLoop, got {other:?}"),
13157        }
13158    }
13159
13160    #[test]
13161    fn self_loop_fires_before_payload_shape_check() {
13162        // The structural "this edge can't exist" error precedes the
13163        // narrower payload-shape diagnostics: a self-edge carrying an
13164        // otherwise-malformed endpoint still reports ContratoSelfLoop,
13165        // not ContratoEndpointInvalid.
13166        let mut s = three_member_spec();
13167        s.contratos.push(WitContract {
13168            de: "cart".into(),
13169            para: "cart".into(),
13170            wit: "wasi:http/proxy".into(),
13171            endpoint: Some("not-absolute".into()),
13172            subject: None,
13173            slot: None,
13174        });
13175        match s.validate().unwrap_err() {
13176            AplicacaoError::ContratoSelfLoop { caixa, .. } => assert_eq!(caixa, "cart"),
13177            other => panic!("expected ContratoSelfLoop, got {other:?}"),
13178        }
13179    }
13180
13181    #[test]
13182    fn self_loop_fires_before_membership_is_satisfied_but_after_missing_member() {
13183        // A self-edge naming a non-member reports the more fundamental
13184        // ContratoMemberMissing first (the member doesn't exist), so the
13185        // self-loop gate is reached only once both endpoints resolve.
13186        let mut s = three_member_spec();
13187        s.contratos.push(contract_http("ghost", "ghost", "/loop"));
13188        match s.validate().unwrap_err() {
13189            AplicacaoError::ContratoMemberMissing { caixa } => assert_eq!(caixa, "ghost"),
13190            other => panic!("expected ContratoMemberMissing, got {other:?}"),
13191        }
13192    }
13193
13194    #[test]
13195    fn rejects_two_node_synchronous_cycle() {
13196        let mut s = three_member_spec();
13197        // existing edges: cart → catalog, cart → payment
13198        // adding catalog → cart closes a 2-cycle on the HTTP subgraph
13199        s.contratos
13200            .push(contract_http("catalog", "cart", "/refresh"));
13201        let err = s.validate().unwrap_err();
13202        match err {
13203            AplicacaoError::ContratoCycle { cycle } => {
13204                // Cycle traversal should mention both endpoints, with
13205                // the back-edge target appearing as both first and last
13206                // element to close the loop.
13207                assert!(cycle.len() >= 3);
13208                assert_eq!(cycle.first(), cycle.last());
13209                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
13210                assert!(body.contains("cart"));
13211                assert!(body.contains("catalog"));
13212            }
13213            other => panic!("expected ContratoCycle, got {other:?}"),
13214        }
13215    }
13216
13217    #[test]
13218    fn rejects_three_node_synchronous_cycle() {
13219        let mut s = three_member_spec();
13220        // Reset to a clean 3-cycle: catalog → cart → payment → catalog
13221        s.contratos = vec![
13222            contract_http("catalog", "cart", "/x"),
13223            contract_http("cart", "payment", "/y"),
13224            contract_http("payment", "catalog", "/z"),
13225        ];
13226        let err = s.validate().unwrap_err();
13227        match err {
13228            AplicacaoError::ContratoCycle { cycle } => {
13229                assert_eq!(cycle.first(), cycle.last());
13230                let body: std::collections::HashSet<_> = cycle.iter().cloned().collect();
13231                assert_eq!(body.len(), 3);
13232                assert!(body.contains("cart"));
13233                assert!(body.contains("catalog"));
13234                assert!(body.contains("payment"));
13235            }
13236            other => panic!("expected ContratoCycle, got {other:?}"),
13237        }
13238    }
13239
13240    #[test]
13241    fn pubsub_edge_breaks_cycle_per_mesh_composition_iii_3() {
13242        // MESH-COMPOSITION §III.3 explicitly says NATS pub-sub is
13243        // "acyclic by construction" — so a cycle whose closing edge
13244        // is pub-sub should NOT raise ContratoCycle.
13245        let mut s = three_member_spec();
13246        s.contratos = vec![
13247            contract_http("catalog", "cart", "/x"),
13248            contract_http("cart", "payment", "/y"),
13249            // Closing edge is pub-sub — async; not a sync deadlock.
13250            WitContract {
13251                de: "payment".into(),
13252                para: "catalog".into(),
13253                wit: "nats:pub-sub".into(),
13254                endpoint: None,
13255                subject: Some("checkout.events.charge.completed".into()),
13256                slot: None,
13257            },
13258        ];
13259        s.validate().expect("pub-sub edge breaks the sync cycle");
13260    }
13261
13262    #[test]
13263    fn store_edge_counts_as_synchronous_for_cycle_detection() {
13264        // wasi:keyvalue/store is request/response; a cycle through one
13265        // *is* a sync deadlock, just like HTTP.
13266        let mut s = three_member_spec();
13267        s.contratos = vec![
13268            contract_http("catalog", "cart", "/x"),
13269            WitContract {
13270                de: "cart".into(),
13271                para: "catalog".into(),
13272                wit: "wasi:keyvalue/store".into(),
13273                endpoint: None,
13274                subject: None,
13275                slot: Some("session/$id".into()),
13276            },
13277        ];
13278        let err = s.validate().unwrap_err();
13279        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
13280    }
13281
13282    #[test]
13283    fn capability_edge_counts_as_synchronous_for_cycle_detection() {
13284        // Capability-only edges (unknown WIT shape, no payload) default
13285        // to synchronous — safer; authors with truly async capability
13286        // semantics can model them as pub-sub explicitly.
13287        let mut s = three_member_spec();
13288        s.contratos = vec![
13289            contract_http("catalog", "cart", "/x"),
13290            WitContract {
13291                de: "cart".into(),
13292                para: "catalog".into(),
13293                wit: "custom:exchange".into(),
13294                endpoint: None,
13295                subject: None,
13296                slot: None,
13297            },
13298        ];
13299        let err = s.validate().unwrap_err();
13300        assert!(matches!(err, AplicacaoError::ContratoCycle { .. }));
13301    }
13302
13303    #[test]
13304    fn long_acyclic_chain_validates() {
13305        // A long sync chain (no back-edges) must validate even when
13306        // every node is reachable from the first.
13307        let mut s = three_member_spec();
13308        s.membros = vec![
13309            membro("a", "^0.1"),
13310            membro("b", "^0.1"),
13311            membro("c", "^0.1"),
13312            membro("d", "^0.1"),
13313            membro("e", "^0.1"),
13314        ];
13315        s.contratos = vec![
13316            contract_http("a", "b", "/1"),
13317            contract_http("b", "c", "/2"),
13318            contract_http("c", "d", "/3"),
13319            contract_http("d", "e", "/4"),
13320        ];
13321        s.entrada.as_mut().unwrap().para = "a".into();
13322        s.validate().unwrap();
13323    }
13324
13325    #[test]
13326    fn diamond_acyclic_validates() {
13327        // a → b, a → c, b → d, c → d. Two paths to d, no cycle.
13328        let mut s = three_member_spec();
13329        s.membros = vec![
13330            membro("a", "^0.1"),
13331            membro("b", "^0.1"),
13332            membro("c", "^0.1"),
13333            membro("d", "^0.1"),
13334        ];
13335        s.contratos = vec![
13336            contract_http("a", "b", "/1"),
13337            contract_http("a", "c", "/2"),
13338            contract_http("b", "d", "/3"),
13339            contract_http("c", "d", "/4"),
13340        ];
13341        s.entrada.as_mut().unwrap().para = "a".into();
13342        s.validate().unwrap();
13343    }
13344
13345    // ── duplicate-`:contratos` build-error gate ──────────────────────────
13346
13347    #[test]
13348    fn rejects_duplicate_http_contrato() {
13349        // Fail-before-pass-after pin: the fixture's `cart → catalog`
13350        // HTTP edge appears once. Push an identical entry — same
13351        // (de, para, wit, endpoint) — and validate() must reject it.
13352        // Until this gate landed the typed surface accepted the
13353        // duplicate silently and caixa-mesh's `cilium_network_policies`
13354        // emitted two ``CiliumNetworkPolicy`` objects with identical
13355        // `metadata.name` (`<aplicacao>-<de>-to-<para>`), which K8s
13356        // admission rejects on `kubectl apply` far from the source.
13357        let mut s = three_member_spec();
13358        s.contratos
13359            .push(contract_http("cart", "catalog", "/products/:id"));
13360        let err = s.validate().unwrap_err();
13361        assert!(
13362            matches!(
13363                err,
13364                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13365                    if de == "cart" && para == "catalog" && wit == "wasi:http/proxy"
13366            ),
13367            "got {err:?}"
13368        );
13369    }
13370
13371    #[test]
13372    fn rejects_duplicate_pubsub_contrato() {
13373        // Same gate on the pub-sub edge axis. Two `nats:pub-sub`
13374        // edges with identical (de, para, subject) are degenerate;
13375        // pin that the typed surface refuses both at validate time.
13376        let mut s = three_member_spec();
13377        let pubsub = WitContract {
13378            de: "payment".into(),
13379            para: "cart".into(),
13380            wit: "nats:pub-sub".into(),
13381            endpoint: None,
13382            subject: Some("checkout.events.charge.failed".into()),
13383            slot: None,
13384        };
13385        s.contratos.push(pubsub.clone());
13386        s.contratos.push(pubsub);
13387        let err = s.validate().unwrap_err();
13388        assert!(
13389            matches!(
13390                err,
13391                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13392                    if de == "payment" && para == "cart" && wit == "nats:pub-sub"
13393            ),
13394            "got {err:?}"
13395        );
13396    }
13397
13398    #[test]
13399    fn rejects_duplicate_store_contrato() {
13400        // Same gate on the key-value edge axis. Two `wasi:keyvalue/store`
13401        // edges with identical (de, para, slot) collapse to one mesh-
13402        // policy edge; pin the build error.
13403        let mut s = three_member_spec();
13404        let store = WitContract {
13405            de: "cart".into(),
13406            para: "payment".into(),
13407            wit: "wasi:keyvalue/store".into(),
13408            endpoint: None,
13409            subject: None,
13410            slot: Some("checkout/$orderId".into()),
13411        };
13412        // Drop the conflicting HTTP `cart → payment` edge from the
13413        // fixture so the duplicate-store pair is the only one
13414        // distinguishable on this pair.
13415        s.contratos
13416            .retain(|c| !(c.de == "cart" && c.para == "payment"));
13417        s.contratos.push(store.clone());
13418        s.contratos.push(store);
13419        let err = s.validate().unwrap_err();
13420        assert!(
13421            matches!(
13422                err,
13423                AplicacaoError::ContratoDuplicate { ref de, ref para, ref wit, .. }
13424                    if de == "cart" && para == "payment" && wit == "wasi:keyvalue/store"
13425            ),
13426            "got {err:?}"
13427        );
13428    }
13429
13430    #[test]
13431    fn rejects_duplicate_capability_contrato() {
13432        // Same gate on the pure-capability axis (no payload selector).
13433        // Two contracts with identical (de, para, wit) and no
13434        // endpoint/subject/slot are duplicate edges; pin so a future
13435        // `target_label` change can't accidentally collapse the
13436        // capability arm into a None-shaped key that compares equal
13437        // to a populated one.
13438        let mut s = three_member_spec();
13439        let capability = WitContract {
13440            de: "cart".into(),
13441            para: "catalog".into(),
13442            wit: "pleme:cap/audit".into(),
13443            endpoint: None,
13444            subject: None,
13445            slot: None,
13446        };
13447        s.contratos.push(capability.clone());
13448        s.contratos.push(capability);
13449        let err = s.validate().unwrap_err();
13450        match err {
13451            AplicacaoError::ContratoDuplicate {
13452                de,
13453                para,
13454                wit,
13455                target,
13456            } => {
13457                assert_eq!(de, "cart");
13458                assert_eq!(para, "catalog");
13459                assert_eq!(wit, "pleme:cap/audit");
13460                assert!(
13461                    target.contains("capability"),
13462                    "capability-edge duplicate diagnostic must surface the \
13463                     no-payload shape (got target = {target:?})"
13464                );
13465            }
13466            other => panic!("expected ContratoDuplicate, got {other:?}"),
13467        }
13468    }
13469
13470    #[test]
13471    fn accepts_distinct_http_paths_between_same_pair() {
13472        // Negative pin: two HTTP contracts cart → catalog at distinct
13473        // endpoints (`/products/:id` and `/search`) are *not*
13474        // duplicates — they're distinct typed edges differing on the
13475        // payload axis. The duplicate-gate must not over-match here,
13476        // since the cart-calls-catalog-on-multiple-paths shape is the
13477        // canonical multi-endpoint pattern (MESH-COMPOSITION §III.1
13478        // example: cart calls catalog at /products/:id, payment at
13479        // /charge — same shape extends to two paths on one para).
13480        let mut s = three_member_spec();
13481        s.contratos
13482            .push(contract_http("cart", "catalog", "/search"));
13483        s.validate()
13484            .expect("distinct endpoints between same (de, para) must validate");
13485    }
13486
13487    #[test]
13488    fn accepts_same_endpoint_on_different_pairs() {
13489        // Negative pin: the same `/charge` endpoint reused on two
13490        // different (de, para) pairs is two distinct edges, not a
13491        // duplicate. Pinning this shape so the gate's identity key
13492        // includes both `de` and `para` (not just `(wit, endpoint)`).
13493        let mut s = three_member_spec();
13494        s.contratos
13495            .push(contract_http("payment", "catalog", "/charge"));
13496        s.validate()
13497            .expect("same endpoint reused on distinct (de, para) must validate");
13498    }
13499
13500    #[test]
13501    fn rejects_duplicate_contrato_diagnostic_names_offending_target() {
13502        // Pin the diagnostic shape: the duplicate-edge error names
13503        // *which* target field carried the conflict, so the author
13504        // doesn't have to re-grep the source caixa.lisp to find it.
13505        // Same self-locating diagnostic discipline as
13506        // ContratoEndpointEmpty / ContratoSubjectEmpty / etc.
13507        let mut s = three_member_spec();
13508        s.contratos
13509            .push(contract_http("cart", "catalog", "/products/:id"));
13510        let err = s.validate().unwrap_err();
13511        let msg = format!("{err}");
13512        assert!(
13513            msg.contains("\"/products/:id\""),
13514            "duplicate-contrato diagnostic must name the offending \
13515             :endpoint payload (got: {msg:?})"
13516        );
13517        assert!(
13518            msg.contains("cart") && msg.contains("catalog"),
13519            "diagnostic must name both endpoints of the duplicate edge \
13520             (got: {msg:?})"
13521        );
13522    }
13523
13524    #[test]
13525    fn duplicate_contrato_gate_runs_after_membership_check() {
13526        // Order pin: a duplicate contract whose `:de` is *also* not in
13527        // `:membros` surfaces the membership error first — the
13528        // missing-member diagnostic is more locating than the
13529        // duplicate-edge one (the author has to fix the membership
13530        // before the duplicate is meaningful). Same ordering
13531        // discipline as `membros_validation_runs_before_contratos_membership_check`.
13532        let mut s = three_member_spec();
13533        s.contratos.push(contract_http("phantom", "catalog", "/x"));
13534        s.contratos.push(contract_http("phantom", "catalog", "/x"));
13535        let err = s.validate().unwrap_err();
13536        assert!(
13537            matches!(err, AplicacaoError::ContratoMemberMissing { ref caixa } if caixa == "phantom"),
13538            "membership-missing must fire before duplicate-edge (got {err:?})"
13539        );
13540    }
13541
13542    #[test]
13543    fn duplicate_contrato_gate_runs_after_target_shape_check() {
13544        // Order pin: a contract with a malformed target (e.g. an HTTP
13545        // wit world with an empty :endpoint) surfaces the target-shape
13546        // error first, not the duplicate one. Even when two such
13547        // malformed entries are identical, the per-contract `target()`
13548        // check fires inside the loop *before* the duplicate-key
13549        // insert, so the diagnostic remains the most-locating one.
13550        let mut s = three_member_spec();
13551        let malformed = WitContract {
13552            de: "cart".into(),
13553            para: "catalog".into(),
13554            wit: "wasi:http/proxy".into(),
13555            endpoint: Some(String::new()),
13556            subject: None,
13557            slot: None,
13558        };
13559        s.contratos.push(malformed.clone());
13560        s.contratos.push(malformed);
13561        let err = s.validate().unwrap_err();
13562        assert!(
13563            matches!(err, AplicacaoError::ContratoEndpointEmpty { .. }),
13564            "endpoint-empty must fire before duplicate-edge (got {err:?})"
13565        );
13566    }
13567
13568    #[test]
13569    fn wit_target_label_pins_per_variant_format() {
13570        // Label format is the single source of truth every duplicate-
13571        // `:contratos` diagnostic + every future `feira app graph`
13572        // consumer routes through. Pin the shape per variant so a
13573        // future edit to `WitTarget::label` (e.g. a JSON emitter that
13574        // strips the leading `:`, or a rename from `endpoint` →
13575        // `path`) surfaces as a red-red test rather than as a silent
13576        // downstream diagnostic drift. Together with the exhaustive
13577        // `match` on `WitTarget` inside `label()`, adding a future
13578        // variant (M4 `Rest` / `Grpc` split, `Queue`-shaped `Store`
13579        // peer, per-edge WIT registry variants) is a compile error at
13580        // the label site — not a fall-through into the `Capability`
13581        // "no payload" default the prior raw-field-probe helper
13582        // silently landed on.
13583        assert_eq!(
13584            WitTarget::Http {
13585                endpoint: "/charge",
13586            }
13587            .label(),
13588            "\
13589:endpoint \"/charge\""
13590        );
13591        assert_eq!(
13592            WitTarget::PubSub {
13593                subject: "events.checkout.paid",
13594            }
13595            .label(),
13596            "\
13597:subject \"events.checkout.paid\""
13598        );
13599        assert_eq!(
13600            WitTarget::Store {
13601                slot: "checkout/$order",
13602            }
13603            .label(),
13604            "\
13605:slot \"checkout/$order\""
13606        );
13607        assert_eq!(WitTarget::Capability.label(), "(capability — no payload)");
13608        // Capability-arm label routes through the lifted
13609        // [`WitTarget::CAPABILITY_LABEL`] const so the "one canonical
13610        // declaration per arm, next to the variant" discipline the
13611        // peer payload-arm [`WitTarget::HTTP_FIELD_NAME`] /
13612        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13613        // consts already carry extends to the payload-less arm; the
13614        // byte-string equality pin below plus this label-routes-
13615        // through-the-const pin make a future rebrand on either the
13616        // const declaration or the `label()` template a build error
13617        // here rather than a downstream consumer surprise.
13618        assert_eq!(WitTarget::Capability.label(), WitTarget::CAPABILITY_LABEL,);
13619        assert_eq!(WitTarget::CAPABILITY_LABEL, "(capability — no payload)");
13620    }
13621
13622    #[test]
13623    fn wit_target_display_routes_through_label_helper() {
13624        // Fail-before-pass-after pin on the fourth (and only remaining)
13625        // typed-shape-discriminator axis to converge onto the
13626        // three-path-convergence discipline the sibling M3
13627        // [`PlacementStrategy`] (0a2f653) and M2
13628        // [`crate::supervisor::RestartStrategy`] /
13629        // [`crate::supervisor::RestartPolicy`] OTP-shape typed enums
13630        // already carry: [`std::fmt::Display`] on [`WitTarget`] routes
13631        // through [`WitTarget::label`], so every consumer reaching for
13632        // `format!("{v}")` on a typed payload target lands on the same
13633        // stable author-facing byte-string [`WitTarget::label`] returns
13634        // — the byte-string the [`AplicacaoError::ContratoDuplicate`]
13635        // `target:` carry the [`AplicacaoSpec::validate`] duplicate-
13636        // `:contratos` gate seeds via [`WitTarget::label`] at
13637        // aplicacao.rs:5491 already threads through.
13638        //
13639        // Pre-lift `format!("{v}")` on [`WitTarget`] would have fallen
13640        // through to the `Debug` derive's structural output
13641        // (`Http { endpoint: "/charge" }` — Rust struct-literal syntax)
13642        // rather than the [`WitTarget::label`] helper's stable byte-
13643        // string (`:endpoint "/charge"` — the author-facing `:contratos`
13644        // keyword form). Every future consumer that reaches for
13645        // `format!("{target}")` — the canonical shape every user-facing
13646        // pretty-print site on the sibling typed-enum axes
13647        // ([`PlacementStrategy`], [`crate::supervisor::RestartStrategy`],
13648        // [`crate::supervisor::RestartPolicy`]) already uses — would
13649        // silently land under a different byte-string than the
13650        // [`WitTarget::label`] callers that the duplicate-`:contratos`
13651        // diagnostic already threads through, with the mismatch
13652        // surfacing as a downstream diagnostic / graph / audit line
13653        // reading one spelling while the substrate's own gate emitted
13654        // another.
13655        //
13656        // Pin the routing here so a future
13657        // `impl std::fmt::Display for WitTarget<'_>` reimplementation
13658        // that hand-rolls the per-arm formatting instead of delegating
13659        // to [`WitTarget::label`] fails at caixa-core build time.
13660        for variant in [
13661            WitTarget::Http {
13662                endpoint: "/charge",
13663            },
13664            WitTarget::PubSub {
13665                subject: "events.checkout.paid",
13666            },
13667            WitTarget::Store {
13668                slot: "checkout/$order",
13669            },
13670            WitTarget::Capability,
13671        ] {
13672            assert_eq!(
13673                variant.to_string(),
13674                variant.label(),
13675                "WitTarget::{variant:?} Display must route through \
13676                 WitTarget::label (single source of truth: the lifted \
13677                 payload_pair 4-arm dispatch the label helper already \
13678                 threads through)"
13679            );
13680        }
13681    }
13682
13683    #[test]
13684    fn wit_target_display_matches_duplicate_contratos_diagnostic_carrier() {
13685        // Consumer-side pin on the three-path convergence:
13686        // [`std::fmt::Display`] agrees byte-for-byte with the
13687        // [`AplicacaoError::ContratoDuplicate`] `target:` carrier the
13688        // [`AplicacaoSpec::validate`] duplicate-`:contratos` gate seeds
13689        // via [`WitTarget::label`] at aplicacao.rs:5491 on every arm.
13690        // Pre-lift the two paths were structurally independent — the
13691        // substrate-side gate reached for `target_view.label()` while a
13692        // future downstream diagnostic / graph / audit line reaching
13693        // for `format!("{target}")` would silently land on the `Debug`
13694        // derive's structural output. Pin the two paths byte-for-byte
13695        // here so any future variant addition (M4 `Rest`/`Grpc` split
13696        // of [`WitTarget::Http`], `Queue`-shaped peer of
13697        // [`WitTarget::Store`]) is a caixa-core-build-time exhaustive-
13698        // match error at [`WitTarget::payload_pair`] rather than a
13699        // silent per-consumer dispatch miss.
13700        for variant in [
13701            WitTarget::Http {
13702                endpoint: "/charge",
13703            },
13704            WitTarget::PubSub {
13705                subject: "events.checkout.paid",
13706            },
13707            WitTarget::Store {
13708                slot: "checkout/$order",
13709            },
13710            WitTarget::Capability,
13711        ] {
13712            assert_eq!(
13713                format!("{variant}"),
13714                variant.label(),
13715                "WitTarget::{variant:?} Display byte-string must match \
13716                 the AplicacaoError::ContratoDuplicate `target:` carrier \
13717                 the AplicacaoSpec::validate duplicate-`:contratos` gate \
13718                 seeds via WitTarget::label — three-path convergence: \
13719                 Display + label + payload_pair all resolve to the same \
13720                 per-arm byte-string"
13721            );
13722        }
13723    }
13724
13725    #[test]
13726    fn wit_target_payload_pair_pins_per_variant() {
13727        // Pin the per-arm `(field-name, payload)` pair single-sourced
13728        // onto [`WitTarget::payload_pair`] — the single 4-arm dispatch
13729        // both [`WitTarget::label`] (formats `":{field} {payload:?}"`
13730        // on `Some`, falls to [`WitTarget::CAPABILITY_LABEL`] on `None`)
13731        // and [`WitTarget::field_name`] (returns the first component)
13732        // route through. Until this lift landed [`WitTarget::label`]
13733        // dispatched on the same three arms with a per-arm
13734        // `format!(":{} {…:?}", …)` invocation each, hand-quoting the
13735        // paired [`WitTarget::HTTP_FIELD_NAME`] /
13736        // [`WitTarget::PUBSUB_FIELD_NAME`] /
13737        // [`WitTarget::STORE_FIELD_NAME`] const at every site — the
13738        // canonical "same shape, written N times" duplication
13739        // THEORY.md §I.3.5 promotes to a build-time concern. A future
13740        // [`WitTarget`] variant addition (`Rest`/`Grpc` split of
13741        // [`WitTarget::Http`], `Queue`-shaped peer of
13742        // [`WitTarget::Store`]) is one match-arm edit at
13743        // [`WitTarget::payload_pair`], visible here as a compile-time
13744        // exhaustiveness error on both this pin and the label-format
13745        // pin above.
13746        assert_eq!(
13747            WitTarget::Http {
13748                endpoint: "/charge"
13749            }
13750            .payload_pair(),
13751            Some((WitTarget::HTTP_FIELD_NAME, "/charge")),
13752        );
13753        assert_eq!(
13754            WitTarget::PubSub {
13755                subject: "events.x",
13756            }
13757            .payload_pair(),
13758            Some((WitTarget::PUBSUB_FIELD_NAME, "events.x")),
13759        );
13760        assert_eq!(
13761            WitTarget::Store {
13762                slot: "checkout/$order",
13763            }
13764            .payload_pair(),
13765            Some((WitTarget::STORE_FIELD_NAME, "checkout/$order")),
13766        );
13767        assert_eq!(WitTarget::Capability.payload_pair(), None);
13768    }
13769
13770    #[test]
13771    fn wit_target_field_name_pins_per_variant() {
13772        // Pin the per-arm author-facing `:contratos` payload field
13773        // name single-sourced onto [`WitTarget::HTTP_FIELD_NAME`] /
13774        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
13775        // + returned by [`WitTarget::field_name`]. Every downstream
13776        // consumer (the [`WitContract::target`] gate's `expected:`
13777        // scalar, the [`WitTarget::label`] template's keyword prefix,
13778        // the `feira app graph` verb's `endpoint=…` prefix) routes
13779        // through the same three peer consts, so a rename on the
13780        // author-surface `(defcaixa … :contratos ((:de … :para …
13781        // :wit … :endpoint …)))` field lands in exactly one place.
13782        assert_eq!(
13783            WitTarget::Http {
13784                endpoint: "/charge"
13785            }
13786            .field_name(),
13787            Some(WitTarget::HTTP_FIELD_NAME),
13788        );
13789        assert_eq!(
13790            WitTarget::PubSub {
13791                subject: "events.x",
13792            }
13793            .field_name(),
13794            Some(WitTarget::PUBSUB_FIELD_NAME),
13795        );
13796        assert_eq!(
13797            WitTarget::Store {
13798                slot: "checkout/$order",
13799            }
13800            .field_name(),
13801            Some(WitTarget::STORE_FIELD_NAME),
13802        );
13803        // Capability arm carries no payload field — the diagnostic
13804        // never reports `expected: "capability"` because the gate's
13805        // Capability arm accepts no payload at all (it fires the
13806        // "expected: none" WrongTarget error instead), so the field-
13807        // name method returns None here rather than a placeholder.
13808        assert_eq!(WitTarget::Capability.field_name(), None);
13809
13810        // Peer const scalar values pinned so a rename on either side
13811        // (author-surface field name in the `(defcaixa …)` DSL, or
13812        // the diagnostic's `expected:` scalar) can't drift without
13813        // failing here first.
13814        assert_eq!(WitTarget::HTTP_FIELD_NAME, "endpoint");
13815        assert_eq!(WitTarget::PUBSUB_FIELD_NAME, "subject");
13816        assert_eq!(WitTarget::STORE_FIELD_NAME, "slot");
13817    }
13818
13819    #[test]
13820    fn wit_target_payload_pins_per_variant() {
13821        // Pin the per-arm payload scalar single-sourced onto the
13822        // [`WitTarget::payload_pair`] 4-arm dispatch and surfaced through
13823        // [`WitTarget::payload`] — the peer per-half projection to
13824        // [`WitTarget::field_name`] on the paired sub-selector axis. The
13825        // three payload-carrying arms round-trip their author-declared
13826        // scalar verbatim (`Http` → `Some("/charge")`, `PubSub` →
13827        // `Some("events.x")`, `Store` → `Some("checkout/$order")`) and
13828        // the payload-less [`WitTarget::Capability`] arm returns `None`.
13829        // Same shape as the sibling `wit_target_field_name_pins_per_variant`
13830        // (c6ec2af) pin on the Component-0 projection axis, extended
13831        // onto the Component-1 projection axis so both per-half readers
13832        // on the paired dispatch carry their own byte-shape pin.
13833        assert_eq!(
13834            WitTarget::Http {
13835                endpoint: "/charge",
13836            }
13837            .payload(),
13838            Some("/charge"),
13839        );
13840        assert_eq!(
13841            WitTarget::PubSub {
13842                subject: "events.x",
13843            }
13844            .payload(),
13845            Some("events.x"),
13846        );
13847        assert_eq!(
13848            WitTarget::Store {
13849                slot: "checkout/$order",
13850            }
13851            .payload(),
13852            Some("checkout/$order"),
13853        );
13854        assert_eq!(WitTarget::Capability.payload(), None);
13855    }
13856
13857    #[test]
13858    fn wit_target_payload_matches_payload_pair_second_component_per_variant() {
13859        // Per-variant equivalence pin: for every arm of [`WitTarget`],
13860        // `.payload()` equals `.payload_pair().map(|(_, p)| p)`
13861        // byte-for-byte. Guards the drift surface where a future refactor
13862        // that split one accessor off the shared match onto its own
13863        // dispatch — a well-meaning "inline the pair back into per-half
13864        // fields for one crate-internal caller who only wanted one half"
13865        // or a scratch `impl` shadowing the derived projection — would
13866        // silently desynchronize [`WitTarget::payload`] from the
13867        // authoritative [`WitTarget::payload_pair`] dispatch, and every
13868        // downstream consumer that thinks "the payload half of the pair"
13869        // would drift from the diagnostic / graph consumers reading the
13870        // same match through [`WitTarget::label`] / [`WitTarget::graph_label`].
13871        // Sibling to the peer [`caixa_flux::GitRefSpec`] `ref_value`
13872        // per-half projection pin (`gitrefspec_ref_pair_projects_
13873        // ref_field_name_and_ref_value_per_variant`, 655a1c0) on the
13874        // FluxCD source-controller `spec.ref.<field>` axis — same "one
13875        // paired dispatch, both per-half projections agree byte-for-
13876        // byte" discipline extended onto the M3 `:contratos` payload-
13877        // arm surface.
13878        for variant in [
13879            WitTarget::Http {
13880                endpoint: "/charge",
13881            },
13882            WitTarget::PubSub {
13883                subject: "events.checkout.paid",
13884            },
13885            WitTarget::Store {
13886                slot: "checkout/$order",
13887            },
13888            WitTarget::Capability,
13889        ] {
13890            let via_projection = variant.payload();
13891            let via_pair = variant.payload_pair().map(|(_, p)| p);
13892            assert_eq!(
13893                via_projection, via_pair,
13894                "WitTarget::{variant:?} payload() must equal \
13895                 payload_pair().map(|(_, p)| p) byte-for-byte — a \
13896                 regression that splits the two per-half projections off \
13897                 their shared match would silently desynchronize the \
13898                 payload accessor from the paired dispatch every \
13899                 diagnostic / graph consumer reads through",
13900            );
13901        }
13902    }
13903
13904    #[test]
13905    fn wit_target_http_endpoint_pins_per_variant() {
13906        // Pin the per-arm HTTP-endpoint scalar single-sourced onto the
13907        // [`WitTarget::http_endpoint`] 2-arm dispatch — the
13908        // substrate-primitive per-arm post-projection accessor every
13909        // L7-HTTP-facing consumer routes through, sibling to the peer
13910        // WitContract pre-projection [`WitContract::endpoint`] (7020470)
13911        // scalar accessor on the raw-field axis. The [`WitTarget::Http`]
13912        // arm round-trips its author-declared endpoint verbatim as
13913        // `Some("/charge")`; the three sibling arms
13914        // ([`WitTarget::PubSub`] / [`WitTarget::Store`] /
13915        // [`WitTarget::Capability`]) each return `None` because they
13916        // carry no HTTP endpoint by definition. Same fail-before-pass-
13917        // after per-variant discipline as the sibling
13918        // `wit_target_payload_pins_per_variant` (5d6dc92) /
13919        // `wit_target_field_name_pins_per_variant` (c6ec2af) /
13920        // `wit_target_payload_pair_pins_per_variant` (6788ed6) pins on
13921        // the peer pan-arm / per-half projection axes — extended onto
13922        // the per-arm HTTP-shape post-projection axis so a future
13923        // [`WitTarget`] variant addition (a `Rest`/`Grpc` split of
13924        // [`WitTarget::Http`], a `Queue`-shaped peer of
13925        // [`WitTarget::Store`]) trips a compile-time exhaustiveness
13926        // error on the sibling [`WitTarget::http_endpoint`] match arms
13927        // whose payload the L7-HTTP-shape accept-set is meant to bound.
13928        assert_eq!(
13929            WitTarget::Http {
13930                endpoint: "/charge",
13931            }
13932            .http_endpoint(),
13933            Some("/charge"),
13934        );
13935        assert_eq!(
13936            WitTarget::PubSub {
13937                subject: "events.checkout.paid",
13938            }
13939            .http_endpoint(),
13940            None,
13941        );
13942        assert_eq!(
13943            WitTarget::Store {
13944                slot: "checkout/$order",
13945            }
13946            .http_endpoint(),
13947            None,
13948        );
13949        assert_eq!(WitTarget::Capability.http_endpoint(), None);
13950    }
13951
13952    #[test]
13953    fn wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere() {
13954        // Per-variant coherence pin: for every arm of [`WitTarget`],
13955        // `.http_endpoint()` equals `.payload()` on the [`WitTarget::Http`]
13956        // arm (both project the same author-declared request-path
13957        // scalar), and returns `None` on every sibling arm regardless of
13958        // whether [`WitTarget::payload`] itself returns `Some` (PubSub /
13959        // Store carry their own payload the pan-arm accessor surfaces,
13960        // but that payload is not an HTTP endpoint — the per-arm
13961        // accessor must not leak it through the HTTP-shape channel).
13962        // Guards the drift surface where a future refactor that
13963        // conflated the per-arm HTTP projection with the pan-arm
13964        // [`WitTarget::payload`] projection — a well-meaning "one
13965        // accessor for the L7 branch, one for the graph" collapse that
13966        // routes both through the same 4-arm dispatch — would silently
13967        // widen the L7-HTTP-shape accept-set onto pub-sub / store
13968        // payloads at the caixa-mesh L7 emit branch, admitting a
13969        // `nats:pub-sub` edge's `:subject` as a Cilium L7 HTTP `path:`
13970        // rule with the operator-side apply-time symptom (Cilium's
13971        // eBPF data-plane rejects every ingress edge whose L7 filter
13972        // doesn't match the wire-format HTTP request line) far from
13973        // the source refactor. Sibling to the peer
13974        // `wit_target_payload_matches_payload_pair_second_component_
13975        // per_variant` (5d6dc92) coherence pin on the pan-arm axis —
13976        // extended onto the per-arm HTTP specialization axis so both
13977        // the pan-arm and the per-arm projections carry their own
13978        // byte-shape coherence witness against the substrate's typed
13979        // arm-family accept-set.
13980        for variant in [
13981            WitTarget::Http {
13982                endpoint: "/charge",
13983            },
13984            WitTarget::PubSub {
13985                subject: "events.checkout.paid",
13986            },
13987            WitTarget::Store {
13988                slot: "checkout/$order",
13989            },
13990            WitTarget::Capability,
13991        ] {
13992            let per_arm = variant.http_endpoint();
13993            let pan_arm = variant.payload();
13994            if variant.is_http() {
13995                assert_eq!(
13996                    per_arm, pan_arm,
13997                    "WitTarget::{variant:?} http_endpoint() must equal \
13998                     payload() on the Http arm — a per-arm-vs-pan-arm \
13999                     split would silently drift the L7 emit branch's \
14000                     path-scalar source from the graph verb's payload \
14001                     scalar source",
14002                );
14003            } else {
14004                assert_eq!(
14005                    per_arm, None,
14006                    "WitTarget::{variant:?} http_endpoint() must return \
14007                     None on non-Http arms — a leak that surfaced a \
14008                     pub-sub :subject or a key/value :slot through the \
14009                     HTTP-endpoint accessor would silently widen the \
14010                     Cilium L7 HTTP `path:` rule accept-set onto \
14011                     protocol shapes Cilium's eBPF data-plane can't \
14012                     introspect",
14013                );
14014            }
14015        }
14016    }
14017
14018    #[test]
14019    fn wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant() {
14020        // Per-variant coherence pin: for every arm of [`WitTarget`],
14021        // `.http_endpoint().is_some()` iff `.is_http()`. Guards the
14022        // drift surface where a future extension of the
14023        // [`WitTarget::http_endpoint`] accessor's accept-set (e.g. a
14024        // `Rest`/`Grpc` split of [`WitTarget::Http`] that widened the
14025        // accessor to cover both peers) landed without a paired
14026        // extension of the [`gen_platform::IsVariant`]-derived
14027        // `is_http()` predicate's accept-set, or vice versa — a
14028        // regression that split the "which arms count as HTTP-shaped
14029        // for L7-path emission?" answer between two dispatch surfaces
14030        // the substrate ships. Sibling to the peer
14031        // `wit_target_field_name_pins_per_variant` (c6ec2af) discipline
14032        // on the paired dispatch axis — extended onto the per-arm
14033        // predicate-vs-accessor coherence axis so the gen-platform
14034        // IsVariant predicate and the substrate-lifted per-arm
14035        // accessor carry one shared answer to "is this the HTTP arm?".
14036        for variant in [
14037            WitTarget::Http {
14038                endpoint: "/charge",
14039            },
14040            WitTarget::PubSub {
14041                subject: "events.checkout.paid",
14042            },
14043            WitTarget::Store {
14044                slot: "checkout/$order",
14045            },
14046            WitTarget::Capability,
14047        ] {
14048            assert_eq!(
14049                variant.http_endpoint().is_some(),
14050                variant.is_http(),
14051                "WitTarget::{variant:?} http_endpoint().is_some() must \
14052                 equal is_http() — a drift would split the L7 emit \
14053                 branch's arm-set gate from the substrate-derived \
14054                 shape-discrimination predicate on the same axis",
14055            );
14056        }
14057    }
14058
14059    #[test]
14060    fn wit_target_pubsub_subject_pins_per_variant() {
14061        // Fail-before-pass-after pin: the substrate-canonical per-arm
14062        // pub-sub-subject scalar accessor [`WitTarget::pubsub_subject`]
14063        // is the single dispatch every future pub-sub-facing consumer
14064        // routes through, sibling to the peer [`WitContract::subject`]
14065        // (63e18a0) pre-projection scalar accessor on the raw-field
14066        // axis and to the peer [`WitTarget::http_endpoint`] (5d6dc92)
14067        // post-projection per-arm accessor on the sibling HTTP-shape
14068        // axis. The [`WitTarget::PubSub`] arm round-trips its
14069        // author-declared subject verbatim as
14070        // `Some("events.checkout.paid")`; the three sibling arms each
14071        // return `None` because they carry no NATS-shaped subject by
14072        // definition. Same fail-before-pass-after per-variant discipline
14073        // as the sibling `wit_target_http_endpoint_pins_per_variant`
14074        // pin on the peer per-arm axis — extended onto the per-arm
14075        // pub-sub-shape post-projection axis so a future [`WitTarget`]
14076        // variant addition (a `Rest`/`Grpc` split of [`WitTarget::Http`],
14077        // a `Queue`-shaped peer of [`WitTarget::Store`]) trips a
14078        // compile-time exhaustiveness error on the sibling
14079        // [`WitTarget::pubsub_subject`] match arms whose payload the
14080        // pub-sub-shape accept-set is meant to bound.
14081        assert_eq!(
14082            WitTarget::PubSub {
14083                subject: "events.checkout.paid",
14084            }
14085            .pubsub_subject(),
14086            Some("events.checkout.paid"),
14087        );
14088        assert_eq!(
14089            WitTarget::Http {
14090                endpoint: "/charge",
14091            }
14092            .pubsub_subject(),
14093            None,
14094        );
14095        assert_eq!(
14096            WitTarget::Store {
14097                slot: "checkout/$order",
14098            }
14099            .pubsub_subject(),
14100            None,
14101        );
14102        assert_eq!(WitTarget::Capability.pubsub_subject(), None);
14103    }
14104
14105    #[test]
14106    fn wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere() {
14107        // Per-variant coherence pin: for every arm of [`WitTarget`],
14108        // `.pubsub_subject()` equals `.payload()` on the
14109        // [`WitTarget::PubSub`] arm (both project the same
14110        // author-declared subject scalar), and returns `None` on every
14111        // sibling arm regardless of whether [`WitTarget::payload`]
14112        // itself returns `Some` (Http / Store carry their own payload
14113        // the pan-arm accessor surfaces, but that payload is not a
14114        // pub-sub subject — the per-arm accessor must not leak it
14115        // through the pub-sub-shape channel). Sibling to the peer
14116        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
14117        // coherence pin on the per-arm HTTP-shape axis — extended onto
14118        // the per-arm pub-sub specialization axis so both per-arm
14119        // projections carry their own byte-shape coherence witness
14120        // against the substrate's typed arm-family accept-set.
14121        for variant in [
14122            WitTarget::Http {
14123                endpoint: "/charge",
14124            },
14125            WitTarget::PubSub {
14126                subject: "events.checkout.paid",
14127            },
14128            WitTarget::Store {
14129                slot: "checkout/$order",
14130            },
14131            WitTarget::Capability,
14132        ] {
14133            let per_arm = variant.pubsub_subject();
14134            let pan_arm = variant.payload();
14135            if variant.is_pubsub() {
14136                assert_eq!(
14137                    per_arm, pan_arm,
14138                    "WitTarget::{variant:?} pubsub_subject() must equal \
14139                     payload() on the PubSub arm — a per-arm-vs-pan-arm \
14140                     split would silently drift the pub-sub-shape emit \
14141                     branch's subject-scalar source from the graph verb's \
14142                     payload scalar source",
14143                );
14144            } else {
14145                assert_eq!(
14146                    per_arm, None,
14147                    "WitTarget::{variant:?} pubsub_subject() must return \
14148                     None on non-PubSub arms — a leak that surfaced an \
14149                     HTTP :endpoint or a key/value :slot through the \
14150                     pub-sub-subject accessor would silently widen the \
14151                     downstream NATS-shape accept-set onto protocol \
14152                     shapes NATS servers can't route",
14153                );
14154            }
14155        }
14156    }
14157
14158    #[test]
14159    fn wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant() {
14160        // Per-variant coherence pin: for every arm of [`WitTarget`],
14161        // `.pubsub_subject().is_some()` iff `.is_pubsub()`. Guards the
14162        // drift surface where a future extension of the
14163        // [`WitTarget::pubsub_subject`] accessor's accept-set landed
14164        // without a paired extension of the [`gen_platform::IsVariant`]-
14165        // derived `is_pubsub()` predicate's accept-set, or vice versa
14166        // — a regression that split the "which arms count as pub-sub-
14167        // shaped for subject emission?" answer between two dispatch
14168        // surfaces the substrate ships. Sibling to the peer
14169        // `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
14170        // pin on the per-arm HTTP-shape axis — extended onto the
14171        // per-arm pub-sub predicate-vs-accessor coherence axis so the
14172        // gen-platform IsVariant predicate and the substrate-lifted
14173        // per-arm accessor carry one shared answer to "is this the
14174        // PubSub arm?".
14175        for variant in [
14176            WitTarget::Http {
14177                endpoint: "/charge",
14178            },
14179            WitTarget::PubSub {
14180                subject: "events.checkout.paid",
14181            },
14182            WitTarget::Store {
14183                slot: "checkout/$order",
14184            },
14185            WitTarget::Capability,
14186        ] {
14187            assert_eq!(
14188                variant.pubsub_subject().is_some(),
14189                variant.is_pubsub(),
14190                "WitTarget::{variant:?} pubsub_subject().is_some() must \
14191                 equal is_pubsub() — a drift would split the pub-sub \
14192                 emit branch's arm-set gate from the substrate-derived \
14193                 shape-discrimination predicate on the same axis",
14194            );
14195        }
14196    }
14197
14198    #[test]
14199    fn wit_target_store_slot_pins_per_variant() {
14200        // Fail-before-pass-after pin: the substrate-canonical per-arm
14201        // key/value-store-slot scalar accessor [`WitTarget::store_slot`]
14202        // is the single dispatch every future store-facing consumer
14203        // routes through, sibling to the peer [`WitContract::slot`]
14204        // pre-projection scalar accessor on the raw-field axis and to
14205        // the peer [`WitTarget::http_endpoint`] (5d6dc92) +
14206        // [`WitTarget::pubsub_subject`] post-projection per-arm
14207        // accessors on the sibling per-payload-arm axes. The
14208        // [`WitTarget::Store`] arm round-trips its author-declared
14209        // slot verbatim as `Some("checkout/$order")`; the three
14210        // sibling arms each return `None` because they carry no
14211        // WASI-key/value slot by definition. Same fail-before-pass-
14212        // after per-variant discipline as the sibling
14213        // `wit_target_http_endpoint_pins_per_variant` +
14214        // `wit_target_pubsub_subject_pins_per_variant` pins on the
14215        // peer per-arm axes — extended onto the per-arm store-shape
14216        // post-projection axis so a future [`WitTarget`] variant
14217        // addition trips a compile-time exhaustiveness error on the
14218        // sibling [`WitTarget::store_slot`] match arms whose payload
14219        // the store-shape accept-set is meant to bound.
14220        assert_eq!(
14221            WitTarget::Store {
14222                slot: "checkout/$order",
14223            }
14224            .store_slot(),
14225            Some("checkout/$order"),
14226        );
14227        assert_eq!(
14228            WitTarget::Http {
14229                endpoint: "/charge",
14230            }
14231            .store_slot(),
14232            None,
14233        );
14234        assert_eq!(
14235            WitTarget::PubSub {
14236                subject: "events.checkout.paid",
14237            }
14238            .store_slot(),
14239            None,
14240        );
14241        assert_eq!(WitTarget::Capability.store_slot(), None);
14242    }
14243
14244    #[test]
14245    fn wit_target_store_slot_matches_payload_on_store_arm_and_is_none_elsewhere() {
14246        // Per-variant coherence pin: for every arm of [`WitTarget`],
14247        // `.store_slot()` equals `.payload()` on the
14248        // [`WitTarget::Store`] arm (both project the same
14249        // author-declared slot scalar), and returns `None` on every
14250        // sibling arm regardless of whether [`WitTarget::payload`]
14251        // itself returns `Some`. Sibling to the peer
14252        // `wit_target_http_endpoint_matches_payload_on_http_arm_and_is_none_elsewhere`
14253        // and `wit_target_pubsub_subject_matches_payload_on_pubsub_arm_and_is_none_elsewhere`
14254        // pins on the per-arm HTTP and PubSub axes — closes the
14255        // per-arm-vs-pan-arm byte-shape coherence trio across all
14256        // three payload arms.
14257        for variant in [
14258            WitTarget::Http {
14259                endpoint: "/charge",
14260            },
14261            WitTarget::PubSub {
14262                subject: "events.checkout.paid",
14263            },
14264            WitTarget::Store {
14265                slot: "checkout/$order",
14266            },
14267            WitTarget::Capability,
14268        ] {
14269            let per_arm = variant.store_slot();
14270            let pan_arm = variant.payload();
14271            if variant.is_store() {
14272                assert_eq!(
14273                    per_arm, pan_arm,
14274                    "WitTarget::{variant:?} store_slot() must equal \
14275                     payload() on the Store arm — a per-arm-vs-pan-arm \
14276                     split would silently drift the store-shape emit \
14277                     branch's slot-scalar source from the graph verb's \
14278                     payload scalar source",
14279                );
14280            } else {
14281                assert_eq!(
14282                    per_arm, None,
14283                    "WitTarget::{variant:?} store_slot() must return \
14284                     None on non-Store arms — a leak that surfaced an \
14285                     HTTP :endpoint or a NATS :subject through the \
14286                     key/value-slot accessor would silently widen the \
14287                     downstream WASI-key/value slot accept-set onto \
14288                     protocol shapes the kv backends can't route",
14289                );
14290            }
14291        }
14292    }
14293
14294    #[test]
14295    fn wit_target_store_slot_agrees_with_is_store_predicate_per_variant() {
14296        // Per-variant coherence pin: for every arm of [`WitTarget`],
14297        // `.store_slot().is_some()` iff `.is_store()`. Guards the
14298        // drift surface where a future extension of the
14299        // [`WitTarget::store_slot`] accessor's accept-set landed
14300        // without a paired extension of the [`gen_platform::IsVariant`]-
14301        // derived `is_store()` predicate's accept-set. Sibling to the
14302        // peer `wit_target_http_endpoint_agrees_with_is_http_predicate_per_variant`
14303        // and `wit_target_pubsub_subject_agrees_with_is_pubsub_predicate_per_variant`
14304        // pins — closes the per-arm predicate-vs-accessor coherence
14305        // trio across all three payload arms so the gen-platform
14306        // IsVariant predicate and the substrate-lifted per-arm
14307        // accessor carry one shared answer to "is this the Store arm?".
14308        for variant in [
14309            WitTarget::Http {
14310                endpoint: "/charge",
14311            },
14312            WitTarget::PubSub {
14313                subject: "events.checkout.paid",
14314            },
14315            WitTarget::Store {
14316                slot: "checkout/$order",
14317            },
14318            WitTarget::Capability,
14319        ] {
14320            assert_eq!(
14321                variant.store_slot().is_some(),
14322                variant.is_store(),
14323                "WitTarget::{variant:?} store_slot().is_some() must \
14324                 equal is_store() — a drift would split the store-shape \
14325                 emit branch's arm-set gate from the substrate-derived \
14326                 shape-discrimination predicate on the same axis",
14327            );
14328        }
14329    }
14330
14331    #[test]
14332    fn wit_target_per_arm_post_projection_accessors_partition_the_payload_arm_set() {
14333        // Fail-before-pass-after cross-axis pin on the trio
14334        // (`http_endpoint`, `pubsub_subject`, `store_slot`): on every
14335        // payload-carrying arm of [`WitTarget`], exactly one per-arm
14336        // accessor returns `Some(payload)` and the two peers return
14337        // `None`; and on the payload-less [`WitTarget::Capability`]
14338        // arm, all three return `None`. Guards the drift surface where
14339        // a future extension of one per-arm accessor's accept-set (e.g.
14340        // a hypothetical `Rest`/`Grpc` split of [`WitTarget::Http`]
14341        // that widened `http_endpoint` to cover both peers without
14342        // narrowing the peer `pubsub_subject` / `store_slot` accept-
14343        // sets to keep the partition mutually exclusive) landed without
14344        // threading through the peer per-arm accessors — the resulting
14345        // silent overlap would land the same edge's payload on two
14346        // downstream per-shape emit branches at once, or leak a
14347        // pub-sub subject through the store-slot channel, at renderer
14348        // emit time far from the substrate primitive's arm-widening
14349        // commit. Peer of the sibling `wit_target_field_names_are_pairwise_distinct`
14350        // 3-way pin on the payload-field-name axis — extended onto the
14351        // per-arm-accessor payload-projection axis so the substrate-
14352        // owned partition invariant is load-bearing at every per-arm
14353        // consumer's read site.
14354        let payload_variants = [
14355            (
14356                WitTarget::Http {
14357                    endpoint: "/charge",
14358                },
14359                "http",
14360            ),
14361            (
14362                WitTarget::PubSub {
14363                    subject: "events.checkout.paid",
14364                },
14365                "pubsub",
14366            ),
14367            (
14368                WitTarget::Store {
14369                    slot: "checkout/$order",
14370                },
14371                "store",
14372            ),
14373        ];
14374        for (variant, own_arm_label) in payload_variants {
14375            let own_arm_hit = match own_arm_label {
14376                "http" => variant.is_http(),
14377                "pubsub" => variant.is_pubsub(),
14378                "store" => variant.is_store(),
14379                other => panic!("unknown own-arm label {other:?}"),
14380            };
14381            let per_arm_results = [
14382                ("http_endpoint", variant.http_endpoint()),
14383                ("pubsub_subject", variant.pubsub_subject()),
14384                ("store_slot", variant.store_slot()),
14385            ];
14386            let some_count = per_arm_results.iter().filter(|(_, v)| v.is_some()).count();
14387            assert_eq!(
14388                some_count, 1,
14389                "WitTarget::{variant:?} must land exactly one per-arm \
14390                 post-projection accessor's Some result — the trio \
14391                 (http_endpoint, pubsub_subject, store_slot) must \
14392                 partition the payload arm-set; got {per_arm_results:?}",
14393            );
14394            assert!(
14395                own_arm_hit,
14396                "WitTarget::{variant:?} own-arm gen-platform predicate \
14397                 must return true on its own arm — a partition failure \
14398                 upstream of this pin",
14399            );
14400            assert!(
14401                variant.payload().is_some(),
14402                "WitTarget::{variant:?} pan-arm payload() must return \
14403                 Some on every payload-carrying arm the trio partitions",
14404            );
14405        }
14406        // The payload-less Capability arm must return None on every
14407        // per-arm accessor — the partition's terminal-fallback shape.
14408        let cap = WitTarget::Capability;
14409        assert_eq!(cap.http_endpoint(), None);
14410        assert_eq!(cap.pubsub_subject(), None);
14411        assert_eq!(cap.store_slot(), None);
14412        assert_eq!(
14413            cap.payload(),
14414            None,
14415            "WitTarget::Capability pan-arm payload() must return None — \
14416             the trio's payload-less-arm coherence witness",
14417        );
14418    }
14419
14420    #[test]
14421    fn wit_target_field_names_are_pairwise_distinct() {
14422        // Distinctness pin: if any two of the three payload-field-name
14423        // scalars ever collapse (e.g. an accidental `endpoint` copy-
14424        // paste over the `subject` const), the [`WitContract::target`]
14425        // gate's diagnostic would point authors at the wrong field —
14426        // an "expected `:endpoint`" error on a pub-sub edge would
14427        // silently misroute the fix. Same cross-axis-distinctness
14428        // discipline as the peer M3 `:placement :estrategia` variant-
14429        // discriminator scalar-value pins (cc8f749) applied to the
14430        // payload-field-name axis.
14431        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::PUBSUB_FIELD_NAME);
14432        assert_ne!(WitTarget::HTTP_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
14433        assert_ne!(WitTarget::PUBSUB_FIELD_NAME, WitTarget::STORE_FIELD_NAME);
14434    }
14435
14436    #[test]
14437    fn wit_target_graph_label_routes_through_payload_pair_on_payload_arms() {
14438        // Fail-before-pass-after pin: the graph-verb payload column's
14439        // per-arm `{field}={payload}` byte-string is derived through the
14440        // single [`WitTarget::payload_pair`] 4-arm dispatch on the three
14441        // payload-carrying arms, not through a hand-rolled per-arm match
14442        // that re-projects [`WitTarget::HTTP_FIELD_NAME`] /
14443        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14444        // inline. A future variant addition — the M4-and-later per-edge
14445        // WIT registry may split [`WitTarget::Http`] into `Rest` / `Grpc`
14446        // peers, or extend [`WitTarget::Store`] with a `Queue`-shaped
14447        // peer — becomes one match-arm edit at [`WitTarget::payload_pair`],
14448        // and both [`WitTarget::label`] (duplicate-`:contratos`
14449        // diagnostic) and [`WitTarget::graph_label`] (`feira app graph`
14450        // payload column) pick up the new arm from the same dispatch.
14451        // Prior to this lift the graph verb open-coded the 4-arm match
14452        // in caixa-feira, so a variant addition would have to be threaded
14453        // through both projections in lockstep or the graph verb would
14454        // silently drop the new arm to `(capability-only)`.
14455        for variant in [
14456            WitTarget::Http {
14457                endpoint: "/charge",
14458            },
14459            WitTarget::PubSub {
14460                subject: "events.checkout.paid",
14461            },
14462            WitTarget::Store {
14463                slot: "checkout/$order",
14464            },
14465        ] {
14466            let (field, payload) = variant
14467                .payload_pair()
14468                .expect("payload arm must expose (field, payload)");
14469            assert_eq!(
14470                variant.graph_label(),
14471                format!("{field}={payload}"),
14472                "WitTarget::{variant:?} graph_label must route the \
14473                 `{{field}}={{payload}}` template through payload_pair — \
14474                 a regression to a hand-rolled per-arm match at the graph \
14475                 verb would silently disagree with a future variant \
14476                 addition landed only at payload_pair"
14477            );
14478        }
14479    }
14480
14481    #[test]
14482    fn wit_target_graph_label_returns_capability_graph_label_const_on_capability_arm() {
14483        // Fail-before-pass-after pin on the payload-less arm: the graph
14484        // verb's `(capability-only)` byte-string routes through the
14485        // lifted [`WitTarget::CAPABILITY_GRAPH_LABEL`] const on the
14486        // [`WitTarget::Capability`] arm, not through an inline
14487        // `.to_string()` literal at the caixa-feira `cmd::app::GraphArgs::run`
14488        // per-`:contratos` payload column. Peer of the sibling
14489        // [`wit_target_label_pins_per_variant_format`] Capability-arm
14490        // assertion on the [`WitTarget::CAPABILITY_LABEL`] const —
14491        // extended here onto the third payload-less-arm consumer axis
14492        // (graph verb, sibling to the duplicate-`:contratos` diagnostic
14493        // axis and the wrong-target diagnostic axis).
14494        assert_eq!(
14495            WitTarget::Capability.graph_label(),
14496            WitTarget::CAPABILITY_GRAPH_LABEL,
14497        );
14498        assert_eq!(WitTarget::CAPABILITY_GRAPH_LABEL, "(capability-only)");
14499    }
14500
14501    #[test]
14502    fn wit_target_capability_graph_label_distinct_from_capability_label() {
14503        // Cross-consumer-axis distinctness pin: the graph-verb
14504        // payload-column const [`WitTarget::CAPABILITY_GRAPH_LABEL`]
14505        // (`(capability-only)`) and the duplicate-`:contratos` diagnostic
14506        // label const [`WitTarget::CAPABILITY_LABEL`] (`(capability — no
14507        // payload)`) surface the payload-less arm on two distinct
14508        // consumer axes; a collapse (an accidental rebrand that lands
14509        // one spelling on both consts, a copy-paste that unifies them
14510        // "for consistency") would silently merge the two byte-strings
14511        // and lose the vocabulary distinction the graph verb's
14512        // compact-column form and the diagnostic's descriptive-clause
14513        // form each carry on purpose. Peer of the sibling 4-way
14514        // [`wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms`]
14515        // pin on the `ContratoWrongTarget::expected` scalar-value axis —
14516        // extended here onto the cross-consumer-axis distinctness of the
14517        // two payload-less-arm consts.
14518        assert_ne!(
14519            WitTarget::CAPABILITY_GRAPH_LABEL,
14520            WitTarget::CAPABILITY_LABEL,
14521            "WitTarget::CAPABILITY_GRAPH_LABEL (graph-verb payload column) \
14522             and WitTarget::CAPABILITY_LABEL (duplicate-`:contratos` \
14523             diagnostic) must remain distinct — a collapse would silently \
14524             merge two consumer axes onto one spelling"
14525        );
14526    }
14527
14528    #[test]
14529    fn wit_target_expected_scalars_are_pairwise_distinct_across_all_four_arms() {
14530        // 4-way distinctness pin extending the sibling
14531        // [`wit_target_field_names_are_pairwise_distinct`] 3-way pin
14532        // (which covers only the HTTP / PubSub / Store payload arms)
14533        // onto the fourth scalar the shared
14534        // [`AplicacaoError::ContratoWrongTarget`] `expected: &'static
14535        // str` axis threads through — [`WitTarget::CAPABILITY_EXPECTED`]
14536        // (`"none"`), the payload-less Capability-arm rejection scalar.
14537        //
14538        // All four [`WitTarget::HTTP_FIELD_NAME`] /
14539        // [`WitTarget::PUBSUB_FIELD_NAME`] / [`WitTarget::STORE_FIELD_NAME`]
14540        // / [`WitTarget::CAPABILITY_EXPECTED`] consts are the closed-set
14541        // dispatch surface [`WitContract::target`] writes onto the
14542        // `ContratoWrongTarget::expected` field — the same `&'static
14543        // str` axis authors read as "this WIT world's shape admits
14544        // (only|not) `:<field>`". Pairwise-distinctness is the invariant
14545        // downstream consumers rely on: an `expected: "endpoint"`
14546        // diagnostic on a Capability-shaped edge tells the author to
14547        // add a `:endpoint "…"` slot to a WIT world that admits none,
14548        // silently misrouting the fix. Until this pin landed the three
14549        // payload-arm consts were distinctness-guarded by the sibling
14550        // 3-way pin (a4a5d09 / 4a1e490) while the fourth Capability-arm
14551        // scalar (d4f54f2) sat unguarded — a rebrand collision (the
14552        // author-facing vocabulary shift from `"none"` to `"endpoint"`
14553        // / `"subject"` / `"slot"` as M4 splits [`WitTarget::Capability`]
14554        // into per-shape peers) would have silently landed one
14555        // Capability-arm rejection on a payload-arm's `expected:` byte-
14556        // string and desynchronized the diagnostic from the author's
14557        // typed shape.
14558        //
14559        // Same 4-way pairwise-distinctness pin discipline as the peer
14560        // [`m3_placement_estrategia_consts_are_pairwise_distinct`]
14561        // (cc8f749) applies on the sibling M3 closed-set typed-enum
14562        // scalar-value dispatch axis; extends the pin trajectory the
14563        // sibling `wit_target_field_names_are_pairwise_distinct`
14564        // 3-way pin opened to cover the last unguarded corner on the
14565        // `ContratoWrongTarget::expected` scalar-value axis.
14566        //
14567        // Fail-before-pass-after locally verified by mutating
14568        // [`WitTarget::CAPABILITY_EXPECTED`] to also read `"endpoint"`
14569        // — this pin fires as expected; restoring passes.
14570        let all = [
14571            WitTarget::HTTP_FIELD_NAME,
14572            WitTarget::PUBSUB_FIELD_NAME,
14573            WitTarget::STORE_FIELD_NAME,
14574            WitTarget::CAPABILITY_EXPECTED,
14575        ];
14576        for (i, a) in all.iter().enumerate() {
14577            for (j, b) in all.iter().enumerate() {
14578                if i != j {
14579                    assert_ne!(
14580                        a, b,
14581                        "WitTarget::{{HTTP_FIELD_NAME, PUBSUB_FIELD_NAME, \
14582                         STORE_FIELD_NAME, CAPABILITY_EXPECTED}} consts must be \
14583                         pairwise distinct — got duplicate {a:?} at indices \
14584                         {i} and {j}; all four scalars thread through the \
14585                         shared `AplicacaoError::ContratoWrongTarget::expected` \
14586                         &'static str axis, so a collapse silently misdirects \
14587                         the diagnostic on which typed shape the WIT world admits",
14588                    );
14589                }
14590            }
14591        }
14592    }
14593
14594    #[test]
14595    fn wit_target_is_variant_predicates_partition_the_arm_set() {
14596        // Fail-before-pass-after pin on the
14597        // [`gen_platform::IsVariant`] derive on [`WitTarget`]: for
14598        // each of the four variants exactly one of the generated
14599        // `is_http` / `is_pubsub` / `is_store` / `is_capability`
14600        // predicates returns `true` and the other three return
14601        // `false`. Prior to this derive the only production
14602        // arm-discriminator on [`WitTarget`] — the sync-cycle
14603        // exclusion in [`AplicacaoSpec::detect_sync_cycles`] — was a
14604        // raw `matches!(c.target()?, WitTarget::PubSub { .. })` on
14605        // the variant that expressed no compile-time link back to
14606        // the closed-set typed dispatch a future fifth
14607        // `:contratos :wit`-shape arm (an M4 per-edge WIT registry
14608        // split of [`WitTarget::PubSub`] into shape-specific peers,
14609        // an M4-and-later `Rest` / `Grpc` split of [`WitTarget::Http`],
14610        // a `Queue`-shaped peer of [`WitTarget::Store`]) would have
14611        // to thread through in lockstep or the DFS exclusion would
14612        // silently disagree with the peer diagnostic templates on
14613        // which arms carry sync-versus-async semantics. Peer of the
14614        // sibling [`crate::CaixaKind`] (f5bba80),
14615        // [`PlacementStrategy`] (766ec63),
14616        // [`crate::supervisor::RestartStrategy`],
14617        // [`crate::supervisor::RestartPolicy`], and
14618        // [`crate::upgrade::UpgradeInstruction`] (915a934)
14619        // `IsVariant` derives on the sibling closed-set typed-enum
14620        // discriminator axes — extends the same one-typed-dispatch-
14621        // per-variant discipline onto the last unlifted closed-set
14622        // typed-enum discriminator on the caixa surface (the M3
14623        // mesh-slot per-`:contratos` target-arm axis), closing the
14624        // arm-discriminator convergence trajectory across every
14625        // closed-set typed enum in caixa-core.
14626        let rows: [(WitTarget<'static>, [bool; 4]); 4] = [
14627            (
14628                WitTarget::Http { endpoint: "/x" },
14629                [true, false, false, false],
14630            ),
14631            (
14632                WitTarget::PubSub {
14633                    subject: "events.x",
14634                },
14635                [false, true, false, false],
14636            ),
14637            (
14638                WitTarget::Store { slot: "kv/x" },
14639                [false, false, true, false],
14640            ),
14641            (WitTarget::Capability, [false, false, false, true]),
14642        ];
14643        for (variant, expected) in rows {
14644            let observed = [
14645                variant.is_http(),
14646                variant.is_pubsub(),
14647                variant.is_store(),
14648                variant.is_capability(),
14649            ];
14650            assert_eq!(
14651                observed, expected,
14652                "WitTarget::{variant:?} is_* predicates must partition \
14653                 the arm set (http, pubsub, store, capability); got {observed:?}"
14654            );
14655        }
14656    }
14657
14658    #[test]
14659    fn wit_target_is_variant_predicates_are_const_fn() {
14660        // The [`gen_platform::IsVariant`] derive emits `const fn`
14661        // predicates on the peer [`crate::CaixaKind`] +
14662        // [`crate::upgrade::UpgradeInstruction`] +
14663        // [`crate::supervisor::RestartStrategy`] +
14664        // [`crate::supervisor::RestartPolicy`] +
14665        // [`PlacementStrategy`] closed-set typed enums — pin the
14666        // same posture on [`WitTarget`] so a future accidental
14667        // downgrade to non-`const` (an added runtime helper reachable
14668        // only from a non-`const` context, a manual hand-rolled
14669        // `impl` that shadows the derive-generated method) trips at
14670        // caixa-core build time rather than surfacing as a downstream
14671        // `const`-context regression far from the derive declaration.
14672        //
14673        // Unlike the peer unit-variant enums (`CaixaKind` /
14674        // `PlacementStrategy` / `RestartStrategy` / `RestartPolicy`)
14675        // whose `const` constructors need no arguments, the three
14676        // payload-carrying [`WitTarget`] arms are const-constructed
14677        // through `&'static str` payloads — the same `'static`
14678        // lifetime the closed-set typed enum's four-arm partition
14679        // pin above already threads through.
14680        //
14681        // The pin lives inside a `const { assert!(..) }` block so the
14682        // compiler enforces both halves (arm predicate is `const`-
14683        // callable AND returns `true` for the matching arm) at
14684        // caixa-core compile time — peer to the sibling
14685        // [`crate::CaixaKind::is_*`] const-block pin on the closed-set
14686        // typed enum arm-predicate const-callability axis.
14687        const {
14688            assert!(WitTarget::Http { endpoint: "/x" }.is_http());
14689            assert!(WitTarget::PubSub { subject: "e" }.is_pubsub());
14690            assert!(WitTarget::Store { slot: "kv/x" }.is_store());
14691            assert!(WitTarget::Capability.is_capability());
14692        }
14693    }
14694
14695    #[test]
14696    fn detect_sync_cycles_skips_pubsub_edges_through_is_pubsub_predicate() {
14697        // Consumer-side pin on the sole production converge site:
14698        // [`AplicacaoSpec::detect_sync_cycles`] excludes pub-sub
14699        // edges from the synchronous-subgraph DFS via the lifted
14700        // [`WitTarget::is_pubsub`] `IsVariant`-derived arm-discriminator
14701        // predicate (rebound from the prior raw
14702        // `matches!(c.target()?, WitTarget::PubSub { .. })` on the
14703        // variant). Byte-equivalent today (`is_pubsub` is the
14704        // derive-generated `matches!(self, Self::PubSub { .. })` by
14705        // construction, the `#[is_variant(name = "pubsub")]` override
14706        // aliasing the auto-derived `is_pub_sub` back to the sibling
14707        // [`WitContract::is_pubsub`] name); pin the behavior so a
14708        // future accidental drift (a rebind onto a peer arm
14709        // predicate, a manual hand-rolled `impl` that shadows the
14710        // derive-generated method with different semantics, a peer
14711        // arm rename that shifts which variant carries sync-versus-
14712        // async semantics) trips at caixa-core test time rather than
14713        // at some downstream operator's runtime dispatch far from the
14714        // rebind commit.
14715        //
14716        // The fixture constructs a two-Servico Aplicacao with one
14717        // pub-sub edge that would close a sync-cycle if the DFS did
14718        // not exclude it: `a → b` (pub-sub) + `b → a` (http). The
14719        // pub-sub exclusion means the DFS sees only the `b → a` HTTP
14720        // edge, which is not a cycle. A regression in the converge
14721        // (a rebind that reads the pub-sub arm as sync) would report
14722        // `AplicacaoError::ContratoCycle`.
14723        let s = AplicacaoSpec {
14724            membros: vec![membro("a", "^0.1"), membro("b", "^0.1")],
14725            contratos: vec![
14726                // Pub-sub edge: DFS must skip via is_pubsub().
14727                WitContract {
14728                    de: "a".into(),
14729                    para: "b".into(),
14730                    wit: "nats:pub-sub".into(),
14731                    endpoint: None,
14732                    subject: Some("events.x".into()),
14733                    slot: None,
14734                },
14735                // HTTP edge: DFS must include.
14736                WitContract {
14737                    de: "b".into(),
14738                    para: "a".into(),
14739                    wit: "wasi:http/proxy".into(),
14740                    endpoint: Some("/x".into()),
14741                    subject: None,
14742                    slot: None,
14743                },
14744            ],
14745            politicas: MeshPolicy::default(),
14746            placement: Placement {
14747                estrategia: PlacementStrategy::Replicated,
14748                clusters: vec!["rio".into()],
14749                affinity: None,
14750                shard_key: None,
14751            },
14752            entrada: None,
14753        };
14754        s.validate()
14755            .expect("pub-sub edge must be excluded from sync-cycle DFS");
14756    }
14757
14758    #[test]
14759    fn wit_target_field_name_routes_through_label_and_expected_diagnostic() {
14760        // Consumer-side pin: the same three peer consts thread through
14761        // both the [`WitTarget::label`] template (leading-`:` keyword
14762        // prefix in the duplicate-`:contratos` diagnostic) and the
14763        // [`WitContract::target`] gate's [`AplicacaoError::
14764        // ContratoMissingTarget`] `expected:` scalar (the field the
14765        // author needs to add). Pin both routes at once so a future
14766        // refactor can't accidentally split them onto separate string
14767        // literals — the "one place, everywhere reaches for it"
14768        // invariant the peer const set carries.
14769        let http_label = WitTarget::Http { endpoint: "/x" }.label();
14770        assert!(
14771            http_label.starts_with(&format!(":{} ", WitTarget::HTTP_FIELD_NAME)),
14772            "label must lead with :{} keyword (got {http_label:?})",
14773            WitTarget::HTTP_FIELD_NAME,
14774        );
14775
14776        let mut s = three_member_spec();
14777        s.contratos.push(WitContract {
14778            de: "cart".into(),
14779            para: "catalog".into(),
14780            wit: "kafka:topic".into(),
14781            endpoint: None,
14782            subject: None,
14783            slot: None,
14784        });
14785        match s.validate().unwrap_err() {
14786            AplicacaoError::ContratoMissingTarget { expected, .. } => {
14787                assert_eq!(expected, WitTarget::PUBSUB_FIELD_NAME);
14788            }
14789            other => panic!("expected ContratoMissingTarget, got {other:?}"),
14790        }
14791    }
14792
14793    #[test]
14794    fn duplicate_pubsub_diagnostic_names_offending_subject() {
14795        // Peer of `rejects_duplicate_contrato_diagnostic_names_offending_target`
14796        // on the pub-sub target axis: the duplicate-edge diagnostic
14797        // must name the `:subject` payload verbatim (not just the
14798        // `(de, para, wit)` triple). Prior to lifting the label onto
14799        // [`WitTarget::label`] the diagnostic derived the label from
14800        // raw [`WitContract`] `Option<String>` probes — a future
14801        // `WitTarget` variant addition (M4 per-edge WIT registry)
14802        // would silently fall through to the `Capability` "no
14803        // payload" default without a compiler warning. Pinning the
14804        // pub-sub arm's format closes the second of three
14805        // payload-carrying `WitTarget` arms this diagnostic threads
14806        // through.
14807        let mut s = three_member_spec();
14808        let pubsub = WitContract {
14809            de: "payment".into(),
14810            para: "cart".into(),
14811            wit: "nats:pub-sub".into(),
14812            endpoint: None,
14813            subject: Some("events.checkout.paid".into()),
14814            slot: None,
14815        };
14816        s.contratos.push(pubsub.clone());
14817        s.contratos.push(pubsub);
14818        let err = s.validate().unwrap_err();
14819        let msg = format!("{err}");
14820        assert!(
14821            msg.contains(":subject \"events.checkout.paid\""),
14822            "duplicate-pubsub diagnostic must name the offending \
14823             :subject payload (got: {msg:?})"
14824        );
14825    }
14826
14827    #[test]
14828    fn duplicate_store_diagnostic_names_offending_slot() {
14829        // Peer of the HTTP + pub-sub duplicate-diagnostic pins on the
14830        // key-value target axis: the diagnostic must name the `:slot`
14831        // payload verbatim. Third of three payload-carrying
14832        // `WitTarget` arms this diagnostic threads through, closing
14833        // the per-arm label pin trilogy (`Http` — 6841,
14834        // `PubSub` + `Store` — this test + peer above).
14835        let mut s = three_member_spec();
14836        let store = WitContract {
14837            de: "cart".into(),
14838            para: "payment".into(),
14839            wit: "wasi:keyvalue/store".into(),
14840            endpoint: None,
14841            subject: None,
14842            slot: Some("checkout/$orderId".into()),
14843        };
14844        s.contratos
14845            .retain(|c| !(c.de == "cart" && c.para == "payment"));
14846        s.contratos.push(store.clone());
14847        s.contratos.push(store);
14848        let err = s.validate().unwrap_err();
14849        let msg = format!("{err}");
14850        assert!(
14851            msg.contains(":slot \"checkout/$orderId\""),
14852            "duplicate-store diagnostic must name the offending :slot \
14853             payload (got: {msg:?})"
14854        );
14855    }
14856
14857    #[test]
14858    fn rejects_entrada_path_without_leading_slash() {
14859        let mut s = three_member_spec();
14860        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "api/products".into()];
14861        let err = s.validate().unwrap_err();
14862        assert!(
14863            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "api/products"),
14864            "got {err:?}"
14865        );
14866    }
14867
14868    #[test]
14869    fn rejects_empty_entrada_path() {
14870        let mut s = three_member_spec();
14871        s.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), String::new()];
14872        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
14873    }
14874
14875    #[test]
14876    fn rejects_duplicate_entrada_paths() {
14877        let mut s = three_member_spec();
14878        s.entrada.as_mut().unwrap().paths = vec![
14879            "/api/cart".into(),
14880            "/api/products".into(),
14881            "/api/cart".into(),
14882        ];
14883        let err = s.validate().unwrap_err();
14884        assert!(
14885            matches!(err, AplicacaoError::EntradaPathDuplicate { ref path } if path == "/api/cart"),
14886            "got {err:?}"
14887        );
14888    }
14889
14890    #[test]
14891    fn rejects_zero_entrada_port() {
14892        let mut s = three_member_spec();
14893        s.entrada.as_mut().unwrap().port = 0;
14894        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
14895    }
14896
14897    // ── :entrada :paths value-shape gate ─────────────────────────────
14898    //
14899    // Mirrors the `:entrada :host` value-shape suite (c7d05ec) on the
14900    // sibling `:paths` axis. Every authoring footgun the K8s Gateway
14901    // API v1 apiserver / webhook would catch on `HTTPRoute.spec.rules[]
14902    // .matches[].path.value` (caixa-mesh/src/lib.rs:498) at admission
14903    // time now becomes a caixa-build-time `EntradaPathInvalid` with
14904    // the offending `:paths` entry named verbatim.
14905
14906    #[test]
14907    fn rejects_entrada_path_with_query() {
14908        // Fail-before-pass-after pin — pre-gate the `?q=1` suffix
14909        // silently passed validate and the Gateway API webhook
14910        // rejected it at apply time with no source citation.
14911        let mut s = three_member_spec();
14912        s.entrada.as_mut().unwrap().paths = vec!["/api/cart?q=1".into()];
14913        let err = s.validate().unwrap_err();
14914        assert!(
14915            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14916                if path == "/api/cart?q=1" && reason.contains("must not contain `?`")),
14917            "got {err:?}"
14918        );
14919    }
14920
14921    #[test]
14922    fn rejects_entrada_path_with_fragment() {
14923        let mut s = three_member_spec();
14924        s.entrada.as_mut().unwrap().paths = vec!["/api/cart#frag".into()];
14925        let err = s.validate().unwrap_err();
14926        assert!(
14927            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14928                if path == "/api/cart#frag" && reason.contains("must not contain `#`")),
14929            "got {err:?}"
14930        );
14931    }
14932
14933    #[test]
14934    fn rejects_entrada_path_with_space() {
14935        let mut s = three_member_spec();
14936        s.entrada.as_mut().unwrap().paths = vec!["/api/my cart".into()];
14937        let err = s.validate().unwrap_err();
14938        assert!(
14939            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14940                if path == "/api/my cart" && reason.contains("whitespace")),
14941            "got {err:?}"
14942        );
14943    }
14944
14945    #[test]
14946    fn rejects_entrada_path_with_tab() {
14947        let mut s = three_member_spec();
14948        s.entrada.as_mut().unwrap().paths = vec!["/api/\tcart".into()];
14949        let err = s.validate().unwrap_err();
14950        assert!(
14951            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14952                if path == "/api/\tcart" && reason.contains("whitespace")),
14953            "got {err:?}"
14954        );
14955    }
14956
14957    #[test]
14958    fn rejects_entrada_path_with_control_char() {
14959        // 0x01 (SOH) — a non-whitespace control char surfaces the
14960        // distinct "control character" reason arm, separate from
14961        // the whitespace arm. Pinned so a future refactor that
14962        // collapses the two arms can't accidentally drop the more
14963        // self-locating diagnostic.
14964        let mut s = three_member_spec();
14965        s.entrada.as_mut().unwrap().paths = vec!["/api/\x01cart".into()];
14966        let err = s.validate().unwrap_err();
14967        assert!(
14968            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14969                if path == "/api/\x01cart" && reason.contains("control character")),
14970            "got {err:?}"
14971        );
14972    }
14973
14974    #[test]
14975    fn rejects_entrada_path_with_non_ascii() {
14976        // `café` — the un-percent-encoded UTF-8 footgun the RFC 3986
14977        // unreserved-set rule rejects. The Gateway API webhook
14978        // rejects literal non-ASCII bytes; percent-encoding is the
14979        // only way to author non-ASCII in a path.
14980        let mut s = three_member_spec();
14981        s.entrada.as_mut().unwrap().paths = vec!["/api/café".into()];
14982        let err = s.validate().unwrap_err();
14983        assert!(
14984            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14985                if path == "/api/café" && reason.contains("non-ASCII")),
14986            "got {err:?}"
14987        );
14988    }
14989
14990    #[test]
14991    fn rejects_entrada_path_with_consecutive_slashes() {
14992        let mut s = three_member_spec();
14993        s.entrada.as_mut().unwrap().paths = vec!["/api//cart".into()];
14994        let err = s.validate().unwrap_err();
14995        assert!(
14996            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
14997                if path == "/api//cart" && reason.contains("consecutive `/`")),
14998            "got {err:?}"
14999        );
15000    }
15001
15002    #[test]
15003    fn rejects_entrada_path_with_dot_segment() {
15004        let mut s = three_member_spec();
15005        s.entrada.as_mut().unwrap().paths = vec!["/api/./cart".into()];
15006        let err = s.validate().unwrap_err();
15007        assert!(
15008            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15009                if path == "/api/./cart" && reason.contains("`.` segment")),
15010            "got {err:?}"
15011        );
15012    }
15013
15014    #[test]
15015    fn rejects_entrada_path_with_trailing_dot_segment() {
15016        // The bare `/.` and the trailing `/foo/.` are both rejected
15017        // by the Gateway API webhook; pinned separately so a future
15018        // narrowing that catches only the inner form surfaces here.
15019        let mut s = three_member_spec();
15020        s.entrada.as_mut().unwrap().paths = vec!["/api/.".into()];
15021        let err = s.validate().unwrap_err();
15022        assert!(
15023            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15024                if path == "/api/." && reason.contains("`.` segment")),
15025            "got {err:?}"
15026        );
15027    }
15028
15029    #[test]
15030    fn rejects_entrada_path_with_parent_segment() {
15031        let mut s = three_member_spec();
15032        s.entrada.as_mut().unwrap().paths = vec!["/api/../etc".into()];
15033        let err = s.validate().unwrap_err();
15034        assert!(
15035            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15036                if path == "/api/../etc" && reason.contains("`..` parent-segment")),
15037            "got {err:?}"
15038        );
15039    }
15040
15041    #[test]
15042    fn rejects_entrada_path_with_trailing_parent_segment() {
15043        // Trailing `/..` — symmetric arm of the parent-segment rule,
15044        // pinned separately so a future relaxation that only checks
15045        // the inner form (`/../`) surfaces here.
15046        let mut s = three_member_spec();
15047        s.entrada.as_mut().unwrap().paths = vec!["/api/..".into()];
15048        let err = s.validate().unwrap_err();
15049        assert!(
15050            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15051                if path == "/api/.." && reason.contains("`..` parent-segment")),
15052            "got {err:?}"
15053        );
15054    }
15055
15056    #[test]
15057    fn rejects_entrada_path_too_long() {
15058        // 1025-byte path — one over the Gateway API HTTPPathMatch.value
15059        // maxLength cap of 1024. Use a `/api/` prefix + a 1020-byte
15060        // ASCII-alphanumeric body so only the length rule fires.
15061        let mut s = three_member_spec();
15062        let big = format!("/api/{}", "a".repeat(1020));
15063        assert_eq!(big.len(), 1025);
15064        s.entrada.as_mut().unwrap().paths = vec![big.clone()];
15065        let err = s.validate().unwrap_err();
15066        assert!(
15067            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15068                if path == &big && reason.contains("max length of 1024")),
15069            "got {err:?}"
15070        );
15071    }
15072
15073    #[test]
15074    fn entrada_path_max_length_validates() {
15075        // 1024-byte path — exactly the Gateway API HTTPPathMatch.value
15076        // maxLength cap. Boundary pin: drift in the cap surfaces here
15077        // and at `rejects_entrada_path_too_long` simultaneously.
15078        let mut s = three_member_spec();
15079        let big = format!("/api/{}", "a".repeat(1019));
15080        assert_eq!(big.len(), 1024);
15081        s.entrada.as_mut().unwrap().paths = vec![big];
15082        s.validate().unwrap();
15083    }
15084
15085    #[test]
15086    fn entrada_accepts_canonical_paths() {
15087        // Positive-control sweep — every form the Gateway API
15088        // apiserver accepts must round-trip through validate. Covers
15089        // the root catch-all, plain paths, dot-prefixed segments
15090        // (hidden-file-style, distinct from `.` and `..` segments
15091        // which are rejected), digit-bearing segments, the canonical
15092        // route-template `:param` form (`:` is RFC 3986 reserved-set
15093        // valid in paths), trailing-slash form, percent-encoded
15094        // segments, and an interior `..` *substring* (`/foo..bar` is
15095        // not the `..` segment and is allowed).
15096        for path in [
15097            "/",
15098            "/api/cart",
15099            "/healthz",
15100            "/api/.config",
15101            "/v1/products",
15102            "/products/:id",
15103            "/api/cart/",
15104            "/api/caf%C3%A9",
15105            "/foo..bar",
15106            "/...",
15107        ] {
15108            let mut s = three_member_spec();
15109            s.entrada.as_mut().unwrap().paths = vec![path.into()];
15110            s.validate()
15111                .unwrap_or_else(|e| panic!("expected {path:?} to validate, got {e:?}"));
15112        }
15113    }
15114
15115    #[test]
15116    fn entrada_path_empty_takes_precedence_over_invalid() {
15117        // Ordering pin: `EntradaPathEmpty` is the more self-locating
15118        // diagnostic on `""` and must lead — `validate_entrada_path`
15119        // is only reached after the empty-check fires at the call
15120        // site. (The predicate itself defends against direct
15121        // invocation by returning the same error on `""`.)
15122        let mut s = three_member_spec();
15123        s.entrada.as_mut().unwrap().paths = vec![String::new()];
15124        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPathEmpty);
15125    }
15126
15127    #[test]
15128    fn entrada_path_not_absolute_takes_precedence_over_invalid() {
15129        // Ordering pin: a path without a leading `/` surfaces the
15130        // narrower `EntradaPathNotAbsolute` diagnostic first; the
15131        // value-shape gate is only consulted on paths that already
15132        // satisfy the absolute-prefix invariant.
15133        let mut s = three_member_spec();
15134        // `bad path` would fire the whitespace rule under the
15135        // value-shape gate, but missing-leading-`/` is the more
15136        // self-locating diagnostic.
15137        s.entrada.as_mut().unwrap().paths = vec!["bad path".into()];
15138        let err = s.validate().unwrap_err();
15139        assert!(
15140            matches!(err, AplicacaoError::EntradaPathNotAbsolute { ref path } if path == "bad path"),
15141            "got {err:?}"
15142        );
15143    }
15144
15145    #[test]
15146    fn entrada_path_invalid_fires_before_duplicate_check() {
15147        // Ordering pin: a malformed path on the *first* entry of a
15148        // would-be duplicate pair fires the value-shape gate before
15149        // the duplicate gate, mirroring the
15150        // `placement_cluster_invalid_fires_before_duplicate_check`
15151        // (6cbb900) pattern on the peer axis.
15152        let mut s = three_member_spec();
15153        s.entrada.as_mut().unwrap().paths = vec!["/api?q".into(), "/api?q".into()];
15154        let err = s.validate().unwrap_err();
15155        assert!(
15156            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, .. } if path == "/api?q"),
15157            "got {err:?}"
15158        );
15159    }
15160
15161    #[test]
15162    fn entrada_path_diagnostic_carries_offending_path() {
15163        // Diagnostic-shape pin — the offending path + a non-empty
15164        // reason flow through verbatim so the author can grep their
15165        // caixa.lisp for `:paths` and fix it in one edit. Same shape
15166        // as `entrada_host_diagnostic_carries_offending_host` (c7d05ec).
15167        let mut s = three_member_spec();
15168        s.entrada.as_mut().unwrap().paths = vec!["/api?q=1".into()];
15169        let err = s.validate().unwrap_err();
15170        match err {
15171            AplicacaoError::EntradaPathInvalid { path, reason } => {
15172                assert_eq!(path, "/api?q=1");
15173                assert!(!reason.is_empty(), "reason field must be non-empty");
15174            }
15175            other => panic!("expected EntradaPathInvalid, got {other:?}"),
15176        }
15177    }
15178
15179    #[test]
15180    fn rejects_entrada_path_with_curly_brace_template_form() {
15181        // Per-axis pin on the shared `is_gateway_api_http_path`
15182        // reserved-byte arm: the canonical "I wrote an OpenAPI
15183        // path-template `{id}` instead of the Gateway API `:id` form"
15184        // footgun the K8s apiserver would otherwise catch at admission
15185        // time on every `HTTPRoute.spec.rules[].matches[].path.value`
15186        // landing site, far from the caixa.lisp. Surfaces as
15187        // `EntradaPathInvalid` carrying the offending path verbatim
15188        // plus the canonical `%7B`/`%7D` percent-encoding remediation
15189        // — the substrate-side `gateway_api_http_path_rejects_every_
15190        // reserved_printable_ascii_byte` predicate-level sweep pins the
15191        // full eleven-byte set; this per-axis pin confirms the
15192        // diagnostic flows through to the `EntradaPathInvalid` variant.
15193        let mut s = three_member_spec();
15194        s.entrada.as_mut().unwrap().paths = vec!["/api/cart/{id}".into()];
15195        let err = s.validate().unwrap_err();
15196        assert!(
15197            matches!(err, AplicacaoError::EntradaPathInvalid { ref path, ref reason }
15198                if path == "/api/cart/{id}"
15199                    && reason.contains("reserved character")
15200                    && reason.contains("'{'")
15201                    && reason.contains("%7B")),
15202            "got {err:?}"
15203        );
15204    }
15205
15206    #[test]
15207    fn rejects_http_contrato_endpoint_with_curly_brace_template_form() {
15208        // Per-axis peer of `rejects_entrada_path_with_curly_brace_
15209        // template_form` on the sibling `:contratos :endpoint` axis.
15210        // Same shared `is_gateway_api_http_path` reserved-byte arm
15211        // fires through `ContratoEndpointInvalid`, with the offending
15212        // endpoint + `:de` + `:para` + reason flowing through verbatim.
15213        // Pins that the lifted predicate's tightening lands on both
15214        // caller axes simultaneously — one source of truth for the
15215        // Gateway API HTTPPathMatch.value accepted set.
15216        let err = contrato_endpoint_err("/api/cart/{id}");
15217        assert!(
15218            matches!(err, AplicacaoError::ContratoEndpointInvalid { ref endpoint, ref reason, .. }
15219                if endpoint == "/api/cart/{id}"
15220                    && reason.contains("reserved character")
15221                    && reason.contains("'{'")
15222                    && reason.contains("%7B")),
15223            "got {err:?}"
15224        );
15225    }
15226
15227    // ── :entrada :host value-shape gate ──────────────────────────────
15228    //
15229    // Mirrors the `:entrada :paths` value-shape suite (eb3456d) on
15230    // the sibling `:host` axis. Every authoring footgun the K8s
15231    // Gateway API v1 apiserver would catch at admission time becomes
15232    // a caixa-build-time `EntradaHostInvalid` with the offending
15233    // `:host` named verbatim. Same diagnostic shape as
15234    // `MembroVersaoInvalid` (9888b13).
15235
15236    #[test]
15237    fn rejects_entrada_host_with_scheme() {
15238        // Fail-before-pass-after pin — pre-gate codebases silently
15239        // accepted `https://…` and the apiserver rejected it at apply
15240        // time with no source citation.
15241        let mut s = three_member_spec();
15242        s.entrada.as_mut().unwrap().host = "https://checkout.quero.cloud".into();
15243        let err = s.validate().unwrap_err();
15244        assert!(
15245            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15246                if host == "https://checkout.quero.cloud"),
15247            "got {err:?}"
15248        );
15249    }
15250
15251    #[test]
15252    fn rejects_entrada_host_with_port() {
15253        // The `:8080` port suffix is the canonical "I forgot the port
15254        // belongs in `:entrada :port`" footgun. The top-level `:` arm
15255        // (introduced after the per-label loop-only impl silently
15256        // surfaced a deep "label \"cloud:8080\" contains invalid
15257        // character ':'" leak) names the canonical fix verbatim — the
15258        // `:entrada :port` slot.
15259        let mut s = three_member_spec();
15260        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
15261        let err = s.validate().unwrap_err();
15262        assert!(
15263            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15264                if host == "checkout.quero.cloud:8080"
15265                && reason.contains(":entrada :port")),
15266            "got {err:?}"
15267        );
15268    }
15269
15270    #[test]
15271    fn rejects_entrada_host_with_trailing_colon() {
15272        // Trailing `:` (e.g. an in-progress `:host "example.com:"`
15273        // edit) — the per-label loop would land it as a deep
15274        // "label \"com:\" must start and end with an alphanumeric"
15275        // / "contains invalid character ':'" leak. The top-level
15276        // `:` arm pre-empts with the canonical `:port` slot
15277        // diagnostic.
15278        let mut s = three_member_spec();
15279        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:".into();
15280        let err = s.validate().unwrap_err();
15281        assert!(
15282            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15283                if host == "checkout.quero.cloud:"
15284                && reason.contains(":entrada :port")),
15285            "got {err:?}"
15286        );
15287    }
15288
15289    #[test]
15290    fn rejects_entrada_host_unbracketed_ipv6_literal() {
15291        // Unbracketed IPv6 literal — Gateway API v1 Hostname forbids IP
15292        // literals across the board (peer with `rejects_entrada_host_
15293        // ipv4_literal` above for the four-label-all-digit IPv4 arm).
15294        // Before this top-level `:` arm landed the per-label loop
15295        // surfaced a single-label byte-class diagnostic that named the
15296        // `:` byte but not the IP-literal prohibition. The top-level
15297        // `:` arm names both the `:port` slot and the IP-literal
15298        // prohibition verbatim, so an author whose `:host "2001:..."`
15299        // value lands here gets a self-locating fix either way.
15300        let mut s = three_member_spec();
15301        s.entrada.as_mut().unwrap().host = "2001:db8::1".into();
15302        let err = s.validate().unwrap_err();
15303        assert!(
15304            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15305                if host == "2001:db8::1"
15306                && reason.contains("IPv6")),
15307            "got {err:?}"
15308        );
15309    }
15310
15311    #[test]
15312    fn rejects_entrada_host_wildcard_with_port() {
15313        // Wildcard host with port suffix — the `*.` strip and the
15314        // per-label loop on `["foo", "quero", "cloud:8080"]` would
15315        // surface the deep byte-class leak. The top-level `:` arm sits
15316        // upstream of the `*.` strip, so it names the canonical `:port`
15317        // fix verbatim regardless of whether the host is wildcard-led.
15318        let mut s = three_member_spec();
15319        s.entrada.as_mut().unwrap().host = "*.quero.cloud:8080".into();
15320        let err = s.validate().unwrap_err();
15321        assert!(
15322            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, ref reason }
15323                if host == "*.quero.cloud:8080"
15324                && reason.contains(":entrada :port")),
15325            "got {err:?}"
15326        );
15327    }
15328
15329    #[test]
15330    fn rejects_entrada_host_with_path() {
15331        let mut s = three_member_spec();
15332        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud/api".into();
15333        let err = s.validate().unwrap_err();
15334        assert!(
15335            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15336                if host == "checkout.quero.cloud/api"),
15337            "got {err:?}"
15338        );
15339    }
15340
15341    #[test]
15342    fn rejects_entrada_host_with_uppercase() {
15343        // Gateway API regex is `[a-z0-9]…` strictly — uppercase is
15344        // rejected, not silently lower-cased.
15345        let mut s = three_member_spec();
15346        s.entrada.as_mut().unwrap().host = "Checkout.quero.cloud".into();
15347        let err = s.validate().unwrap_err();
15348        assert!(
15349            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15350                if reason.contains("uppercase")),
15351            "got {err:?}"
15352        );
15353    }
15354
15355    #[test]
15356    fn rejects_entrada_host_with_underscore() {
15357        // RFC 1123 allows `[a-z0-9-]` only; underscore is the
15358        // canonical "I'm thinking of HTTP cookies / SRV records" leak.
15359        let mut s = three_member_spec();
15360        s.entrada.as_mut().unwrap().host = "checkout_app.quero.cloud".into();
15361        let err = s.validate().unwrap_err();
15362        assert!(
15363            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15364                if reason.contains('_')),
15365            "got {err:?}"
15366        );
15367    }
15368
15369    #[test]
15370    fn rejects_entrada_host_ipv4_literal() {
15371        // Gateway API v1 explicitly forbids IP literals as Hostnames.
15372        let mut s = three_member_spec();
15373        s.entrada.as_mut().unwrap().host = "10.0.0.1".into();
15374        let err = s.validate().unwrap_err();
15375        assert!(
15376            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15377                if reason.contains("IPv4")),
15378            "got {err:?}"
15379        );
15380    }
15381
15382    #[test]
15383    fn rejects_entrada_host_with_trailing_dot() {
15384        // The Gateway API regex anchors at end-of-string with no
15385        // trailing `.` allowance — the FQDN root-dot form is rejected.
15386        let mut s = three_member_spec();
15387        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud.".into();
15388        let err = s.validate().unwrap_err();
15389        assert!(
15390            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15391                if host == "checkout.quero.cloud."),
15392            "got {err:?}"
15393        );
15394    }
15395
15396    #[test]
15397    fn rejects_entrada_host_with_leading_dot() {
15398        let mut s = three_member_spec();
15399        s.entrada.as_mut().unwrap().host = ".checkout.quero.cloud".into();
15400        let err = s.validate().unwrap_err();
15401        assert!(
15402            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15403                if reason.contains("empty label")),
15404            "got {err:?}"
15405        );
15406    }
15407
15408    #[test]
15409    fn rejects_entrada_host_with_consecutive_dots() {
15410        let mut s = three_member_spec();
15411        s.entrada.as_mut().unwrap().host = "checkout..quero.cloud".into();
15412        let err = s.validate().unwrap_err();
15413        assert!(
15414            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15415                if reason.contains("empty label")),
15416            "got {err:?}"
15417        );
15418    }
15419
15420    #[test]
15421    fn rejects_entrada_host_with_leading_hyphen_label() {
15422        let mut s = three_member_spec();
15423        s.entrada.as_mut().unwrap().host = "-checkout.quero.cloud".into();
15424        let err = s.validate().unwrap_err();
15425        assert!(
15426            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15427                if reason.contains("alphanumeric")),
15428            "got {err:?}"
15429        );
15430    }
15431
15432    #[test]
15433    fn rejects_entrada_host_with_trailing_hyphen_label() {
15434        let mut s = three_member_spec();
15435        s.entrada.as_mut().unwrap().host = "checkout-.quero.cloud".into();
15436        let err = s.validate().unwrap_err();
15437        assert!(
15438            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15439                if reason.contains("alphanumeric")),
15440            "got {err:?}"
15441        );
15442    }
15443
15444    #[test]
15445    fn rejects_entrada_host_with_inner_wildcard() {
15446        // Gateway API allows `*` only as the first label (`*.foo`);
15447        // any inner or trailing `*` is rejected.
15448        let mut s = three_member_spec();
15449        s.entrada.as_mut().unwrap().host = "checkout.*.quero.cloud".into();
15450        let err = s.validate().unwrap_err();
15451        assert!(
15452            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15453                if reason.contains("wildcard")),
15454            "got {err:?}"
15455        );
15456    }
15457
15458    #[test]
15459    fn rejects_entrada_host_bare_wildcard() {
15460        // `*.` with no domain is meaningless; Gateway API rejects it.
15461        let mut s = three_member_spec();
15462        s.entrada.as_mut().unwrap().host = "*.".into();
15463        let err = s.validate().unwrap_err();
15464        assert!(
15465            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15466                if reason.contains("wildcard")),
15467            "got {err:?}"
15468        );
15469    }
15470
15471    #[test]
15472    fn rejects_entrada_host_with_whitespace() {
15473        let mut s = three_member_spec();
15474        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15475        let err = s.validate().unwrap_err();
15476        assert!(
15477            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15478                if reason.contains("whitespace")),
15479            "got {err:?}"
15480        );
15481    }
15482
15483    #[test]
15484    fn rejects_entrada_host_space_names_offending_byte() {
15485        // Embedded space in the `:entrada :host` axis surfaces the
15486        // byte-naming diagnostic through the lifted
15487        // `find_ascii_whitespace_byte` predicate. Peer with the
15488        // sibling `parse_rejects_leading_whitespace` pins on
15489        // `supervisor::duration_codec` (a7ae622) — same "the
15490        // diagnostic carries the offending byte's `0x{b:02x}` shape"
15491        // discipline extended from the shared duration codec to the
15492        // Gateway API v1 Hostname axis.
15493        let mut s = three_member_spec();
15494        s.entrada.as_mut().unwrap().host = "checkout .quero.cloud".into();
15495        let err = s.validate().unwrap_err();
15496        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15497            panic!("expected EntradaHostInvalid, got {err:?}");
15498        };
15499        assert!(
15500            reason.contains("ASCII whitespace byte"),
15501            "expected byte-naming diagnostic, got {reason:?}"
15502        );
15503        assert!(
15504            reason.contains("0x20"),
15505            "expected offending space byte 0x20, got {reason:?}"
15506        );
15507    }
15508
15509    #[test]
15510    fn rejects_entrada_host_tab_names_offending_byte() {
15511        // Embedded tab byte in the `:entrada :host` axis — the
15512        // canonical paste-from-YAML-block-scalar / paste-from-
15513        // indented-doc footgun. Pins that the lifted predicate covers
15514        // the full ASCII-whitespace set (`u8::is_ascii_whitespace` —
15515        // space `0x20`, tab `0x09`, LF `0x0a`, FF `0x0c`, CR `0x0d`),
15516        // not just the leading-space case the pre-lift `.bytes().any`
15517        // arm's opaque "must not contain whitespace" reason already
15518        // covered. Peer with `parse_rejects_tab_byte` on
15519        // `supervisor::duration_codec` (a7ae622).
15520        let mut s = three_member_spec();
15521        s.entrada.as_mut().unwrap().host = "checkout.\tquero.cloud".into();
15522        let err = s.validate().unwrap_err();
15523        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15524            panic!("expected EntradaHostInvalid, got {err:?}");
15525        };
15526        assert!(
15527            reason.contains("ASCII whitespace byte"),
15528            "expected byte-naming diagnostic, got {reason:?}"
15529        );
15530        assert!(
15531            reason.contains("0x09"),
15532            "expected offending tab byte 0x09, got {reason:?}"
15533        );
15534    }
15535
15536    #[test]
15537    fn rejects_entrada_host_lf_names_offending_byte() {
15538        // Embedded LF byte in the `:entrada :host` axis — the
15539        // canonical paste-from-shell-heredoc / paste-from-multiline-
15540        // doc footgun the caixa-mesh YAML emitter would silently
15541        // reinterpret at the Gateway API v1 HTTPRoute admission
15542        // layer (an embedded LF byte in a YAML plain scalar either
15543        // truncates the value at the emitter or crashes the parser
15544        // on the k8s-apiserver side). Pins the third representative
15545        // of the full ASCII-whitespace set through the shared
15546        // predicate.
15547        let mut s = three_member_spec();
15548        s.entrada.as_mut().unwrap().host = "checkout\n.quero.cloud".into();
15549        let err = s.validate().unwrap_err();
15550        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15551            panic!("expected EntradaHostInvalid, got {err:?}");
15552        };
15553        assert!(
15554            reason.contains("ASCII whitespace byte"),
15555            "expected byte-naming diagnostic, got {reason:?}"
15556        );
15557        assert!(
15558            reason.contains("0x0a"),
15559            "expected offending LF byte 0x0a, got {reason:?}"
15560        );
15561    }
15562
15563    #[test]
15564    fn rejects_entrada_host_nbsp_names_offending_codepoint() {
15565        // Leading NBSP (`U+00A0`, `\u{00A0}`) in the `:entrada :host`
15566        // axis — the canonical paste-from-typography /
15567        // paste-from-word-processor footgun. Before the non-ASCII
15568        // Unicode `White_Space` scan lifted through the shared
15569        // `find_non_ascii_whitespace_char` predicate, the UTF-8 bytes
15570        // of NBSP (`0xC2 0xA0`) survived the ASCII byte-scan (neither
15571        // `0xC2` nor `0xA0` is `u8::is_ascii_whitespace`) and landed
15572        // on the per-label `bytes[0].is_ascii_alphanumeric()` arm
15573        // with the far-from-source `label "…" must start and end
15574        // with an alphanumeric` diagnostic — burying the
15575        // paste-from-typography origin under a label-shape leak.
15576        // Peer with the sibling non-ASCII-whitespace pins at
15577        // `limits::parse_byte_size` (`parse_byte_size_rejects_leading_nbsp`
15578        // — 1b75b38), `limits::parse_duration`,
15579        // `limits::parse_millicores`, and the shared duration codec
15580        // — same "the diagnostic carries the offending Unicode
15581        // codepoint's `U+XXXX` shape" discipline extended from every
15582        // typed-magnitude codec to the Gateway API v1 Hostname axis.
15583        let mut s = three_member_spec();
15584        s.entrada.as_mut().unwrap().host = "\u{00A0}checkout.quero.cloud".into();
15585        let err = s.validate().unwrap_err();
15586        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15587            panic!("expected EntradaHostInvalid, got {err:?}");
15588        };
15589        assert!(
15590            reason.contains("non-ASCII Unicode whitespace character"),
15591            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15592        );
15593        assert!(
15594            reason.contains("U+00A0"),
15595            "expected offending NBSP codepoint U+00A0, got {reason:?}"
15596        );
15597    }
15598
15599    #[test]
15600    fn rejects_entrada_host_line_separator_names_offending_codepoint() {
15601        // Trailing LINE SEPARATOR (`U+2028`, `\u{2028}`) in the
15602        // `:entrada :host` axis — the canonical paste-from-web-doc /
15603        // paste-from-published-HTML footgun. `char::is_whitespace`
15604        // returns true for `U+2028` per the Unicode `White_Space`
15605        // property, so `str::trim` at any downstream site would
15606        // silently strip it — same drift class as NBSP but on a
15607        // different codepoint region. Pins the second representative
15608        // (non-Latin-1 `char::is_whitespace` member) through the
15609        // shared predicate. Peer with
15610        // `parse_byte_size_rejects_internal_line_separator` on
15611        // `limits::parse_byte_size` (1b75b38).
15612        let mut s = three_member_spec();
15613        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud\u{2028}".into();
15614        let err = s.validate().unwrap_err();
15615        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15616            panic!("expected EntradaHostInvalid, got {err:?}");
15617        };
15618        assert!(
15619            reason.contains("non-ASCII Unicode whitespace character"),
15620            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15621        );
15622        assert!(
15623            reason.contains("U+2028"),
15624            "expected offending LINE SEPARATOR codepoint U+2028, got {reason:?}"
15625        );
15626    }
15627
15628    #[test]
15629    fn rejects_entrada_host_ideographic_space_names_offending_codepoint() {
15630        // Embedded IDEOGRAPHIC SPACE (`U+3000`, `\u{3000}`) between
15631        // labels in the `:entrada :host` axis — the canonical
15632        // paste-from-CJK-typography footgun (CJK IMEs default to
15633        // full-width whitespace when the space bar is pressed in
15634        // Japanese / Chinese input modes). Pins the third
15635        // representative of the non-ASCII Unicode `White_Space` set
15636        // through the shared predicate: the CJK block, distinct from
15637        // the Latin-1 NBSP `U+00A0` and the punctuation-region LINE
15638        // SEPARATOR `U+2028` — covering the same axis breadth the
15639        // sibling `parse_byte_size_rejects_trailing_ideographic_space`
15640        // (1b75b38) pins on `limits::parse_byte_size`.
15641        let mut s = three_member_spec();
15642        s.entrada.as_mut().unwrap().host = "checkout\u{3000}.quero.cloud".into();
15643        let err = s.validate().unwrap_err();
15644        let AplicacaoError::EntradaHostInvalid { reason, .. } = err else {
15645            panic!("expected EntradaHostInvalid, got {err:?}");
15646        };
15647        assert!(
15648            reason.contains("non-ASCII Unicode whitespace character"),
15649            "expected non-ASCII codepoint-naming diagnostic, got {reason:?}"
15650        );
15651        assert!(
15652            reason.contains("U+3000"),
15653            "expected offending IDEOGRAPHIC SPACE codepoint U+3000, got {reason:?}"
15654        );
15655    }
15656
15657    #[test]
15658    fn rejects_entrada_host_too_long() {
15659        // Total length cap = 253; build a 254-byte host out of two
15660        // 63-byte labels + one 62-byte label + dots.
15661        let mut s = three_member_spec();
15662        let big = format!(
15663            "{}.{}.{}.{}",
15664            "a".repeat(63),
15665            "b".repeat(63),
15666            "c".repeat(63),
15667            "d".repeat(254 - 63 * 3 - 3)
15668        );
15669        assert_eq!(big.len(), 254);
15670        s.entrada.as_mut().unwrap().host = big;
15671        let err = s.validate().unwrap_err();
15672        assert!(
15673            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15674                if reason.contains("max length of 253")),
15675            "got {err:?}"
15676        );
15677    }
15678
15679    #[test]
15680    fn rejects_entrada_host_label_too_long() {
15681        let mut s = three_member_spec();
15682        // 64-byte label — one over the per-label cap.
15683        s.entrada.as_mut().unwrap().host = format!("{}.quero.cloud", "x".repeat(64));
15684        let err = s.validate().unwrap_err();
15685        assert!(
15686            matches!(err, AplicacaoError::EntradaHostInvalid { ref reason, .. }
15687                if reason.contains("label max length of 63")),
15688            "got {err:?}"
15689        );
15690    }
15691
15692    #[test]
15693    fn entrada_host_diagnostic_carries_offending_host() {
15694        // Diagnostic-shape pin — the offending host + a non-empty
15695        // reason flow through verbatim so the author can grep their
15696        // caixa.lisp for `:host "<host>"` and fix it in one edit.
15697        let mut s = three_member_spec();
15698        s.entrada.as_mut().unwrap().host = "checkout.quero.cloud:8080".into();
15699        let err = s.validate().unwrap_err();
15700        match err {
15701            AplicacaoError::EntradaHostInvalid { host, reason } => {
15702                assert_eq!(host, "checkout.quero.cloud:8080");
15703                assert!(!reason.is_empty(), "reason field must be non-empty");
15704            }
15705            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15706        }
15707    }
15708
15709    #[test]
15710    fn entrada_host_empty_takes_precedence_over_invalid() {
15711        // Ordering pin: `EmptyEntradaHost` is the more self-locating
15712        // diagnostic on `""` and must lead — `validate_entrada_host`
15713        // is only reached after the empty-check fires at the call
15714        // site. (The predicate itself defends against direct
15715        // invocation by returning the same error on `""`.)
15716        let mut s = three_member_spec();
15717        s.entrada.as_mut().unwrap().host = String::new();
15718        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EmptyEntradaHost);
15719    }
15720
15721    #[test]
15722    fn entrada_host_member_missing_takes_precedence_over_host_invalid() {
15723        // Ordering pin: a missing :para member is the more
15724        // self-locating diagnostic and fires before the host gate.
15725        let mut s = three_member_spec();
15726        let e = s.entrada.as_mut().unwrap();
15727        e.para = "ghost".into();
15728        e.host = "BAD HOST".into();
15729        let err = s.validate().unwrap_err();
15730        assert!(
15731            matches!(err, AplicacaoError::EntradaMemberMissing { ref para } if para == "ghost"),
15732            "got {err:?}"
15733        );
15734    }
15735
15736    #[test]
15737    fn entrada_host_invalid_fires_before_port_zero() {
15738        // Ordering pin: the host gate fires before the port gate so
15739        // a malformed host is named even when the port is also wrong.
15740        let mut s = three_member_spec();
15741        let e = s.entrada.as_mut().unwrap();
15742        e.host = "Checkout.quero.cloud".into();
15743        e.port = 0;
15744        let err = s.validate().unwrap_err();
15745        assert!(
15746            matches!(err, AplicacaoError::EntradaHostInvalid { ref host, .. }
15747                if host == "Checkout.quero.cloud"),
15748            "got {err:?}"
15749        );
15750    }
15751
15752    #[test]
15753    fn entrada_accepts_canonical_hosts() {
15754        // Positive-control sweep — every form the Gateway API
15755        // apiserver accepts must round-trip through validate. Covers
15756        // a plain DNS subdomain, a leading wildcard, a single-label
15757        // host (cluster-internal), a max-length-edge label, a
15758        // hyphen-bearing label, and a Punycode IDN label.
15759        for host in [
15760            "checkout.quero.cloud",
15761            "*.quero.cloud",
15762            "checkout",
15763            // 63-byte label — exactly the per-label cap.
15764            "abcdefghijklmnopqrstuvwxyz0123456789abcdefghijklmnopqrstuvwxyz0.quero.cloud",
15765            "foo-bar.quero.cloud",
15766            // Punycode IDN — valid because the author pre-encoded.
15767            "xn--bcher-kva.example.com",
15768        ] {
15769            let mut s = three_member_spec();
15770            s.entrada.as_mut().unwrap().host = host.into();
15771            s.validate()
15772                .unwrap_or_else(|e| panic!("expected {host:?} to validate, got {e:?}"));
15773        }
15774    }
15775
15776    #[test]
15777    fn entrada_host_max_length_validates() {
15778        // 253-byte host is the cap exactly — must validate. Build a
15779        // 253-byte host out of three 63-byte labels + one 61-byte
15780        // label + 3 dots = 252 bytes, then pad one byte to 253.
15781        let mut s = three_member_spec();
15782        let host = format!(
15783            "{}.{}.{}.{}",
15784            "a".repeat(63),
15785            "b".repeat(63),
15786            "c".repeat(63),
15787            "d".repeat(253 - 63 * 3 - 3)
15788        );
15789        assert_eq!(host.len(), 253);
15790        s.entrada.as_mut().unwrap().host = host;
15791        s.validate().unwrap();
15792    }
15793
15794    #[test]
15795    fn entrada_host_total_length_cap_threads_lifted_render_const() {
15796        // Cross-crate-side pin: the aplicacao-side `:entrada :host`
15797        // total-length gate now reads the K8s Gateway API v1 Hostname
15798        // `maxLength: 253` cap from the lifted
15799        // [`crate::render::GATEWAY_API_HOSTNAME_MAX_LEN`] canonical source
15800        // of truth — the same constant every future Gateway-API-Hostname
15801        // landing site (the M4 `mesh.pleme.io/v1alpha1/Aplicacao` CR
15802        // materializer's per-host validator, the future per-`Certificate`
15803        // SAN emitter for cert-manager, the multi-`:entrada`
15804        // host-collision gate when M4 lands `:entrada` as a `Vec`) reads
15805        // from. Before the lift, the aplicacao-side reader consumed a
15806        // private const alias `ENTRADA_HOST_MAX_LEN` sitting at the same
15807        // 253-byte value as the peer render-side canonical bounds
15808        // ([`GATEWAY_API_HTTP_PATH_MAX_LEN`], [`DNS_1123_LABEL_MAX_LEN`],
15809        // [`NATS_SUBJECT_MAX_LEN`], [`WASI_KV_SLOT_MAX_LEN`],
15810        // [`WIT_IDENT_MAX_LEN`]) but structurally split from them at the
15811        // module boundary — a future 253-byte drift on either side would
15812        // silently split into two axes' worth of admission-schema mismatch
15813        // without a build-time signal. Pin the cap through a fresh 254-
15814        // byte host that hits the total-length arm, then read the reason
15815        // for the exact byte count the shared constant carries: any future
15816        // regression on the lift (a private alias reintroduced, a hard-
15817        // coded literal at the arm, a mismatch between the aplicacao-side
15818        // and render-side canonicals) surfaces as this pin's diagnostic
15819        // failing to match, not as a per-cluster admission rejection far
15820        // from the caixa.lisp source line.
15821        let mut s = three_member_spec();
15822        let over_cap = format!(
15823            "{}.{}.{}.{}",
15824            "a".repeat(63),
15825            "b".repeat(63),
15826            "c".repeat(63),
15827            "d".repeat(crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1 - 63 * 3 - 3)
15828        );
15829        assert_eq!(
15830            over_cap.len(),
15831            crate::render::GATEWAY_API_HOSTNAME_MAX_LEN + 1
15832        );
15833        s.entrada.as_mut().unwrap().host = over_cap;
15834        let err = s.validate().unwrap_err();
15835        match err {
15836            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15837                let needle = format!(
15838                    "max length of {} bytes",
15839                    crate::render::GATEWAY_API_HOSTNAME_MAX_LEN,
15840                );
15841                assert!(
15842                    reason.contains(&needle),
15843                    "diagnostic must name the lifted \
15844                     GATEWAY_API_HOSTNAME_MAX_LEN cap verbatim, got: {reason:?}",
15845                );
15846            }
15847            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15848        }
15849    }
15850
15851    #[test]
15852    fn entrada_host_per_label_cap_threads_lifted_dns_1123_const() {
15853        // Peer of [`entrada_host_total_length_cap_threads_lifted_render_const`]
15854        // on the per-label-cap axis. Before the lift, the aplicacao-side
15855        // per-label arm consumed a private const alias
15856        // `ENTRADA_HOST_LABEL_MAX_LEN` sitting at the same 63-byte value
15857        // as [`crate::render::DNS_1123_LABEL_MAX_LEN`] but structurally
15858        // split from it at the module boundary — every `.`-separated
15859        // label in a Gateway API v1 Hostname is a DNS-1123 label under
15860        // the apiserver's OpenAPI regex `[a-z0-9]([-a-z0-9]*[a-z0-9])?`,
15861        // so the private alias's 63 and the canonical const's 63 were
15862        // pinning the same underlying rule twice. Pin the cap through a
15863        // 64-byte label that hits the per-label arm, then read the reason
15864        // for the exact byte count the shared constant carries: any
15865        // future drift on either side (a private alias reintroduced, a
15866        // hard-coded literal at the arm, a mismatch between the two
15867        // 63-byte pins) surfaces at this pin's diagnostic rather than at
15868        // a per-cluster admission rejection whose "field is invalid"
15869        // opacity misframes the root cause.
15870        let mut s = three_member_spec();
15871        let over_cap_label = format!(
15872            "{}.quero.cloud",
15873            "x".repeat(crate::render::DNS_1123_LABEL_MAX_LEN + 1),
15874        );
15875        s.entrada.as_mut().unwrap().host = over_cap_label;
15876        let err = s.validate().unwrap_err();
15877        match err {
15878            AplicacaoError::EntradaHostInvalid { reason, .. } => {
15879                let needle = format!(
15880                    "label max length of {} bytes",
15881                    crate::render::DNS_1123_LABEL_MAX_LEN,
15882                );
15883                assert!(
15884                    reason.contains(&needle),
15885                    "diagnostic must name the lifted DNS_1123_LABEL_MAX_LEN \
15886                     cap verbatim on the per-label arm, got: {reason:?}",
15887                );
15888            }
15889            other => panic!("expected EntradaHostInvalid, got {other:?}"),
15890        }
15891    }
15892
15893    #[test]
15894    fn entrada_with_empty_paths_validates() {
15895        // Empty `:paths` is the documented "match every path" form;
15896        // caixa-mesh's gateway_routes synthesizes a `/` catch-all.
15897        let mut s = three_member_spec();
15898        s.entrada.as_mut().unwrap().paths = vec![];
15899        s.validate().unwrap();
15900    }
15901
15902    #[test]
15903    fn entrada_root_path_validates() {
15904        // The author-supplied bare-root `:entrada :paths` entry is the
15905        // same byte-shape the peer emit-side catch-all constant
15906        // [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] renders when
15907        // the author's `:paths` list is empty — sweeping the test-side
15908        // probe literal onto the lifted const closes the two-axis pin
15909        // (author-side admit + emit-side canonical fallback) around
15910        // one `&'static str`, so a future rebrand of the catch-all
15911        // reaches both consumers by construction. Peer to
15912        // [`crate::tests::gateway_api_default_http_route_path_pins_canonical_root_literal`]
15913        // on the canonical-literal pin surface.
15914        let mut s = three_member_spec();
15915        s.entrada.as_mut().unwrap().paths = vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH.into()];
15916        s.validate().unwrap();
15917    }
15918
15919    #[test]
15920    fn placement_strategy_variants_round_trip() {
15921        for s in [
15922            PlacementStrategy::SingleNode,
15923            PlacementStrategy::Replicated,
15924            PlacementStrategy::Sharded,
15925        ] {
15926            let p = Placement {
15927                estrategia: s,
15928                clusters: vec!["rio".into()],
15929                affinity: None,
15930                // Route the paired `:shard-key` fixture-builder through the
15931                // typed cross-slot invariant predicate
15932                // [`PlacementStrategy::requires_shard_key`] rather than the
15933                // [`gen_platform::IsVariant`]-derived [`Self::is_sharded`]
15934                // arm-identity predicate — the two answer the same
15935                // question under today's closed accept-set but a future
15936                // arm addition that consumed `:shard-key` under a
15937                // non-`Sharded` name would silently mis-attach the
15938                // fixture's `:shard-key` if the builder read through the
15939                // arm-identity predicate. The cross-slot-invariant
15940                // predicate migrates through one caixa-core edit on any
15941                // future arm addition; the fixture keeps producing a
15942                // `validate()`-passing round-trip by construction.
15943                shard_key: if s.requires_shard_key() {
15944                    Some("$key".into())
15945                } else {
15946                    None
15947                },
15948            };
15949            let json = serde_json::to_string(&p).unwrap();
15950            let back: Placement = serde_json::from_str(&json).unwrap();
15951            assert_eq!(back, p);
15952        }
15953    }
15954
15955    #[test]
15956    fn placement_strategy_variants_serialize_to_lifted_scalar_values() {
15957        // The fail-before-pass-after pin: pre-lift there was no
15958        // single-source binding between the [`PlacementStrategy`]
15959        // variant name the `Serialize` derive emits and the byte-
15960        // string every downstream cluster-side dispatcher (the
15961        // `lareira-fleet-programs` aggregator's per-entry strategy
15962        // branch, the future `app-operator` reconciler, the M3
15963        // Adaptive compression pass's per-strategy weighting) probes
15964        // verbatim under [`crate::M3_PLACEMENT_KEY_ESTRATEGIA`]. A
15965        // future `#[serde(rename_all = "kebab-case")]` attribute on
15966        // the enum — or a variant rename in the source — would
15967        // silently rebrand the emitted scalar under one spelling
15968        // while every downstream dispatcher still probed the other,
15969        // with the failure surfacing at the aggregator's dispatch
15970        // step or the operator's reconcile posture (workloads coming
15971        // up under the `default()` `Replicated` arm rather than the
15972        // typed slot's declared strategy) far from the source
15973        // rebrand commit and with no field naming the drift. Pinning
15974        // the two paths (the `Serialize` derive's serialized string
15975        // AND the [`PlacementStrategy::as_str`] helper) to the same
15976        // three lifted [`crate::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`]
15977        // / [`crate::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
15978        // [`crate::M3_PLACEMENT_ESTRATEGIA_SHARDED`] byte-strings
15979        // makes any future drift on either endpoint fail here at
15980        // caixa-core build time.
15981        for (variant, expected) in [
15982            (
15983                PlacementStrategy::SingleNode,
15984                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
15985            ),
15986            (
15987                PlacementStrategy::Replicated,
15988                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
15989            ),
15990            (
15991                PlacementStrategy::Sharded,
15992                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
15993            ),
15994        ] {
15995            let json = serde_json::to_string(&variant).unwrap();
15996            assert_eq!(
15997                json,
15998                format!("\"{expected}\""),
15999                "PlacementStrategy::{variant:?} must serialize to {expected:?}"
16000            );
16001            assert_eq!(
16002                variant.as_str(),
16003                expected,
16004                "PlacementStrategy::{variant:?}.as_str() must return the lifted \
16005                 M3_PLACEMENT_ESTRATEGIA_* constant"
16006            );
16007        }
16008    }
16009
16010    #[test]
16011    fn m3_placement_estrategia_consts_are_pairwise_distinct() {
16012        // Cross-arm drift-detection pin on the M3
16013        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE`] /
16014        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] /
16015        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED`] closed-set
16016        // scalar-value pentad: a future collapse of two canonical
16017        // variant byte-strings onto the same value (an accidental
16018        // copy-paste flip of
16019        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to also
16020        // read `"SingleNode"`, a per-arm rebrand that lands one const
16021        // without touching its paired peer) would silently reroute
16022        // every downstream operator's per-strategy dispatch onto the
16023        // sibling arm's reconcile branch and pass every
16024        // propagation-probe test that expected only the stale arm's
16025        // value — a `Replicated`-declared Aplicacao would come up
16026        // under the `SingleNode` primary-and-standby reconcile
16027        // posture, so every-cluster active-active workload would
16028        // silently collapse onto one-cluster-runs-at-a-time takeover
16029        // semantics against its declared strategy, with no field
16030        // naming the strategy-value drift root cause. Peer of the
16031        // sibling
16032        // [`crate::supervisor::tests::supervisor_estrategia_consts_are_pairwise_distinct`]
16033        // (09ffb2d) /
16034        // [`crate::supervisor::tests::supervisor_child_restart_consts_are_pairwise_distinct`]
16035        // (ccdf955) /
16036        // [`crate::kind::tests::caixa_kind_label_consts_are_pairwise_distinct`]
16037        // (d739850) distinctness pins on the sibling OTP-shape /
16038        // caixa-kind closed-set typed-enum discriminator axes — the
16039        // fourth (and structurally the M3 mesh-primitive-defining)
16040        // closed-set typed-enum axis to converge on the same
16041        // "pairwise-distinct-by-construction" discipline.
16042        //
16043        // Fail-before-pass-after locally verified by mutating
16044        // [`crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED`] to
16045        // also read `"SingleNode"` — this pin fires as expected;
16046        // restoring passes.
16047        let all = [
16048            crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16049            crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16050            crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16051        ];
16052        for (i, a) in all.iter().enumerate() {
16053            for (j, b) in all.iter().enumerate() {
16054                if i != j {
16055                    assert_ne!(
16056                        a, b,
16057                        "M3_PLACEMENT_ESTRATEGIA_* consts must be pairwise \
16058                         distinct — got duplicate {a:?} at indices {i} and {j}",
16059                    );
16060                }
16061            }
16062        }
16063    }
16064
16065    #[test]
16066    fn placement_strategy_display_routes_through_as_str_helper() {
16067        // The fail-before-pass-after pin: pre-lift the sibling
16068        // OTP-shape typed enums [`crate::supervisor::RestartStrategy`]
16069        // / [`crate::supervisor::RestartPolicy`] both carried a stable
16070        // [`std::fmt::Display`] surface via their
16071        // `#[discriminant(also_display)]` gen-platform derive, but
16072        // [`PlacementStrategy`] did not — every consumer reaching for
16073        // a strategy byte-string past the wire format had to pick
16074        // between three paths ([`PlacementStrategy::as_str`], the
16075        // `Serialize` derive's serialized string, or `format!("{v:?}")`
16076        // on the `Debug` derive), any two of which a future variant
16077        // rename or `#[serde(rename_all = "kebab-case")]` attribute
16078        // would silently desynchronize. Wiring [`std::fmt::Display`]
16079        // through [`PlacementStrategy::as_str`] closes the third path:
16080        // every `format!("{v}")` call reaches the same lifted
16081        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
16082        // and the [`PlacementStrategy::as_str`] helper already route
16083        // through, so a future variant rename lands at exactly one
16084        // place. Pin the routing here so a future
16085        // `impl std::fmt::Display for PlacementStrategy` reimplementation
16086        // that hand-rolls the arms instead of delegating to
16087        // [`PlacementStrategy::as_str`] fails at caixa-core build time.
16088        for variant in [
16089            PlacementStrategy::SingleNode,
16090            PlacementStrategy::Replicated,
16091            PlacementStrategy::Sharded,
16092        ] {
16093            assert_eq!(
16094                variant.to_string(),
16095                variant.as_str(),
16096                "PlacementStrategy::{variant:?} Display must route through \
16097                 PlacementStrategy::as_str (single source of truth: the lifted \
16098                 M3_PLACEMENT_ESTRATEGIA_* const the wire format also emits)"
16099            );
16100        }
16101    }
16102
16103    #[test]
16104    fn placement_strategy_display_matches_serialized_wire_byte_string() {
16105        // The fail-before-pass-after pin on the second half of the
16106        // three-path convergence: `Display` (user-facing text) agrees
16107        // byte-for-byte with the `Serialize` derive's wire format
16108        // (canonical camelCase-schema `M3_PLACEMENT_KEY_ESTRATEGIA`
16109        // scalar) on every variant. Pre-lift the two paths were
16110        // structurally independent — a future
16111        // `#[serde(rename_all = "kebab-case")]` attribute on the enum
16112        // would silently rebrand the emitted wire scalar
16113        // (`single-node`, `replicated`, `sharded`) while every consumer
16114        // that pretty-prints the strategy (the M3 diagnostic templates,
16115        // the future `feira app graph` per-Aplicacao strategy line,
16116        // the future M4 CR materializer's admission-webhook rejection
16117        // body) would still emit the TitleCase form the `as_str` /
16118        // `Display` route returns, with the mismatch surfacing at
16119        // consumer parse time / operator dispatch time far from the
16120        // source rebrand commit. Pin the two paths byte-for-byte here
16121        // so any future serde-attribute or variant-rename drift is a
16122        // caixa-core-build-time test failure at this call, not a
16123        // silent per-consumer dispatch miss.
16124        for variant in [
16125            PlacementStrategy::SingleNode,
16126            PlacementStrategy::Replicated,
16127            PlacementStrategy::Sharded,
16128        ] {
16129            let wire = serde_json::to_string(&variant).unwrap();
16130            // Strip the outer `"…"` the JSON string form carries — the
16131            // wire scalar the K8s / YAML apiserver consumes is the
16132            // enclosed byte-string, not the quote wrapper.
16133            let unquoted = wire
16134                .strip_prefix('"')
16135                .and_then(|s| s.strip_suffix('"'))
16136                .expect("serialized PlacementStrategy is a JSON string");
16137            assert_eq!(
16138                variant.to_string(),
16139                unquoted,
16140                "PlacementStrategy::{variant:?} Display byte-string must match the \
16141                 Serialize derive's wire byte-string (three-path convergence: \
16142                 Display + as_str + Serialize all resolve to the same \
16143                 M3_PLACEMENT_ESTRATEGIA_* const)"
16144            );
16145        }
16146    }
16147
16148    #[test]
16149    fn placement_strategy_is_variant_predicates_partition_the_arm_set() {
16150        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
16151        // derive on [`PlacementStrategy`]: for each of the three variants
16152        // exactly one of the generated `is_single_node` / `is_replicated`
16153        // / `is_sharded` predicates returns `true` and the other two
16154        // return `false`. Prior to this derive the three per-arm
16155        // `matches!(s, PlacementStrategy::Sharded)` sites in this crate
16156        // (the `placement_strategy_variants_round_trip` fixture, the
16157        // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
16158        // fixture, and the
16159        // `validate_placement_reads_through_lifted_estrategia_accessor`
16160        // fixture) each open-coded a per-arm PartialEq compare against
16161        // the enum variant — three sites that expressed no compile-time
16162        // link back to the closed-set typed dispatch a future fourth
16163        // `:placement :estrategia` (e.g. an `Anycast` mesh-anycast arm
16164        // for the future MESH-COMPOSITION §II.5 hint the roadmap names)
16165        // would have to thread through in lockstep or one fixture would
16166        // silently disagree with the others on which arms consume the
16167        // `:shard-key` axis. Peer of the sibling
16168        // [`crate::CaixaKind`] / [`crate::supervisor::RestartStrategy`]
16169        // / [`crate::supervisor::RestartPolicy`] /
16170        // [`crate::upgrade::UpgradeInstruction`] `IsVariant` derives on
16171        // the sibling closed-set typed-enum discriminator axes — extends
16172        // the same one-typed-dispatch-per-variant discipline onto the
16173        // fifth (and only remaining) closed-set typed-enum discriminator
16174        // on the caixa surface, closing the axis on the M3 mesh-slot
16175        // family.
16176        let rows: [(PlacementStrategy, [bool; 3]); 3] = [
16177            (PlacementStrategy::SingleNode, [true, false, false]),
16178            (PlacementStrategy::Replicated, [false, true, false]),
16179            (PlacementStrategy::Sharded, [false, false, true]),
16180        ];
16181        for (variant, expected) in rows {
16182            let observed = [
16183                variant.is_single_node(),
16184                variant.is_replicated(),
16185                variant.is_sharded(),
16186            ];
16187            assert_eq!(
16188                observed, expected,
16189                "PlacementStrategy::{variant:?} is_* predicates must partition \
16190                 the arm set (single_node, replicated, sharded); got {observed:?}"
16191            );
16192        }
16193    }
16194
16195    #[test]
16196    fn placement_strategy_is_variant_predicates_are_const_fn() {
16197        // The [`gen_platform::IsVariant`] derive emits `const fn`
16198        // predicates on the peer [`crate::CaixaKind`] +
16199        // [`crate::upgrade::UpgradeInstruction`] +
16200        // [`crate::supervisor::RestartStrategy`] +
16201        // [`crate::supervisor::RestartPolicy`] closed-set typed enums —
16202        // pin the same posture on [`PlacementStrategy`] so a future
16203        // accidental downgrade to non-`const` (an added runtime helper
16204        // reachable only from a non-`const` context, a manual hand-rolled
16205        // `impl` that shadows the derive-generated method) trips at
16206        // caixa-core build time rather than surfacing as a downstream
16207        // `const`-context regression far from the derive declaration.
16208        //
16209        // The pin lives inside a `const { assert!(..) }` block so the
16210        // compiler enforces both halves (arm predicate is `const`-
16211        // callable AND returns `true` for the matching arm) at
16212        // caixa-core compile time — peer to the sibling
16213        // [`crate::CaixaKind::is_*`] + [`WitTarget::is_*`] const-block
16214        // pins on the closed-set typed enum arm-predicate const-
16215        // callability axis.
16216        const {
16217            assert!(PlacementStrategy::SingleNode.is_single_node());
16218            assert!(PlacementStrategy::Replicated.is_replicated());
16219            assert!(PlacementStrategy::Sharded.is_sharded());
16220        }
16221    }
16222
16223    #[test]
16224    fn placement_strategy_requires_shard_key_partitions_the_arm_set() {
16225        // Fail-before-pass-after pin on the substrate-lifted
16226        // [`PlacementStrategy::requires_shard_key`] cross-slot-invariant
16227        // per-arm predicate: for each variant in the closed accept-set the
16228        // predicate returns `true` iff the variant consumes the paired
16229        // [`Placement::shard_key`] axis under
16230        // [`AplicacaoSpec::validate_placement`]'s `Sharded` ↔ non-`Sharded`
16231        // partition. Today the accept-set is the singleton `{Sharded}` —
16232        // `Sharded` is the Akka-style hash-keyed distribution arm
16233        // (MESH-COMPOSITION §II.4), `SingleNode` (Erlang/OTP takeover —
16234        // §II.1) and `Replicated` (active-active) refuse the axis through
16235        // [`AplicacaoError::ShardKeyOnNonSharded`].
16236        //
16237        // Pins the per-arm truth-table so a future arm addition (an
16238        // `Anycast` mesh-anycast arm the MESH-COMPOSITION §II.5 hint the
16239        // roadmap names, a `WeightedShard` promotion the future M5
16240        // adaptive-placement engine acknowledges) that landed a variant
16241        // without extending this predicate's arm-set would surface as a
16242        // caixa-core build-time exhaustiveness error at the
16243        // `match self { … }` arm-fan below rather than a silent per-consumer
16244        // mis-classification at renderer emit time. The paired
16245        // [`Self::is_sharded`] `gen_platform::IsVariant`-derived arm-identity
16246        // predicate stays a distinct question — arm-identity (which the
16247        // sibling
16248        // [`placement_strategy_is_variant_predicates_partition_the_arm_set`]
16249        // pin already locks) is not cross-slot-invariant consumption; today
16250        // they trip on the same singleton but the pair migrates through
16251        // one caixa-core edit on any future arm addition.
16252        //
16253        // Peer of the sibling per-arm classifier pins
16254        // [`wit_contract_is_capability_partitions_the_wit_shape_space`]
16255        // (7b97d26) on the [`WitContract`] pre-projection WIT-shape axis
16256        // and the [`WitTarget::is_capability`] `gen_platform::IsVariant`-
16257        // derived paired predicate on the post-projection typed-view axis
16258        // — same "per-arm semantic-classification predicate paired with
16259        // the arm-identity predicate the derive already emits" discipline
16260        // extended onto the M3 mesh-slot `:placement :estrategia` ↔
16261        // `:placement :shard-key` cross-slot-invariant axis.
16262        let rows: [(PlacementStrategy, bool); 3] = [
16263            (PlacementStrategy::SingleNode, false),
16264            (PlacementStrategy::Replicated, false),
16265            (PlacementStrategy::Sharded, true),
16266        ];
16267        for (variant, expected) in rows {
16268            assert_eq!(
16269                variant.requires_shard_key(),
16270                expected,
16271                "PlacementStrategy::{variant:?}.requires_shard_key() must \
16272                 be {expected} (the substrate-canonical cross-slot invariant \
16273                 on the :placement :shard-key axis; today `Sharded` is the \
16274                 singleton consuming arm — MESH-COMPOSITION §II.4)",
16275            );
16276        }
16277    }
16278
16279    #[test]
16280    fn placement_strategy_requires_shard_key_is_const_fn() {
16281        // The [`PlacementStrategy::requires_shard_key`] cross-slot-
16282        // invariant per-arm predicate is declared `#[must_use] pub const
16283        // fn` — pin the `const`-eval posture here so a future accidental
16284        // downgrade to non-`const` (an added runtime helper reachable
16285        // only from a non-`const` context, a manual hand-rolled `impl`
16286        // that shadows the current three-arm `match self { … }` dispatch)
16287        // trips at caixa-core build time rather than surfacing as a
16288        // downstream `const`-context regression far from the declaration.
16289        // Same shape as the sibling
16290        // [`placement_strategy_is_variant_predicates_are_const_fn`] pin on
16291        // the peer [`gen_platform::IsVariant`]-derived arm-identity
16292        // predicate axis, but here the load-bearing assertions live in
16293        // module-scope `const _: () = assert!(…)` items so a violation
16294        // fails at compile time (const-eval trip) rather than test time —
16295        // strictly stronger than the runtime `assert!(CONST)` pattern the
16296        // sibling pin uses, and side-steps the
16297        // `clippy::assertions_on_constants` lint the runtime pattern
16298        // otherwise accumulates on the module baseline.
16299        //
16300        // The test body simply witnesses that the module-scope items
16301        // compiled and the runtime dispatch agrees with the const-eval
16302        // dispatch on every arm — the runtime read gives the test a
16303        // failure surface (rather than an empty test body clippy would
16304        // flag as a no-op).
16305        const REQUIRES_SINGLE_NODE: bool = PlacementStrategy::SingleNode.requires_shard_key();
16306        const REQUIRES_REPLICATED: bool = PlacementStrategy::Replicated.requires_shard_key();
16307        const REQUIRES_SHARDED: bool = PlacementStrategy::Sharded.requires_shard_key();
16308        assert_eq!(
16309            [REQUIRES_SINGLE_NODE, REQUIRES_REPLICATED, REQUIRES_SHARDED,],
16310            [
16311                PlacementStrategy::SingleNode.requires_shard_key(),
16312                PlacementStrategy::Replicated.requires_shard_key(),
16313                PlacementStrategy::Sharded.requires_shard_key(),
16314            ],
16315            "runtime and const-eval dispatch on \
16316             PlacementStrategy::requires_shard_key must agree on every arm",
16317        );
16318    }
16319
16320    #[test]
16321    fn placement_estrategia_accessor_is_const_fn() {
16322        // The [`Placement::estrategia`] per-`:placement` distribution-
16323        // strategy `Copy`-return scalar accessor is declared
16324        // `#[must_use] pub const fn` — matching the peer M3 mesh-slot
16325        // `Copy`-return accessor family ([`MeshPolicy::timeout`] /
16326        // [`MeshPolicy::retries`] / [`MeshPolicy::mtls_required`] /
16327        // [`MeshPolicy::rate_limit`] / [`MeshPolicy::circuit_breaker`]
16328        // on the parent [`MeshPolicy`], [`CircuitBreaker::max_failures`]
16329        // / [`CircuitBreaker::window`] on the sibling [`CircuitBreaker`],
16330        // [`RateLimit::rate`] / [`RateLimit::window`] on the sibling
16331        // [`RateLimit`], every one a `pub const fn`). Pin the
16332        // `const`-eval posture here so a future accidental downgrade to
16333        // non-`const` (an added runtime helper reachable only from a
16334        // non-`const` context, a slot promotion to a non-`Copy` return
16335        // that would silently drop the `const` qualifier, a manual
16336        // hand-rolled shadow) trips at caixa-core build time rather
16337        // than surfacing as a downstream `const`-context regression far
16338        // from the declaration.
16339        //
16340        // Same shape as the sibling
16341        // [`placement_strategy_requires_shard_key_is_const_fn`] pin on
16342        // the peer [`PlacementStrategy::requires_shard_key`] `const fn`
16343        // predicate axis — the load-bearing witness lives in the
16344        // module-scope `const fn` wrapper `estrategia_via_const_fn`
16345        // below: a body that calls [`Placement::estrategia`] under a
16346        // `const fn` signature is well-formed only when the callee is
16347        // itself `const fn`, so any future accidental downgrade of
16348        // [`Placement::estrategia`] to non-`const` fails at caixa-core
16349        // build time (const-eval E0015 / E0658 depending on the arm),
16350        // strictly stronger than a runtime `assert!(CONST)` and
16351        // side-stepping the destructor-in-const restriction that
16352        // blocks direct `const _: PlacementStrategy = FIXTURE.estrategia()`
16353        // items on `Placement`'s `Vec<String>` / `Option<String>`
16354        // carriers.
16355        //
16356        // The runtime body witnesses that the const-eval-shaped
16357        // wrapper agrees with a direct call on every closed-set arm.
16358        const fn estrategia_via_const_fn(p: &Placement) -> PlacementStrategy {
16359            p.estrategia()
16360        }
16361        for estrategia in [
16362            PlacementStrategy::SingleNode,
16363            PlacementStrategy::Replicated,
16364            PlacementStrategy::Sharded,
16365        ] {
16366            let placement = Placement {
16367                estrategia,
16368                clusters: Vec::new(),
16369                affinity: None,
16370                shard_key: None,
16371            };
16372            assert_eq!(
16373                estrategia_via_const_fn(&placement),
16374                placement.estrategia(),
16375                "const-fn-wrapped and direct dispatch on \
16376                 Placement::estrategia must agree for {estrategia:?}",
16377            );
16378        }
16379    }
16380
16381    #[test]
16382    fn entrada_port_accessor_is_const_fn() {
16383        // The [`Entrada::port`] per-`:entrada` L4-port `Copy`-return
16384        // scalar accessor is declared `#[must_use] pub const fn` —
16385        // matching the peer M3 mesh-slot `Copy`-return accessor family
16386        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`] /
16387        // [`MeshPolicy::mtls_required`] / [`MeshPolicy::rate_limit`] /
16388        // [`MeshPolicy::circuit_breaker`] on the parent [`MeshPolicy`],
16389        // [`CircuitBreaker::max_failures`] / [`CircuitBreaker::window`]
16390        // on the sibling [`CircuitBreaker`], [`RateLimit::rate`] /
16391        // [`RateLimit::window`] on the sibling [`RateLimit`], the
16392        // sibling per-`:placement` [`Placement::estrategia`] pinned by
16393        // [`placement_estrategia_accessor_is_const_fn`] above — every
16394        // one a `pub const fn`). Pin the `const`-eval posture here so
16395        // a future accidental downgrade to non-`const` (an added
16396        // runtime helper reachable only from a non-`const` context, an
16397        // `Option<u16>`-shape migration once the substrate grows
16398        // per-`:membros` heterogeneous listener ports that would
16399        // silently drop the `const` qualifier, a manual hand-rolled
16400        // shadow) trips at caixa-core build time rather than surfacing
16401        // as a downstream `const`-context regression far from the
16402        // declaration.
16403        //
16404        // Same shape as the sibling
16405        // [`placement_estrategia_accessor_is_const_fn`] pin above — the
16406        // load-bearing witness lives in the module-scope `const fn`
16407        // wrapper `port_via_const_fn`: a body that calls
16408        // [`Entrada::port`] under a `const fn` signature is well-formed
16409        // only when the callee is itself `const fn`, side-stepping the
16410        // destructor-in-const restriction that would otherwise block a
16411        // direct `const _: u16 = FIXTURE.port()` item on `Entrada`'s
16412        // `String` / `Vec<String>` carriers.
16413        //
16414        // The runtime body sweeps a representative port set spanning
16415        // the [`SERVICO_PORT_MIN`] floor, the substrate-canonical
16416        // [`DEFAULT_SERVICO_PORT`] default, and the top-edge `u16::MAX`
16417        // ceiling — the const-fn-wrapped call must agree with a direct
16418        // call on every fixture (a violation trips the test) and every
16419        // returned scalar must byte-equal the input `port` (a violation
16420        // means the accessor stopped being a raw field-return copy).
16421        const fn port_via_const_fn(e: &Entrada) -> u16 {
16422            e.port()
16423        }
16424        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, u16::MAX] {
16425            let entrada = Entrada {
16426                host: String::new(),
16427                para: String::new(),
16428                port,
16429                paths: Vec::new(),
16430            };
16431            assert_eq!(
16432                port_via_const_fn(&entrada),
16433                entrada.port(),
16434                "const-fn-wrapped and direct dispatch on Entrada::port \
16435                 must agree for port={port}",
16436            );
16437            assert_eq!(
16438                entrada.port(),
16439                port,
16440                "Entrada::port must return the storage-side u16 verbatim \
16441                 for port={port}",
16442            );
16443        }
16444    }
16445
16446    #[test]
16447    fn validate_placement_admits_paired_shape_iff_strategy_requires_shard_key() {
16448        // Load-bearing cross-slot-partition pin closing the loop between
16449        // the substrate-lifted
16450        // [`PlacementStrategy::requires_shard_key`] per-arm predicate on
16451        // the closed-set typed enum and the actual
16452        // [`AplicacaoSpec::validate_placement`] runtime behavior across
16453        // the paired `:placement :shard-key` axis: every validated
16454        // [`Placement`] past [`AplicacaoSpec::validate_placement`]
16455        // satisfies `placement.shard_key().is_some() ==
16456        // placement.estrategia().requires_shard_key()`. The four-cell
16457        // shape witness sweeps every combination of (variant in the
16458        // closed accept-set, `:shard-key` Some/None) and pins:
16459        //
16460        //   * variant.requires_shard_key() && shard_key.is_some() →
16461        //     validate() passes; the paired shape is the sole
16462        //     `requires_shard_key` arm-family accepted shape.
16463        //   * variant.requires_shard_key() && shard_key.is_none() →
16464        //     validate() fails with [`AplicacaoError::ShardedWithoutKey`];
16465        //     the paired shape is the refused missing-key shape on
16466        //     Sharded-family arms.
16467        //   * !variant.requires_shard_key() && shard_key.is_some() →
16468        //     validate() fails with
16469        //     [`AplicacaoError::ShardKeyOnNonSharded`]; the paired shape
16470        //     is the refused declared-but-inert shape on non-Sharded-
16471        //     family arms.
16472        //   * !variant.requires_shard_key() && shard_key.is_none() →
16473        //     validate() passes; the paired shape is the sole
16474        //     non-`requires_shard_key` arm-family accepted shape.
16475        //
16476        // The compile-time-exhaustive `match p.estrategia()` dispatch at
16477        // [`AplicacaoSpec::validate_placement`] preserves its structural
16478        // arm-fan (a future arm addition still surfaces a build-time
16479        // exhaustiveness error there); this pin closes the semantic loop
16480        // between the arm-fan's shape-gate cascades and the substrate-
16481        // canonical predicate every downstream consumer of the paired
16482        // shape reads through. Fail-before-pass-after locally verified by
16483        // mutating the predicate's `Sharded => true` arm to `false` — the
16484        // truthy `expects_ok` cell for `Sharded` + `Some` trips the
16485        // `validate() must pass` assertion; restoring passes. Same "close
16486        // the loop between the typed predicate and the runtime behavior"
16487        // discipline as the sibling
16488        // [`wit_contract_is_capability_agrees_with_projected_wit_target_capability_variant`]
16489        // (7b97d26) cross-projection pin on the peer [`WitTarget`]
16490        // per-arm classifier axis.
16491        for variant in [
16492            PlacementStrategy::SingleNode,
16493            PlacementStrategy::Replicated,
16494            PlacementStrategy::Sharded,
16495        ] {
16496            for present in [false, true] {
16497                let mut spec = three_member_spec();
16498                spec.placement.estrategia = variant;
16499                spec.placement.shard_key = present.then(|| "tenantId".into());
16500                let expects_ok = variant.requires_shard_key() == present;
16501                let result = spec.validate();
16502                match (expects_ok, &result) {
16503                    (true, Ok(())) => {}
16504                    (false, Err(err)) => {
16505                        // Cross-check the refusal diagnostic names the
16506                        // right cell of the four-cell shape witness — the
16507                        // `requires_shard_key && !present` cell must trip
16508                        // [`AplicacaoError::ShardedWithoutKey`]; the
16509                        // `!requires_shard_key && present` cell must trip
16510                        // [`AplicacaoError::ShardKeyOnNonSharded`].
16511                        match (variant.requires_shard_key(), present, err) {
16512                            (true, false, AplicacaoError::ShardedWithoutKey) => {}
16513                            (
16514                                false,
16515                                true,
16516                                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. },
16517                            ) => {
16518                                assert_eq!(
16519                                    *e, variant,
16520                                    "ShardKeyOnNonSharded.estrategia must byte-equal \
16521                                     the paired PlacementStrategy",
16522                                );
16523                            }
16524                            _ => panic!(
16525                                "unexpected refusal for estrategia={variant:?} \
16526                                 present={present}: {err:?}"
16527                            ),
16528                        }
16529                    }
16530                    (true, Err(err)) => panic!(
16531                        "validate() must pass for estrategia={variant:?} \
16532                         present={present} (requires_shard_key={} == present={present}), \
16533                         got {err:?}",
16534                        variant.requires_shard_key(),
16535                    ),
16536                    (false, Ok(())) => panic!(
16537                        "validate() must fail for estrategia={variant:?} \
16538                         present={present} (requires_shard_key={} != present={present})",
16539                        variant.requires_shard_key(),
16540                    ),
16541                }
16542            }
16543        }
16544    }
16545
16546    #[test]
16547    fn placement_without_clusters_diagnostic_carries_strategy_display_byte_string() {
16548        // Pin the M3 diagnostic template routes through the typed
16549        // [`PlacementStrategy`] Display byte-string (rebound from the
16550        // prior `{estrategia:?}` `Debug` route). Pre-lift the two
16551        // routes emitted identical bytes (the `Debug` derive on a
16552        // unit variant emits the variant name verbatim, exactly what
16553        // `as_str` returns), but the two paths were structurally
16554        // independent — a future `#[serde(rename_all = "…")]`
16555        // attribute or variant rename would coordinate the wire /
16556        // `Display` / `as_str` triple through the lifted const but
16557        // leave the `Debug` route on the compiler-derived variant name,
16558        // silently desynchronizing the diagnostic byte-string from the
16559        // wire byte-string. Rebinding the template onto `Display`
16560        // ties the diagnostic to the same lifted
16561        // [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const the wire format
16562        // emits — drift becomes structurally impossible. Pin the
16563        // byte-string here so a future edit that reverts the template
16564        // to `{estrategia:?}` is caught at caixa-core test time, not
16565        // at consumer dispatch time.
16566        for (variant, expected_scalar) in [
16567            (
16568                PlacementStrategy::SingleNode,
16569                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16570            ),
16571            (
16572                PlacementStrategy::Replicated,
16573                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16574            ),
16575            (
16576                PlacementStrategy::Sharded,
16577                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16578            ),
16579        ] {
16580            let err = AplicacaoError::PlacementWithoutClusters {
16581                estrategia: variant,
16582            };
16583            let msg = err.to_string();
16584            assert!(
16585                msg.starts_with(&format!(":placement {expected_scalar} requires")),
16586                "PlacementWithoutClusters diagnostic for {variant:?} must open \
16587                 with the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16588            );
16589        }
16590    }
16591
16592    #[test]
16593    fn shard_key_on_non_sharded_diagnostic_carries_strategy_display_byte_string() {
16594        // Peer of
16595        // [`placement_without_clusters_diagnostic_carries_strategy_display_byte_string`]
16596        // on the second M3 diagnostic that carries the typed
16597        // [`PlacementStrategy`] in its `#[error(…)]` template. Both
16598        // diagnostics now route the strategy scalar through the same
16599        // [`std::fmt::Display`] surface, tying the diagnostic
16600        // byte-string to the lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`]
16601        // const set the wire format also emits. The two non-Sharded
16602        // arms are exercised here (the diagnostic exists to flag a
16603        // `:shard-key` slot the current strategy will never consume);
16604        // the peer `Sharded` arm never reaches this diagnostic (the
16605        // `Sharded` strategy consumes `:shard-key` — the
16606        // [`AplicacaoError::ShardedWithoutKey`] arm reports the missing
16607        // slot instead).
16608        for (variant, expected_scalar) in [
16609            (
16610                PlacementStrategy::SingleNode,
16611                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16612            ),
16613            (
16614                PlacementStrategy::Replicated,
16615                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16616            ),
16617        ] {
16618            let err = AplicacaoError::ShardKeyOnNonSharded {
16619                estrategia: variant,
16620                shard_key: "$tenantId".into(),
16621            };
16622            let msg = err.to_string();
16623            assert!(
16624                msg.starts_with(&format!(":placement {expected_scalar} carries")),
16625                "ShardKeyOnNonSharded diagnostic for {variant:?} must open with \
16626                 the lifted `{expected_scalar}` scalar via Display; got {msg:?}"
16627            );
16628        }
16629    }
16630
16631    #[test]
16632    fn placement_strategy_all_enumerates_every_variant_once() {
16633        // Fail-before-pass-after pin on the [`PlacementStrategy::ALL`]
16634        // exhaustive-iteration surface: every variant appears exactly
16635        // once, and the slice length matches the arm count of the
16636        // closed set. Every consumer that walks the accepted-strategy
16637        // set (a future `feira app placement --list` CLI-side surfacing,
16638        // a future M4 admission-webhook's rejection body naming the
16639        // accepted-strategy list, the [`PlacementStrategy::from_wire`]
16640        // reverse-projection consumers that iterate the accept-set for
16641        // a "did you mean" hint) reads through this slice, so a future
16642        // variant addition (an `Anycast` mesh-anycast arm the
16643        // MESH-COMPOSITION §II.5 hint names as a trajectory item) that
16644        // grows the enum but forgets to grow [`Self::ALL`] silently
16645        // truncates every downstream consumer's accept-set at the same
16646        // pre-addition boundary — this pin fails at caixa-core build
16647        // time on the pairwise-distinct + arm-count invariants.
16648        //
16649        // Peer of the sibling [`RateLimitUnit::ALL`] (6bce03d) /
16650        // [`crate::dep::DepList::ALL`] (45ee563) exhaustive-iteration
16651        // pins on the peer closed-set typed-enum axes.
16652        let all: &[PlacementStrategy] = PlacementStrategy::ALL;
16653        assert_eq!(
16654            all.len(),
16655            3,
16656            "PlacementStrategy::ALL must enumerate every variant of the \
16657             three-arm closed set (SingleNode, Replicated, Sharded); got {all:?}"
16658        );
16659        for (i, a) in all.iter().enumerate() {
16660            for (j, b) in all.iter().enumerate() {
16661                if i != j {
16662                    assert_ne!(
16663                        a, b,
16664                        "PlacementStrategy::ALL must carry every variant exactly \
16665                         once — got duplicate {a:?} at indices {i} and {j}"
16666                    );
16667                }
16668            }
16669        }
16670        for variant in [
16671            PlacementStrategy::SingleNode,
16672            PlacementStrategy::Replicated,
16673            PlacementStrategy::Sharded,
16674        ] {
16675            assert!(
16676                all.contains(&variant),
16677                "PlacementStrategy::ALL must contain {variant:?} — a future variant \
16678                 addition that grows the enum but forgets to grow the ALL slice \
16679                 silently truncates every downstream consumer's accept-set at the \
16680                 pre-addition boundary"
16681            );
16682        }
16683    }
16684
16685    #[test]
16686    fn placement_strategy_from_wire_accepts_every_lifted_constant() {
16687        // Fail-before-pass-after pin on the forward accept-set of the
16688        // [`PlacementStrategy::from_wire`] reverse projection: every
16689        // canonical [`crate::render::M3_PLACEMENT_ESTRATEGIA_*`]
16690        // constant the [`PlacementStrategy::as_str`] emitter walks
16691        // parses back to its paired variant. Any future arm addition
16692        // that grows the emitter's `as_str` match but forgets to grow
16693        // the parser's `from_str` match silently splits the two halves
16694        // of the round-trip — the wire byte-string one non-serde
16695        // consumer parses from the one the emitter wrote — with the
16696        // failure surfacing at parse time far from the rebrand commit.
16697        // Pinning the three-arm accept-set here catches the drift at
16698        // caixa-core build time.
16699        //
16700        // Peer of the sibling [`crate::CaixaKind::from_wire`] (2aa6d23)
16701        // + [`RateLimitUnit::from_suffix`] accept-set pins on the peer
16702        // closed-set typed-enum `str → Self` axes.
16703        for (wire, expected) in [
16704            (
16705                crate::render::M3_PLACEMENT_ESTRATEGIA_SINGLE_NODE,
16706                PlacementStrategy::SingleNode,
16707            ),
16708            (
16709                crate::render::M3_PLACEMENT_ESTRATEGIA_REPLICATED,
16710                PlacementStrategy::Replicated,
16711            ),
16712            (
16713                crate::render::M3_PLACEMENT_ESTRATEGIA_SHARDED,
16714                PlacementStrategy::Sharded,
16715            ),
16716        ] {
16717            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16718                panic!(
16719                    "PlacementStrategy::from_wire({wire:?}) must accept every \
16720                     M3_PLACEMENT_ESTRATEGIA_* constant — got None for the \
16721                     lifted canonical byte-string that PlacementStrategy::{expected:?} \
16722                     serializes as under M3_PLACEMENT_KEY_ESTRATEGIA"
16723                )
16724            });
16725            assert_eq!(
16726                parsed, expected,
16727                "PlacementStrategy::from_wire({wire:?}) must return \
16728                 PlacementStrategy::{expected:?}; got PlacementStrategy::{parsed:?}"
16729            );
16730        }
16731    }
16732
16733    #[test]
16734    fn placement_strategy_from_wire_round_trips_through_as_str() {
16735        // Fail-before-pass-after pin on the closed round-trip between
16736        // the forward [`PlacementStrategy::as_str`] emitter and the
16737        // reverse [`PlacementStrategy::from_wire`] parser: for every
16738        // variant in [`PlacementStrategy::ALL`], parsing the emitter's
16739        // output must return exactly the same variant. Any per-arm
16740        // divergence — a future arm added to `as_str` but not
16741        // `from_str`, an accidental copy-paste flip in one but not the
16742        // other — silently splits the emit and parse halves and the
16743        // failure surfaces at consumer parse time far from the drift
16744        // site. The `ALL`-iterating shape means a future variant
16745        // addition picks up the coverage by construction.
16746        //
16747        // Peer of the sibling [`crate::kind::tests`] round-trip pin on
16748        // [`crate::CaixaKind::from_wire`] and the
16749        // [`super::tests::rate_limit_unit_from_suffix_round_trips_through_as_suffix`]
16750        // sibling round-trip pin on [`RateLimitUnit`].
16751        for &variant in PlacementStrategy::ALL {
16752            let wire = variant.as_str();
16753            let parsed = PlacementStrategy::from_wire(wire).unwrap_or_else(|| {
16754                panic!(
16755                    "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16756                     must be Some({variant:?}) — the two halves of the round-trip \
16757                     dispatch on the same lifted M3_PLACEMENT_ESTRATEGIA_* consts; \
16758                     got None on wire byte-string {wire:?}"
16759                )
16760            });
16761            assert_eq!(
16762                parsed, variant,
16763                "PlacementStrategy::from_wire(PlacementStrategy::{variant:?}.as_str()) \
16764                 must round-trip to the same variant; got {parsed:?}"
16765            );
16766        }
16767    }
16768
16769    #[test]
16770    fn placement_strategy_from_wire_rejects_unknown_byte_strings() {
16771        // Fail-before-pass-after pin on the closed-set refusal
16772        // discipline of [`PlacementStrategy::from_wire`]: every
16773        // byte-string outside the three-arm accept-set returns `None`
16774        // rather than silently collapsing onto the [`Default`]
16775        // (`Replicated`) arm or an arbitrary neighbor. The refusal set
16776        // exercised here sweeps the load-bearing drift shapes: the
16777        // empty string (a stripped serde-attribute drift), an all-
16778        // whitespace string (the canonical text-editor accidental
16779        // padding shape), the lowercased kebab-case forms a future
16780        // `#[serde(rename_all = "kebab-case")]` attribute would emit
16781        // (`"single-node"`, `"replicated"`, `"sharded"` — the last two
16782        // coincidentally match the accepted canonical scalars, so only
16783        // `"single-node"` fires as a refusal, but pinning the case-
16784        // sensitivity of the accepted arms via the peer [`SingleNode`]
16785        // assertion in the round-trip pin makes the discipline
16786        // structurally clear), the lowercased single-word forms
16787        // (`"singlenode"`), the padded canonical scalar
16788        // (`" Sharded "`), the trailing-comma / trailing-newline shapes
16789        // (`"Sharded\n"`), and a pointer-different `&'static str` that
16790        // happens to alias a canonical byte-string by content but not
16791        // by identity (validated implicitly by the emitter's routing
16792        // through `crate::render::M3_PLACEMENT_ESTRATEGIA_*`, whose
16793        // identity a paired [`crate::assert_str_reexport_identity`] pin
16794        // in caixa-core's per-const declaration surface would catch).
16795        //
16796        // Peer of the sibling
16797        // [`crate::kind::tests::caixa_kind_from_wire_rejects_unknown_byte_strings`]
16798        // (2aa6d23) refusal pin on [`crate::CaixaKind::from_wire`].
16799        for bad in [
16800            "",
16801            " ",
16802            "\n",
16803            "\t",
16804            "single-node",
16805            "singlenode",
16806            "SingleNodes",
16807            "single_node",
16808            "single node",
16809            "SINGLENODE",
16810            "SingleNode ",
16811            " SingleNode",
16812            " Sharded ",
16813            "Sharded\n",
16814            "replicated ",
16815            "sharded",
16816            "REPLICATED",
16817            "Anycast",
16818            "Global",
16819            "?",
16820        ] {
16821            assert!(
16822                PlacementStrategy::from_wire(bad).is_none(),
16823                "PlacementStrategy::from_wire({bad:?}) must return None — the \
16824                 parser's accept-set is exactly the three PlacementStrategy::as_str \
16825                 outputs (SingleNode, Replicated, Sharded), and this byte-string \
16826                 is outside that closed set"
16827            );
16828        }
16829    }
16830
16831    #[test]
16832    fn placement_strategy_from_wire_matches_serialize_derive_wire_byte_string() {
16833        // Fail-before-pass-after pin on the third path of the four-path
16834        // convergence: `from_str` (the reverse projection) inverts the
16835        // `Serialize` derive's wire byte-string on every variant.
16836        // Together with the pre-existing three-path convergence
16837        // (`Display` + `as_str` + `Serialize` all resolve to the same
16838        // lifted [`crate::M3_PLACEMENT_ESTRATEGIA_*`] const, pinned by
16839        // the peer
16840        // [`placement_strategy_display_matches_serialized_wire_byte_string`])
16841        // this closes the round-trip: the wire byte-string the
16842        // `Serialize` derive emits parses back to the same variant
16843        // through `from_str`, so any future serde-attribute or variant-
16844        // rename drift on the emit half now surfaces as a matched drift
16845        // on the parse half at caixa-core build time — the two halves
16846        // migrate as a unit through the lifted consts on any future
16847        // rename, and the round-trip cannot silently split.
16848        //
16849        // Peer of the sibling
16850        // [`placement_strategy_display_matches_serialized_wire_byte_string`]
16851        // wire-format pin — extends the three-path convergence
16852        // (`Display` + `as_str` + `Serialize`) onto the fourth path
16853        // (`from_str`), closing the `str ↔ Self` round-trip on the
16854        // M3 `:placement :estrategia` closed-set axis.
16855        for &variant in PlacementStrategy::ALL {
16856            let wire = serde_json::to_string(&variant).unwrap();
16857            let unquoted = wire
16858                .strip_prefix('"')
16859                .and_then(|s| s.strip_suffix('"'))
16860                .expect("serialized PlacementStrategy is a JSON string");
16861            let parsed = PlacementStrategy::from_wire(unquoted).unwrap_or_else(|| {
16862                panic!(
16863                    "PlacementStrategy::from_wire({unquoted:?}) must accept the \
16864                     Serialize derive's wire byte-string for \
16865                     PlacementStrategy::{variant:?} — the four-path convergence \
16866                     (Display + as_str + Serialize + from_str) resolves through \
16867                     the same lifted M3_PLACEMENT_ESTRATEGIA_* const; got None"
16868                )
16869            });
16870            assert_eq!(
16871                parsed, variant,
16872                "PlacementStrategy::from_wire of the Serialize derive's wire \
16873                 byte-string for PlacementStrategy::{variant:?} must round-trip \
16874                 to the same variant; got {parsed:?}"
16875            );
16876        }
16877    }
16878
16879    #[test]
16880    fn rejects_zero_policy_timeout() {
16881        let mut s = three_member_spec();
16882        s.politicas.timeout = Some(Duration::ZERO);
16883        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
16884    }
16885
16886    #[test]
16887    fn rejects_zero_policy_retries() {
16888        let mut s = three_member_spec();
16889        s.politicas.retries = Some(0);
16890        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyRetriesZero);
16891    }
16892
16893    #[test]
16894    fn rejects_policy_retries_above_cap() {
16895        // The fail-before-pass-after pin: `Some(11)` is structurally
16896        // one past the [`POLICY_RETRIES_MAX`] ceiling and silently
16897        // passed validate on every pre-gate codebase because the
16898        // typed slot's only check was the zero-floor arm. The
16899        // thundering-herd amplification vector only surfaced at the
16900        // runtime substrate (Envoy / Cilium L7 retry overlay)
16901        // far from the source caixa.lisp with no field naming the
16902        // offending policy.
16903        let mut s = three_member_spec();
16904        s.politicas.retries = Some(POLICY_RETRIES_MAX + 1);
16905        assert_eq!(
16906            s.validate().unwrap_err(),
16907            AplicacaoError::PolicyRetriesExceedsCap {
16908                retries: POLICY_RETRIES_MAX + 1
16909            }
16910        );
16911    }
16912
16913    #[test]
16914    fn rejects_policy_retries_far_above_cap() {
16915        // The `u32::MAX` worst case — the four-billion-retry policy
16916        // a typo (`(:retries 4294967295)`) or struct-literal
16917        // copy-paste lands in the slot. Pin the cap arm's coverage
16918        // explicitly across the full `u32` overflow so a future
16919        // relaxation that drops the upper bound surfaces here.
16920        let mut s = three_member_spec();
16921        s.politicas.retries = Some(u32::MAX);
16922        assert_eq!(
16923            s.validate().unwrap_err(),
16924            AplicacaoError::PolicyRetriesExceedsCap { retries: u32::MAX }
16925        );
16926    }
16927
16928    #[test]
16929    fn accepts_policy_retries_at_cap() {
16930        // The boundary value — exactly [`POLICY_RETRIES_MAX`] —
16931        // must validate. The cap is inclusive on the top edge,
16932        // matching the [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
16933        // discipline on the sibling [`crate::LimitsSpec::memory`]
16934        // axis. Pin the boundary explicitly so a future off-by-one
16935        // tightening (`>= POLICY_RETRIES_MAX` instead of `>`)
16936        // surfaces here as a test failure rather than a silent
16937        // contract narrowing.
16938        let mut s = three_member_spec();
16939        s.politicas.retries = Some(POLICY_RETRIES_MAX);
16940        s.validate()
16941            .expect("retries == POLICY_RETRIES_MAX must validate");
16942    }
16943
16944    #[test]
16945    fn accepts_policy_retries_typical_values() {
16946        // The full inclusive `1..=POLICY_RETRIES_MAX` sweep —
16947        // every value in the validated set must pass. The
16948        // Envoy / Istio production-playbook recommendation band
16949        // (`num_retries ≤ 5`) and the AWS App Mesh schema cap
16950        // (`maxRetries ≤ 10`) both lie within this set.
16951        for r in 1..=POLICY_RETRIES_MAX {
16952            let mut s = three_member_spec();
16953            s.politicas.retries = Some(r);
16954            s.validate()
16955                .unwrap_or_else(|e| panic!("retries={r} must validate; got {e:?}"));
16956        }
16957    }
16958
16959    #[test]
16960    fn policy_retries_zero_takes_precedence_over_cap() {
16961        // The cross-arm ordering pin: `Some(0)` is structurally
16962        // outside both `1..` (zero-floor) and `..=POLICY_RETRIES_MAX`
16963        // (cap), but the zero-floor diagnostic is the more
16964        // self-locating one (it directly names the omit-axis
16965        // remediation), so the validate gate must fire on zero
16966        // first. Pin the order so a future refactor that reorders
16967        // the arms surfaces here as a test failure rather than a
16968        // silent diagnostic regression. Same shape every other
16969        // zero-then-shape ordering on this surface uses
16970        // ([`AplicacaoError::PolicyTimeoutZero`] then
16971        // [`AplicacaoError::PolicyTimeoutNotCanonical`];
16972        // [`AplicacaoError::PolicyBreakerZeroWindow`] then
16973        // [`AplicacaoError::PolicyBreakerWindowNotCanonical`]).
16974        let mut s = three_member_spec();
16975        s.politicas.retries = Some(0);
16976        assert_eq!(
16977            s.validate().unwrap_err(),
16978            AplicacaoError::PolicyRetriesZero,
16979            "Some(0) must surface the zero-floor diagnostic, not the cap diagnostic"
16980        );
16981    }
16982
16983    #[test]
16984    fn policy_retries_cap_diagnostic_carries_offending_value() {
16985        // The diagnostic-shape pin: the offending `u32` is carried
16986        // verbatim into the [`AplicacaoError::PolicyRetriesExceedsCap`]
16987        // variant so the surfaced error message names the value the
16988        // author wrote (`":politicas :retries (47) exceeds the
16989        // mesh-policy ceiling …"`), not just the cap. Same
16990        // self-locating diagnostic shape every other typed-cap arm
16991        // on this surface carries
16992        // ([`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
16993        // offending byte count verbatim).
16994        let mut s = three_member_spec();
16995        s.politicas.retries = Some(47);
16996        let err = s.validate().unwrap_err();
16997        assert!(
16998            matches!(err, AplicacaoError::PolicyRetriesExceedsCap { retries: 47 }),
16999            "got {err:?}"
17000        );
17001        let msg = err.to_string();
17002        assert!(
17003            msg.contains("47"),
17004            ":politicas :retries cap diagnostic must carry the offending value verbatim (got: {msg})"
17005        );
17006    }
17007
17008    #[test]
17009    fn policy_retries_cap_is_aws_app_mesh_aligned() {
17010        // The [`POLICY_RETRIES_MAX`] constant pins the value at 10,
17011        // matching AWS App Mesh's `gRPCRouteRetryPolicy.maxRetries`
17012        // schema cap — the only upstream mesh-policy schema that
17013        // documents an explicit hard cap. Pinning the literal value
17014        // here surfaces a future drift (a relaxation to 20, a
17015        // tightening to 5) as a deliberate test edit, not a silent
17016        // contract narrowing.
17017        assert_eq!(POLICY_RETRIES_MAX, 10);
17018    }
17019
17020    #[test]
17021    fn rejects_circuit_breaker_zero_max_failures() {
17022        let mut s = three_member_spec();
17023        s.politicas.circuit_breaker = Some(CircuitBreaker {
17024            max_failures: 0,
17025            window: Duration::from_secs(60),
17026        });
17027        assert_eq!(
17028            s.validate().unwrap_err(),
17029            AplicacaoError::PolicyBreakerZeroFailures
17030        );
17031    }
17032
17033    #[test]
17034    fn rejects_circuit_breaker_max_failures_above_cap() {
17035        // The fail-before-pass-after pin: `1001` is structurally one
17036        // past the [`POLICY_BREAKER_MAX_FAILURES_MAX`] ceiling and
17037        // silently passed validate on every pre-gate codebase
17038        // because the typed slot's only check was the zero-floor
17039        // arm. The breaker-no-op vector only surfaced at the runtime
17040        // substrate (Envoy / Cilium L7 outlier-detection overlay)
17041        // far from the source caixa.lisp with no field naming the
17042        // offending policy.
17043        let mut s = three_member_spec();
17044        s.politicas.circuit_breaker = Some(CircuitBreaker {
17045            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17046            window: Duration::from_secs(60),
17047        });
17048        assert_eq!(
17049            s.validate().unwrap_err(),
17050            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17051                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17052            }
17053        );
17054    }
17055
17056    #[test]
17057    fn rejects_circuit_breaker_max_failures_far_above_cap() {
17058        // The `u32::MAX` worst case — the four-billion-failure
17059        // threshold a typo (`(:max-failures 4294967295)`) or a
17060        // struct-literal copy-paste lands in the slot. Pin the cap
17061        // arm's coverage explicitly across the full `u32` overflow
17062        // so a future relaxation that drops the upper bound surfaces
17063        // here.
17064        let mut s = three_member_spec();
17065        s.politicas.circuit_breaker = Some(CircuitBreaker {
17066            max_failures: u32::MAX,
17067            window: Duration::from_secs(60),
17068        });
17069        assert_eq!(
17070            s.validate().unwrap_err(),
17071            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17072                max_failures: u32::MAX,
17073            }
17074        );
17075    }
17076
17077    #[test]
17078    fn accepts_circuit_breaker_max_failures_at_cap() {
17079        // The boundary value — exactly
17080        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] — must validate. The
17081        // cap is inclusive on the top edge, matching the
17082        // [`POLICY_RETRIES_MAX`] / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]
17083        // discipline on the sibling capped axes. Pin the boundary
17084        // explicitly so a future off-by-one tightening
17085        // (`>= POLICY_BREAKER_MAX_FAILURES_MAX` instead of `>`)
17086        // surfaces here as a test failure rather than a silent
17087        // contract narrowing.
17088        let mut s = three_member_spec();
17089        s.politicas.circuit_breaker = Some(CircuitBreaker {
17090            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
17091            window: Duration::from_secs(60),
17092        });
17093        s.validate()
17094            .expect("max_failures == POLICY_BREAKER_MAX_FAILURES_MAX must validate");
17095    }
17096
17097    #[test]
17098    fn accepts_circuit_breaker_max_failures_typical_values() {
17099        // The documented production-playbook band positive-control
17100        // sweep — every value Hystrix / Istio / Envoy / Polly /
17101        // Resilience4j recommend (5..=50) must pass, plus a sweep
17102        // through the hyperscale band (100, 500, 1000) the cap
17103        // accepts. Pin the inclusive validated set explicitly so a
17104        // future tightening of the ceiling surfaces here.
17105        for n in [1u32, 5, 10, 20, 50, 100, 500, 1000] {
17106            let mut s = three_member_spec();
17107            s.politicas.circuit_breaker = Some(CircuitBreaker {
17108                max_failures: n,
17109                window: Duration::from_secs(60),
17110            });
17111            s.validate()
17112                .unwrap_or_else(|e| panic!("max_failures={n} must validate; got {e:?}"));
17113        }
17114    }
17115
17116    #[test]
17117    fn circuit_breaker_zero_max_failures_takes_precedence_over_cap() {
17118        // The cross-arm ordering pin: `0` is structurally outside
17119        // both `1..` (zero-floor) and `..=POLICY_BREAKER_MAX_FAILURES_MAX`
17120        // (cap), but the zero-floor diagnostic is the more
17121        // self-locating one (it directly names the omit-axis
17122        // remediation), so the validate gate must fire on zero
17123        // first. Same shape every other zero-then-shape ordering on
17124        // this surface uses
17125        // ([`AplicacaoError::PolicyRetriesZero`] then
17126        // [`AplicacaoError::PolicyRetriesExceedsCap`];
17127        // [`AplicacaoError::PolicyTimeoutZero`] then
17128        // [`AplicacaoError::PolicyTimeoutNotCanonical`]).
17129        let mut s = three_member_spec();
17130        s.politicas.circuit_breaker = Some(CircuitBreaker {
17131            max_failures: 0,
17132            window: Duration::from_secs(60),
17133        });
17134        assert_eq!(
17135            s.validate().unwrap_err(),
17136            AplicacaoError::PolicyBreakerZeroFailures,
17137            "max_failures == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
17138        );
17139    }
17140
17141    #[test]
17142    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_gates() {
17143        // The cross-arm ordering pin between the cap and the
17144        // sibling `:window` gates (zero-window, canonical-window).
17145        // A breaker carrying both an over-cap `max_failures` AND a
17146        // structurally invalid window (zero, sub-ms) must surface
17147        // the cap diagnostic first — the cap arm is wired
17148        // immediately after the zero-failure arm and strictly
17149        // before the window arms, so the offending value the
17150        // diagnostic names matches the order the author would
17151        // discover the gates by reading top-to-bottom through
17152        // [`AplicacaoSpec::validate_politicas`]. Pin the order so a
17153        // future refactor that reorders the arms surfaces here as a
17154        // test failure rather than a silent diagnostic regression.
17155        let mut s = three_member_spec();
17156        s.politicas.circuit_breaker = Some(CircuitBreaker {
17157            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17158            window: Duration::ZERO,
17159        });
17160        assert_eq!(
17161            s.validate().unwrap_err(),
17162            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17163                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
17164            },
17165            "over-cap max_failures must surface the cap diagnostic before any window-axis diagnostic"
17166        );
17167    }
17168
17169    #[test]
17170    fn policy_breaker_max_failures_cap_diagnostic_carries_offending_value() {
17171        // The diagnostic-shape pin: the offending `u32` is carried
17172        // verbatim into the
17173        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]
17174        // variant so the surfaced error message names the value the
17175        // author wrote (`":politicas :circuit-breaker :max-failures
17176        // (50000) exceeds the mesh-policy ceiling …"`), not just
17177        // the cap. Same self-locating diagnostic shape every other
17178        // typed-cap arm on this surface carries
17179        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
17180        // offending retry count verbatim,
17181        // [`crate::LimitsError::MemoryExceedsWasm32Cap`] carries the
17182        // offending byte count verbatim).
17183        let mut s = three_member_spec();
17184        s.politicas.circuit_breaker = Some(CircuitBreaker {
17185            max_failures: 50_000,
17186            window: Duration::from_secs(60),
17187        });
17188        let err = s.validate().unwrap_err();
17189        assert!(
17190            matches!(
17191                err,
17192                AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
17193                    max_failures: 50_000
17194                }
17195            ),
17196            "got {err:?}"
17197        );
17198        let msg = err.to_string();
17199        assert!(
17200            msg.contains("50000"),
17201            ":politicas :circuit-breaker :max-failures cap diagnostic must carry the offending value verbatim (got: {msg})"
17202        );
17203    }
17204
17205    #[test]
17206    fn policy_breaker_max_failures_cap_pins_canonical_value() {
17207        // The [`POLICY_BREAKER_MAX_FAILURES_MAX`] constant pins the
17208        // value at 1000 — an order of magnitude above every
17209        // documented production-playbook recommendation band
17210        // (Hystrix `requestVolumeThreshold` default 20, Istio
17211        // `outlierDetection.consecutive5xxErrors` default 5, Envoy
17212        // `outlier_detection.consecutive_5xx` default 5, Polly /
17213        // Resilience4j typical 5..=50) and below the
17214        // clearly-pathological "effectively no protection" floor
17215        // (10_000, 100_000, u32::MAX). Pinning the literal value
17216        // here surfaces a future drift (a relaxation to 10_000, a
17217        // tightening to 100) as a deliberate test edit, not a
17218        // silent contract narrowing.
17219        assert_eq!(POLICY_BREAKER_MAX_FAILURES_MAX, 1000);
17220    }
17221
17222    #[test]
17223    fn rejects_circuit_breaker_zero_window() {
17224        let mut s = three_member_spec();
17225        s.politicas.circuit_breaker = Some(CircuitBreaker {
17226            max_failures: 5,
17227            window: Duration::ZERO,
17228        });
17229        assert_eq!(
17230            s.validate().unwrap_err(),
17231            AplicacaoError::PolicyBreakerZeroWindow
17232        );
17233    }
17234
17235    #[test]
17236    fn rejects_zero_rate_limit() {
17237        let mut s = three_member_spec();
17238        s.politicas.rate_limit = Some(RateLimit {
17239            rate: 0,
17240            window: Duration::from_secs(1),
17241        });
17242        assert_eq!(
17243            s.validate().unwrap_err(),
17244            AplicacaoError::PolicyRateLimitZero
17245        );
17246    }
17247
17248    #[test]
17249    fn rejects_rate_limit_zero_window() {
17250        // `RateLimit { rate: 100, window: Duration::ZERO }` is
17251        // constructible programmatically (the typed `Duration` field
17252        // imposes no nonzero invariant) but renders through
17253        // `rate_limit_codec::render` as `"100/0s"` — a fragment the
17254        // codec's `parse` rejects as `unknown rate-limit window unit
17255        // "0s"`. Until this validate-time gate landed the typed slot
17256        // accepted the value silently and the round-trip break only
17257        // surfaced at deserialize time (potentially in a downstream
17258        // consumer that never re-validates). Pin the rejection at
17259        // `AplicacaoSpec::validate` so the typed slot's valid set
17260        // matches the codec's round-trippable set structurally.
17261        let mut s = three_member_spec();
17262        s.politicas.rate_limit = Some(RateLimit {
17263            rate: 100,
17264            window: Duration::ZERO,
17265        });
17266        assert_eq!(
17267            s.validate().unwrap_err(),
17268            AplicacaoError::PolicyRateLimitWindowNotCanonical {
17269                window: Duration::ZERO
17270            }
17271        );
17272    }
17273
17274    #[test]
17275    fn rejects_rate_limit_arbitrary_seconds_window() {
17276        // 45 seconds is a valid `Duration` but not one of the three
17277        // canonical rate-limit windows the codec round-trips
17278        // (1s / 60s / 3600s). Renders as `"100/45s"`, which the parser
17279        // refuses on round-trip — same round-trip-break shape the
17280        // zero-window arm above pins, with a non-zero magnitude to
17281        // guard against a future "reject only zero" half-measure.
17282        let mut s = three_member_spec();
17283        let window = Duration::from_secs(45);
17284        s.politicas.rate_limit = Some(RateLimit { rate: 100, window });
17285        assert_eq!(
17286            s.validate().unwrap_err(),
17287            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17288        );
17289    }
17290
17291    #[test]
17292    fn rejects_rate_limit_two_minute_window() {
17293        // 120 seconds = 2 minutes is a "looks-canonical" but
17294        // not-canonical window: it's a clean integer multiple of the
17295        // minute unit, but the codec only round-trips the
17296        // unit-magnitude-1 forms (`"<n>/m"` ≡ 60s, *not* `"<n>/2m"`).
17297        // A `Duration::from_secs(120)` window renders as `"100/120s"`
17298        // which the parser rejects. Pinning this case rules out a
17299        // future "accept any clean multiple of s/m/h" relaxation
17300        // that would silently break the codec contract.
17301        let mut s = three_member_spec();
17302        let window = Duration::from_secs(120);
17303        s.politicas.rate_limit = Some(RateLimit { rate: 50, window });
17304        assert_eq!(
17305            s.validate().unwrap_err(),
17306            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17307        );
17308    }
17309
17310    #[test]
17311    fn rejects_rate_limit_subsecond_window() {
17312        // A sub-second window (e.g. 500ms) is a valid `Duration` but
17313        // unrepresentable in the codec's `<n>/<s|m|h>` author surface.
17314        // Pin the rejection so a future relaxation can't silently
17315        // admit fractional-second windows that the codec can't
17316        // round-trip.
17317        let mut s = three_member_spec();
17318        let window = Duration::from_millis(500);
17319        s.politicas.rate_limit = Some(RateLimit { rate: 200, window });
17320        assert_eq!(
17321            s.validate().unwrap_err(),
17322            AplicacaoError::PolicyRateLimitWindowNotCanonical { window }
17323        );
17324    }
17325
17326    #[test]
17327    fn rejects_policy_rate_limit_above_cap() {
17328        // The fail-before-pass-after pin: `rate = POLICY_RATE_LIMIT_MAX + 1`
17329        // is structurally one past the cap and silently passed
17330        // validate on every pre-gate codebase because the typed slot's
17331        // only `rate` check was the zero-floor arm. The no-op-limiter
17332        // shape only surfaced at the runtime substrate (Envoy's
17333        // `local_rate_limit.token_bucket.max_tokens`, the future
17334        // Cilium L7 rate-limit overlay) far from the source caixa.lisp
17335        // with no field naming the offending policy.
17336        let mut s = three_member_spec();
17337        s.politicas.rate_limit = Some(RateLimit {
17338            rate: POLICY_RATE_LIMIT_MAX + 1,
17339            window: Duration::from_secs(1),
17340        });
17341        assert_eq!(
17342            s.validate().unwrap_err(),
17343            AplicacaoError::PolicyRateLimitExceedsCap {
17344                rate: POLICY_RATE_LIMIT_MAX + 1
17345            }
17346        );
17347    }
17348
17349    #[test]
17350    fn rejects_policy_rate_limit_far_above_cap() {
17351        // The `u32::MAX` worst case — the four-billion-token rate-limit
17352        // a typo (`(:rate-limit "4294967295/s")`) or struct-literal
17353        // copy-paste lands in the slot. Pin the cap arm's coverage
17354        // explicitly across the full `u32` overflow so a future
17355        // relaxation that drops the upper bound surfaces here. Peer to
17356        // `rejects_policy_retries_far_above_cap` on the sibling
17357        // `:retries` axis and `rejects_policy_breaker_max_failures_far_above_cap`
17358        // on the sibling `:max-failures` axis.
17359        let mut s = three_member_spec();
17360        s.politicas.rate_limit = Some(RateLimit {
17361            rate: u32::MAX,
17362            window: Duration::from_secs(1),
17363        });
17364        assert_eq!(
17365            s.validate().unwrap_err(),
17366            AplicacaoError::PolicyRateLimitExceedsCap { rate: u32::MAX }
17367        );
17368    }
17369
17370    #[test]
17371    fn accepts_policy_rate_limit_at_cap() {
17372        // The boundary value — exactly [`POLICY_RATE_LIMIT_MAX`] —
17373        // must validate. The cap is inclusive on the top edge, matching
17374        // every other typed upper bound in this crate
17375        // ([`POLICY_RETRIES_MAX`], [`POLICY_BREAKER_MAX_FAILURES_MAX`],
17376        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`]). Pin the boundary
17377        // across all three canonical windows so a future off-by-one
17378        // tightening (`>= POLICY_RATE_LIMIT_MAX` instead of `>`) or a
17379        // window-conditional cap surfaces here as a test failure rather
17380        // than a silent contract narrowing.
17381        for secs in [1u64, 60, 3600] {
17382            let mut s = three_member_spec();
17383            s.politicas.rate_limit = Some(RateLimit {
17384                rate: POLICY_RATE_LIMIT_MAX,
17385                window: Duration::from_secs(secs),
17386            });
17387            s.validate().unwrap_or_else(|e| {
17388                panic!("rate == POLICY_RATE_LIMIT_MAX must validate (window={secs}s); got {e:?}",)
17389            });
17390        }
17391    }
17392
17393    #[test]
17394    fn accepts_policy_rate_limit_typical_values() {
17395        // The documented production-playbook recommendation band —
17396        // Envoy / Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare /
17397        // AWS API Gateway 10_000..=100_000 per-minute, Cloudflare
17398        // Enterprise ~1M per-hour. Every value in the validated set
17399        // must pass; pin the band explicitly so a future tightening
17400        // surfaces here.
17401        for rate in [1u32, 10, 100, 1_000, 10_000, 100_000, 1_000_000] {
17402            for secs in [1u64, 60, 3600] {
17403                let mut s = three_member_spec();
17404                s.politicas.rate_limit = Some(RateLimit {
17405                    rate,
17406                    window: Duration::from_secs(secs),
17407                });
17408                s.validate().unwrap_or_else(|e| {
17409                    panic!("rate={rate} window={secs}s must validate; got {e:?}")
17410                });
17411            }
17412        }
17413    }
17414
17415    #[test]
17416    fn policy_rate_limit_zero_takes_precedence_over_cap() {
17417        // The cross-arm ordering pin: `rate == 0` is structurally
17418        // outside both `1..` (zero-floor) and `..=POLICY_RATE_LIMIT_MAX`
17419        // (cap), but the zero-floor diagnostic is the more
17420        // self-locating one (it directly names the omit-axis
17421        // remediation). Pin the order so a future refactor that
17422        // reorders the arms surfaces here as a test failure rather
17423        // than a silent diagnostic regression. Same shape every other
17424        // zero-then-cap ordering on this surface uses
17425        // ([`AplicacaoError::PolicyRetriesZero`] then
17426        // [`AplicacaoError::PolicyRetriesExceedsCap`];
17427        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
17428        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
17429        let mut s = three_member_spec();
17430        s.politicas.rate_limit = Some(RateLimit {
17431            rate: 0,
17432            window: Duration::from_secs(1),
17433        });
17434        assert_eq!(
17435            s.validate().unwrap_err(),
17436            AplicacaoError::PolicyRateLimitZero,
17437            "rate == 0 must surface the zero-floor diagnostic, not the cap diagnostic"
17438        );
17439    }
17440
17441    #[test]
17442    fn policy_rate_limit_cap_takes_precedence_over_non_canonical_window() {
17443        // Two-axis-bad pin: rate above cap *and* window non-canonical.
17444        // The validate gate must fire on the rate cap first — the
17445        // amplification-shape (no-op limiter) diagnostic is the more
17446        // fundamental one; the window-canonical diagnostic is the
17447        // narrower codec-round-trip shape. Pin the ordering so a future
17448        // refactor that reorders the rate-then-window check arms
17449        // surfaces here as a test failure rather than a silent
17450        // diagnostic regression.
17451        let mut s = three_member_spec();
17452        s.politicas.rate_limit = Some(RateLimit {
17453            rate: POLICY_RATE_LIMIT_MAX + 1,
17454            window: Duration::from_secs(45),
17455        });
17456        assert_eq!(
17457            s.validate().unwrap_err(),
17458            AplicacaoError::PolicyRateLimitExceedsCap {
17459                rate: POLICY_RATE_LIMIT_MAX + 1
17460            },
17461            "above-cap rate must surface the cap diagnostic, not the window diagnostic"
17462        );
17463    }
17464
17465    #[test]
17466    fn policy_rate_limit_cap_diagnostic_carries_offending_value() {
17467        // The diagnostic-shape pin: the offending `u32` is carried
17468        // verbatim into the [`AplicacaoError::PolicyRateLimitExceedsCap`]
17469        // variant so the surfaced error message names the value the
17470        // author wrote (`":politicas :rate-limit rate (5000000) exceeds
17471        // the mesh-policy ceiling …"`), not just the cap. Same
17472        // self-locating diagnostic shape every other typed-cap arm on
17473        // this surface carries ([`AplicacaoError::PolicyRetriesExceedsCap`]
17474        // carries the offending retries count verbatim,
17475        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`] carries
17476        // the offending failure count verbatim).
17477        let mut s = three_member_spec();
17478        s.politicas.rate_limit = Some(RateLimit {
17479            rate: 5_000_000,
17480            window: Duration::from_secs(1),
17481        });
17482        let err = s.validate().unwrap_err();
17483        assert!(
17484            matches!(
17485                err,
17486                AplicacaoError::PolicyRateLimitExceedsCap { rate: 5_000_000 }
17487            ),
17488            "got {err:?}"
17489        );
17490        let msg = err.to_string();
17491        assert!(
17492            msg.contains("5000000"),
17493            ":politicas :rate-limit cap diagnostic must carry the offending value verbatim (got: {msg})"
17494        );
17495    }
17496
17497    #[test]
17498    fn policy_rate_limit_cap_pins_canonical_value() {
17499        // The [`POLICY_RATE_LIMIT_MAX`] constant pins the value at
17500        // 1_000_000 — two-to-three orders of magnitude above every
17501        // documented production-playbook recommendation band (Envoy /
17502        // Istio / Kong / NGINX 10..=10_000 RPS, Cloudflare / AWS API
17503        // Gateway 10_000..=100_000 per-minute) and below the
17504        // clearly-pathological "paste-from-binary blob" floor
17505        // (100_000_000, u32::MAX). Pinning the literal value here
17506        // surfaces a future drift (a relaxation to 10_000_000, a
17507        // tightening to 100_000) as a deliberate test edit, not a
17508        // silent contract narrowing.
17509        assert_eq!(POLICY_RATE_LIMIT_MAX, 1_000_000);
17510    }
17511
17512    #[test]
17513    fn rate_limit_zero_rate_takes_precedence_over_non_canonical_window() {
17514        // Both axes are invalid here: rate == 0 *and* window is
17515        // non-canonical. The validate gate must fire on rate first
17516        // (matching the existing `rejects_zero_rate_limit` ordering),
17517        // so the existing diagnostic continues to lead with the
17518        // simpler "zero rate" framing. Pinning the order of checks
17519        // so a future refactor that reorders the arms surfaces here
17520        // as a test failure rather than a silent diagnostic
17521        // regression.
17522        let mut s = three_member_spec();
17523        s.politicas.rate_limit = Some(RateLimit {
17524            rate: 0,
17525            window: Duration::from_secs(45),
17526        });
17527        assert_eq!(
17528            s.validate().unwrap_err(),
17529            AplicacaoError::PolicyRateLimitZero
17530        );
17531    }
17532
17533    #[test]
17534    fn rate_limit_canonical_windows_validate() {
17535        // The three canonical windows the codec round-trips
17536        // losslessly — 1s / 60s / 3600s — must all pass `validate()`
17537        // unchanged. Pin the full canonical set as a positive case
17538        // (the existing `rate_limit_round_trip_seconds` /
17539        // `rate_limit_round_trip_minutes` tests pin the
17540        // serialize-then-deserialize property at the codec layer; this
17541        // test pins the validate-side complement so a future tightening
17542        // of the canonical set — e.g. dropping `:hour` — surfaces here
17543        // as a test failure rather than a silent contract narrowing).
17544        for secs in [1u64, 60, 3600] {
17545            let mut s = three_member_spec();
17546            s.politicas.rate_limit = Some(RateLimit {
17547                rate: 100,
17548                window: Duration::from_secs(secs),
17549            });
17550            s.validate().expect("canonical window must validate");
17551        }
17552    }
17553
17554    #[test]
17555    fn rate_limit_validated_value_round_trips_through_codec() {
17556        // The structural property the validate gate enforces:
17557        // every `RateLimit` past `AplicacaoSpec::validate` round-trips
17558        // losslessly through the `rate_limit_codec` (serialize → string
17559        // → deserialize → equal value). Pin this end-to-end so a future
17560        // change to either side (the validate gate's accepted window
17561        // set, the codec's parse/render unit set) that breaks the
17562        // alignment surfaces here. The previous-state shape (typed
17563        // slot accepts arbitrary `Duration`, codec only round-trips
17564        // 1s/60s/3600s) would fail this test for a `Duration::from_secs(45)`
17565        // window — the validate gate now forecloses that.
17566        for secs in [1u64, 60, 3600] {
17567            let mut s = three_member_spec();
17568            s.politicas.rate_limit = Some(RateLimit {
17569                rate: 250,
17570                window: Duration::from_secs(secs),
17571            });
17572            s.validate().unwrap();
17573            let json = serde_json::to_string(&s.politicas).unwrap();
17574            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17575            assert_eq!(
17576                back.rate_limit, s.politicas.rate_limit,
17577                "every validated :rate-limit must round-trip losslessly through the codec"
17578            );
17579        }
17580    }
17581
17582    #[test]
17583    fn rate_limit_canonical_per_hour_renders_with_h_suffix() {
17584        // The hour-window canonical form (`"<n>/h"`) was missing from
17585        // the prior `rate_limit_round_trip_seconds` / `_minutes` test
17586        // pair. Now that the validate gate pins 3600s as part of the
17587        // canonical set, pin its serialize-side render shape too so
17588        // the third leg of the s/m/h tripod is explicitly tested.
17589        let policy = MeshPolicy {
17590            rate_limit: Some(RateLimit {
17591                rate: 10000,
17592                window: Duration::from_secs(3600),
17593            }),
17594            ..Default::default()
17595        };
17596        let json = serde_json::to_string(&policy).unwrap();
17597        assert!(
17598            json.contains("\"10000/h\""),
17599            "hour-window canonical form must render with `h` suffix (got: {json})"
17600        );
17601        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
17602        assert_eq!(back.rate_limit.unwrap().window, Duration::from_secs(3600));
17603    }
17604
17605    #[test]
17606    fn canonical_rate_limit_window_set_tracks_codec_via_canonical_unit() {
17607        // Pin the substrate-primitive [`RateLimit::canonical_unit`]
17608        // typed accessor's accepted-window set against the codec's
17609        // accepted set explicitly. A future addition to the codec
17610        // (e.g. accepting `:day`/`:week` as authoring units) must be
17611        // accompanied by a parallel addition here, and a regression
17612        // that drops one of the three canonical units from either
17613        // side surfaces as a test failure. The accessor is the
17614        // single source of truth for the canonical-window set —
17615        // [`AplicacaoSpec::validate_politicas`]'s canonical-window
17616        // gate and [`rate_limit_codec::render`]'s canonical arm both
17617        // read through it — this test enshrines that its
17618        // `Duration → Option<RateLimitUnit>` projection matches the
17619        // codec's parse / render arms' accepted-window set exactly.
17620        //
17621        // Predecessor: this pin previously read the module-private
17622        // free helper `is_canonical_rate_limit_window` — a delegate
17623        // that composed [`RateLimitUnit::from_window`] with `.is_some()`
17624        // — but the helper had no production consumers left after the
17625        // validate-gate migration onto [`RateLimit::canonical_unit`]
17626        // and was deleted; the closed-set arm-window bijection now
17627        // lives on exactly one typed dispatch on the substrate
17628        // primitive.
17629        let canonical_unit = |window: Duration| -> Option<super::RateLimitUnit> {
17630            RateLimit { rate: 1, window }.canonical_unit()
17631        };
17632        assert!(canonical_unit(Duration::from_secs(1)).is_some());
17633        assert!(canonical_unit(Duration::from_secs(60)).is_some());
17634        assert!(canonical_unit(Duration::from_secs(3600)).is_some());
17635        // Non-canonical windows the accessor rejects.
17636        assert!(canonical_unit(Duration::ZERO).is_none());
17637        assert!(canonical_unit(Duration::from_secs(2)).is_none());
17638        assert!(canonical_unit(Duration::from_secs(30)).is_none());
17639        assert!(canonical_unit(Duration::from_secs(120)).is_none());
17640        assert!(canonical_unit(Duration::from_secs(86400)).is_none());
17641        // Sub-second windows: even `Duration::from_millis(1000)` is
17642        // exactly 1s and accepted; `Duration::from_millis(500)` is
17643        // sub-second and rejected.
17644        assert!(canonical_unit(Duration::from_millis(1000)).is_some());
17645        assert!(canonical_unit(Duration::from_millis(500)).is_none());
17646        assert!(canonical_unit(Duration::from_millis(1500)).is_none());
17647    }
17648
17649    #[test]
17650    fn rate_limit_unit_table_projections_are_mutual_inverses() {
17651        // Bidirection pin against the closed-set typed enum
17652        // [`RateLimitUnit`] arm-table (the canonical
17653        // `{"s" ↔ 1s, "m" ↔ 60s, "h" ↔ 3600s}` bijection every consumer
17654        // of the rate-limit unit surface reads from). The two
17655        // projection directions [`RateLimitUnit::from_suffix`] /
17656        // [`RateLimitUnit::window`] (str → Duration, exposed as one
17657        // typed dispatch through [`RateLimitUnit::window_from_suffix`])
17658        // and [`RateLimitUnit::from_window`] / [`RateLimitUnit::as_suffix`]
17659        // (Duration → str, exposed as one typed dispatch through
17660        // [`RateLimit::canonical_unit`] composed with
17661        // [`RateLimitUnit::as_suffix`]) are the substrate primitives the
17662        // codec's parse arm ([`rate_limit_codec::parse`] via
17663        // [`RateLimitUnit::window_from_suffix`]), the codec's render arm
17664        // ([`rate_limit_codec::render`] via [`RateLimit::canonical_unit`]),
17665        // and the validate gate ([`AplicacaoSpec::validate_politicas`]
17666        // via [`RateLimit::canonical_unit`]) all key off. A future
17667        // rate-limit-unit addition (a `"d"` day suffix, a `"ms"`
17668        // sub-second window) is one variant + one arm per method on the
17669        // closed-set enum; the compiler-enforced exhaustiveness on
17670        // every consumer's `match self` arms picks it up by
17671        // construction. This pin enshrines that both projection
17672        // directions agree on every canonical arm row and neither
17673        // leaks a spurious entry the other doesn't recognize.
17674        //
17675        // Predecessor: this test previously read the two vestigial
17676        // module-private free helpers `rate_limit_window_unit` and
17677        // `rate_limit_window_from_unit` on the `Duration → &str` and
17678        // `&str → Duration` axes; the former was deleted after its
17679        // sole production consumer ([`rate_limit_codec::render`])
17680        // migrated onto [`RateLimit::canonical_unit`] (61421a6), and
17681        // the latter is folded here into the substrate primitive
17682        // [`RateLimitUnit::window_from_suffix`] so both projection
17683        // directions live on the closed-set enum's arm-table.
17684        for (unit, secs) in [("s", 1u64), ("m", 60), ("h", 3600)] {
17685            let window = super::RateLimitUnit::window_from_suffix(unit)
17686                .unwrap_or_else(|| panic!("canonical unit {unit:?} must resolve to a Duration"));
17687            assert_eq!(
17688                window,
17689                Duration::from_secs(secs),
17690                "unit {unit:?} must resolve to {secs}s"
17691            );
17692            let projected_suffix = RateLimit { rate: 1, window }
17693                .canonical_unit()
17694                .map(super::RateLimitUnit::as_suffix);
17695            assert_eq!(
17696                projected_suffix,
17697                Some(unit),
17698                "Duration({secs}s) must render as {unit:?} \
17699                 via RateLimit::canonical_unit + RateLimitUnit::as_suffix"
17700            );
17701        }
17702        // Non-table units yield None on the `unit → Duration`
17703        // projection — a future `"d"` addition to the table would
17704        // flip this arm; today it pins the current three-row table's
17705        // rejection semantics.
17706        assert!(super::RateLimitUnit::window_from_suffix("d").is_none());
17707        assert!(super::RateLimitUnit::window_from_suffix("ms").is_none());
17708        assert!(super::RateLimitUnit::window_from_suffix("").is_none());
17709        // Non-table Durations yield None on the `Duration → unit`
17710        // projection — pins that the two projections agree on the
17711        // "not in the table" semantic too, so a drift where the
17712        // parse-side accepts a value the render-side can't emit is
17713        // a build error at the two-arm pair, not a silent codec
17714        // round-trip break.
17715        let projected_suffix = |window: Duration| -> Option<&'static str> {
17716            RateLimit { rate: 1, window }
17717                .canonical_unit()
17718                .map(super::RateLimitUnit::as_suffix)
17719        };
17720        assert!(projected_suffix(Duration::from_secs(2)).is_none());
17721        assert!(projected_suffix(Duration::from_secs(86_400)).is_none());
17722        assert!(projected_suffix(Duration::from_millis(1500)).is_none());
17723    }
17724
17725    #[test]
17726    fn rate_limit_unit_window_from_suffix_composes_from_suffix_and_window() {
17727        // Byte-parity pin on the [`RateLimitUnit::window_from_suffix`]
17728        // substrate-primitive `&str → Duration` associated method the
17729        // codec's parse arm ([`rate_limit_codec::parse`]) now routes
17730        // through. Every canonical arm (`"s"`, `"m"`, `"h"`) must resolve
17731        // to the same [`Duration`] the two-step composition
17732        // [`RateLimitUnit::from_suffix`] with [`RateLimitUnit::window`]
17733        // returns; every non-arm suffix (`"d"`, `"ms"`, `""`, `"seconds"`,
17734        // `"MIN"`) must project to [`None`] on both paths. A future
17735        // implementation of `window_from_suffix` that took a shortcut
17736        // through a per-suffix `match` table (bypassing the arm-table's
17737        // `Self::from_suffix` scan and the arm-table's `Self::window`
17738        // dispatch) would silently split the accept-set — the parse
17739        // arm would accept a suffix the enum's arm-table doesn't know,
17740        // or reject a suffix the enum's arm-table does; this pin
17741        // surfaces that drift at caixa-core build time rather than at a
17742        // downstream serde round-trip audit on a live `MeshPolicy`.
17743        //
17744        // Same byte-parity discipline the sibling
17745        // [`canonical_rate_limit_window_set_tracks_codec_via_canonical_unit`]
17746        // pin carries on the peer `Duration → RateLimitUnit` axis via
17747        // [`RateLimit::canonical_unit`], and the peer
17748        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
17749        // carries on the bidirectional arm-table axis — extended here
17750        // onto the fifth (and last unlifted) projection axis on the
17751        // closed-set enum's arm-table.
17752        let composition = |suffix: &str| -> Option<Duration> {
17753            super::RateLimitUnit::from_suffix(suffix).map(super::RateLimitUnit::window)
17754        };
17755        for suffix in ["s", "m", "h"] {
17756            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17757            let via_composition = composition(suffix);
17758            assert_eq!(
17759                via_method, via_composition,
17760                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17761                 from_suffix({suffix:?}).map(window) — the substrate-primitive \
17762                 method must delegate to the arm-table's two typed dispatches, \
17763                 not shortcut through a per-suffix match table"
17764            );
17765            assert!(
17766                via_method.is_some(),
17767                "canonical suffix {suffix:?} must resolve to Some(Duration) via \
17768                 RateLimitUnit::window_from_suffix"
17769            );
17770        }
17771        for suffix in ["d", "ms", "", "seconds", "MIN", "S", "H", "/"] {
17772            let via_method = super::RateLimitUnit::window_from_suffix(suffix);
17773            let via_composition = composition(suffix);
17774            assert_eq!(
17775                via_method, via_composition,
17776                "RateLimitUnit::window_from_suffix({suffix:?}) must byte-equal \
17777                 from_suffix({suffix:?}).map(window) on the non-arm rejection \
17778                 axis too"
17779            );
17780            assert!(
17781                via_method.is_none(),
17782                "non-arm suffix {suffix:?} must project to None via \
17783                 RateLimitUnit::window_from_suffix — a future extension that \
17784                 accepted this suffix without a corresponding arm on the enum \
17785                 would split the codec's parse-accepted set from the enum's \
17786                 arm-table"
17787            );
17788        }
17789        // And the codec's parse arm now reads through this method: a
17790        // canonical `"100/<u>"` MeshPolicy JSON payload round-trips to
17791        // the same `Duration` the method returns for its unit, closing
17792        // the two-consumer drift surface (the codec's parse arm and the
17793        // enum's arm-table) with one typed dispatch on the substrate
17794        // primitive.
17795        for suffix in ["s", "m", "h"] {
17796            let wire = format!(r#"{{"rateLimit":"100/{suffix}"}}"#);
17797            let mp: MeshPolicy = serde_json::from_str(&wire)
17798                .unwrap_or_else(|e| panic!("wire {wire:?} must parse: {e}"));
17799            let parsed = mp.rate_limit().expect("rate_limit payload present");
17800            let via_method = super::RateLimitUnit::window_from_suffix(suffix)
17801                .unwrap_or_else(|| panic!("suffix {suffix:?} must resolve via window_from_suffix"));
17802            assert_eq!(
17803                parsed.window(),
17804                via_method,
17805                "codec parse arm on {wire:?} must resolve the window through \
17806                 RateLimitUnit::window_from_suffix, not a divergent path"
17807            );
17808        }
17809    }
17810
17811    #[test]
17812    fn rate_limit_unit_all_enumerates_every_arm_once() {
17813        // Fail-before-pass-after pin: [`RateLimitUnit::ALL`] must
17814        // enumerate every arm of the closed-set enum exactly once, in
17815        // the canonical shortest-to-longest window order (Second before
17816        // Minute before Hour) — the same order the sibling
17817        // [`crate::supervisor::RestartStrategy`] /
17818        // [`crate::supervisor::RestartPolicy`] /
17819        // [`crate::PlacementStrategy`] / [`crate::CaixaKind`] closed-set
17820        // typed enums carry (the arm declared first is the arm listed
17821        // first). A future variant addition that extends the enum
17822        // without appending to [`RateLimitUnit::ALL`] leaves the
17823        // exhaustive iteration surface silently short one arm — the
17824        // codec's parse arm would then reject the new suffix even
17825        // though the enum knows it. This pin closes the drift.
17826        assert_eq!(
17827            super::RateLimitUnit::ALL,
17828            &[
17829                super::RateLimitUnit::Second,
17830                super::RateLimitUnit::Minute,
17831                super::RateLimitUnit::Hour,
17832            ],
17833            "RateLimitUnit::ALL must enumerate every arm exactly once, \
17834             in canonical shortest-to-longest window order"
17835        );
17836    }
17837
17838    #[test]
17839    fn rate_limit_unit_from_suffix_and_as_suffix_round_trip() {
17840        // Total round-trip pin on the `(from_suffix, as_suffix)` pair:
17841        // every arm's [`RateLimitUnit::as_suffix`] output must parse
17842        // back through [`RateLimitUnit::from_suffix`] to the same
17843        // variant. A future arm addition that lands `as_suffix` but
17844        // forgets `from_suffix` (`from_suffix` iterates
17845        // [`RateLimitUnit::ALL`] so the peer arm's inclusion in `ALL`
17846        // is the load-bearing carrier of the round-trip; the sibling
17847        // `rate_limit_unit_all_enumerates_every_arm_once` pin covers
17848        // the `ALL` half) trips here at caixa-core build time rather
17849        // than surfacing as a codec round-trip miss (a `render` emit
17850        // that lands a suffix the paired `parse` cannot decode).
17851        for unit in super::RateLimitUnit::ALL {
17852            let suffix = unit.as_suffix();
17853            let parsed = super::RateLimitUnit::from_suffix(suffix).unwrap_or_else(|| {
17854                panic!(
17855                    "RateLimitUnit::from_suffix({suffix:?}) must accept every \
17856                     RateLimitUnit::as_suffix output — got None for {unit:?}"
17857                )
17858            });
17859            assert_eq!(
17860                parsed, *unit,
17861                "RateLimitUnit::from_suffix(RateLimitUnit::{unit:?}.as_suffix()) \
17862                 must return RateLimitUnit::{unit:?}"
17863            );
17864        }
17865    }
17866
17867    #[test]
17868    fn rate_limit_unit_from_window_and_window_round_trip() {
17869        // Total round-trip pin on the `(from_window, window)` pair:
17870        // every arm's [`RateLimitUnit::window`] output must parse back
17871        // through [`RateLimitUnit::from_window`] to the same variant.
17872        // Sibling of `rate_limit_unit_from_suffix_and_as_suffix_round_trip`
17873        // on the peer `Duration` axis — the two round-trip pins
17874        // together enshrine that both projections of the typed
17875        // canonical-unit bijection are total on the arm-set.
17876        for unit in super::RateLimitUnit::ALL {
17877            let window = unit.window();
17878            let parsed = super::RateLimitUnit::from_window(window).unwrap_or_else(|| {
17879                panic!(
17880                    "RateLimitUnit::from_window({window:?}) must accept every \
17881                     RateLimitUnit::window output — got None for {unit:?}"
17882                )
17883            });
17884            assert_eq!(
17885                parsed, *unit,
17886                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17887                 must return RateLimitUnit::{unit:?}"
17888            );
17889        }
17890    }
17891
17892    #[test]
17893    fn rate_limit_unit_from_window_accessor_is_const_fn() {
17894        // Fail-before-pass-after pin: witnesses the
17895        // [`RateLimitUnit::from_window`] `const`-eval posture via a
17896        // `const fn` wrapper `from_window_via_const_fn(window: Duration)
17897        // -> Option<RateLimitUnit>` whose body calls
17898        // `RateLimitUnit::from_window(window)`, well-formed only when
17899        // the callee is itself `const fn` (any future downgrade to
17900        // non-`const` fails at caixa-core build time with E0015 `cannot
17901        // call non-const function`, strictly stronger than a runtime
17902        // `assert!`, side-stepping the destructor-in-const restriction
17903        // that blocks direct `const _: Option<RateLimitUnit> =
17904        // RateLimitUnit::from_window(...)` items on `Duration`'s
17905        // carrier). The runtime body sweeps every closed-set
17906        // [`RateLimitUnit::ALL`] arm plus a representative non-canonical
17907        // rejection sample (`Duration::from_millis(500)` sub-second
17908        // residue) and asserts the wrapped and direct dispatches agree
17909        // — a violation means the wrapper stopped compiling under a
17910        // future `const`-posture downgrade, or the reverse resolver's
17911        // arm-set silently split from the peer `Self::window` emitter's
17912        // arm-set. Peer of the sibling
17913        // [`crate::supervisor::tests::child_spec_restart_accessor_is_const_fn`]
17914        // (152c868) /
17915        // [`crate::supervisor::tests::supervisor_spec_estrategia_accessor_is_const_fn`]
17916        // (152c868) /
17917        // [`entrada_port_accessor_is_const_fn`] (bafa004) /
17918        // [`placement_estrategia_accessor_is_const_fn`] (bafa004)
17919        // `const`-eval-surface pins on the peer M2 / M3 substrate-
17920        // primitive `Copy`-return accessor axes, extended onto the
17921        // reverse `Duration → RateLimitUnit` projection axis on the
17922        // M3 mesh-slot rate-limit closed-set typed enum.
17923        const fn from_window_via_const_fn(window: Duration) -> Option<super::RateLimitUnit> {
17924            super::RateLimitUnit::from_window(window)
17925        }
17926        for unit in super::RateLimitUnit::ALL {
17927            let window = unit.window();
17928            let via_wrapper = from_window_via_const_fn(window);
17929            let direct = super::RateLimitUnit::from_window(window);
17930            assert_eq!(
17931                via_wrapper, direct,
17932                "RateLimitUnit::from_window({window:?}) via const fn \
17933                 wrapper must agree with direct dispatch for {unit:?}"
17934            );
17935            assert_eq!(
17936                via_wrapper,
17937                Some(*unit),
17938                "RateLimitUnit::from_window({window:?}) via const fn \
17939                 wrapper must return Some({unit:?}) for the peer \
17940                 window() output"
17941            );
17942        }
17943        assert!(from_window_via_const_fn(Duration::from_millis(500)).is_none());
17944        assert!(from_window_via_const_fn(Duration::from_secs(30)).is_none());
17945    }
17946
17947    #[test]
17948    fn rate_limit_unit_from_window_composes_through_window_accessor() {
17949        // Composition-witness pin on the routing-through-peer discipline:
17950        // [`RateLimitUnit::from_window`]'s per-arm probes each dispatch
17951        // through the peer `pub const fn` [`RateLimitUnit::window`]
17952        // canonical-`Duration` projection rather than a hand-authored
17953        // per-arm second-magnitude literal — a future arm-magnitude edit
17954        // on the sibling `window()` accessor (a `Second → 2s` typo, a
17955        // `Hour → 3599s` off-by-one) must therefore reach this reverse
17956        // resolver by construction. A pin that hard-coded the three
17957        // second-magnitudes here would silently split from the peer
17958        // emitter on any such edit; instead, this pin asserts the
17959        // composition invariant `from_window(u.window()) == Some(u)`
17960        // holds byte-for-byte on every closed-set [`RateLimitUnit::ALL`]
17961        // arm — a violation means either the peer `Self::window`
17962        // accessor drifted (breaking every downstream consumer that
17963        // reads through it), or the reverse resolver stopped routing
17964        // through the peer (introducing a hand-authored literal that
17965        // silently disagrees with the emitter). Either failure is a
17966        // caixa-core-build-time surface, not a downstream renderer
17967        // round-trip regression.
17968        //
17969        // Peer of the sibling
17970        // [`crate::render::assert_str_reexport_identity`] discipline on
17971        // the substrate-primitive `&'static str` re-export axis and the
17972        // [`rate_limit_unit_from_window_and_window_round_trip`]
17973        // round-trip pin on the peer projection direction; extends the
17974        // one-canonical-dispatch-per-projection discipline onto the
17975        // reverse-resolver's per-arm probe axis.
17976        for unit in super::RateLimitUnit::ALL {
17977            let window_via_peer = unit.window();
17978            let resolved = super::RateLimitUnit::from_window(window_via_peer);
17979            assert_eq!(
17980                resolved,
17981                Some(*unit),
17982                "RateLimitUnit::from_window(RateLimitUnit::{unit:?}.window()) \
17983                 must return Some({unit:?}) — the reverse resolver's per-arm \
17984                 probes must route through the peer `Self::window` accessor \
17985                 so any future arm-magnitude edit reaches both projection \
17986                 directions by construction"
17987            );
17988        }
17989    }
17990
17991    #[test]
17992    fn rate_limit_canonical_unit_accessor_is_const_fn() {
17993        // Fail-before-pass-after pin: witnesses the
17994        // [`RateLimit::canonical_unit`] `const`-eval posture via a
17995        // `const fn` wrapper
17996        // `canonical_unit_via_const_fn(rl: &RateLimit) -> Option<RateLimitUnit>`
17997        // whose body calls `rl.canonical_unit()`, well-formed only when
17998        // the callee is itself `const fn` (any future downgrade to
17999        // non-`const` fails at caixa-core build time with E0015 `cannot
18000        // call non-const method`). The runtime body sweeps every
18001        // closed-set [`RateLimitUnit::ALL`] arm — for each arm,
18002        // constructs a typed [`RateLimit`] with the peer `Self::window`
18003        // canonical `Duration`, then asserts both the wrapper and the
18004        // direct dispatch agree and both return `Some(unit)`. Composes
18005        // with the sibling
18006        // [`rate_limit_unit_from_window_accessor_is_const_fn`] pin: the
18007        // typed [`RateLimit`] projection layer's `const`-posture is
18008        // load-bearing on the reverse resolver's `const`-posture, and
18009        // both must migrate together (a downgrade of either surface
18010        // splits the paired `const`-eval-surface pass on the M3
18011        // mesh-slot rate-limit `Duration ↔ Self` bijection).
18012        const fn canonical_unit_via_const_fn(
18013            rl: &super::RateLimit,
18014        ) -> Option<super::RateLimitUnit> {
18015            rl.canonical_unit()
18016        }
18017        for unit in super::RateLimitUnit::ALL {
18018            let rl = super::RateLimit {
18019                rate: 1,
18020                window: unit.window(),
18021            };
18022            let via_wrapper = canonical_unit_via_const_fn(&rl);
18023            let direct = rl.canonical_unit();
18024            assert_eq!(
18025                via_wrapper, direct,
18026                "RateLimit::canonical_unit() via const fn wrapper must \
18027                 agree with direct dispatch for {unit:?}"
18028            );
18029            assert_eq!(
18030                via_wrapper,
18031                Some(*unit),
18032                "RateLimit::canonical_unit() via const fn wrapper must \
18033                 return Some({unit:?}) for a RateLimit whose window is \
18034                 the peer RateLimitUnit::{unit:?}.window() output"
18035            );
18036        }
18037    }
18038
18039    #[test]
18040    fn rate_limit_unit_projections_are_pairwise_distinct() {
18041        // Distinctness pin: [`RateLimitUnit::as_suffix`] and
18042        // [`RateLimitUnit::window`] outputs must be pairwise distinct
18043        // across every arm — an accidental copy-paste flip that
18044        // reroutes one arm's suffix or window to also match another
18045        // silently collapses two arms onto one, so
18046        // [`RateLimitUnit::from_suffix`] / [`RateLimitUnit::from_window`]
18047        // (both using `find` on `Self::ALL`) would return whichever
18048        // arm the linear scan lands on first — a match-arm-ordering-
18049        // dependent outcome the closed-set typed-enum shape is meant
18050        // to rule out structurally. Peer of the sibling
18051        // `caixa_kind_wire_consts_are_pairwise_distinct` /
18052        // `caixa_kind_label_consts_are_pairwise_distinct` pins on the
18053        // other closed-set typed-enum discriminator axes.
18054        let all = super::RateLimitUnit::ALL;
18055        for (i, a) in all.iter().enumerate() {
18056            for (j, b) in all.iter().enumerate() {
18057                if i != j {
18058                    assert_ne!(
18059                        a.as_suffix(),
18060                        b.as_suffix(),
18061                        "RateLimitUnit::{a:?}.as_suffix() and {b:?}.as_suffix() \
18062                         must be distinct — a collision silently collapses two \
18063                         arms onto one under from_suffix's linear scan"
18064                    );
18065                    assert_ne!(
18066                        a.window(),
18067                        b.window(),
18068                        "RateLimitUnit::{a:?}.window() and {b:?}.window() \
18069                         must be distinct — a collision silently collapses two \
18070                         arms onto one under from_window's linear scan"
18071                    );
18072                }
18073            }
18074        }
18075    }
18076
18077    #[test]
18078    fn rate_limit_unit_display_routes_through_as_suffix() {
18079        // Route pin: [`std::fmt::Display`] must byte-equal
18080        // [`RateLimitUnit::as_suffix`] on every arm — the single
18081        // source of truth for the canonical suffix. A future
18082        // reimplementation that hand-rolls the arms instead of
18083        // delegating to [`RateLimitUnit::as_suffix`] would silently
18084        // desynchronize `format!("{u}")` from the codec's parse arm
18085        // (which uses `as_suffix` to compare suffixes). Peer of the
18086        // sibling `caixa_kind_display_routes_through_as_str_helper` /
18087        // `placement_strategy_display_routes_through_as_str_helper`
18088        // pins on the peer closed-set typed-enum Display axes.
18089        for unit in super::RateLimitUnit::ALL {
18090            assert_eq!(
18091                unit.to_string(),
18092                unit.as_suffix(),
18093                "RateLimitUnit::{unit:?} Display must route through \
18094                 as_suffix (single source of truth: the canonical suffix \
18095                 the codec parses and renders)"
18096            );
18097        }
18098    }
18099
18100    #[test]
18101    fn rate_limit_unit_from_window_rejects_non_canonical() {
18102        // Rejection pin on the parser's accept-set: any Duration
18103        // outside the three-arm [`RateLimitUnit::window`] output set
18104        // (sub-second residue, or a second-magnitude outside `{1, 60,
18105        // 3600}`) must return `None`. A future accidental widening of
18106        // the accept-set (rounding down sub-second residue to the
18107        // nearest arm, admitting `Duration::from_secs(30)` as a
18108        // half-minute unit) would silently drift the parser's accept-
18109        // set from the emitter's — a validated slot with a
18110        // non-canonical window would then round-trip through the
18111        // codec to a canonical form the author never wrote.
18112        assert!(super::RateLimitUnit::from_window(Duration::ZERO).is_none());
18113        assert!(super::RateLimitUnit::from_window(Duration::from_secs(2)).is_none());
18114        assert!(super::RateLimitUnit::from_window(Duration::from_secs(30)).is_none());
18115        assert!(super::RateLimitUnit::from_window(Duration::from_secs(120)).is_none());
18116        assert!(super::RateLimitUnit::from_window(Duration::from_secs(86_400)).is_none());
18117        assert!(super::RateLimitUnit::from_window(Duration::from_millis(500)).is_none());
18118        assert!(super::RateLimitUnit::from_window(Duration::from_millis(1500)).is_none());
18119    }
18120
18121    #[test]
18122    fn rate_limit_unit_from_suffix_rejects_unknown() {
18123        // Rejection pin on the suffix parser's accept-set: any string
18124        // outside the three-arm [`RateLimitUnit::as_suffix`] output
18125        // set must return `None`. Peer of the sibling
18126        // `caixa_kind_from_wire_rejects_unknown_byte_strings` pin on
18127        // the [`crate::CaixaKind`] `from_wire` accept-set.
18128        for bad in [
18129            "", "S", "M", "H", "sec", "min", "hour", "d", "ms", "ns", "us", "week", "1s", "s/",
18130            " s",
18131        ] {
18132            assert!(
18133                super::RateLimitUnit::from_suffix(bad).is_none(),
18134                "RateLimitUnit::from_suffix({bad:?}) must return None — the \
18135                 parser's accept-set is exactly the three RateLimitUnit::as_suffix \
18136                 outputs"
18137            );
18138        }
18139    }
18140
18141    #[test]
18142    fn rate_limit_canonical_unit_returns_typed_arm_on_validated_windows() {
18143        // Fail-before-pass-after pin on [`RateLimit::canonical_unit`]:
18144        // every canonical `:window` magnitude the validate gate
18145        // accepts must map to the paired [`RateLimitUnit`] arm through
18146        // this accessor. A future validate-gate rebrand that widened
18147        // the accepted-window set without extending [`RateLimitUnit`]
18148        // would silently split the accessor's `Some`-return set from
18149        // the validate gate's accept-set — a slot that satisfies
18150        // validate would land at the accessor with `None`, so a
18151        // consumer past validate that pattern-matches on the returned
18152        // `Some` would silently miss the newly-accepted magnitude.
18153        for (window_secs, expected) in [
18154            (1u64, super::RateLimitUnit::Second),
18155            (60, super::RateLimitUnit::Minute),
18156            (3600, super::RateLimitUnit::Hour),
18157        ] {
18158            let rl = RateLimit {
18159                rate: 100,
18160                window: Duration::from_secs(window_secs),
18161            };
18162            assert_eq!(
18163                rl.canonical_unit(),
18164                Some(expected),
18165                "RateLimit {{ window: {window_secs}s, .. }}.canonical_unit() \
18166                 must return Some({expected:?})"
18167            );
18168        }
18169        // Non-canonical windows the validate gate rejects also return
18170        // None here — the accessor is the typed-enum projection of
18171        // the sibling `is_canonical_rate_limit_window` predicate.
18172        let bad = RateLimit {
18173            rate: 100,
18174            window: Duration::from_secs(30),
18175        };
18176        assert!(
18177            bad.canonical_unit().is_none(),
18178            "RateLimit with a non-canonical window must return None from \
18179             canonical_unit — the validate gate rejects the same set"
18180        );
18181    }
18182
18183    #[test]
18184    fn rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix() {
18185        // Fail-before-pass-after byte-parity pin: for every canonical
18186        // window the [`rate_limit_codec::render`] arm's emitted string
18187        // equals `format!("{}/{}", rl.rate(), unit.as_suffix())` where
18188        // `unit = rl.canonical_unit().unwrap()`. Pins the migration from
18189        // the vestigial free helper [`rate_limit_window_unit`] (a
18190        // `find_map`-walked `Duration → &'static str` delegate) onto the
18191        // substrate primitive [`RateLimit::canonical_unit`] typed method
18192        // (a closed-set `match self.window` arm on
18193        // [`RateLimitUnit::from_window`], projected through
18194        // [`RateLimitUnit::as_suffix`] via the enum's
18195        // [`std::fmt::Display`] impl). A future re-routing of the render
18196        // arm through a differently-computed unit projection would break
18197        // this pin at build time rather than as a silent per-consumer
18198        // codec round-trip drift far from the substrate primitive edit.
18199        //
18200        // Sibling to the peer
18201        // [`rate_limit_unit_table_projections_are_mutual_inverses`] pin
18202        // on the free-helper axis: that pin locks the two projections
18203        // (`from_suffix` / `as_suffix` / `from_window` / `window`) agree
18204        // on the closed-set arm table; this pin locks the codec's render
18205        // arm reads through the typed accessor rather than the free
18206        // helper. Two production consumers of the canonical-unit axis
18207        // now key off one typed dispatch on the substrate primitive.
18208        for (window_secs, unit) in [
18209            (1u64, super::RateLimitUnit::Second),
18210            (60, super::RateLimitUnit::Minute),
18211            (3600, super::RateLimitUnit::Hour),
18212        ] {
18213            let rl = RateLimit {
18214                rate: 42,
18215                window: Duration::from_secs(window_secs),
18216            };
18217            let policy = MeshPolicy {
18218                rate_limit: Some(rl),
18219                ..Default::default()
18220            };
18221            let json = serde_json::to_string(&policy).unwrap();
18222            let expected = format!("\"{}/{}\"", rl.rate(), unit.as_suffix());
18223            assert!(
18224                json.contains(&expected),
18225                "rate_limit_codec::render must emit {expected} (via \
18226                 RateLimit::canonical_unit + RateLimitUnit::as_suffix) \
18227                 for a {window_secs}s window; serialized MeshPolicy was: {json}"
18228            );
18229            // And the accessor route resolves to the same typed unit
18230            // the render arm's Display formatting is asked to produce —
18231            // so a future edit that split the two paths (one through
18232            // the accessor, one through a re-introduced free helper)
18233            // trips this pin.
18234            assert_eq!(
18235                rl.canonical_unit(),
18236                Some(unit),
18237                "RateLimit::canonical_unit must return Some({unit:?}) for a \
18238                 {window_secs}s window; the codec render arm reads the same \
18239                 typed unit through this accessor"
18240            );
18241        }
18242    }
18243
18244    #[test]
18245    fn validate_politicas_rate_limit_canonical_window_gate_routes_through_canonical_unit() {
18246        // Fail-before-pass-after byte-parity pin on the validate gate's
18247        // canonical-window shape probe: every non-canonical `:window`
18248        // the free-helper predicate [`is_canonical_rate_limit_window`]
18249        // rejects is also rejected by the substrate primitive
18250        // [`RateLimit::canonical_unit`] `.is_none()` route the validate
18251        // gate now reads through, and vice versa on the accepted set
18252        // (the three canonical windows). Locks the migration from the
18253        // free helper onto the substrate primitive: a future re-routing
18254        // of one of the two paths through a differently-computed unit
18255        // projection would silently split the codec's accepted set from
18256        // the validate gate's accepted set — a two-consumer drift the
18257        // codec-round-trip pin
18258        // [`rate_limit_codec_render_routes_through_canonical_unit_and_as_suffix`]
18259        // above closes on the render arm and this pin closes on the
18260        // validate arm.
18261        for canonical_window_secs in [1u64, 60, 3600] {
18262            let mut s = three_member_spec();
18263            let rl = RateLimit {
18264                rate: 100,
18265                window: Duration::from_secs(canonical_window_secs),
18266            };
18267            s.politicas.rate_limit = Some(rl);
18268            assert!(
18269                s.validate().is_ok(),
18270                "canonical {canonical_window_secs}s window must pass \
18271                 validate_politicas — the validate gate now reads \
18272                 RateLimit::canonical_unit().is_none() and the accessor \
18273                 returns Some on every canonical arm"
18274            );
18275            assert!(
18276                rl.canonical_unit().is_some(),
18277                "canonical {canonical_window_secs}s window must resolve to \
18278                 Some on RateLimit::canonical_unit — the validate gate reads \
18279                 this accessor directly"
18280            );
18281        }
18282        for non_canonical_window_secs in [2u64, 30, 120, 86_400] {
18283            let mut s = three_member_spec();
18284            let rl = RateLimit {
18285                rate: 100,
18286                window: Duration::from_secs(non_canonical_window_secs),
18287            };
18288            s.politicas.rate_limit = Some(rl);
18289            assert_eq!(
18290                s.validate().unwrap_err(),
18291                AplicacaoError::PolicyRateLimitWindowNotCanonical {
18292                    window: rl.window(),
18293                },
18294                "non-canonical {non_canonical_window_secs}s window must be \
18295                 rejected by validate_politicas — the validate gate now \
18296                 keys off RateLimit::canonical_unit().is_none()"
18297            );
18298            assert!(
18299                rl.canonical_unit().is_none(),
18300                "non-canonical {non_canonical_window_secs}s window must \
18301                 resolve to None on RateLimit::canonical_unit — the two \
18302                 paths (the free helper the validate gate previously read \
18303                 and the substrate primitive the validate gate now reads) \
18304                 must agree on the same rejected set"
18305            );
18306        }
18307        // And the substrate-primitive [`RateLimit::canonical_unit`]
18308        // accessor's accepted-window set matches the codec's parse arm's
18309        // accepted-suffix set on every canonical / non-canonical shape,
18310        // so a future silent drift between the codec's accepted set and
18311        // the validate gate's accepted set is a build error at test time
18312        // (both consumers key off the same closed-set enum's `match self`
18313        // arms). The predecessor free helper `is_canonical_rate_limit_window`
18314        // — a delegate that composed [`RateLimitUnit::from_window`] with
18315        // `.is_some()` — was deleted after this migration; the
18316        // canonical-window set now lives on exactly one typed dispatch
18317        // on the substrate primitive.
18318        for (secs, expected) in [
18319            (1u64, true),
18320            (60, true),
18321            (3600, true),
18322            (2, false),
18323            (30, false),
18324            (86_400, false),
18325        ] {
18326            let window = Duration::from_secs(secs);
18327            let rl = RateLimit { rate: 1, window };
18328            assert_eq!(
18329                rl.canonical_unit().is_some(),
18330                expected,
18331                "RateLimit::canonical_unit().is_some() must agree with the \
18332                 codec-accepted canonical-window set on {secs}s"
18333            );
18334            let suffix_from_axis = super::RateLimitUnit::window_from_suffix(match secs {
18335                1 => "s",
18336                60 => "m",
18337                3600 => "h",
18338                _ => return,
18339            })
18340            .is_some_and(|d| d == window);
18341            if expected {
18342                assert!(
18343                    suffix_from_axis,
18344                    "the codec's `&str → Duration` axis \
18345                     ({secs}s) must round-trip to the same Duration the \
18346                     substrate primitive's accessor returns Some on"
18347                );
18348            }
18349        }
18350    }
18351
18352    #[test]
18353    fn rate_limit_unit_is_variant_predicates_partition_the_arm_set() {
18354        // Fail-before-pass-after pin on the [`gen_platform::IsVariant`]
18355        // derive: for each of the three variants, exactly one of the
18356        // generated `is_second` / `is_minute` / `is_hour` predicates
18357        // returns `true` and the other two return `false`. Peer of
18358        // the sibling
18359        // `caixa_kind_is_variant_predicates_partition_the_arm_set` /
18360        // sibling `IsVariant`-derived closed-set typed-enum pins.
18361        let rows: [(super::RateLimitUnit, [bool; 3]); 3] = [
18362            (super::RateLimitUnit::Second, [true, false, false]),
18363            (super::RateLimitUnit::Minute, [false, true, false]),
18364            (super::RateLimitUnit::Hour, [false, false, true]),
18365        ];
18366        for (variant, expected) in rows {
18367            let observed = [variant.is_second(), variant.is_minute(), variant.is_hour()];
18368            assert_eq!(
18369                observed, expected,
18370                "RateLimitUnit::{variant:?} is_* predicates must partition \
18371                 the arm set (second, minute, hour); got {observed:?}"
18372            );
18373        }
18374    }
18375
18376    #[test]
18377    fn rejects_policy_timeout_sub_millisecond() {
18378        // A purely sub-millisecond `Duration` (`from_micros(500)` =
18379        // 500_000 ns) is not the zero `Duration` — the `is_zero()`
18380        // arm passes — but `as_millis() == 0`, so the shared codec's
18381        // `render` arm returns the literal `"0s"`, which the
18382        // codec's `parse` arm then deserializes as `Duration::ZERO`
18383        // and the `PolicyTimeoutZero` zero-floor gate would reject
18384        // on re-validate. Pin the rejection at the typed slot's
18385        // canonical-floor gate so the round-trip break surfaces at
18386        // validate time, naming the offending `Duration`, rather
18387        // than at the next serialize → deserialize round-trip far
18388        // from the source `caixa.lisp`.
18389        let mut s = three_member_spec();
18390        let timeout = Duration::from_micros(500);
18391        s.politicas.timeout = Some(timeout);
18392        assert_eq!(
18393            s.validate().unwrap_err(),
18394            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
18395        );
18396    }
18397
18398    #[test]
18399    fn rejects_policy_timeout_non_integer_millisecond() {
18400        // A `Duration` with non-integer-millisecond residue
18401        // (`from_micros(1500)` = 1.5 ms = 1_500_000 ns) renders
18402        // through the shared codec's `render` arm as `"1ms"` (the
18403        // `as_millis()` floor truncates), which the codec's `parse`
18404        // arm then deserializes as `Duration::from_millis(1)` =
18405        // 1_000_000 ns — silently *different* from the original.
18406        // Pin the rejection so this round-trip break surfaces at
18407        // validate time, where the offending `Duration` is named,
18408        // rather than as a silent value-laundered round-trip on the
18409        // next codec round-trip.
18410        let mut s = three_member_spec();
18411        let timeout = Duration::from_micros(1500);
18412        s.politicas.timeout = Some(timeout);
18413        assert_eq!(
18414            s.validate().unwrap_err(),
18415            AplicacaoError::PolicyTimeoutNotCanonical { timeout }
18416        );
18417    }
18418
18419    #[test]
18420    fn accepts_policy_timeout_integer_millisecond_forms() {
18421        // The codec's accepted set — integer multiples of 1ms — is
18422        // the typed slot's accepted set: `1ms`, `500ms`, `30s`, `2m`,
18423        // `1h` all pass the canonical gate. Pin the canonical-forms
18424        // sweep so a future tightening of the codec's grammar (e.g.
18425        // dropping `:ms`) surfaces here as a test failure rather
18426        // than a silent contract narrowing on the typed slot.
18427        for timeout in [
18428            Duration::from_millis(1),
18429            Duration::from_millis(500),
18430            Duration::from_millis(1500),
18431            Duration::from_secs(30),
18432            Duration::from_secs(120),
18433            Duration::from_secs(3600),
18434        ] {
18435            let mut s = three_member_spec();
18436            s.politicas.timeout = Some(timeout);
18437            s.validate()
18438                .expect("integer-millisecond :timeout must validate");
18439        }
18440    }
18441
18442    #[test]
18443    fn policy_timeout_zero_takes_precedence_over_canonical() {
18444        // `Duration::ZERO` carries `subsec_nanos() == 0` and would
18445        // pass the canonical-millisecond gate; the more self-locating
18446        // `PolicyTimeoutZero` arm (which names the omit-axis
18447        // remediation directly) must fire first. Pin the ordering so
18448        // a future refactor that reorders the arms surfaces here as a
18449        // test failure rather than a silent diagnostic regression.
18450        let mut s = three_member_spec();
18451        s.politicas.timeout = Some(Duration::ZERO);
18452        assert_eq!(s.validate().unwrap_err(), AplicacaoError::PolicyTimeoutZero);
18453    }
18454
18455    #[test]
18456    fn policy_timeout_canonical_diagnostic_carries_offending_duration() {
18457        // The diagnostic envelope carries the offending `Duration`
18458        // verbatim so the author can grep their `caixa.lisp` for
18459        // `:timeout "<value>"` and fix it in one edit. Same
18460        // diagnostic shape every other typed-slot canonical-form
18461        // gate (`PolicyRateLimitWindowNotCanonical`) uses on the
18462        // peer `:rate-limit :window` axis.
18463        let mut s = three_member_spec();
18464        let timeout = Duration::from_nanos(1_000_001);
18465        s.politicas.timeout = Some(timeout);
18466        match s.validate().unwrap_err() {
18467            AplicacaoError::PolicyTimeoutNotCanonical { timeout: t } => {
18468                assert_eq!(t, timeout, "diagnostic must carry the offending Duration");
18469            }
18470            other => panic!("expected PolicyTimeoutNotCanonical, got {other:?}"),
18471        }
18472    }
18473
18474    #[test]
18475    fn rejects_policy_timeout_above_cap() {
18476        // The fail-before-pass-after pin: 3601s = 1h + 1s is
18477        // structurally one canonical-tick past the
18478        // [`POLICY_TIMEOUT_MAX`] ceiling (1h = 3600s) — an
18479        // integer-millisecond magnitude the canonical-form arm above
18480        // accepts cleanly, that the codec round-trips losslessly as
18481        // `"3601s"`, and that silently passed validate on every
18482        // pre-gate codebase because the typed slot's only checks were
18483        // the zero-floor and canonical-form arms. The mesh-level
18484        // deadline degenerates only at the runtime substrate (Envoy
18485        // / Cilium L7 timeout overlay) far from the source
18486        // `caixa.lisp` with no field naming the offending policy.
18487        let mut s = three_member_spec();
18488        let timeout = POLICY_TIMEOUT_MAX + Duration::from_secs(1);
18489        s.politicas.timeout = Some(timeout);
18490        assert_eq!(
18491            s.validate().unwrap_err(),
18492            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18493        );
18494    }
18495
18496    #[test]
18497    fn rejects_policy_timeout_one_millisecond_above_cap() {
18498        // Boundary case: exactly 1ms past the cap (the granularity
18499        // the canonical-form gate enforces). Catches a future
18500        // "strictly less than" half-measure and pins the diagnostic
18501        // to name the offending `Duration` verbatim. Peer of
18502        // [`crate::limits`]'s `validate_rejects_memory_one_byte_above_wasm32_cap`
18503        // boundary pin on the sibling `:limits :memory` top edge.
18504        let mut s = three_member_spec();
18505        let timeout = POLICY_TIMEOUT_MAX + Duration::from_millis(1);
18506        s.politicas.timeout = Some(timeout);
18507        assert_eq!(
18508            s.validate().unwrap_err(),
18509            AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18510        );
18511    }
18512
18513    #[test]
18514    fn rejects_policy_timeout_far_above_cap() {
18515        // The "obvious authoring footgun" case: a `(:timeout "24h")`
18516        // or `(:timeout "86400s")` — values the canonical-form arm
18517        // accepts as integer-millisecond magnitudes, the codec
18518        // round-trips losslessly through serde, but the mesh-level
18519        // policy cannot honor (a 24-hour synchronous-`:contratos`
18520        // deadline is operationally indistinguishable from
18521        // omit-the-axis). Until this gate landed validate accepted
18522        // it. Pin both common above-cap values (24h, 7d) so a future
18523        // relaxation that drops the upper bound surfaces here.
18524        for timeout in [
18525            Duration::from_secs(86_400),    // 24h
18526            Duration::from_secs(604_800),   // 7d
18527            Duration::from_secs(1_000_000), // ~11.5 days
18528        ] {
18529            let mut s = three_member_spec();
18530            s.politicas.timeout = Some(timeout);
18531            assert_eq!(
18532                s.validate().unwrap_err(),
18533                AplicacaoError::PolicyTimeoutExceedsCap { timeout }
18534            );
18535        }
18536    }
18537
18538    #[test]
18539    fn accepts_policy_timeout_at_cap() {
18540        // The boundary value — exactly [`POLICY_TIMEOUT_MAX`] (1h) —
18541        // must validate. The cap is inclusive on the top edge,
18542        // matching the [`POLICY_RETRIES_MAX`] /
18543        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] /
18544        // [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18545        // sibling capped axes. Pin the boundary explicitly so a
18546        // future off-by-one tightening (`>= POLICY_TIMEOUT_MAX`
18547        // instead of `>`) surfaces here as a test failure rather
18548        // than a silent contract narrowing.
18549        let mut s = three_member_spec();
18550        s.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
18551        s.validate()
18552            .expect("timeout == POLICY_TIMEOUT_MAX must validate");
18553    }
18554
18555    #[test]
18556    fn accepts_policy_timeout_typical_values() {
18557        // The documented production-playbook band positive-control
18558        // sweep — every value Envoy / Istio / Linkerd / AWS App Mesh
18559        // / Kubernetes ingress-nginx recommend (1s..=60s) must pass,
18560        // plus a sweep through the long-running-workflow band
18561        // (5m, 15m, 30m, 1h) the cap accepts. Pin the inclusive
18562        // validated set explicitly so a future tightening of the
18563        // ceiling surfaces here as a deliberate test edit, not a
18564        // silent contract narrowing.
18565        for timeout in [
18566            Duration::from_millis(1),
18567            Duration::from_millis(500),
18568            Duration::from_secs(1),
18569            Duration::from_secs(10),
18570            Duration::from_secs(15), // Envoy default
18571            Duration::from_secs(30),
18572            Duration::from_secs(60), // AWS App Mesh typical
18573            Duration::from_secs(300),
18574            Duration::from_secs(900),
18575            Duration::from_secs(1800),
18576            Duration::from_secs(3600), // exactly 1h, the cap
18577        ] {
18578            let mut s = three_member_spec();
18579            s.politicas.timeout = Some(timeout);
18580            s.validate()
18581                .unwrap_or_else(|e| panic!("timeout={timeout:?} must validate; got {e:?}"));
18582        }
18583    }
18584
18585    #[test]
18586    fn policy_timeout_zero_takes_precedence_over_cap() {
18587        // The cross-arm ordering pin: `Duration::ZERO` is
18588        // structurally outside both `>= 1ms` (zero-floor) and
18589        // `<= POLICY_TIMEOUT_MAX` (cap), but the zero-floor
18590        // diagnostic is the more self-locating one (it directly
18591        // names the omit-axis remediation), so the validate gate
18592        // must fire on zero first. Same shape every other
18593        // zero-then-shape ordering on this surface uses
18594        // ([`AplicacaoError::PolicyRetriesZero`] then
18595        // [`AplicacaoError::PolicyRetriesExceedsCap`];
18596        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18597        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18598        let mut s = three_member_spec();
18599        s.politicas.timeout = Some(Duration::ZERO);
18600        assert_eq!(
18601            s.validate().unwrap_err(),
18602            AplicacaoError::PolicyTimeoutZero,
18603            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18604        );
18605    }
18606
18607    #[test]
18608    fn policy_timeout_canonical_takes_precedence_over_cap() {
18609        // The cross-arm ordering pin: a `Duration` that is *both*
18610        // sub-millisecond (non-canonical-form) and structurally
18611        // above the cap surfaces the canonical-form diagnostic
18612        // first, because the round-trip-shape break is the more
18613        // fundamental issue (the value can't even round-trip
18614        // through the codec, so the cap diagnostic naming
18615        // `1ms..=1h` would be misleading — there's no integer-ms
18616        // form of the offending value). Pin the order so a future
18617        // refactor that reorders the arms surfaces here as a test
18618        // failure rather than a silent diagnostic regression.
18619        let mut s = three_member_spec();
18620        // A `Duration` with `subsec_nanos() == 1` (sub-ms residue)
18621        // *and* total magnitude above the 1h cap.
18622        let timeout = POLICY_TIMEOUT_MAX + Duration::from_nanos(1);
18623        s.politicas.timeout = Some(timeout);
18624        assert_eq!(
18625            s.validate().unwrap_err(),
18626            AplicacaoError::PolicyTimeoutNotCanonical { timeout },
18627            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18628        );
18629    }
18630
18631    #[test]
18632    fn policy_timeout_cap_diagnostic_carries_offending_value() {
18633        // The diagnostic-shape pin: the offending `Duration` is
18634        // carried verbatim into the
18635        // [`AplicacaoError::PolicyTimeoutExceedsCap`] variant so the
18636        // surfaced error message names the value the author wrote
18637        // (`":politicas :timeout (Duration { secs: 7200, nanos: 0 })
18638        // exceeds the mesh-policy ceiling …"`), not just the cap.
18639        // Same self-locating diagnostic shape every other typed-cap
18640        // arm on this surface carries
18641        // ([`AplicacaoError::PolicyRetriesExceedsCap`] carries the
18642        // offending retry count verbatim).
18643        let mut s = three_member_spec();
18644        let timeout = Duration::from_secs(7200); // 2h
18645        s.politicas.timeout = Some(timeout);
18646        let err = s.validate().unwrap_err();
18647        assert!(
18648            matches!(err, AplicacaoError::PolicyTimeoutExceedsCap { timeout: t } if t == timeout),
18649            "got {err:?}"
18650        );
18651        let msg = err.to_string();
18652        assert!(
18653            msg.contains("7200"),
18654            ":politicas :timeout cap diagnostic must carry the offending value verbatim (got: {msg})"
18655        );
18656    }
18657
18658    #[test]
18659    fn policy_timeout_cap_pins_canonical_value() {
18660        // The [`POLICY_TIMEOUT_MAX`] constant pins the value at
18661        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit
18662        // the shared duration codec emits as a clean canonical
18663        // string (`"<n>h"`). Pinning the literal value here surfaces
18664        // a future drift (a relaxation to 24h, a tightening to 5m)
18665        // as a deliberate test edit, not a silent contract
18666        // narrowing. Same shape every other typed-cap value pin on
18667        // this surface uses (`policy_retries_cap_is_aws_app_mesh_aligned`).
18668        assert_eq!(POLICY_TIMEOUT_MAX, Duration::from_secs(3600));
18669        assert_eq!(POLICY_TIMEOUT_MAX.as_millis(), 3_600_000);
18670    }
18671
18672    #[test]
18673    fn policy_timeout_cap_value_round_trips_through_codec() {
18674        // The codec round-trip property the cap arm preserves: the
18675        // [`POLICY_TIMEOUT_MAX`] constant itself round-trips through
18676        // the shared duration codec — every value at the cap renders
18677        // to a clean canonical string (`"1h"`) and parses back to
18678        // the same `Duration`. Pin this so a future drift between
18679        // the cap constant and the codec's largest emitted unit
18680        // surfaces here. Same shape every other typed boundary pin
18681        // on this surface uses
18682        // (`wasm32_memory_cap_matches_parsed_4_gib`).
18683        let policy = MeshPolicy {
18684            timeout: Some(POLICY_TIMEOUT_MAX),
18685            ..Default::default()
18686        };
18687        let json = serde_json::to_string(&policy).unwrap();
18688        // The codec emits `"1h"` for the canonical 1-hour magnitude.
18689        assert!(
18690            json.contains("\"1h\""),
18691            "the POLICY_TIMEOUT_MAX value must render to the canonical \"1h\" form (got: {json})"
18692        );
18693        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
18694        assert_eq!(back.timeout, Some(POLICY_TIMEOUT_MAX));
18695    }
18696
18697    #[test]
18698    fn rejects_circuit_breaker_window_sub_millisecond() {
18699        // Peer of the `:timeout` sub-millisecond arm on the second
18700        // typed-`Duration` `:politicas` axis: a purely sub-ms
18701        // `Duration` (`from_micros(500)`) renders through the shared
18702        // codec as `"0s"`, which the codec parses back to
18703        // `Duration::ZERO`, which the `PolicyBreakerZeroWindow`
18704        // zero-floor gate then rejects on re-validate.
18705        let mut s = three_member_spec();
18706        let window = Duration::from_micros(500);
18707        s.politicas.circuit_breaker = Some(CircuitBreaker {
18708            max_failures: 5,
18709            window,
18710        });
18711        assert_eq!(
18712            s.validate().unwrap_err(),
18713            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18714        );
18715    }
18716
18717    #[test]
18718    fn rejects_circuit_breaker_window_non_integer_millisecond() {
18719        // Peer of the `:timeout` non-integer-ms arm: a `Duration`
18720        // with non-integer-millisecond residue renders through the
18721        // shared codec as the truncated `"<n>ms"` form, parsing back
18722        // to a *different* `Duration` on the next round-trip.
18723        let mut s = three_member_spec();
18724        let window = Duration::from_micros(1500);
18725        s.politicas.circuit_breaker = Some(CircuitBreaker {
18726            max_failures: 5,
18727            window,
18728        });
18729        assert_eq!(
18730            s.validate().unwrap_err(),
18731            AplicacaoError::PolicyBreakerWindowNotCanonical { window }
18732        );
18733    }
18734
18735    #[test]
18736    fn accepts_circuit_breaker_window_integer_millisecond_forms() {
18737        // The canonical-forms sweep on the breaker axis: every
18738        // integer-ms multiple the codec round-trips losslessly
18739        // passes the canonical gate.
18740        for window in [
18741            Duration::from_millis(1),
18742            Duration::from_millis(500),
18743            Duration::from_millis(1500),
18744            Duration::from_secs(30),
18745            Duration::from_secs(60),
18746            Duration::from_secs(3600),
18747        ] {
18748            let mut s = three_member_spec();
18749            s.politicas.circuit_breaker = Some(CircuitBreaker {
18750                max_failures: 5,
18751                window,
18752            });
18753            s.validate()
18754                .expect("integer-millisecond :circuit-breaker :window must validate");
18755        }
18756    }
18757
18758    #[test]
18759    fn circuit_breaker_zero_window_takes_precedence_over_canonical() {
18760        // `Duration::ZERO` would pass the canonical-ms gate (the
18761        // sub-ns residue is zero) but must surface the narrower
18762        // `PolicyBreakerZeroWindow` diagnostic with its omit-axis
18763        // remediation.
18764        let mut s = three_member_spec();
18765        s.politicas.circuit_breaker = Some(CircuitBreaker {
18766            max_failures: 5,
18767            window: Duration::ZERO,
18768        });
18769        assert_eq!(
18770            s.validate().unwrap_err(),
18771            AplicacaoError::PolicyBreakerZeroWindow
18772        );
18773    }
18774
18775    #[test]
18776    fn circuit_breaker_zero_failures_takes_precedence_over_window_canonical() {
18777        // Both axes invalid: max_failures == 0 *and* window is
18778        // sub-ms. The validate gate must fire on max_failures first
18779        // (matching the existing ordering pin
18780        // `rejects_circuit_breaker_zero_max_failures` enshrines), so
18781        // the existing diagnostic continues to lead with the simpler
18782        // "zero threshold" framing.
18783        let mut s = three_member_spec();
18784        s.politicas.circuit_breaker = Some(CircuitBreaker {
18785            max_failures: 0,
18786            window: Duration::from_micros(500),
18787        });
18788        assert_eq!(
18789            s.validate().unwrap_err(),
18790            AplicacaoError::PolicyBreakerZeroFailures
18791        );
18792    }
18793
18794    #[test]
18795    fn circuit_breaker_window_canonical_diagnostic_carries_offending_duration() {
18796        let mut s = three_member_spec();
18797        let window = Duration::from_nanos(60_000_000_001);
18798        s.politicas.circuit_breaker = Some(CircuitBreaker {
18799            max_failures: 5,
18800            window,
18801        });
18802        match s.validate().unwrap_err() {
18803            AplicacaoError::PolicyBreakerWindowNotCanonical { window: w } => {
18804                assert_eq!(w, window, "diagnostic must carry the offending Duration");
18805            }
18806            other => panic!("expected PolicyBreakerWindowNotCanonical, got {other:?}"),
18807        }
18808    }
18809
18810    #[test]
18811    fn rejects_circuit_breaker_window_above_cap() {
18812        // The fail-before-pass-after pin: 3601s = 1h + 1s is
18813        // structurally one canonical-tick past the
18814        // [`POLICY_BREAKER_WINDOW_MAX`] ceiling (1h = 3600s) — an
18815        // integer-millisecond magnitude the canonical-form arm above
18816        // accepts cleanly, that the codec round-trips losslessly as
18817        // `"3601s"`, and that silently passed validate on every
18818        // pre-gate codebase because the typed slot's only checks were
18819        // the zero-floor and canonical-form arms. The
18820        // rolling-window-to-lifetime-counter degeneration surfaces
18821        // only at the runtime substrate (Envoy's outlier_detection
18822        // interval, the future CiliumClusterwideEnvoyConfig overlay)
18823        // far from the source `caixa.lisp` with no field naming the
18824        // offending policy.
18825        let mut s = three_member_spec();
18826        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18827        s.politicas.circuit_breaker = Some(CircuitBreaker {
18828            max_failures: 5,
18829            window,
18830        });
18831        assert_eq!(
18832            s.validate().unwrap_err(),
18833            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18834        );
18835    }
18836
18837    #[test]
18838    fn rejects_circuit_breaker_window_one_millisecond_above_cap() {
18839        // Boundary case: exactly 1ms past the cap (the granularity the
18840        // canonical-form gate enforces). Catches a future "strictly
18841        // less than" half-measure and pins the diagnostic to name the
18842        // offending `Duration` verbatim. Peer of
18843        // `rejects_policy_timeout_one_millisecond_above_cap` on the
18844        // sibling duration-typed `:politicas :timeout` top edge.
18845        let mut s = three_member_spec();
18846        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_millis(1);
18847        s.politicas.circuit_breaker = Some(CircuitBreaker {
18848            max_failures: 5,
18849            window,
18850        });
18851        assert_eq!(
18852            s.validate().unwrap_err(),
18853            AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18854        );
18855    }
18856
18857    #[test]
18858    fn rejects_circuit_breaker_window_far_above_cap() {
18859        // The "obvious authoring footgun" case: a `(:window "24h")` or
18860        // `(:window "86400s")` — values the canonical-form arm
18861        // accepts as integer-millisecond magnitudes, the codec
18862        // round-trips losslessly through serde, but the
18863        // rolling-window breaker contract cannot honor (a 24-hour
18864        // rolling failure window is operationally a lifetime counter).
18865        // Until this gate landed validate accepted it. Pin both common
18866        // above-cap values (24h, 7d) so a future relaxation that
18867        // drops the upper bound surfaces here.
18868        for window in [
18869            Duration::from_secs(86_400),    // 24h
18870            Duration::from_secs(604_800),   // 7d
18871            Duration::from_secs(1_000_000), // ~11.5 days
18872        ] {
18873            let mut s = three_member_spec();
18874            s.politicas.circuit_breaker = Some(CircuitBreaker {
18875                max_failures: 5,
18876                window,
18877            });
18878            assert_eq!(
18879                s.validate().unwrap_err(),
18880                AplicacaoError::PolicyBreakerWindowExceedsCap { window }
18881            );
18882        }
18883    }
18884
18885    #[test]
18886    fn accepts_circuit_breaker_window_at_cap() {
18887        // The boundary value — exactly [`POLICY_BREAKER_WINDOW_MAX`]
18888        // (1h) — must validate. The cap is inclusive on the top edge,
18889        // matching the [`POLICY_TIMEOUT_MAX`] /
18890        // [`POLICY_RETRIES_MAX`] / [`POLICY_BREAKER_MAX_FAILURES_MAX`]
18891        // / [`crate::LIMITS_MEMORY_WASM32_MAX_BYTES`] discipline on the
18892        // sibling capped axes. Pin the boundary explicitly so a
18893        // future off-by-one tightening (`>= POLICY_BREAKER_WINDOW_MAX`
18894        // instead of `>`) surfaces here as a test failure rather than
18895        // a silent contract narrowing.
18896        let mut s = three_member_spec();
18897        s.politicas.circuit_breaker = Some(CircuitBreaker {
18898            max_failures: 5,
18899            window: POLICY_BREAKER_WINDOW_MAX,
18900        });
18901        s.validate()
18902            .expect("window == POLICY_BREAKER_WINDOW_MAX must validate");
18903    }
18904
18905    #[test]
18906    fn accepts_circuit_breaker_window_typical_values() {
18907        // The documented production-playbook band positive-control
18908        // sweep — every value Hystrix / resilience4j / Istio / Envoy
18909        // / AWS App Mesh recommend (1s..=300s) must pass, plus a sweep
18910        // through the long-tail failure-detection band (15m, 30m, 1h)
18911        // the cap accepts. Pin the inclusive validated set explicitly
18912        // so a future tightening of the ceiling surfaces here as a
18913        // deliberate test edit, not a silent contract narrowing.
18914        for window in [
18915            Duration::from_millis(1),
18916            Duration::from_millis(500),
18917            Duration::from_secs(1),
18918            Duration::from_secs(10), // Hystrix / Istio / Envoy default
18919            Duration::from_secs(30),
18920            Duration::from_secs(60),  // resilience4j typical
18921            Duration::from_secs(300), // AWS App Mesh typical
18922            Duration::from_secs(900),
18923            Duration::from_secs(1800),
18924            Duration::from_secs(3600), // exactly 1h, the cap
18925        ] {
18926            let mut s = three_member_spec();
18927            s.politicas.circuit_breaker = Some(CircuitBreaker {
18928                max_failures: 5,
18929                window,
18930            });
18931            s.validate()
18932                .unwrap_or_else(|e| panic!("window={window:?} must validate; got {e:?}"));
18933        }
18934    }
18935
18936    #[test]
18937    fn circuit_breaker_zero_window_takes_precedence_over_cap() {
18938        // The cross-arm ordering pin: `Duration::ZERO` is structurally
18939        // outside both `>= 1ms` (zero-floor) and
18940        // `<= POLICY_BREAKER_WINDOW_MAX` (cap), but the zero-floor
18941        // diagnostic is the more self-locating one (it directly names
18942        // the omit-axis remediation), so the validate gate must fire
18943        // on zero first. Same shape every other zero-then-cap
18944        // ordering on this surface uses
18945        // ([`AplicacaoError::PolicyTimeoutZero`] then
18946        // [`AplicacaoError::PolicyTimeoutExceedsCap`];
18947        // [`AplicacaoError::PolicyBreakerZeroFailures`] then
18948        // [`AplicacaoError::PolicyBreakerMaxFailuresExceedsCap`]).
18949        let mut s = three_member_spec();
18950        s.politicas.circuit_breaker = Some(CircuitBreaker {
18951            max_failures: 5,
18952            window: Duration::ZERO,
18953        });
18954        assert_eq!(
18955            s.validate().unwrap_err(),
18956            AplicacaoError::PolicyBreakerZeroWindow,
18957            "Duration::ZERO must surface the zero-floor diagnostic, not the cap diagnostic"
18958        );
18959    }
18960
18961    #[test]
18962    fn circuit_breaker_window_canonical_takes_precedence_over_cap() {
18963        // The cross-arm ordering pin: a `Duration` that is *both*
18964        // sub-millisecond (non-canonical-form) and structurally above
18965        // the cap surfaces the canonical-form diagnostic first,
18966        // because the round-trip-shape break is the more fundamental
18967        // issue (the value can't even round-trip through the codec, so
18968        // the cap diagnostic naming `1ms..=1h` would be misleading —
18969        // there's no integer-ms form of the offending value). Pin the
18970        // order so a future refactor that reorders the arms surfaces
18971        // here as a test failure rather than a silent diagnostic
18972        // regression. Peer of
18973        // `policy_timeout_canonical_takes_precedence_over_cap` on the
18974        // sibling duration-typed `:politicas :timeout` axis.
18975        let mut s = three_member_spec();
18976        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_nanos(1);
18977        s.politicas.circuit_breaker = Some(CircuitBreaker {
18978            max_failures: 5,
18979            window,
18980        });
18981        assert_eq!(
18982            s.validate().unwrap_err(),
18983            AplicacaoError::PolicyBreakerWindowNotCanonical { window },
18984            "sub-ms above-cap value must surface the canonical-form diagnostic, not the cap diagnostic"
18985        );
18986    }
18987
18988    #[test]
18989    fn circuit_breaker_max_failures_cap_takes_precedence_over_window_cap() {
18990        // The cross-arm ordering pin between the two breaker axes: a
18991        // `CircuitBreaker` whose *both* `max_failures` is above its
18992        // cap *and* `window` is above its cap surfaces the
18993        // max-failures cap diagnostic first, because the validate
18994        // gate visits the failures arm before the window arm. Pin the
18995        // order so a future refactor that reorders the breaker arms
18996        // surfaces here.
18997        let mut s = three_member_spec();
18998        let window = POLICY_BREAKER_WINDOW_MAX + Duration::from_secs(1);
18999        s.politicas.circuit_breaker = Some(CircuitBreaker {
19000            max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1,
19001            window,
19002        });
19003        assert_eq!(
19004            s.validate().unwrap_err(),
19005            AplicacaoError::PolicyBreakerMaxFailuresExceedsCap {
19006                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX + 1
19007            },
19008            "both-axes-above-cap must surface the max-failures cap diagnostic first (arm order)"
19009        );
19010    }
19011
19012    #[test]
19013    fn circuit_breaker_window_cap_diagnostic_carries_offending_value() {
19014        // The diagnostic-shape pin: the offending `Duration` is
19015        // carried verbatim into the
19016        // [`AplicacaoError::PolicyBreakerWindowExceedsCap`] variant so
19017        // the surfaced error message names the value the author wrote
19018        // (`":politicas :circuit-breaker :window (Duration { secs:
19019        // 7200, nanos: 0 }) exceeds the mesh-policy ceiling …"`), not
19020        // just the cap. Same self-locating diagnostic shape every
19021        // other typed-cap arm on this surface carries
19022        // ([`AplicacaoError::PolicyTimeoutExceedsCap`] carries the
19023        // offending `Duration` verbatim).
19024        let mut s = three_member_spec();
19025        let window = Duration::from_secs(7200); // 2h
19026        s.politicas.circuit_breaker = Some(CircuitBreaker {
19027            max_failures: 5,
19028            window,
19029        });
19030        let err = s.validate().unwrap_err();
19031        assert!(
19032            matches!(err, AplicacaoError::PolicyBreakerWindowExceedsCap { window: w } if w == window),
19033            "got {err:?}"
19034        );
19035        let msg = err.to_string();
19036        assert!(
19037            msg.contains("7200"),
19038            ":politicas :circuit-breaker :window cap diagnostic must carry the offending value verbatim (got: {msg})"
19039        );
19040    }
19041
19042    #[test]
19043    fn circuit_breaker_window_cap_pins_canonical_value() {
19044        // The [`POLICY_BREAKER_WINDOW_MAX`] constant pins the value at
19045        // exactly 1 hour (3600s = 3_600_000ms) — the largest unit the
19046        // shared duration codec emits as a clean canonical string
19047        // (`"<n>h"`) and the same value [`POLICY_TIMEOUT_MAX`] pins on
19048        // the sibling duration-typed `:politicas :timeout` axis (the
19049        // two duration-typed `:politicas` axes share a uniform top
19050        // edge). Pinning the literal value here surfaces a future
19051        // drift (a relaxation to 24h, a tightening to 5m) as a
19052        // deliberate test edit, not a silent contract narrowing. Same
19053        // shape every other typed-cap value pin on this surface uses
19054        // (`policy_timeout_cap_pins_canonical_value`).
19055        assert_eq!(POLICY_BREAKER_WINDOW_MAX, Duration::from_secs(3600));
19056        assert_eq!(POLICY_BREAKER_WINDOW_MAX.as_millis(), 3_600_000);
19057        assert_eq!(
19058            POLICY_BREAKER_WINDOW_MAX, POLICY_TIMEOUT_MAX,
19059            "the two duration-typed `:politicas` caps share the same top edge"
19060        );
19061    }
19062
19063    #[test]
19064    fn circuit_breaker_window_cap_value_round_trips_through_codec() {
19065        // The codec round-trip property the cap arm preserves: the
19066        // [`POLICY_BREAKER_WINDOW_MAX`] constant itself round-trips
19067        // through the shared duration codec — every value at the cap
19068        // renders to a clean canonical string (`"1h"`) and parses back
19069        // to the same `Duration`. Pin this so a future drift between
19070        // the cap constant and the codec's largest emitted unit
19071        // surfaces here. Same shape every other typed boundary pin on
19072        // this surface uses
19073        // (`policy_timeout_cap_value_round_trips_through_codec`).
19074        let policy = MeshPolicy {
19075            circuit_breaker: Some(CircuitBreaker {
19076                max_failures: 5,
19077                window: POLICY_BREAKER_WINDOW_MAX,
19078            }),
19079            ..Default::default()
19080        };
19081        let json = serde_json::to_string(&policy).unwrap();
19082        // The codec emits `"1h"` for the canonical 1-hour magnitude.
19083        assert!(
19084            json.contains("\"1h\""),
19085            "the POLICY_BREAKER_WINDOW_MAX value must render to the canonical \"1h\" form (got: {json})"
19086        );
19087        let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19088        assert_eq!(
19089            back.circuit_breaker.unwrap().window,
19090            POLICY_BREAKER_WINDOW_MAX
19091        );
19092    }
19093
19094    #[test]
19095    fn is_integer_millisecond_duration_predicate_tracks_codec() {
19096        // Pin the predicate's accepted set against the codec's
19097        // accepted set explicitly. The codec parses
19098        // `<integer><unit>` for unit ∈ {`ms`,`s`,`m`,`h`} — every
19099        // accepted value is an integer-millisecond multiple — so the
19100        // predicate must accept exactly that set. Same shape every
19101        // other predicate-on-the-typed-slot helper carries
19102        // (`is_canonical_rate_limit_window_predicate_tracks_codec`).
19103        // Read directly from the codec-owned predicate — the crate's
19104        // single source of truth every typed-`Duration` axis now routes
19105        // through via
19106        // [`crate::render::require_positive_canonical_bounded_duration`].
19107        use super::supervisor::duration_codec::is_integer_millisecond_duration;
19108        assert!(is_integer_millisecond_duration(Duration::ZERO));
19109        assert!(is_integer_millisecond_duration(Duration::from_millis(1)));
19110        assert!(is_integer_millisecond_duration(Duration::from_millis(500)));
19111        assert!(is_integer_millisecond_duration(Duration::from_millis(1500)));
19112        assert!(is_integer_millisecond_duration(Duration::from_secs(30)));
19113        assert!(is_integer_millisecond_duration(Duration::from_secs(3600)));
19114        // Non-integer-millisecond residue: rejected.
19115        assert!(!is_integer_millisecond_duration(Duration::from_micros(1)));
19116        assert!(!is_integer_millisecond_duration(Duration::from_micros(500)));
19117        assert!(!is_integer_millisecond_duration(Duration::from_micros(
19118            1500
19119        )));
19120        assert!(!is_integer_millisecond_duration(Duration::from_nanos(1)));
19121        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
19122            999_999
19123        )));
19124        // The 1-ns-past-1ms boundary: rejected (no longer a clean
19125        // integer-millisecond multiple).
19126        assert!(!is_integer_millisecond_duration(Duration::from_nanos(
19127            1_000_001
19128        )));
19129    }
19130
19131    #[test]
19132    fn policy_timeout_validated_value_round_trips_through_codec() {
19133        // The structural property the canonical-ms gate enforces:
19134        // every `MeshPolicy::timeout` past `AplicacaoSpec::validate`
19135        // round-trips losslessly through the shared `duration_codec`
19136        // (serialize → string → deserialize → equal value). Pin this
19137        // end-to-end so a future change to either side (the validate
19138        // gate's accepted granularity, the codec's parse/render unit
19139        // set) that breaks the alignment surfaces here. The
19140        // previous-state shape (typed slot accepts arbitrary
19141        // `Duration`, codec only round-trips integer-ms) would fail
19142        // this test for any `Duration::from_micros(1500)` timeout —
19143        // the validate gate now forecloses that.
19144        for timeout in [
19145            Duration::from_millis(1),
19146            Duration::from_millis(1500),
19147            Duration::from_secs(30),
19148            Duration::from_secs(3600),
19149        ] {
19150            let mut s = three_member_spec();
19151            s.politicas.timeout = Some(timeout);
19152            s.validate().unwrap();
19153            let json = serde_json::to_string(&s.politicas).unwrap();
19154            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19155            assert_eq!(
19156                back.timeout, s.politicas.timeout,
19157                "every validated :timeout must round-trip losslessly through the codec"
19158            );
19159        }
19160    }
19161
19162    #[test]
19163    fn circuit_breaker_window_validated_value_round_trips_through_codec() {
19164        // Peer of the `:timeout` round-trip property on the breaker
19165        // axis.
19166        for window in [
19167            Duration::from_millis(1),
19168            Duration::from_millis(1500),
19169            Duration::from_secs(30),
19170            Duration::from_secs(3600),
19171        ] {
19172            let mut s = three_member_spec();
19173            s.politicas.circuit_breaker = Some(CircuitBreaker {
19174                max_failures: 5,
19175                window,
19176            });
19177            s.validate().unwrap();
19178            let json = serde_json::to_string(&s.politicas).unwrap();
19179            let back: MeshPolicy = serde_json::from_str(&json).unwrap();
19180            assert_eq!(
19181                back.circuit_breaker.unwrap().window,
19182                window,
19183                "every validated :circuit-breaker :window must round-trip losslessly"
19184            );
19185        }
19186    }
19187
19188    #[test]
19189    fn empty_politicas_validates() {
19190        // Omitting every policy axis is fine — defaults express "no
19191        // policy on this axis", not "policy = 0". The fixture's typical
19192        // values continue to validate; this test pins that
19193        // MeshPolicy::default() is a clean pass through validate().
19194        let mut s = three_member_spec();
19195        s.politicas = MeshPolicy::default();
19196        s.validate().unwrap();
19197    }
19198
19199    #[test]
19200    fn typical_politicas_validates_with_every_axis_set() {
19201        // The full §III.1 example block (timeout + retries + breaker +
19202        // mtls + rate-limit) — every axis nonzero — must remain a
19203        // clean pass.
19204        let mut s = three_member_spec();
19205        s.politicas = MeshPolicy {
19206            timeout: Some(Duration::from_secs(30)),
19207            retries: Some(3),
19208            circuit_breaker: Some(CircuitBreaker {
19209                max_failures: 5,
19210                window: Duration::from_secs(60),
19211            }),
19212            mtls_required: Some(true),
19213            rate_limit: Some(RateLimit {
19214                rate: 100,
19215                window: Duration::from_secs(1),
19216            }),
19217        };
19218        s.validate().unwrap();
19219    }
19220
19221    #[test]
19222    fn rejects_empty_cluster_name() {
19223        let mut s = three_member_spec();
19224        s.placement.clusters = vec!["rio".into(), String::new()];
19225        assert_eq!(
19226            s.validate().unwrap_err(),
19227            AplicacaoError::PlacementClusterEmpty
19228        );
19229    }
19230
19231    #[test]
19232    fn rejects_duplicate_cluster_names() {
19233        let mut s = three_member_spec();
19234        s.placement.clusters = vec!["rio".into(), "mar".into(), "rio".into()];
19235        let err = s.validate().unwrap_err();
19236        assert!(
19237            matches!(err, AplicacaoError::PlacementClusterDuplicate { ref cluster } if cluster == "rio"),
19238            "got {err:?}"
19239        );
19240    }
19241
19242    #[test]
19243    fn rejects_placement_cluster_with_uppercase() {
19244        // The canonical "I copied the cluster's display name verbatim"
19245        // typo — K8s context names are lowercase per DNS-1123 label
19246        // rule, but org docs often round-trip a TitleCase identifier
19247        // (`Rio`, `Mar-East`) from an ADR. Mirrors the
19248        // `rejects_membro_caixa_with_uppercase` gate's shape (3f9d7a0)
19249        // on the peer name axis.
19250        let mut s = three_member_spec();
19251        s.placement.clusters = vec!["Rio".into(), "mar".into()];
19252        let err = s.validate().unwrap_err();
19253        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19254            panic!("expected PlacementClusterInvalid, got other variant");
19255        };
19256        assert_eq!(cluster, "Rio");
19257        assert!(
19258            reason.contains("uppercase"),
19259            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19260        );
19261        assert!(
19262            reason.contains("\"rio\""),
19263            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19264        );
19265    }
19266
19267    #[test]
19268    fn rejects_placement_cluster_with_underscore() {
19269        // The canonical "I'm thinking of an env var / hostname slug"
19270        // leak — `_` is forbidden by every DNS-1123 / DNS-1035 label
19271        // schema. K8s context filtering on `my_cluster` silently misses
19272        // the cluster the author intended; the gate moves it to caixa-
19273        // build time. Same shape as `rejects_membro_caixa_with_underscore`
19274        // (3f9d7a0).
19275        let mut s = three_member_spec();
19276        s.placement.clusters = vec!["my_cluster".into()];
19277        let err = s.validate().unwrap_err();
19278        assert!(
19279            matches!(
19280                err,
19281                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19282                    if cluster == "my_cluster" && reason.contains('_')
19283            ),
19284            "got {err:?}"
19285        );
19286    }
19287
19288    #[test]
19289    fn rejects_placement_cluster_with_dot() {
19290        // A `:placement :clusters` entry is a single DNS-1123 *label*,
19291        // not a subdomain — even though K8s context names sometimes
19292        // carry a dotted form via kubeconfig conventions, the strictest
19293        // floor among the use sites (DNS-1035 cluster.x-k8s.io
19294        // `metadata.name`, Cilium identity label values) wins. The "I
19295        // want to namespace my cluster names with `.`" intent is
19296        // expressed via `-` (`mar-east`).
19297        let mut s = three_member_spec();
19298        s.placement.clusters = vec!["team.rio".into()];
19299        let err = s.validate().unwrap_err();
19300        assert!(
19301            matches!(
19302                err,
19303                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19304                    if cluster == "team.rio" && reason.contains('.')
19305            ),
19306            "got {err:?}"
19307        );
19308    }
19309
19310    #[test]
19311    fn rejects_placement_cluster_with_leading_hyphen() {
19312        // DNS-1123 / DNS-1035 boundary rule: labels must start and end
19313        // with an alphanumeric. The K8s apiserver rejects `-rio`
19314        // outright; the rendered fan-out would emit a `metadata.name:
19315        // "-rio"` that fails admission far from the source caixa.lisp.
19316        let mut s = three_member_spec();
19317        s.placement.clusters = vec!["-rio".into()];
19318        let err = s.validate().unwrap_err();
19319        assert!(
19320            matches!(
19321                err,
19322                AplicacaoError::PlacementClusterInvalid { ref cluster, ref reason }
19323                    if cluster == "-rio" && reason.contains("start and end")
19324            ),
19325            "got {err:?}"
19326        );
19327    }
19328
19329    #[test]
19330    fn rejects_placement_cluster_with_trailing_hyphen() {
19331        // The symmetric arm of the boundary rule. Pin separately so
19332        // both ends are covered against a future relaxation that only
19333        // checks one boundary (parallel to
19334        // `rejects_membro_caixa_with_trailing_hyphen`, 3f9d7a0).
19335        let mut s = three_member_spec();
19336        s.placement.clusters = vec!["rio-".into()];
19337        let err = s.validate().unwrap_err();
19338        assert!(
19339            matches!(
19340                err,
19341                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19342                    if cluster == "rio-"
19343            ),
19344            "got {err:?}"
19345        );
19346    }
19347
19348    #[test]
19349    fn rejects_placement_cluster_with_unicode() {
19350        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19351        // before it reaches K8s. The byte-by-byte ASCII validity check
19352        // rejects multi-byte UTF-8 sequences by the first byte that
19353        // fails `[a-z0-9-]`.
19354        let mut s = three_member_spec();
19355        s.placement.clusters = vec!["rió".into()];
19356        let err = s.validate().unwrap_err();
19357        assert!(
19358            matches!(
19359                err,
19360                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19361                    if cluster == "rió"
19362            ),
19363            "got {err:?}"
19364        );
19365    }
19366
19367    #[test]
19368    fn rejects_placement_cluster_with_whitespace() {
19369        // Whitespace is the canonical "I pasted from a sketch / doc"
19370        // footgun. The apiserver rejects every cluster `metadata.name`
19371        // value carrying whitespace.
19372        let mut s = three_member_spec();
19373        s.placement.clusters = vec!["rio cluster".into()];
19374        let err = s.validate().unwrap_err();
19375        assert!(
19376            matches!(
19377                err,
19378                AplicacaoError::PlacementClusterInvalid { ref cluster, .. }
19379                    if cluster == "rio cluster"
19380            ),
19381            "got {err:?}"
19382        );
19383    }
19384
19385    #[test]
19386    fn rejects_placement_cluster_too_long() {
19387        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
19388        // pin. The diagnostic names both the cap (63) and the actual
19389        // length so the author can shorten in one edit. Mirrors
19390        // `rejects_membro_caixa_too_long` (3f9d7a0).
19391        let mut s = three_member_spec();
19392        let too_long = "a".repeat(64);
19393        s.placement.clusters = vec![too_long.clone()];
19394        let err = s.validate().unwrap_err();
19395        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19396            panic!("expected PlacementClusterInvalid");
19397        };
19398        assert_eq!(cluster, too_long);
19399        assert!(
19400            reason.contains("63") && reason.contains("64"),
19401            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19402        );
19403    }
19404
19405    #[test]
19406    fn placement_cluster_max_length_validates() {
19407        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
19408        // future tightening (e.g. dropping to 62) surfaces here as a
19409        // regression, mirroring `membro_caixa_max_length_validates`
19410        // (3f9d7a0).
19411        let mut s = three_member_spec();
19412        s.placement.clusters = vec!["a".repeat(63)];
19413        s.validate().unwrap();
19414    }
19415
19416    #[test]
19417    fn accepts_canonical_placement_cluster_forms() {
19418        // The DNS-1123 label shapes a caixa author is realistically
19419        // going to write for cluster names: single-word lowercase
19420        // (`rio`), regional hyphen-joined (`mar-east`), single
19421        // character (`a` — boundary), digit-start (`3-prod` — DNS-1123
19422        // allows this, unlike DNS-1035), version-suffixed (`prod-v2`).
19423        // Pin every leg so a future tightening that bans (e.g.) digit-
19424        // start identifiers surfaces here.
19425        for form in ["rio", "mar", "mar-east", "a", "p1", "3-prod", "prod-v2"] {
19426            let mut s = three_member_spec();
19427            s.placement.clusters = vec![form.into()];
19428            s.validate().unwrap_or_else(|e| {
19429                panic!("canonical cluster form {form:?} must validate, got {e:?}")
19430            });
19431        }
19432    }
19433
19434    #[test]
19435    fn placement_cluster_empty_takes_precedence_over_invalid() {
19436        // Order pin: the existing `PlacementClusterEmpty` diagnostic
19437        // (which doesn't try to parse) fires before the new
19438        // `PlacementClusterInvalid` parse-side diagnostic, so an empty
19439        // `:clusters` entry keeps its narrower error message — the new
19440        // gate would also reject `""`, but the empty-string arm is the
19441        // more self-locating diagnostic. Mirrors the
19442        // `membro_caixa_empty_takes_precedence_over_invalid` pin
19443        // (3f9d7a0).
19444        let mut s = three_member_spec();
19445        s.placement.clusters = vec!["rio".into(), String::new()];
19446        let err = s.validate().unwrap_err();
19447        assert_eq!(err, AplicacaoError::PlacementClusterEmpty);
19448    }
19449
19450    #[test]
19451    fn placement_cluster_invalid_fires_before_duplicate_check() {
19452        // Order pin: a malformed-shape `:clusters` entry surfaces *its
19453        // own* diagnostic, even when a later entry would otherwise
19454        // collapse onto a duplicate name. The per-entry shape gate runs
19455        // inline before the duplicate-key insert, parallel to
19456        // `membro_caixa_invalid_fires_before_duplicate_check` (3f9d7a0).
19457        let mut s = three_member_spec();
19458        s.placement.clusters = vec!["Rio".into(), "rio".into()];
19459        let err = s.validate().unwrap_err();
19460        assert!(
19461            matches!(
19462                err,
19463                AplicacaoError::PlacementClusterInvalid { ref cluster, .. } if cluster == "Rio"
19464            ),
19465            "got {err:?}"
19466        );
19467    }
19468
19469    #[test]
19470    fn placement_cluster_invalid_diagnostic_carries_offending_cluster() {
19471        // The diagnostic-shape pin: the error names the offending
19472        // `:clusters` value verbatim so the author can grep their
19473        // caixa.lisp without re-running the build, and carries a
19474        // non-empty `reason` naming the specific violation. Same shape
19475        // every typed-shape gate enshrines
19476        // (3f9d7a0's `membro_caixa_invalid_diagnostic_carries_offending_caixa`,
19477        // c7d05ec's `entrada_host_diagnostic_carries_offending_host`).
19478        let mut s = three_member_spec();
19479        s.placement.clusters = vec!["BAD_CLUSTER".into()];
19480        let err = s.validate().unwrap_err();
19481        let AplicacaoError::PlacementClusterInvalid { cluster, reason } = err else {
19482            panic!("expected PlacementClusterInvalid");
19483        };
19484        assert_eq!(cluster, "BAD_CLUSTER");
19485        assert!(
19486            !reason.is_empty(),
19487            "PlacementClusterInvalid `reason` must carry a parser-shaped wording"
19488        );
19489    }
19490
19491    #[test]
19492    fn rejects_sharded_with_empty_clusters() {
19493        // §III.1: Sharded uses :clusters as the shard pool. An empty
19494        // pool means "shard across no clusters" — meaningless, same as
19495        // Replicated with no hosts.
19496        let mut s = three_member_spec();
19497        s.placement.estrategia = PlacementStrategy::Sharded;
19498        s.placement.shard_key = Some("$tenantId".into());
19499        s.placement.clusters = vec![];
19500        assert!(matches!(
19501            s.validate().unwrap_err(),
19502            AplicacaoError::PlacementWithoutClusters {
19503                estrategia: PlacementStrategy::Sharded
19504            }
19505        ));
19506    }
19507
19508    #[test]
19509    fn rejects_sharded_with_empty_shard_key() {
19510        let mut s = three_member_spec();
19511        s.placement.estrategia = PlacementStrategy::Sharded;
19512        s.placement.shard_key = Some(String::new());
19513        assert_eq!(s.validate().unwrap_err(), AplicacaoError::ShardedKeyEmpty);
19514    }
19515
19516    #[test]
19517    fn rejects_shard_key_under_replicated_strategy() {
19518        // The fail-before-pass-after pin: a `:placement (:estrategia
19519        // Replicated :shard-key "tenantId")` manifest carries the
19520        // hash-keyed-distribution slot on a strategy that never consumes
19521        // it. Before the gate the typed slot's value silently vanished
19522        // at the renderer layer (caixa-mesh emits `placement.shardKey`
19523        // verbatim regardless of strategy; the Akka-style cluster-
19524        // sharding reconciler keys off `estrategia == Sharded` and
19525        // ignores the slot otherwise), with no diagnostic. Lifting the
19526        // rejection to a build-time gate makes the
19527        // `shard_key.is_some() == matches!(estrategia, Sharded)`
19528        // partition a structural property of every validated
19529        // [`Placement`].
19530        let mut s = three_member_spec();
19531        // The fixture already uses Replicated; just add a shard-key.
19532        s.placement.shard_key = Some("$tenantId".into());
19533        let err = s.validate().unwrap_err();
19534        let AplicacaoError::ShardKeyOnNonSharded {
19535            estrategia,
19536            shard_key,
19537        } = err
19538        else {
19539            panic!("expected ShardKeyOnNonSharded, got {err:?}");
19540        };
19541        assert_eq!(estrategia, PlacementStrategy::Replicated);
19542        assert_eq!(shard_key, "$tenantId");
19543    }
19544
19545    #[test]
19546    fn rejects_shard_key_under_singlenode_strategy() {
19547        // Peer of the Replicated case above on the SingleNode arm: OTP
19548        // distributed-app takeover (one cluster runs at a time) has no
19549        // hash-keyed routing axis to consume `:shard-key` either, so
19550        // the rejection fires on both non-Sharded arms uniformly.
19551        let mut s = three_member_spec();
19552        s.placement.estrategia = PlacementStrategy::SingleNode;
19553        s.placement.shard_key = Some("$tenantId".into());
19554        let err = s.validate().unwrap_err();
19555        let AplicacaoError::ShardKeyOnNonSharded {
19556            estrategia,
19557            shard_key,
19558        } = err
19559        else {
19560            panic!("expected ShardKeyOnNonSharded, got {err:?}");
19561        };
19562        assert_eq!(estrategia, PlacementStrategy::SingleNode);
19563        assert_eq!(shard_key, "$tenantId");
19564    }
19565
19566    #[test]
19567    fn rejects_empty_shard_key_under_replicated_strategy() {
19568        // The `Some("")` case under non-Sharded is rejected by
19569        // [`AplicacaoError::ShardKeyOnNonSharded`] (the strategy gate
19570        // fires before the empty-value gate), not
19571        // [`AplicacaoError::ShardedKeyEmpty`] (which is reserved for
19572        // the `Sharded` arm). Pin the partition so a future reorder of
19573        // the validate_placement match arms doesn't silently swap which
19574        // diagnostic the author sees — both are author errors, but
19575        // ShardKeyOnNonSharded names which strategy is the actual fix
19576        // (drop the slot, or switch to Sharded), while ShardedKeyEmpty
19577        // only says "pick a non-empty key".
19578        let mut s = three_member_spec();
19579        s.placement.shard_key = Some(String::new());
19580        let err = s.validate().unwrap_err();
19581        assert!(
19582            matches!(
19583                err,
19584                AplicacaoError::ShardKeyOnNonSharded {
19585                    estrategia: PlacementStrategy::Replicated,
19586                    ref shard_key,
19587                } if shard_key.is_empty()
19588            ),
19589            "got {err:?}"
19590        );
19591    }
19592
19593    #[test]
19594    fn replicated_without_shard_key_validates() {
19595        // The complement of the rejection: `:placement :estrategia
19596        // Replicated` with `:shard-key None` is the canonical happy
19597        // path on every existing fixture. Pin the no-shard-key case so
19598        // the new gate doesn't accidentally fire on `None`.
19599        let mut s = three_member_spec();
19600        assert!(matches!(
19601            s.placement.estrategia,
19602            PlacementStrategy::Replicated
19603        ));
19604        s.placement.shard_key = None;
19605        s.validate().unwrap();
19606    }
19607
19608    #[test]
19609    fn singlenode_without_shard_key_validates() {
19610        // Peer of the Replicated no-shard-key case on the SingleNode
19611        // arm — both non-Sharded strategies must validate cleanly when
19612        // the slot is omitted.
19613        let mut s = three_member_spec();
19614        s.placement.estrategia = PlacementStrategy::SingleNode;
19615        s.placement.shard_key = None;
19616        s.validate().unwrap();
19617    }
19618
19619    fn sharded_spec_with_key(key: &str) -> AplicacaoSpec {
19620        // Fixture builder for the `:placement :shard-key` shape gate
19621        // tests: a three-member Aplicacao on the `Sharded` strategy
19622        // with the supplied `:shard-key` slot. Co-locates the
19623        // arm-construction so every test below carries one line of
19624        // setup (the offending `:shard-key` value) and the assertion.
19625        let mut s = three_member_spec();
19626        s.placement.estrategia = PlacementStrategy::Sharded;
19627        s.placement.shard_key = Some(key.into());
19628        s
19629    }
19630
19631    #[test]
19632    fn rejects_shard_key_with_embedded_space() {
19633        // The canonical paste-from-aligned-doc footgun:
19634        // `:shard-key "$tenant Id"` — the Akka-style entity-id
19635        // extractor reads the slot as a single-token reference, and an
19636        // embedded space breaks the token boundary at the runtime
19637        // hash-extractor pass with no diagnostic naming the offending
19638        // entry.
19639        let s = sharded_spec_with_key("$tenant Id");
19640        let err = s.validate().unwrap_err();
19641        assert!(
19642            matches!(
19643                err,
19644                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19645                    if shard_key == "$tenant Id" && reason.contains("space")
19646            ),
19647            "got {err:?}"
19648        );
19649    }
19650
19651    #[test]
19652    fn rejects_shard_key_with_leading_space() {
19653        // Leading-space arm of the embedded-whitespace footgun — the
19654        // paste-from-aligned-doc / paste-from-CSV-cell variant where
19655        // the leading column-padding leaked into the slot.
19656        let s = sharded_spec_with_key(" $tenantId");
19657        let err = s.validate().unwrap_err();
19658        assert!(
19659            matches!(
19660                err,
19661                AplicacaoError::ShardKeyInvalid { ref shard_key, .. }
19662                    if shard_key == " $tenantId"
19663            ),
19664            "got {err:?}"
19665        );
19666    }
19667
19668    #[test]
19669    fn rejects_shard_key_with_trailing_newline() {
19670        // The canonical paste-from-shell-heredoc footgun — every
19671        // `<<EOF` heredoc terminator paste leaves a trailing newline
19672        // the YAML emitter then folds away inconsistently across
19673        // emitter implementations.
19674        let s = sharded_spec_with_key("$tenantId\n");
19675        let err = s.validate().unwrap_err();
19676        assert!(
19677            matches!(
19678                err,
19679                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19680                    if shard_key == "$tenantId\n" && reason.contains("0x0a")
19681            ),
19682            "got {err:?}"
19683        );
19684    }
19685
19686    #[test]
19687    fn rejects_shard_key_with_embedded_tab() {
19688        // The paste-from-aligned-doc tab-stop variant — tabs land
19689        // alongside spaces in copy-paste from formatted columns.
19690        let s = sharded_spec_with_key("$tenant\tId");
19691        let err = s.validate().unwrap_err();
19692        assert!(
19693            matches!(
19694                err,
19695                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19696                    if shard_key == "$tenant\tId" && reason.contains("tab")
19697            ),
19698            "got {err:?}"
19699        );
19700    }
19701
19702    #[test]
19703    fn rejects_shard_key_with_control_character() {
19704        // The paste-from-binary / paste-from-screen-cleared-terminal
19705        // footgun — an embedded `\x01` (SOH) byte that some YAML
19706        // emitters silently strip and others escape as ``,
19707        // breaking round-trip across emitter implementations.
19708        let s = sharded_spec_with_key("$tenant\u{0001}Id");
19709        let err = s.validate().unwrap_err();
19710        assert!(
19711            matches!(
19712                err,
19713                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19714                    if shard_key == "$tenant\u{0001}Id" && reason.contains("control")
19715            ),
19716            "got {err:?}"
19717        );
19718    }
19719
19720    #[test]
19721    fn rejects_shard_key_with_non_ascii() {
19722        // The canonical un-Punycode-encoded IDN / paste-from-Unicode-doc
19723        // footgun — non-ASCII bytes normalize differently between the
19724        // caixa-mesh-side YAML emitter and the in-cluster reconciler's
19725        // YAML parser, the same entity ID can silently map to two
19726        // distinct shards on a re-render.
19727        let s = sharded_spec_with_key("$tenàntId");
19728        let err = s.validate().unwrap_err();
19729        assert!(
19730            matches!(
19731                err,
19732                AplicacaoError::ShardKeyInvalid { ref shard_key, ref reason }
19733                    if shard_key == "$tenàntId" && reason.contains("non-ASCII")
19734            ),
19735            "got {err:?}"
19736        );
19737    }
19738
19739    #[test]
19740    fn rejects_shard_key_too_long() {
19741        // Length cap pin: 64 bytes — one byte over the
19742        // PLACEMENT_SHARD_KEY_MAX_LEN (63) cap. The realistic shape
19743        // here is a paste-from-doc multi-line blob landing in
19744        // `:shard-key` instead of a single-token extractor expression.
19745        let too_long = "a".repeat(64);
19746        let s = sharded_spec_with_key(&too_long);
19747        let err = s.validate().unwrap_err();
19748        let AplicacaoError::ShardKeyInvalid {
19749            ref shard_key,
19750            ref reason,
19751        } = err
19752        else {
19753            panic!("expected ShardKeyInvalid, got {err:?}");
19754        };
19755        assert_eq!(shard_key, &too_long);
19756        assert!(
19757            reason.contains("63") && reason.contains("64"),
19758            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
19759        );
19760    }
19761
19762    #[test]
19763    fn shard_key_max_length_validates() {
19764        // Boundary pin: 63 bytes exactly — the
19765        // `PLACEMENT_SHARD_KEY_MAX_LEN` cap. A future tightening (e.g.
19766        // dropping to 62) surfaces here as a regression, mirroring
19767        // `placement_cluster_max_length_validates` /
19768        // `placement_affinity_max_length_validates` on the peer
19769        // identifier-shaped slots.
19770        let s = sharded_spec_with_key(&"a".repeat(63));
19771        s.validate().unwrap();
19772    }
19773
19774    #[test]
19775    fn accepts_canonical_shard_key_forms() {
19776        // The Akka-style entity-id extractor shapes a caixa author is
19777        // realistically going to write — pin every leg so a future
19778        // tightening that bans (e.g.) the `${...}` interpolation
19779        // variant or the `metadata.<field>` JSONPath form surfaces
19780        // here as a regression. The canonical forms span:
19781        //
19782        //   - bare property name (`tenantId`, `customerId`)
19783        //   - Akka `ExtractEntityId` placeholder (`$tenantId`)
19784        //   - JSONPath-style nested reference (`metadata.tenantId`,
19785        //     `$.user.id`)
19786        //   - interpolation-style template (`${tenant}`)
19787        //   - snake_case property name (`customer_id`)
19788        //   - kebab-case property name (`customer-id` — accepted
19789        //     because the slot is a printable-ASCII single-token
19790        //     reference, not a DNS-1123 label like
19791        //     `:placement :affinity` / `:clusters`)
19792        //   - single character (`a`, `$` — boundary)
19793        for form in [
19794            "tenantId",
19795            "customerId",
19796            "$tenantId",
19797            "metadata.tenantId",
19798            "$.user.id",
19799            "${tenant}",
19800            "customer_id",
19801            "customer-id",
19802            "a",
19803            "$",
19804        ] {
19805            let s = sharded_spec_with_key(form);
19806            s.validate().unwrap_or_else(|e| {
19807                panic!("canonical shard-key form {form:?} must validate, got {e:?}")
19808            });
19809        }
19810    }
19811
19812    #[test]
19813    fn shard_key_empty_takes_precedence_over_invalid() {
19814        // Order pin: the existing `ShardedKeyEmpty` diagnostic
19815        // (reserved for the `Sharded` `Some("")` arm) fires before the
19816        // new `ShardKeyInvalid` parse-side diagnostic, so an empty
19817        // `:shard-key` keeps its narrower error message — the new gate
19818        // would also reject `""` defensively, but the empty-string arm
19819        // is the more self-locating diagnostic. Mirrors the
19820        // `placement_cluster_empty_takes_precedence_over_invalid` pin
19821        // on the peer identifier-shaped slot.
19822        let s = sharded_spec_with_key("");
19823        let err = s.validate().unwrap_err();
19824        assert_eq!(err, AplicacaoError::ShardedKeyEmpty);
19825    }
19826
19827    #[test]
19828    fn shard_key_invalid_diagnostic_carries_offending_value() {
19829        // The diagnostic-shape pin: the error names the offending
19830        // `:shard-key` value verbatim so the author can grep their
19831        // caixa.lisp without re-running the build, and carries a
19832        // parser-shaped `reason:` naming the specific violation —
19833        // mirrors `placement_cluster_invalid_diagnostic_carries_offending_cluster`
19834        // on the peer identifier-shaped slot.
19835        let s = sharded_spec_with_key("$tenant Id");
19836        let err = s.validate().unwrap_err();
19837        let AplicacaoError::ShardKeyInvalid {
19838            ref shard_key,
19839            ref reason,
19840        } = err
19841        else {
19842            panic!("expected ShardKeyInvalid, got {err:?}");
19843        };
19844        assert_eq!(shard_key, "$tenant Id");
19845        assert!(
19846            !reason.is_empty(),
19847            "reason must name the specific violation, got empty string"
19848        );
19849    }
19850
19851    #[test]
19852    fn shard_key_shape_fires_after_non_sharded_strategy_gate() {
19853        // Order pin: the `ShardKeyOnNonSharded` arm (which rejects
19854        // `:shard-key` carried on non-Sharded strategies) fires before
19855        // the shape gate, so a malformed `:shard-key` carried on (e.g.)
19856        // a `Replicated` strategy surfaces the more self-locating
19857        // strategy-mismatch diagnostic (naming the actual fix — drop
19858        // the slot, or switch to Sharded) rather than the shape
19859        // diagnostic. The strategy-mismatch arm is the more actionable
19860        // diagnostic: a malformed shard-key on Replicated is "you
19861        // shouldn't have a :shard-key here at all", not "your
19862        // :shard-key value is malformed".
19863        let mut s = three_member_spec();
19864        // Replicated is the default fixture strategy.
19865        s.placement.shard_key = Some("$tenant Id".into());
19866        let err = s.validate().unwrap_err();
19867        assert!(
19868            matches!(
19869                err,
19870                AplicacaoError::ShardKeyOnNonSharded {
19871                    estrategia: PlacementStrategy::Replicated,
19872                    ..
19873                }
19874            ),
19875            "got {err:?}"
19876        );
19877    }
19878
19879    #[test]
19880    fn rejects_empty_affinity_hint() {
19881        let mut s = three_member_spec();
19882        s.placement.affinity = Some(String::new());
19883        assert_eq!(
19884            s.validate().unwrap_err(),
19885            AplicacaoError::PlacementAffinityEmpty
19886        );
19887    }
19888
19889    #[test]
19890    fn placement_without_affinity_validates() {
19891        // Omitting :affinity is fine — the placement engine falls back
19892        // to the default heuristic. Pin the no-hint case so the
19893        // affinity-empty rejection doesn't accidentally fire on `None`.
19894        let mut s = three_member_spec();
19895        s.placement.affinity = None;
19896        s.validate().unwrap();
19897    }
19898
19899    #[test]
19900    fn rejects_placement_affinity_with_uppercase() {
19901        // The canonical "I copied the ADR's display name verbatim" typo
19902        // — placement hints land verbatim in K8s label-selector
19903        // territory, where the apiserver enforces the DNS-1123 label
19904        // rule (lowercase-only) on every identity-keyed admission axis.
19905        // Mirrors `rejects_placement_cluster_with_uppercase` on the
19906        // sibling slot.
19907        let mut s = three_member_spec();
19908        s.placement.affinity = Some("DataLocality".into());
19909        let err = s.validate().unwrap_err();
19910        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
19911            panic!("expected PlacementAffinityInvalid, got other variant");
19912        };
19913        assert_eq!(affinity, "DataLocality");
19914        assert!(
19915            reason.contains("uppercase"),
19916            "diagnostic must name the violation as `uppercase` (got: {reason:?})"
19917        );
19918        assert!(
19919            reason.contains("\"datalocality\""),
19920            "diagnostic must suggest the lower-cased fix verbatim (got: {reason:?})"
19921        );
19922    }
19923
19924    #[test]
19925    fn rejects_placement_affinity_with_underscore() {
19926        // The canonical "I'm thinking of an env var / Python identifier"
19927        // leak — `_` is forbidden by every DNS-1123 label schema. Same
19928        // shape as `rejects_placement_cluster_with_underscore` on the
19929        // sibling slot.
19930        let mut s = three_member_spec();
19931        s.placement.affinity = Some("data_locality".into());
19932        let err = s.validate().unwrap_err();
19933        assert!(
19934            matches!(
19935                err,
19936                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19937                    if affinity == "data_locality" && reason.contains('_')
19938            ),
19939            "got {err:?}"
19940        );
19941    }
19942
19943    #[test]
19944    fn rejects_placement_affinity_with_dot() {
19945        // A `:placement :affinity` value is a single DNS-1123 *label*
19946        // (it lands as a K8s label value selector key), not a subdomain.
19947        // The "I want to namespace my hint with `.`" intent is expressed
19948        // via `-` (`data-locality-east`).
19949        let mut s = three_member_spec();
19950        s.placement.affinity = Some("data.locality".into());
19951        let err = s.validate().unwrap_err();
19952        assert!(
19953            matches!(
19954                err,
19955                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19956                    if affinity == "data.locality" && reason.contains('.')
19957            ),
19958            "got {err:?}"
19959        );
19960    }
19961
19962    #[test]
19963    fn rejects_placement_affinity_with_unicode() {
19964        // DNS-1123 is ASCII-only; IDN must be pre-encoded as Punycode
19965        // before it reaches K8s. The byte-by-byte ASCII validity check
19966        // rejects multi-byte UTF-8 sequences by the first byte that
19967        // fails `[a-z0-9-]`.
19968        let mut s = three_member_spec();
19969        s.placement.affinity = Some("data-localité".into());
19970        let err = s.validate().unwrap_err();
19971        assert!(
19972            matches!(
19973                err,
19974                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
19975                    if affinity == "data-localité"
19976            ),
19977            "got {err:?}"
19978        );
19979    }
19980
19981    #[test]
19982    fn rejects_placement_affinity_with_leading_hyphen() {
19983        // DNS-1123 boundary rule: labels must start with an
19984        // alphanumeric. Pin separately from the trailing-hyphen arm so
19985        // a future relaxation that only checks one boundary surfaces
19986        // here as a regression (parallel to
19987        // `rejects_placement_cluster_with_leading_hyphen`).
19988        let mut s = three_member_spec();
19989        s.placement.affinity = Some("-data-locality".into());
19990        let err = s.validate().unwrap_err();
19991        assert!(
19992            matches!(
19993                err,
19994                AplicacaoError::PlacementAffinityInvalid { ref affinity, ref reason }
19995                    if affinity == "-data-locality" && reason.contains("start and end")
19996            ),
19997            "got {err:?}"
19998        );
19999    }
20000
20001    #[test]
20002    fn rejects_placement_affinity_with_trailing_hyphen() {
20003        // Symmetric arm of the DNS-1123 boundary rule. Pinned so both
20004        // ends are covered against a future relaxation.
20005        let mut s = three_member_spec();
20006        s.placement.affinity = Some("data-locality-".into());
20007        let err = s.validate().unwrap_err();
20008        assert!(
20009            matches!(
20010                err,
20011                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
20012                    if affinity == "data-locality-"
20013            ),
20014            "got {err:?}"
20015        );
20016    }
20017
20018    #[test]
20019    fn rejects_placement_affinity_with_whitespace() {
20020        // Whitespace is the canonical "I pasted from a sketch / doc"
20021        // footgun. The apiserver rejects every label-selector value
20022        // carrying whitespace.
20023        let mut s = three_member_spec();
20024        s.placement.affinity = Some("data locality".into());
20025        let err = s.validate().unwrap_err();
20026        assert!(
20027            matches!(
20028                err,
20029                AplicacaoError::PlacementAffinityInvalid { ref affinity, .. }
20030                    if affinity == "data locality"
20031            ),
20032            "got {err:?}"
20033        );
20034    }
20035
20036    #[test]
20037    fn rejects_placement_affinity_too_long() {
20038        // 64 bytes exceeds the DNS-1123 label cap by one — the boundary
20039        // pin. The diagnostic names both the cap (63) and the actual
20040        // length so the author can shorten in one edit. Mirrors
20041        // `rejects_placement_cluster_too_long`.
20042        let mut s = three_member_spec();
20043        let too_long = "a".repeat(64);
20044        s.placement.affinity = Some(too_long.clone());
20045        let err = s.validate().unwrap_err();
20046        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
20047            panic!("expected PlacementAffinityInvalid");
20048        };
20049        assert_eq!(affinity, too_long);
20050        assert!(
20051            reason.contains("63") && reason.contains("64"),
20052            "diagnostic must name the cap (63) and the actual length (64): {reason:?}"
20053        );
20054    }
20055
20056    #[test]
20057    fn placement_affinity_max_length_validates() {
20058        // 63 bytes exactly — the DNS-1123 label cap. Boundary pin so a
20059        // future tightening (e.g. dropping to 62) surfaces here as a
20060        // regression, mirroring `placement_cluster_max_length_validates`.
20061        let mut s = three_member_spec();
20062        s.placement.affinity = Some("a".repeat(63));
20063        s.validate().unwrap();
20064    }
20065
20066    #[test]
20067    fn accepts_canonical_placement_affinity_forms() {
20068        // The DNS-1123 label shapes a caixa author is realistically
20069        // going to write for placement hints: the M3 canonical examples
20070        // (`data-locality`, `low-latency`, `anti-affinity`), the
20071        // single-token form (`affinity`), the single-character boundary
20072        // (`a`), the digit-start (DNS-1123 allows this, unlike
20073        // DNS-1035), and a regional-suffixed form. Pin every leg so a
20074        // future tightening that bans (e.g.) digit-start identifiers
20075        // surfaces here.
20076        for form in [
20077            "data-locality",
20078            "low-latency",
20079            "anti-affinity",
20080            "affinity",
20081            "a",
20082            "3-tier",
20083            "locality-east",
20084        ] {
20085            let mut s = three_member_spec();
20086            s.placement.affinity = Some(form.into());
20087            s.validate().unwrap_or_else(|e| {
20088                panic!("canonical affinity form {form:?} must validate, got {e:?}")
20089            });
20090        }
20091    }
20092
20093    #[test]
20094    fn placement_affinity_empty_takes_precedence_over_invalid() {
20095        // Order pin: the existing `PlacementAffinityEmpty` diagnostic
20096        // (which doesn't try to parse) fires before the new
20097        // `PlacementAffinityInvalid` parse-side diagnostic, so an empty
20098        // `:affinity` keeps its narrower error message — the new gate
20099        // would also reject `""`, but the empty-string arm is the more
20100        // self-locating diagnostic. Mirrors the
20101        // `placement_cluster_empty_takes_precedence_over_invalid` pin.
20102        let mut s = three_member_spec();
20103        s.placement.affinity = Some(String::new());
20104        let err = s.validate().unwrap_err();
20105        assert_eq!(err, AplicacaoError::PlacementAffinityEmpty);
20106    }
20107
20108    #[test]
20109    fn placement_affinity_invalid_diagnostic_carries_offending_value() {
20110        // The diagnostic shape pin: every rejection carries the offending
20111        // `affinity:` verbatim plus a parser-shaped `reason:` so the
20112        // author can grep their caixa.lisp for `:affinity "<hint>"` and
20113        // fix it in one edit. Mirrors the
20114        // `placement_cluster_invalid_diagnostic_carries_offending_cluster`
20115        // pin on the sibling slot.
20116        let mut s = three_member_spec();
20117        s.placement.affinity = Some("Data_Locality".into());
20118        let err = s.validate().unwrap_err();
20119        let AplicacaoError::PlacementAffinityInvalid { affinity, reason } = err else {
20120            panic!("expected PlacementAffinityInvalid");
20121        };
20122        assert_eq!(affinity, "Data_Locality");
20123        assert!(
20124            !reason.is_empty(),
20125            "diagnostic reason must not be empty (got: {reason:?})"
20126        );
20127    }
20128
20129    #[test]
20130    fn singlenode_with_takeover_candidates_validates() {
20131        // OTP distributed-application convention (MESH-COMPOSITION
20132        // §II.1): SingleNode runs on one cluster at a time but the
20133        // :clusters list enumerates the takeover candidates. Multiple
20134        // entries are not a contradiction — they are the failover pool.
20135        let mut s = three_member_spec();
20136        s.placement.estrategia = PlacementStrategy::SingleNode;
20137        s.placement.clusters = vec!["rio".into(), "mar".into(), "plo".into()];
20138        s.validate().unwrap();
20139    }
20140
20141    // ── MeshPolicy::is_empty() — typed emptiness predicate ────────────────
20142
20143    #[test]
20144    fn mesh_policy_default_is_empty() {
20145        // The Default impl carries None on every axis — the typed
20146        // analog of an unset `:politicas (())` slot. Renderers that
20147        // overlay the policy onto a cluster artifact key off this
20148        // predicate to skip the slot entirely; pinning so a future
20149        // axis added to MeshPolicy can't silently break the contract
20150        // (a new field whose Default is non-None would flip is_empty
20151        // to false on every existing caixa, surfacing here).
20152        assert!(MeshPolicy::default().is_empty());
20153    }
20154
20155    #[test]
20156    fn mesh_policy_with_only_timeout_is_not_empty() {
20157        let p = MeshPolicy {
20158            timeout: Some(Duration::from_secs(30)),
20159            ..Default::default()
20160        };
20161        assert!(!p.is_empty());
20162    }
20163
20164    #[test]
20165    fn mesh_policy_with_only_retries_is_not_empty() {
20166        let p = MeshPolicy {
20167            retries: Some(3),
20168            ..Default::default()
20169        };
20170        assert!(!p.is_empty());
20171    }
20172
20173    #[test]
20174    fn mesh_policy_with_only_circuit_breaker_is_not_empty() {
20175        let p = MeshPolicy {
20176            circuit_breaker: Some(CircuitBreaker {
20177                max_failures: 5,
20178                window: Duration::from_secs(60),
20179            }),
20180            ..Default::default()
20181        };
20182        assert!(!p.is_empty());
20183    }
20184
20185    #[test]
20186    fn mesh_policy_with_only_mtls_required_is_not_empty() {
20187        // Even `mtls_required: Some(false)` (an explicit opt-out) is
20188        // not empty — the author *named* the axis, the renderer needs
20189        // to honor that vs. fall back to the cluster default.
20190        let p = MeshPolicy {
20191            mtls_required: Some(false),
20192            ..Default::default()
20193        };
20194        assert!(!p.is_empty());
20195    }
20196
20197    #[test]
20198    fn mesh_policy_with_only_rate_limit_is_not_empty() {
20199        let p = MeshPolicy {
20200            rate_limit: Some(RateLimit {
20201                rate: 100,
20202                window: Duration::from_secs(1),
20203            }),
20204            ..Default::default()
20205        };
20206        assert!(!p.is_empty());
20207    }
20208
20209    #[test]
20210    fn mesh_policy_is_empty_round_trips_through_three_member_fixture() {
20211        // The three-member happy-path fixture sets timeout + retries +
20212        // mtls_required — every populated axis must read non-empty.
20213        // Pin the round-trip so the M3.x per-:politicas emitter (the
20214        // M3.x roadmap CiliumClusterwideEnvoyConfig artifact) can rely
20215        // on is_empty() to decide whether to emit at all without
20216        // re-deriving the contract from inline field probes.
20217        assert!(!three_member_spec().politicas.is_empty());
20218    }
20219
20220    // ── shared duration codec: cross-slot integer-magnitude gate ──
20221    //
20222    // The integer-magnitude discipline applied to
20223    // `supervisor::duration_codec::parse` lifts onto every typed slot
20224    // that routes through the shared codec — `MeshPolicy::timeout`
20225    // (`:politicas :timeout`) and `CircuitBreaker::window`
20226    // (`:politicas :circuit-breaker :window`) on the Aplicacao side.
20227    // These cross-slot tests pin that the gate fires at the serde
20228    // layer for both typed slots, not just for the supervisor side.
20229
20230    #[test]
20231    fn policy_timeout_serde_rejects_fractional_seconds() {
20232        // `MeshPolicy::timeout` uses `with = "supervisor::duration_codec"`,
20233        // so the shared codec's integer-magnitude gate applies on
20234        // deserialize. `"1.5s"` previously parsed to 1500ms and round-
20235        // tripped to `"1500ms"` on next emit — DRIFT. Now refused at
20236        // deserialize with the canonical-form diagnostic naming the
20237        // offending `"1.5"` and the remediation `"1500ms"`.
20238        let payload = r#"{"timeout":"1.5s"}"#;
20239        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20240        let msg = err.to_string();
20241        assert!(
20242            msg.contains("not a non-negative integer"),
20243            "expected integer-magnitude diagnostic in {msg:?}"
20244        );
20245        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
20246        assert!(
20247            msg.contains("\"1500ms\""),
20248            "missing canonical-form remediation in {msg:?}"
20249        );
20250    }
20251
20252    #[test]
20253    fn policy_timeout_serde_rejects_leading_plus_sign() {
20254        // Pin the leading-`+` arm cross-slot — the prior f64 parser
20255        // accepted `"+30s"` silently and round-tripped to `"30s"`.
20256        let payload = r#"{"timeout":"+30s"}"#;
20257        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20258        let msg = err.to_string();
20259        assert!(msg.contains("\"+30\""), "missing magnitude in {msg:?}");
20260    }
20261
20262    #[test]
20263    fn circuit_breaker_window_serde_rejects_fractional_minutes() {
20264        // `CircuitBreaker::window` uses `with =
20265        // "supervisor::duration_codec_required"` (the required-Duration
20266        // variant that delegates to the same shared parser). `"0.5m"`
20267        // parsed to 30s and round-tripped to `"30s"` on next emit —
20268        // DRIFT closed.
20269        let payload = format!(
20270            r#"{{"{max_failures}":5,"{window}":"0.5m"}}"#,
20271            max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
20272            window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
20273        );
20274        let err = serde_json::from_str::<CircuitBreaker>(&payload).unwrap_err();
20275        let msg = err.to_string();
20276        assert!(
20277            msg.contains("not a non-negative integer"),
20278            "expected integer-magnitude diagnostic in {msg:?}"
20279        );
20280        assert!(msg.contains("\"0.5\""), "missing magnitude in {msg:?}");
20281        assert!(
20282            msg.contains("\"30s\""),
20283            "missing canonical-form remediation in {msg:?}"
20284        );
20285    }
20286
20287    #[test]
20288    fn circuit_breaker_window_serde_accepts_integer_canonical_form() {
20289        // Pin the happy-path on the cross-slot side: every canonical
20290        // author shape `render` ever emits parses cleanly through the
20291        // shared codec on the `CircuitBreaker` slot. The
20292        // codec's accepted set (post-gate) is exactly its emitted set
20293        // for the integer-magnitude class.
20294        for window_lit in ["30s", "500ms", "2m", "1h"] {
20295            let payload = format!(
20296                r#"{{"{max_failures}":5,"{window}":"{window_lit}"}}"#,
20297                max_failures = crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
20298                window = crate::CIRCUIT_BREAKER_KEY_WINDOW,
20299            );
20300            let cb: CircuitBreaker = serde_json::from_str(&payload).unwrap_or_else(|e| {
20301                panic!("expected {window_lit:?} to parse cleanly through shared codec: {e}")
20302            });
20303            assert_eq!(cb.max_failures, 5);
20304        }
20305    }
20306
20307    // ── rate_limit_codec: integer-magnitude gate ──
20308    //
20309    // The integer-magnitude discipline the 1c55a2a / 818dd38 / d1fd67b
20310    // / 737a676 / d53c922 trajectory landed on every typed-duration /
20311    // typed-byte-size codec in caixa-core lifts onto the fifth typed
20312    // codec — `rate_limit_codec` — through the digit-only magnitude
20313    // gate on the `<rate>` half of the `<rate>/<unit>` author surface.
20314    // These tests pin the gate at the serde layer for `:politicas
20315    // :rate-limit` (the only typed slot the codec backs), and at the
20316    // codec-internal `parse` layer for the canonical positive cases.
20317
20318    #[test]
20319    fn rate_limit_serde_rejects_fractional_rate() {
20320        // `"1.5/s"` previously hit `u32::from_str`'s rejection arm with
20321        // the value-laundered `"rate-limit rate \"1.5\" not a u32"`
20322        // wording, which didn't name the canonical-form remediation or
20323        // the round-trip drift the next emit would produce. Now refused
20324        // at deserialize with the canonical-form diagnostic naming the
20325        // offending `"1.5"` magnitude and the round-trip drift wording.
20326        let payload = r#"{"rateLimit":"1.5/s"}"#;
20327        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20328        let msg = err.to_string();
20329        assert!(
20330            msg.contains("not a non-negative integer"),
20331            "expected integer-magnitude diagnostic in {msg:?}"
20332        );
20333        assert!(msg.contains("\"1.5\""), "missing magnitude in {msg:?}");
20334        assert!(
20335            msg.contains("THEORY.md"),
20336            "missing render-determinism contract citation in {msg:?}"
20337        );
20338    }
20339
20340    #[test]
20341    fn rate_limit_serde_rejects_leading_plus_sign() {
20342        // `u32::from_str("+100")` returns `Ok(100)` (Rust's
20343        // permissive-`+` parse), so `"+100/s"` silently parsed to
20344        // `RateLimit { 100, 1s }` and round-tripped through `render` to
20345        // `"100/s"` — a *different* canonical string on the next emit,
20346        // breaking the THEORY.md Part V render-determinism contract
20347        // exactly the way the peer duration codecs' `"+30s"` case did.
20348        // This is the load-bearing class the digit-only gate closes
20349        // beyond what `u32::from_str`'s strictness covers on its own.
20350        let payload = r#"{"rateLimit":"+100/s"}"#;
20351        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20352        let msg = err.to_string();
20353        assert!(
20354            msg.contains("not a non-negative integer"),
20355            "expected integer-magnitude diagnostic in {msg:?}"
20356        );
20357        assert!(msg.contains("\"+100\""), "missing magnitude in {msg:?}");
20358    }
20359
20360    #[test]
20361    fn rate_limit_serde_rejects_leading_minus_sign() {
20362        // The signed-negative arm: `"-1/s"` lands on the
20363        // non-canonical-but-numeric branch via the `i64` fallback (the
20364        // `f64` parse also succeeds), surfacing the canonical-form
20365        // diagnostic. Replaces the prior value-laundered "not a u32"
20366        // wording with the unified diagnostic across signs.
20367        let payload = r#"{"rateLimit":"-1/s"}"#;
20368        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20369        let msg = err.to_string();
20370        assert!(
20371            msg.contains("not a non-negative integer"),
20372            "expected integer-magnitude diagnostic in {msg:?}"
20373        );
20374        assert!(msg.contains("\"-1\""), "missing magnitude in {msg:?}");
20375    }
20376
20377    #[test]
20378    fn rate_limit_serde_rejects_decimal_shaped_integer() {
20379        // `"100.0/s"` is integer-valued numerically but not in the
20380        // codec's accepted set — `render` emits `"100/s"`, so the
20381        // round-trip would drift. Lifted to the canonical-form
20382        // diagnostic peer with the duration codec's `"1.0s"` case
20383        // (1c55a2a).
20384        let payload = r#"{"rateLimit":"100.0/s"}"#;
20385        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20386        let msg = err.to_string();
20387        assert!(
20388            msg.contains("not a non-negative integer"),
20389            "expected integer-magnitude diagnostic in {msg:?}"
20390        );
20391        assert!(msg.contains("\"100.0\""), "missing magnitude in {msg:?}");
20392    }
20393
20394    #[test]
20395    fn rate_limit_serde_garbage_still_falls_through_to_not_a_u32() {
20396        // Non-numeric, non-digit-only input lands on the existing
20397        // narrower `"not a u32"` arm (preserved for diagnostic-shape
20398        // stability on the parser-shape footgun case). Pin this so a
20399        // future relaxation of the numeric-fallback predicate doesn't
20400        // silently collapse garbage onto the canonical-form arm — same
20401        // partition the peer duration codecs draw between
20402        // `NonIntegerDurationMagnitude` and `BadDurationMagnitude`.
20403        let payload = r#"{"rateLimit":"abc/s"}"#;
20404        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20405        let msg = err.to_string();
20406        assert!(
20407            msg.contains("not a u32"),
20408            "garbage magnitude must surface the narrower `not a u32` wording, got: {msg:?}"
20409        );
20410        assert!(
20411            !msg.contains("not a non-negative integer"),
20412            "garbage magnitude must NOT surface the canonical-form arm, got: {msg:?}"
20413        );
20414    }
20415
20416    #[test]
20417    fn rate_limit_serde_u32_overflow_surfaces_as_overflow() {
20418        // `u32::MAX + 1` (= 4_294_967_296) is digit-only but exceeds
20419        // u32's range. The digit-only gate passes; `u32::from_str`
20420        // fails on overflow. Surface that with the overflow-shaped
20421        // diagnostic naming the offending magnitude verbatim, peer
20422        // with `supervisor::duration_codec`'s overflow arm. Pinning
20423        // the wording so a future refactor doesn't silently collapse
20424        // overflow onto the canonical-form arm.
20425        let payload = r#"{"rateLimit":"4294967296/s"}"#;
20426        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20427        let msg = err.to_string();
20428        assert!(
20429            msg.contains("overflows u32"),
20430            "expected overflow diagnostic in {msg:?}"
20431        );
20432        assert!(
20433            msg.contains("\"4294967296\""),
20434            "missing offending magnitude in {msg:?}"
20435        );
20436    }
20437
20438    #[test]
20439    fn rate_limit_serde_rejects_leading_zero_magnitude() {
20440        // `"0100/s"` is digit-only, so the existing
20441        // non-digit-only / sign / fractional arm doesn't catch it —
20442        // `u32::from_str("0100")` returns `Ok(100)`, so before this
20443        // gate `"0100/s"` parsed to `RateLimit { 100, 1s }` and
20444        // round-tripped through `render` to `"100/s"` — a *different*
20445        // canonical string on the next emit, breaking the THEORY.md
20446        // Part V render-determinism contract exactly the way the
20447        // peer `"+100/s"` case did before the leading-`+` arm landed.
20448        // This is the load-bearing class the leading-zero gate closes
20449        // beyond what the existing digit-only / sign / fractional
20450        // gates cover, and the peer arm to the leading-`+` test
20451        // (`rate_limit_serde_rejects_leading_plus_sign`) on the same
20452        // canonical-form-drift axis.
20453        let payload = r#"{"rateLimit":"0100/s"}"#;
20454        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20455        let msg = err.to_string();
20456        assert!(
20457            msg.contains("non-canonical leading zero"),
20458            "expected leading-zero diagnostic in {msg:?}"
20459        );
20460        assert!(msg.contains("\"0100\""), "missing magnitude in {msg:?}");
20461        assert!(
20462            msg.contains("THEORY.md"),
20463            "missing render-determinism contract citation in {msg:?}"
20464        );
20465    }
20466
20467    #[test]
20468    fn rate_limit_serde_rejects_multi_digit_zero_magnitude() {
20469        // `"00/s"` is the degenerate leading-zero case — every byte
20470        // is `0`, the magnitude parses to `u32` = 0, and `render(0)`
20471        // emits `"0/s"`. Round-trip drift: `"00/s"` → 0 → `"0/s"`,
20472        // a *different* canonical string, same render-determinism
20473        // violation. The single-byte `"0/s"` itself is in the
20474        // accepted set (round-trips losslessly through `render`,
20475        // refused downstream by `PolicyRateLimitZero`); the
20476        // multi-byte `"00/s"` is not. Pins the boundary between the
20477        // accepted single-`0` and the rejected leading-zero class.
20478        let payload = r#"{"rateLimit":"00/s"}"#;
20479        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20480        let msg = err.to_string();
20481        assert!(
20482            msg.contains("non-canonical leading zero"),
20483            "expected leading-zero diagnostic in {msg:?}"
20484        );
20485        assert!(msg.contains("\"00\""), "missing magnitude in {msg:?}");
20486    }
20487
20488    #[test]
20489    fn rate_limit_serde_rejects_leading_zero_per_hour_window() {
20490        // Cross-window pin — the gate is window-agnostic; the
20491        // leading-zero class is a property of the magnitude, not the
20492        // unit. `"007/h"` → 7 → `"7/h"`, same drift. Mirrors the
20493        // peer `rate_limit_serde_rejects_leading_plus_sign` arm's
20494        // single-window coverage extended across the three canonical
20495        // windows the codec accepts.
20496        let payload = r#"{"rateLimit":"007/h"}"#;
20497        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20498        let msg = err.to_string();
20499        assert!(
20500            msg.contains("non-canonical leading zero"),
20501            "expected leading-zero diagnostic in {msg:?}"
20502        );
20503        assert!(msg.contains("\"007\""), "missing magnitude in {msg:?}");
20504    }
20505
20506    #[test]
20507    fn rate_limit_serde_rejects_leading_whitespace() {
20508        // `" 100/s"` — the canonical paste-from-aligned-doc /
20509        // paste-from-YAML-quoted-plain-scalar footgun. Before this gate
20510        // the top-level `s.trim()` silently ate the leading space and
20511        // parsed the value to `RateLimit { 100, 1s }`, which then
20512        // round-tripped through `render` to `"100/s"` (a *different*
20513        // canonical string on the next emit) — the exact
20514        // canonical-form-drift class the leading-`+` / leading-zero
20515        // arms already close, extended to the whitespace byte class.
20516        let payload = r#"{"rateLimit":" 100/s"}"#;
20517        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20518        let msg = err.to_string();
20519        assert!(
20520            msg.contains("contains whitespace byte"),
20521            "expected whitespace diagnostic in {msg:?}"
20522        );
20523        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20524        assert!(
20525            msg.contains("THEORY.md"),
20526            "missing render-determinism contract citation in {msg:?}"
20527        );
20528    }
20529
20530    #[test]
20531    fn rate_limit_serde_rejects_trailing_whitespace() {
20532        // `"100/s "` — the canonical shell-history / trailing-space
20533        // paste footgun. Before this gate the top-level `s.trim()`
20534        // silently ate the trailing space and parsed to
20535        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` on the
20536        // next emit — same canonical-form drift as the leading-space
20537        // sibling, closed on the same whitespace-byte arm.
20538        let payload = r#"{"rateLimit":"100/s "}"#;
20539        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20540        let msg = err.to_string();
20541        assert!(
20542            msg.contains("contains whitespace byte"),
20543            "expected whitespace diagnostic in {msg:?}"
20544        );
20545        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20546    }
20547
20548    #[test]
20549    fn rate_limit_serde_rejects_internal_whitespace_around_separator() {
20550        // `"100 / s"` — the canonical typographically-spaced author
20551        // shape (the same idiom every prose reference to a rate limit
20552        // renders as, mistakenly retained when the value is pasted
20553        // into a codec-shaped slot). Before this gate the per-part
20554        // `rate_str.trim()` / `unit.trim()` calls silently ate both
20555        // spaces on either side of `/` and parsed to
20556        // `RateLimit { 100, 1s }`, round-tripping to `"100/s"` — the
20557        // codec's *internal* whitespace-tolerance vector, orthogonal
20558        // to the leading / trailing surface but the same canonical-
20559        // form-drift class. Pins the arm as strictly stronger than the
20560        // pre-existing top-level `s.trim()` behavior: it fires on
20561        // whitespace anywhere in the value, not just at the string
20562        // boundary.
20563        let payload = r#"{"rateLimit":"100 / s"}"#;
20564        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20565        let msg = err.to_string();
20566        assert!(
20567            msg.contains("contains whitespace byte"),
20568            "expected whitespace diagnostic in {msg:?}"
20569        );
20570        assert!(msg.contains("0x20"), "missing offending byte in {msg:?}");
20571    }
20572
20573    #[test]
20574    fn rate_limit_serde_rejects_tab_byte() {
20575        // `"\t100/s"` — the canonical paste-from-indented-doc /
20576        // paste-from-YAML-block-scalar footgun where a tab byte leads
20577        // the magnitude. Pins that the gate covers tab (`0x09`) as
20578        // well as space (`0x20`) — both are `u8::is_ascii_whitespace`
20579        // members and both would be silently swallowed by `s.trim()`
20580        // pre-gate. The `is_ascii_whitespace` coverage extends beyond
20581        // space alone to the full ASCII-whitespace set (space `0x20`,
20582        // tab `0x09`, LF `0x0A`, FF `0x0C`, CR `0x0D`); this test pins
20583        // the tab arm as a representative of the non-space members.
20584        let payload = r#"{"rateLimit":"\t100/s"}"#;
20585        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20586        let msg = err.to_string();
20587        assert!(
20588            msg.contains("contains whitespace byte"),
20589            "expected whitespace diagnostic in {msg:?}"
20590        );
20591        assert!(
20592            msg.contains("0x09"),
20593            "missing offending tab byte in {msg:?}"
20594        );
20595    }
20596
20597    // ── canonical-form: non-ASCII Unicode `White_Space` rate-limit gate ───
20598    //
20599    // Successor to the ASCII-whitespace arm (1ad7755) on
20600    // `rate_limit_codec` — closes the strictly-complementary class the
20601    // byte-scan cannot see, through the lifted
20602    // [`crate::render::find_non_ascii_whitespace_char`] predicate.
20603
20604    #[test]
20605    fn rate_limit_serde_rejects_leading_nbsp() {
20606        // NBSP prefix — paste-from-typography footgun. Byte-scan
20607        // misses, `str::trim` silently strips it, value drifts to
20608        // `"100/s"` on next serialize.
20609        let payload = "{\"rateLimit\":\"\u{00A0}100/s\"}";
20610        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20611        let msg = err.to_string();
20612        assert!(
20613            msg.contains("non-ASCII Unicode whitespace character"),
20614            "expected non-ASCII whitespace diagnostic in {msg:?}"
20615        );
20616        assert!(msg.contains("U+00A0"), "missing codepoint in {msg:?}");
20617    }
20618
20619    #[test]
20620    fn rate_limit_serde_rejects_internal_em_space() {
20621        // EM-SPACE (`\u{2003}`) between magnitude and unit — canonical
20622        // paste-from-typography footgun on the `<integer>/<unit>`
20623        // shape.
20624        let payload = "{\"rateLimit\":\"100\u{2003}/s\"}";
20625        let err = serde_json::from_str::<MeshPolicy>(payload).unwrap_err();
20626        let msg = err.to_string();
20627        assert!(
20628            msg.contains("non-ASCII Unicode whitespace character"),
20629            "expected non-ASCII whitespace diagnostic in {msg:?}"
20630        );
20631        assert!(msg.contains("U+2003"), "missing codepoint in {msg:?}");
20632    }
20633
20634    #[test]
20635    fn rate_limit_serde_accepts_ascii_only_canonical_forms_after_unicode_arm() {
20636        // Positive-control pin: every ASCII-only canonical form the
20637        // renderer emits stays accepted through the new arm.
20638        for lit in [r#""100/s""#, r#""5000/m""#, r#""10000/h""#] {
20639            let payload = format!(r#"{{"rateLimit":{lit}}}"#);
20640            let p: MeshPolicy = serde_json::from_str(&payload)
20641                .unwrap_or_else(|e| panic!("expected {lit} to parse; got {e}"));
20642            assert!(p.rate_limit.is_some());
20643        }
20644    }
20645
20646    #[test]
20647    fn rate_limit_serde_accepts_single_zero_magnitude_at_codec_layer() {
20648        // The boundary case — `"0/s"` is the canonical form
20649        // `render(RateLimit { 0, 1s })` emits, so the codec accepts
20650        // it at the parse layer; the downstream
20651        // [`AplicacaoError::PolicyRateLimitZero`] gate refuses
20652        // `rate == 0` at the typed-validate layer above. Pins the
20653        // partition: the leading-zero gate at the codec layer does
20654        // not poach the rate-zero semantic-validation arm at the
20655        // typed-validate layer above (a future stricter codec must
20656        // not reject `"0/s"` here, or it'd collapse the diagnostic
20657        // partitioning that lets `PolicyRateLimitZero` name the
20658        // offending typed slot).
20659        let payload = r#"{"rateLimit":"0/s"}"#;
20660        let policy: MeshPolicy = serde_json::from_str(payload).unwrap_or_else(|e| {
20661            panic!("`\"0/s\"` must parse cleanly through rate_limit_codec: {e}")
20662        });
20663        let rl = policy.rate_limit.expect("rate_limit must be Some");
20664        assert_eq!(rl.rate, 0, "single-`0` magnitude must parse to rate=0");
20665        assert_eq!(
20666            rl.window,
20667            Duration::from_secs(1),
20668            "single-`0` magnitude with `s` unit must parse to window=1s"
20669        );
20670    }
20671
20672    #[test]
20673    fn rate_limit_serde_accepts_canonical_magnitude_with_leading_one() {
20674        // The complementary boundary pin — every magnitude
20675        // `render` emits starts with `[1-9]` (or is the single byte
20676        // `"0"`), so the canonical-form predicate is `(len == 1) ||
20677        // (first byte != '0')`. Pinning the `len > 1 && first byte ==
20678        // '1'` case explicitly so a future tightening of the gate
20679        // (e.g. an over-eager "no leading digit < 5" rule, or a
20680        // mistakenly anchored start-of-magnitude byte check) lands
20681        // here before the canonical-forms-iterating test would catch
20682        // it.
20683        let payload = r#"{"rateLimit":"100/s"}"#;
20684        let policy: MeshPolicy = serde_json::from_str(payload)
20685            .unwrap_or_else(|e| panic!("canonical `\"100/s\"` must parse cleanly: {e}"));
20686        let rl = policy.rate_limit.expect("rate_limit must be Some");
20687        assert_eq!(
20688            rl.rate, 100,
20689            "canonical-100 magnitude must parse to rate=100"
20690        );
20691    }
20692
20693    #[test]
20694    fn rate_limit_serde_accepts_integer_canonical_forms() {
20695        // Pin the happy-path: every canonical author shape `render`
20696        // ever emits parses cleanly through the codec post-gate. The
20697        // codec's accepted set (post-gate) is exactly its emitted set
20698        // for the integer-magnitude class — same property
20699        // `parse_byte_size`'s and `parse_duration`'s integer-magnitude
20700        // gates guarantee on the peer codecs. Iterating across rate
20701        // magnitudes (including `"0"`, which the codec accepts even
20702        // though `validate_politicas` rejects `rate == 0` at the typed
20703        // layer above) closes the codec contract at the parse layer
20704        // independently of the validate layer.
20705        for rate_lit in ["0", "1", "100", "5000", "1000000", "4294967295"] {
20706            for unit_lit in ["s", "m", "h"] {
20707                let lit = format!("{rate_lit}/{unit_lit}");
20708                let payload = format!(r#"{{"rateLimit":{lit:?}}}"#);
20709                let policy: MeshPolicy = serde_json::from_str(&payload).unwrap_or_else(|e| {
20710                    panic!("expected {lit:?} to parse cleanly through rate_limit_codec: {e}")
20711                });
20712                let rl = policy.rate_limit.expect("rate_limit must be Some");
20713                assert_eq!(
20714                    rl.rate,
20715                    rate_lit.parse::<u32>().unwrap(),
20716                    "rate mismatch for {lit:?}"
20717                );
20718            }
20719        }
20720    }
20721
20722    #[test]
20723    fn rate_limit_serde_round_trip_holds_for_every_canonical_form() {
20724        // The structural property the gate enforces: serialize ∘
20725        // deserialize is the identity on every canonical author shape.
20726        // Peer of `parse_byte_size`'s and `parse_duration`'s
20727        // `_round_trips_through_render_for_every_canonical_form` tests
20728        // on the rate-limit axis. Before the gate, `"+100/s"` violated
20729        // this (`parse` → `RateLimit { 100, 1s }` → `render` →
20730        // `"100/s"` ≠ `"+100/s"`); the gate forecloses that class.
20731        for rate in [1u32, 100, 5000, 1_000_000] {
20732            for (window, unit) in [
20733                (Duration::from_secs(1), "s"),
20734                (Duration::from_secs(60), "m"),
20735                (Duration::from_secs(3600), "h"),
20736            ] {
20737                let policy = MeshPolicy {
20738                    rate_limit: Some(RateLimit { rate, window }),
20739                    ..Default::default()
20740                };
20741                let json = serde_json::to_string(&policy).unwrap();
20742                let expected = format!("\"{rate}/{unit}\"");
20743                assert!(
20744                    json.contains(&expected),
20745                    "expected {expected:?} in {json:?}"
20746                );
20747                let back: MeshPolicy = serde_json::from_str(&json).unwrap();
20748                assert_eq!(
20749                    back.rate_limit, policy.rate_limit,
20750                    "round-trip for {json:?}"
20751                );
20752            }
20753        }
20754    }
20755
20756    // ── self-membership cross-slot gate ──────────────────────────────
20757
20758    #[test]
20759    fn validate_no_self_membership_rejects_self_named_membro() {
20760        // An Aplicacao whose `:membros` lists its own `:nome` is a
20761        // one-node lacre-closure recursion — rejected, naming the parent.
20762        let membros = vec![
20763            membro("catalog", "^0.1"),
20764            membro("checkout", "^0.1"),
20765            membro("cart", "^0.1"),
20766        ];
20767        let err = validate_no_self_membership(&membros, "checkout").unwrap_err();
20768        assert!(
20769            matches!(err, AplicacaoError::MembroIsSelfAplicacao { ref caixa } if caixa == "checkout"),
20770            "got {err:?}"
20771        );
20772    }
20773
20774    #[test]
20775    fn validate_no_self_membership_accepts_distinct_membros() {
20776        // Positive control: distinct member names (including a member
20777        // that is itself an Aplicacao — recursive composition is valid,
20778        // MESH-COMPOSITION §V) pass the gate.
20779        let membros = vec![membro("catalog", "^0.1"), membro("sub-aplicacao", "^0.1")];
20780        validate_no_self_membership(&membros, "checkout").unwrap();
20781    }
20782
20783    #[test]
20784    fn validate_no_self_membership_empty_membros_is_vacuously_ok() {
20785        // An empty `:membros` is rejected by `AplicacaoSpec::validate`'s
20786        // `NoMembros` arm (the more-fundamental "graph must have nodes"
20787        // gate), not by this cross-slot self-edge gate. Keeping the
20788        // self-membership predicate vacuously-ok on the empty input
20789        // matches its supervisor-axis peer
20790        // (`validate_no_self_supervision_empty_children_is_ok`) and
20791        // makes the gate composable from any future call site (an M4
20792        // CR materializer's per-membros validator) without re-checking
20793        // emptiness.
20794        validate_no_self_membership(&[], "checkout").unwrap();
20795    }
20796
20797    #[test]
20798    fn validate_no_self_membership_diagnostic_names_offending_caixa() {
20799        // Pinning the Display: the self-membership diagnostic must name
20800        // the offending caixa verbatim + the "lists itself" framing the
20801        // author can grep for, so the cluster-far failure surfaces at
20802        // build time with one-line remediation. Same diagnostic shape
20803        // as the supervisor-axis `ChildSupervisesSelf` peer.
20804        let membros = vec![membro("orquestra", "^0.1")];
20805        let err = validate_no_self_membership(&membros, "orquestra").unwrap_err();
20806        let msg = err.to_string();
20807        assert!(
20808            msg.contains("orquestra"),
20809            "diagnostic must name the offending caixa nome (got: {msg:?})"
20810        );
20811        assert!(
20812            msg.contains("lists itself"),
20813            "diagnostic must use the canonical `lists itself` framing (got: {msg:?})"
20814        );
20815    }
20816
20817    #[test]
20818    fn default_servico_port_constant_pins_canonical_8080_literal() {
20819        // The canonical-constant arm — pins [`DEFAULT_SERVICO_PORT`]
20820        // at the verbatim `8080` literal both consumers (the
20821        // `Entrada::port` serde default via [`default_port`] and the
20822        // `caixa-mesh` `CiliumNetworkPolicy` L4-fallback at
20823        // `caixa-mesh/src/lib.rs:344`) read from. Peer with the
20824        // [`crate::DEFAULT_NAMESPACE`]-pins-`"tatara-system"`
20825        // discipline (a085b26) on the per-renderer canonical-K8s-axis
20826        // string-constant axis: a future refactor that drifts the
20827        // constant out from under either consumer surfaces here ahead
20828        // of every per-renderer's first emission. The literal value
20829        // matches the well-known HTTP-alt port the `pleme-computeunit`
20830        // library chart already emits as its `trigger.service.port`
20831        // default — by construction the same value the substrate
20832        // assumes about every Servico's in-cluster L4 listener.
20833        assert_eq!(
20834            DEFAULT_SERVICO_PORT, 8080,
20835            "canonical Servico port literal must remain `8080` verbatim — \
20836             this is the value both the `Entrada::port` serde default and the \
20837             caixa-mesh `CiliumNetworkPolicy` L4-fallback read from"
20838        );
20839    }
20840
20841    #[test]
20842    fn default_port_helper_returns_canonical_servico_port_constant() {
20843        // The bridge-arm — pins that the [`default_port`] helper
20844        // [`Entrada::port`]'s `#[serde(default = "default_port")]`
20845        // attribute hooks routes through the lifted
20846        // [`DEFAULT_SERVICO_PORT`] constant, not an open-coded
20847        // literal. A future refactor that re-introduces the `8080`
20848        // literal at the helper's return site (silently re-opening
20849        // the drift footgun this lift closed) surfaces here ahead of
20850        // every author-side `(:entrada (:host … :para …))` slot
20851        // without an explicit `:port`. Peer with the
20852        // `default_namespace_re_export_points_at_caixa_core_canonical`
20853        // pin on the caixa-mesh-side re-export axis.
20854        assert_eq!(
20855            default_port(),
20856            DEFAULT_SERVICO_PORT,
20857            "the serde-default helper must route through the lifted constant"
20858        );
20859    }
20860
20861    #[test]
20862    fn entrada_serde_default_port_inherits_canonical_servico_port_constant() {
20863        // The end-to-end pin — an author-surface `(:entrada (:host …
20864        // :para …))` without an explicit `:port` slot deserializes to
20865        // a typed [`Entrada`] carrying [`DEFAULT_SERVICO_PORT`]
20866        // verbatim. Routes the canonical lifted constant through both
20867        // the serde-default machinery (the `#[serde(default =
20868        // "default_port")]` attribute) and the typed-value-shape
20869        // contract (the resulting [`Entrada::port`] value). A future
20870        // refactor that drifts either axis — replacing the serde
20871        // hook's helper, changing the typed slot's wire shape — would
20872        // surface here before any per-renderer's CNP / Gateway /
20873        // HTTPRoute emission consumed the drifted default.
20874        let entrada: Entrada =
20875            serde_yaml::from_str("host: checkout.quero.cloud\npara: cart\n").expect("yaml parses");
20876        assert_eq!(
20877            entrada.port, DEFAULT_SERVICO_PORT,
20878            "the serde default must materialize as the lifted canonical Servico port"
20879        );
20880    }
20881
20882    #[test]
20883    fn servico_port_min_pins_canonical_accept_set_floor() {
20884        // The canonical-constant arm — pins [`SERVICO_PORT_MIN`] at the
20885        // verbatim `1` literal every typed `:entrada :port` acceptance
20886        // gate keys off. Peer with the
20887        // [`default_servico_port_constant_pins_canonical_8080_literal`]
20888        // discipline on the canonical-Servico-port-constant axis: a
20889        // future refactor that drifts the accept-set floor out from
20890        // under the sole consumer at [`AplicacaoSpec::validate`]'s
20891        // `if e.port < SERVICO_PORT_MIN` gate surfaces here ahead of
20892        // every per-`:entrada` `EntradaPortZero` diagnostic. The
20893        // literal value matches the IANA-registered TCP/UDP port
20894        // space floor (`1..=65535` — port `0` is the "any ephemeral"
20895        // sentinel, not a well-defined destination the substrate's
20896        // per-`Entrada` Gateway API v1 `HTTPRoute.backendRefs[].port`
20897        // axis can honor).
20898        assert_eq!(
20899            SERVICO_PORT_MIN, 1,
20900            "canonical Servico port accept-set floor must remain `1` verbatim — \
20901             this is the value the `AplicacaoSpec::validate` gate at \
20902             `if e.port < SERVICO_PORT_MIN` rejects `port: 0` against"
20903        );
20904    }
20905
20906    #[test]
20907    fn default_servico_port_satisfies_lifted_servico_port_min_floor() {
20908        // The cross-const invariant pin — the substrate's canonical
20909        // default port must satisfy its own accept-set floor by
20910        // construction: `SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT`.
20911        // A future rebrand that moved [`DEFAULT_SERVICO_PORT`] below
20912        // [`SERVICO_PORT_MIN`] — a hypothetical `0` typo, a per-cluster
20913        // override the operator pins through a future
20914        // `:placement :default-port` slot that lands out-of-range, a
20915        // per-edition Servico-port migration that lifted the floor
20916        // above the previous default without coordinating the pair —
20917        // would silently invalidate the serde-default emission at
20918        // every author-side `(:entrada (:host … :para …))` slot
20919        // without an explicit `:port`: the default port would fall
20920        // below the accept-set floor, the `AplicacaoSpec::validate`
20921        // gate would reject every default-carrying Aplicacao as
20922        // `EntradaPortZero`, and the substrate's typed
20923        // `(defcaixa … :kind Aplicacao)` surface would fail validate
20924        // on every Aplicacao whose author omitted `:entrada :port`
20925        // for the substrate's chosen default — a class of authoring-
20926        // surface footguns the compile-time pin structurally closes.
20927        // Peer with the
20928        // [`standalone_and_cluster_bundle_lareira_enabled_defaults_are_inverse_by_construction`]
20929        // (27f9b34) cross-const invariant pin discipline on the peer
20930        // canonical-Helm-per-values-block child-chart-enablement-toggle
20931        // axis pair.
20932        const {
20933            assert!(
20934                SERVICO_PORT_MIN <= DEFAULT_SERVICO_PORT,
20935                "the substrate's canonical default port DEFAULT_SERVICO_PORT \
20936                 must satisfy its own accept-set floor SERVICO_PORT_MIN — \
20937                 every default-carrying `(:entrada (:host … :para …))` slot \
20938                 without an explicit `:port` inherits `DEFAULT_SERVICO_PORT` \
20939                 through the serde default hook and must pass the \
20940                 `AplicacaoSpec::validate` floor gate by construction",
20941            );
20942        }
20943    }
20944
20945    #[test]
20946    fn entrada_port_zero_gate_routes_through_lifted_servico_port_min_floor() {
20947        // The gate-site pin — asserts the `AplicacaoSpec::validate`
20948        // floor gate at `if e.port < SERVICO_PORT_MIN` fires the
20949        // `EntradaPortZero` diagnostic on the below-floor input
20950        // `port: 0` (the only below-floor value the `u16` field can
20951        // carry — `SERVICO_PORT_MIN` is `1`, so the below-floor set
20952        // is the singleton `{0}`). A future refactor that drifts the
20953        // gate off the lifted const (silently re-introducing an
20954        // inline `if e.port == 0` byte-check) surfaces here — the
20955        // pin cannot distinguish `< 1` from `== 0` on the current
20956        // floor, but it *does* pin that the diagnostic fires on `0`
20957        // through whichever gate is wired, so any future accept-set
20958        // floor migration (a hypothetical unprivileged-only
20959        // migration lifting `SERVICO_PORT_MIN` to `1024`) must
20960        // update this test alongside the const declaration —
20961        // structurally guaranteeing the gate + accept-set + pin
20962        // trio move together. Peer with the
20963        // [`rejects_zero_entrada_port`] behavioral pin on the same
20964        // per-`:entrada :port` axis — that pin asserts the pre-lift
20965        // behavioral contract (`port: 0` → `EntradaPortZero`); this
20966        // pin adds the structural link to the lifted floor const.
20967        assert_eq!(SERVICO_PORT_MIN, 1, "current floor pinned above");
20968        let mut s = three_member_spec();
20969        s.entrada.as_mut().unwrap().port = 0;
20970        assert_eq!(s.validate().unwrap_err(), AplicacaoError::EntradaPortZero);
20971    }
20972
20973    // ── drift-detection: serde-derive-to-MEMBRO_KEY_* identity ────────────
20974
20975    #[test]
20976    fn membro_serde_keys_match_lifted_membro_key_consts() {
20977        // Load-bearing invariant: the two `MEMBRO_KEY_*` consts
20978        // ([`crate::MEMBRO_KEY_CAIXA`] / [`crate::MEMBRO_KEY_VERSAO`])
20979        // name the exact camelCase JSON keys the
20980        // `#[serde(rename_all = "camelCase")]` attribute on
20981        // [`Membro`] emits. Serialize a fully-populated `Membro` and pin
20982        // that each canonical byte-sequence appears verbatim in the
20983        // JSON — a future accidental `rename_all = "snake_case"` /
20984        // `"kebab-case"` / verbatim-field-name flip at the derive
20985        // attribute (any of which would silently break every downstream
20986        // JSON consumer that reaches for one of the two consts via
20987        // `Value::get(...)`) surfaces here as a build-time test failure
20988        // at `aplicacao.rs`, not as an apply-time
20989        // `.get(<stale-canonical-const>)` returning `None` far from the
20990        // derive-attr drift's commit. Peer with the sibling
20991        // `supervisor_spec_serde_keys_match_lifted_supervisor_key_consts`
20992        // (40cc4e5) pin on the M2 supervision-tree top-level axis —
20993        // same discipline the SupervisorSpec top-level lift established,
20994        // extended here to the M3 [`Membro`] per-`:membros` axis.
20995        let m = Membro {
20996            caixa: "catalog".into(),
20997            versao: "^0.1".into(),
20998        };
20999        let json = serde_json::to_string(&m).unwrap();
21000        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
21001            let quoted = format!("\"{key}\"");
21002            assert!(
21003                json.contains(&quoted),
21004                "serialized Membro must carry the lifted MEMBRO_KEY_* \
21005                 byte-sequence {quoted} verbatim in the JSON emission \
21006                 (got: {json})",
21007            );
21008        }
21009    }
21010
21011    #[test]
21012    fn membro_key_consts_are_pairwise_distinct() {
21013        // Cross-axis drift-detection pin: a future collapse of the two
21014        // canonical [`Membro`] per-entry byte-strings onto the same
21015        // value (e.g. an accidental copy-paste flip of
21016        // [`crate::MEMBRO_KEY_VERSAO`] to also read `"caixa"`) would
21017        // silently reroute every downstream probe on one axis onto the
21018        // sibling axis's overlay entry and pass every propagation-probe
21019        // test that expected only the stale axis's value. Peer of the
21020        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*` tetrad
21021        // (40cc4e5).
21022        let all = [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO];
21023        for (i, a) in all.iter().enumerate() {
21024            for b in all.iter().skip(i + 1) {
21025                assert_ne!(
21026                    a, b,
21027                    "MEMBRO_KEY_* consts must be pairwise-distinct \
21028                     canonical byte-sequences — got `{a}` == `{b}`",
21029                );
21030            }
21031        }
21032    }
21033
21034    // ── Entrada::resolved_paths — the substrate-canonical per-`:entrada`
21035    //    URL-path fallback resolver every HTTPRoute-aware renderer
21036    //    reaching for a per-rule path-list resolution routes through.
21037    //    The four pin tests below fix the four-way accept-set the
21038    //    resolver must always honor: (:paths-non-empty-verbatim,
21039    //    :paths-empty-falls-back-to-catchall, :paths-single-entry-verbatim,
21040    //    :paths-preserves-order-across-multiple-entries) — drift on any
21041    //    arm surfaces at caixa-core build time rather than at cluster-
21042    //    apply time. Peer discipline with `MeshPolicy::is_empty` on the
21043    //    sibling `:politicas` typed-primitive dispatch axis.
21044
21045    fn entrada_with_paths(paths: Vec<&str>) -> Entrada {
21046        Entrada {
21047            host: "example.com".into(),
21048            para: "cart".into(),
21049            paths: paths.into_iter().map(String::from).collect(),
21050            port: DEFAULT_SERVICO_PORT,
21051        }
21052    }
21053
21054    #[test]
21055    fn resolved_paths_returns_declared_paths_verbatim_when_non_empty() {
21056        // The typed `:entrada :paths` slot carries an author-declared
21057        // list — the resolver returns each entry verbatim, no
21058        // catch-all substitution. The canonical "author declared
21059        // paths, honor them verbatim" arm of the path-list dispatch.
21060        let e = entrada_with_paths(vec!["/api/cart", "/api/products"]);
21061        assert_eq!(
21062            e.resolved_paths(),
21063            vec!["/api/cart", "/api/products"],
21064            "resolved_paths must return each `:entrada :paths` entry \
21065             verbatim when the typed slot is non-empty (got {:?})",
21066            e.resolved_paths(),
21067        );
21068    }
21069
21070    #[test]
21071    fn resolved_paths_falls_back_to_gateway_api_default_http_route_path_when_paths_empty() {
21072        // Empty `:entrada :paths` slot — the resolver substitutes the
21073        // singleton [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
21074        // catch-all fallback verbatim. Pins the empty-arm of the
21075        // resolver's four-way accept-set against a future silent
21076        // detour that returned an empty Vec (which would emit an
21077        // HTTPRoute with zero rules — silently dropping every
21078        // external `:entrada` flow at admission time), routed to a
21079        // different fallback shape, or dropped the catch-all
21080        // altogether.
21081        let e = entrada_with_paths(vec![]);
21082        assert_eq!(
21083            e.resolved_paths(),
21084            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
21085            "resolved_paths on empty `:entrada :paths` must fall back \
21086             to the lifted GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH catch-\
21087             all — got {:?}",
21088            e.resolved_paths(),
21089        );
21090    }
21091
21092    #[test]
21093    fn resolved_paths_returns_single_declared_path_verbatim_when_len_one() {
21094        // Single-entry `:entrada :paths` — the resolver returns the
21095        // single declared path verbatim, NOT the catch-all fallback
21096        // (author declared a path, honor it — the empty-arm and the
21097        // len-1 arm are semantically distinct axes of the resolver's
21098        // accept-set). Pins that the resolver treats "author declared
21099        // one path" as authored input, not as the empty case.
21100        let e = entrada_with_paths(vec!["/api/only"]);
21101        assert_eq!(
21102            e.resolved_paths(),
21103            vec!["/api/only"],
21104            "resolved_paths on single-entry `:entrada :paths` must \
21105             return the declared path verbatim, NOT the catch-all \
21106             fallback (got {:?})",
21107            e.resolved_paths(),
21108        );
21109    }
21110
21111    #[test]
21112    fn resolved_paths_preserves_author_declared_order() {
21113        // The `:entrada :paths` list is author-ordered — the resolver
21114        // preserves the author's declaration order verbatim, since
21115        // per-rule dispatch order at the K8s Gateway API HTTPRoute
21116        // consumer is significant (first-match-wins under the
21117        // path-prefix matcher). Pins against a future silent
21118        // re-sort / dedup / normalize detour that reordered author
21119        // input.
21120        let e = entrada_with_paths(vec!["/z/last", "/a/first", "/m/mid"]);
21121        assert_eq!(
21122            e.resolved_paths(),
21123            vec!["/z/last", "/a/first", "/m/mid"],
21124            "resolved_paths must preserve author-declared `:entrada \
21125             :paths` order verbatim — got {:?}",
21126            e.resolved_paths(),
21127        );
21128    }
21129
21130    // ── Entrada::paths — the substrate-canonical per-`:entrada` raw-
21131    //    slot `&[String]` slice accessor every per-`:entrada` consumer
21132    //    that must see the author's declaration verbatim (not the
21133    //    fallback-applied projection the sibling `resolved_paths`
21134    //    returns) routes through. The three pin tests below fix the
21135    //    accept-set the accessor must honor: (:non-empty-byte-equal,
21136    //    :empty-projects-empty-slice, :preserves-author-declared-order)
21137    //    — drift on any arm surfaces at caixa-core build time rather
21138    //    than at cluster-apply time. Peer discipline with the sibling
21139    //    [`Placement::clusters`] (a6e18d7) `&[String]` accessor on the
21140    //    peer M3 mesh-slot `Vec<String>`-carry axis.
21141
21142    #[test]
21143    fn paths_returns_entrada_paths_slice_byte_equal_across_permutations() {
21144        // Byte-equal pin: [`Entrada::paths`] must project the raw
21145        // `:entrada :paths` `Vec<String>` verbatim as a `&[String]`
21146        // slice borrowed from the typed slot's own [`Vec<String>`]
21147        // storage — no re-ordering, no dedup, no per-entry normalization,
21148        // no fallback substitution (the fallback-applying projection is
21149        // the sibling [`Entrada::resolved_paths`] resolver). Pins against
21150        // a future silent detour that re-normalized the list, dropped
21151        // duplicates the [`AplicacaoSpec::validate`]
21152        // `EntradaPathDuplicate` refusal already rejects at build time,
21153        // or (most severe) accidentally routed through the fallback-
21154        // applying sibling and returned the substrate catch-all when
21155        // the author declared an empty list — collapsing the raw-slot
21156        // and fallback-applied axes into one and breaking the
21157        // [`AplicacaoSpec::validate`] "empty `:paths` is `Ok(())`" contract.
21158        //
21159        // Peer of the sibling
21160        // [`Placement::clusters`]-shape byte-equal pin
21161        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
21162        // (a6e18d7) on the peer M3 mesh-slot `Vec<String>`-carry axis.
21163        let fixtures: Vec<Vec<String>> = vec![
21164            Vec::new(),
21165            vec!["/api/cart".into()],
21166            vec!["/api/cart".into(), "/api/products".into()],
21167            vec!["/z/last".into(), "/a/first".into(), "/m/mid".into()],
21168        ];
21169        for paths in fixtures {
21170            let e = Entrada {
21171                host: "example.com".into(),
21172                para: "cart".into(),
21173                paths: paths.clone(),
21174                port: DEFAULT_SERVICO_PORT,
21175            };
21176            assert_eq!(
21177                e.paths(),
21178                paths.as_slice(),
21179                "Entrada::paths must return :entrada :paths verbatim \
21180                 (got {:?}, expected {:?})",
21181                e.paths(),
21182                paths.as_slice(),
21183            );
21184            assert_eq!(
21185                e.paths(),
21186                e.paths.as_slice(),
21187                "Entrada::paths accessor and .paths.as_slice() field \
21188                 access must byte-equal — the accessor is the substrate-\
21189                 primitive typed dispatch every downstream per-`:entrada` \
21190                 raw-slot path-list consumer must route through",
21191            );
21192            assert_eq!(
21193                e.paths().len(),
21194                e.paths.len(),
21195                "Entrada::paths().len() must byte-equal self.paths.len() \
21196                 — a length drift would silently split the paired \
21197                 pre-flight cascade-head `.is_empty()` probe input in \
21198                 the sibling [`Entrada::resolved_paths`] resolver from \
21199                 the per-entry validate loop's traversal input in \
21200                 [`AplicacaoSpec::validate`]",
21201            );
21202        }
21203    }
21204
21205    #[test]
21206    fn resolved_paths_reads_through_lifted_paths_accessor() {
21207        // Two-consumer coherence pin: the [`Entrada::resolved_paths`]
21208        // pre-flight `.paths().is_empty()` cascade-head probe (which
21209        // must trip the [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`]
21210        // catch-all fallback arm when the accessor projects the empty
21211        // slice) and the per-entry `.paths().iter().map(String::as_str)`
21212        // projection (which must reach every entry in the same order
21213        // the accessor projects, so the sibling
21214        // [`AplicacaoSpec::validate`] per-entry gate and the resolver's
21215        // per-entry projection stay in lockstep by construction) must
21216        // both key off the lifted accessor. Pins the two-site coherence
21217        // by exercising each production consumer end-to-end: (1) the
21218        // catch-all-fallback arm under the empty slice, (2) the
21219        // author-declared-verbatim arm under a two-entry cohort whose
21220        // per-entry projection must byte-equal the input's per-entry
21221        // author-declared paths in the author's declared order.
21222        //
21223        // Peer of the sibling M3
21224        // [`AplicacaoSpec::validate_placement`]-shape two-consumer pin
21225        // `validate_placement_reads_through_lifted_clusters_accessor`
21226        // on the sibling `Placement::clusters` reader-site convergence.
21227        let empty = entrada_with_paths(vec![]);
21228        assert_eq!(
21229            empty.resolved_paths(),
21230            vec![crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH],
21231            "resolved_paths on empty :entrada :paths must trip the \
21232             lifted [`crate::GATEWAY_API_DEFAULT_HTTP_ROUTE_PATH`] \
21233             catch-all fallback — routing through the lifted paths() \
21234             accessor must not silently drop the fallback arm",
21235        );
21236
21237        let declared = entrada_with_paths(vec!["/api/cart", "/api/products"]);
21238        assert_eq!(
21239            declared.resolved_paths(),
21240            vec!["/api/cart", "/api/products"],
21241            "resolved_paths on non-empty :entrada :paths must return each \
21242             entry verbatim in the author's declared order — routing \
21243             through the lifted paths() accessor must not silently \
21244             reorder or drop entries",
21245        );
21246        // Byte-equal pin against the raw-slot accessor to keep the
21247        // fallback-applying resolver's per-entry projection input in
21248        // lockstep with the raw-slot accessor's projection.
21249        let raw_projected: Vec<&str> = declared.paths().iter().map(String::as_str).collect();
21250        assert_eq!(
21251            declared.resolved_paths(),
21252            raw_projected,
21253            "resolved_paths non-empty projection must byte-equal the \
21254             lifted paths() accessor's per-entry String::as_str projection \
21255             — the two projections share the same input slice by \
21256             construction, so any drift here would surface a silent \
21257             re-ordering / dedup / normalization detour in the resolver",
21258        );
21259    }
21260
21261    #[test]
21262    fn validate_reads_through_lifted_entrada_paths_accessor() {
21263        // Two-consumer coherence pin: the [`AplicacaoSpec::validate`]
21264        // per-entry value-shape gate's `for p in e.paths()` traversal
21265        // (which must reach every entry in the same order the accessor
21266        // projects, so both the per-entry `EntradaPathEmpty` /
21267        // `EntradaPathNotAbsolute` / `EntradaPathInvalid` gates and
21268        // the duplicate-detection HashSet insert that trips
21269        // [`AplicacaoError::EntradaPathDuplicate`] key off the accessor's
21270        // projection) must route through the lifted accessor. Pins the
21271        // coherence by exercising each production consumer end-to-end:
21272        // (1) the `EntradaPathEmpty` refusal fires on the second entry
21273        // of a two-entry cohort whose head is valid but tail is empty
21274        // (which requires the loop to reach the second entry through
21275        // the accessor), and (2) the `EntradaPathDuplicate` refusal
21276        // fires on the second entry of a two-entry cohort that shares
21277        // a path (which requires the loop to reach both entries — a
21278        // first-entry-only projection would silently pass since the
21279        // dedup HashSet has room for the first insert).
21280        //
21281        // Peer of the sibling
21282        // `validate_placement_reads_through_lifted_clusters_accessor`
21283        // on the sibling `Placement::clusters` reader-site convergence.
21284        let base = crate::AplicacaoSpec {
21285            membros: vec![crate::Membro {
21286                caixa: "cart".into(),
21287                versao: "^0.1".into(),
21288            }],
21289            contratos: Vec::new(),
21290            politicas: crate::MeshPolicy::default(),
21291            placement: crate::Placement {
21292                estrategia: crate::PlacementStrategy::SingleNode,
21293                clusters: vec!["rio".into()],
21294                shard_key: None,
21295                affinity: None,
21296            },
21297            entrada: Some(Entrada {
21298                host: "example.com".into(),
21299                para: "cart".into(),
21300                paths: vec!["/api/cart".into(), String::new()],
21301                port: DEFAULT_SERVICO_PORT,
21302            }),
21303        };
21304        assert_eq!(
21305            base.validate(),
21306            Err(crate::AplicacaoError::EntradaPathEmpty),
21307            "validate must trip EntradaPathEmpty on the second entry of \
21308             a two-entry cohort — routing through the lifted paths() \
21309             accessor must not silently short-circuit the loop at the \
21310             valid head entry",
21311        );
21312
21313        let mut dup = base;
21314        dup.entrada.as_mut().unwrap().paths = vec!["/api/cart".into(), "/api/cart".into()];
21315        assert_eq!(
21316            dup.validate(),
21317            Err(crate::AplicacaoError::EntradaPathDuplicate {
21318                path: "/api/cart".into(),
21319            }),
21320            "validate must trip EntradaPathDuplicate on the second entry \
21321             of a two-entry cohort that shares a path — routing through \
21322             the lifted paths() accessor must not silently short-circuit \
21323             the dedup HashSet insert at the first entry",
21324        );
21325    }
21326
21327    // ── Entrada::hostname / Entrada::hostnames — the substrate-
21328    //    canonical per-`:entrada` DNS-hostname resolver pair every
21329    //    Gateway-API-aware renderer reaching for a per-listener
21330    //    singular `hostname:` filter (Gateway) or a per-route plural
21331    //    `spec.hostnames[]` filter list (HTTPRoute) routes through.
21332    //    The three pin tests below fix the two-way accept-set the pair
21333    //    must always honor: (:singular-byte-equal-to-host,
21334    //    :plural-is-singleton-of-singular, :plural-len-is-one) — drift
21335    //    on any arm surfaces at caixa-core build time rather than at
21336    //    cluster-apply time when the API server refuses the HTTPRoute
21337    //    for non-intersecting hostname filters. Peer discipline with
21338    //    the sibling `resolved_paths` accept-set pin block above on the
21339    //    per-`:entrada` path-list resolver axis.
21340
21341    fn entrada_with_host(host: &str) -> Entrada {
21342        Entrada {
21343            host: host.into(),
21344            para: "cart".into(),
21345            paths: Vec::new(),
21346            port: DEFAULT_SERVICO_PORT,
21347        }
21348    }
21349
21350    #[test]
21351    fn hostname_returns_entrada_host_byte_equal() {
21352        // The canonical singular-axis pin: [`Entrada::hostname`] must
21353        // return the `:entrada :host` field byte-for-byte, borrowed
21354        // from the typed slot's own [`String`] storage. Pins against a
21355        // future silent detour that re-normalized the host (an
21356        // accidental `.to_lowercase()` — validate_entrada_host already
21357        // enforces lowercase, so any re-normalization is redundant + a
21358        // drift surface between the validator and the accessor), a
21359        // trailing-`.` fully-qualified DNS shape substitution, or a
21360        // Punycode round-trip that lowered a Unicode host through IDNA.
21361        let e = entrada_with_host("checkout.quero.cloud");
21362        assert_eq!(
21363            e.hostname(),
21364            "checkout.quero.cloud",
21365            "Entrada::hostname must return :entrada :host verbatim \
21366             (got {:?})",
21367            e.hostname(),
21368        );
21369        assert_eq!(
21370            e.hostname(),
21371            e.host.as_str(),
21372            "Entrada::hostname must byte-equal the .host field access",
21373        );
21374    }
21375
21376    #[test]
21377    fn hostnames_returns_singleton_of_hostname_accessor() {
21378        // The pair-invariant pin: [`Entrada::hostnames`] must always
21379        // return exactly `vec![hostname()]` — the singleton list whose
21380        // sole entry is the substrate's canonical per-`:entrada`
21381        // singular hostname. Pins the two-consumer coherence axis: the
21382        // Gateway listener's singular `hostname:` filter and the
21383        // HTTPRoute's plural `spec.hostnames[]` filter list must
21384        // agree, else the Gateway API v1.x conformance layer rejects
21385        // the HTTPRoute at attach time with
21386        // `Accepted:False/NoMatchingParent` (the parent Gateway's
21387        // listener hostname doesn't intersect the route's hostname
21388        // filter list) — a divergence whose apply-time symptom is far
21389        // from any single-site commit and never surfaces in the
21390        // emitted YAML. Pinning the pair-invariant here makes any
21391        // future accidental split (an accidental `.to_string() + "."`
21392        // trailing-`.` on the plural side that didn't land on the
21393        // singular side, an accidental prefix stripping on one axis,
21394        // an accidental wildcard prepend the SNI fan-out overlay
21395        // authors on the plural side without a paired singular
21396        // migration) trip at caixa-core build time.
21397        let e = entrada_with_host("checkout.quero.cloud");
21398        assert_eq!(
21399            e.hostnames(),
21400            vec![e.hostname()],
21401            "Entrada::hostnames must return `vec![hostname()]` under \
21402             the pair-invariant — got {:?} vs. singleton {:?}",
21403            e.hostnames(),
21404            vec![e.hostname()],
21405        );
21406    }
21407
21408    #[test]
21409    fn hostnames_is_singleton_under_single_host_author_surface() {
21410        // The singleton-shape pin: under today's single-hostname-per-
21411        // `:entrada` author surface (the `:host` slot is a single
21412        // [`String`], not a `Vec<String>`), [`Entrada::hostnames`]
21413        // must always return a list of length exactly one. Pins
21414        // against a future silent detour that returned an empty list
21415        // (which would emit an HTTPRoute with `spec.hostnames: []` —
21416        // matching every incoming Host header regardless of the
21417        // Aplicacao's declared ingress apex, silently over-matching
21418        // every foreign VirtualHost the parent Gateway also fronts) or
21419        // a duplicated entry (which the Gateway API v1.x parser
21420        // accepts as a `[]-length-2 list of equal hostnames]` but
21421        // whose semantics differ from the intended singleton). The
21422        // author-surface extension point ("a future `:entrada
21423        // :alt-hosts` list overlay" the docstring names) is the sole
21424        // future axis that flips this pin — that migration will re-
21425        // author this test to pin the new plural cardinality.
21426        let e = entrada_with_host("checkout.quero.cloud");
21427        assert_eq!(
21428            e.hostnames().len(),
21429            1,
21430            "Entrada::hostnames must be a singleton under today's \
21431             single-hostname-per-`:entrada` author surface — got \
21432             length {}: {:?}",
21433            e.hostnames().len(),
21434            e.hostnames(),
21435        );
21436    }
21437
21438    // ── Entrada::destination — the substrate-canonical per-`:entrada`
21439    //    destination-Servico scalar accessor every Gateway-API
21440    //    HTTPRoute-aware renderer reaching for a per-CR `metadata.name`
21441    //    discriminator arg (HTTPRoute name composer) or a per-rule
21442    //    `backendRefs[0].name` axis routes through. The two pin tests
21443    //    below fix (:byte-equal-to-para, :borrow-not-copy) — drift on
21444    //    either arm surfaces at caixa-core build time rather than at
21445    //    cluster-apply time when an HTTPRoute's `metadata.name` and
21446    //    `backendRefs[]` silently disagree on which destination Servico
21447    //    the ingress fronts. Peer discipline with the sibling
21448    //    `resolved_paths` + `hostname` + `hostnames` accept-set pin
21449    //    blocks above on the per-`:entrada` path-list / DNS-hostname
21450    //    resolver axes.
21451
21452    #[test]
21453    fn destination_returns_entrada_para_byte_equal() {
21454        // The canonical destination-scalar pin: [`Entrada::destination`]
21455        // must return the `:entrada :para` field byte-for-byte, borrowed
21456        // from the typed slot's own [`String`] storage. Pins against a
21457        // future silent detour that re-normalized the destination (an
21458        // accidental `.to_lowercase()` — the destination Servico is
21459        // already validated as a DNS-1123 label upstream, so any
21460        // re-normalization is redundant + a drift surface between the
21461        // validator and the accessor), a namespace-prefix rewrite (an
21462        // accidental `format!("{namespace}/{para}")` per-CR fully-
21463        // qualified rewrite that didn't land on the peer axis), or a
21464        // per-cluster suffix stamp the operator authors on one
21465        // consumer without the other.
21466        for para in ["cart", "checkout", "catalog", "orders-v2"] {
21467            let e = Entrada {
21468                host: "checkout.quero.cloud".into(),
21469                para: para.into(),
21470                paths: Vec::new(),
21471                port: DEFAULT_SERVICO_PORT,
21472            };
21473            assert_eq!(
21474                e.destination(),
21475                para,
21476                "Entrada::destination must return :entrada :para verbatim \
21477                 (got {:?}, expected {para:?})",
21478                e.destination(),
21479            );
21480            assert_eq!(
21481                e.destination(),
21482                e.para.as_str(),
21483                "Entrada::destination must byte-equal the .para field access",
21484            );
21485        }
21486    }
21487
21488    #[test]
21489    fn destination_borrows_from_entrada_para_storage() {
21490        // The borrow-not-copy pin: [`Entrada::destination`] must
21491        // return a `&str` slice that borrows from the typed slot's
21492        // own [`String`] storage — same-address invariant with
21493        // `entrada.para.as_str()`. Pins against a future silent detour
21494        // that allocated a fresh `String` (`self.para.clone()` in the
21495        // body would type-check but silently drop the borrow, and
21496        // every downstream consumer that assumed the returned slice
21497        // outlives `&self` would break on a stale-reference use-after-
21498        // free). Peer with the sibling `hostname_returns_entrada_
21499        // host_byte_equal` on the singular-DNS-hostname axis.
21500        let e = entrada_with_host("checkout.quero.cloud");
21501        let dest = e.destination();
21502        let para_slice = e.para.as_str();
21503        assert_eq!(
21504            dest.as_ptr(),
21505            para_slice.as_ptr(),
21506            "Entrada::destination must borrow from the .para String's \
21507             backing storage — a fresh allocation here means the \
21508             accessor no longer names the substrate-primitive typed \
21509             dispatch and every downstream consumer would silently \
21510             carry a detached copy",
21511        );
21512        assert_eq!(
21513            dest.len(),
21514            para_slice.len(),
21515            "Entrada::destination and .para.as_str() must byte-equal in \
21516             length as well as in address",
21517        );
21518    }
21519
21520    #[test]
21521    fn port_returns_entrada_port_verbatim_across_permutations() {
21522        // The canonical L4-port-scalar pin: [`Entrada::port`] must
21523        // return the `:entrada :port` field verbatim as a `u16` across
21524        // every author-declared value in the validated accept-set
21525        // ([`SERVICO_PORT_MIN`]`..=u16::MAX`). Pins against a future
21526        // silent detour that clamped the port (an accidental
21527        // `.min(HTTPS_STANDARD_PORT)` per-cluster ceiling that didn't
21528        // land on the peer [`AplicacaoSpec::port_for_destination`]
21529        // resolver), rewrote it through a per-cluster port-remap table
21530        // the operator authors on one consumer without the other, or
21531        // substituted [`DEFAULT_SERVICO_PORT`] when the field held its
21532        // serde-default value (which would silently collapse the
21533        // distinction between "author explicitly declared `:port 8080`"
21534        // and "author omitted the slot and inherited the default" the
21535        // future per-cluster override slot depends on). Peer with the
21536        // sibling `destination_returns_entrada_para_byte_equal` +
21537        // `hostname_returns_entrada_host_byte_equal` pins on the
21538        // per-`:entrada` `&str` scalar axes.
21539        for port in [
21540            SERVICO_PORT_MIN,
21541            DEFAULT_SERVICO_PORT,
21542            8443u16,
21543            9090u16,
21544            u16::MAX,
21545        ] {
21546            let e = Entrada {
21547                host: "checkout.quero.cloud".into(),
21548                para: "cart".into(),
21549                paths: Vec::new(),
21550                port,
21551            };
21552            assert_eq!(
21553                e.port(),
21554                port,
21555                "Entrada::port must return :entrada :port verbatim \
21556                 (got {}, expected {port})",
21557                e.port(),
21558            );
21559            assert_eq!(
21560                e.port(),
21561                e.port,
21562                "Entrada::port accessor and .port field access must \
21563                 byte-equal — the accessor is the substrate-primitive \
21564                 typed dispatch every downstream L4-port consumer must \
21565                 route through",
21566            );
21567        }
21568    }
21569
21570    #[test]
21571    fn validate_entrada_port_floor_gate_reads_through_lifted_port_accessor() {
21572        // Two-consumer coherence pin: the
21573        // [`AplicacaoSpec::validate`] entrada-block structural-floor gate
21574        // (which reads through [`Entrada::port`] to compare against
21575        // [`SERVICO_PORT_MIN`]) and the
21576        // [`AplicacaoSpec::port_for_destination`] resolver (which reads
21577        // through [`Entrada::port`] to emit the per-destination
21578        // `HTTPRoute.backendRefs[0].port` scalar) must both key off the
21579        // lifted accessor, so any future rebrand on the typed slot's
21580        // reader shape lands at exactly one place. Pins the two-site
21581        // coherence by exercising a below-floor port through validate
21582        // (which must reject) and a validated in-accept-set port through
21583        // port_for_destination (which must emit the same value the
21584        // accessor returns).
21585        let mut spec = three_member_spec();
21586        if let Some(e) = spec.entrada.as_mut() {
21587            e.port = 0;
21588        }
21589        assert_eq!(
21590            spec.validate().unwrap_err(),
21591            AplicacaoError::EntradaPortZero,
21592            "validate must reject `:entrada :port 0` through the lifted \
21593             Entrada::port accessor — port zero lies below \
21594             SERVICO_PORT_MIN and the validator routes through port() \
21595             to name the floor",
21596        );
21597
21598        for port in [SERVICO_PORT_MIN, DEFAULT_SERVICO_PORT, 8443u16] {
21599            let mut spec = three_member_spec();
21600            if let Some(e) = spec.entrada.as_mut() {
21601                e.port = port;
21602            }
21603            spec.validate().expect(
21604                "entrada with in-accept-set :port must validate — the \
21605                 structural-floor gate reads through Entrada::port",
21606            );
21607            let entrada_ref = spec.entrada().expect(":entrada present");
21608            assert_eq!(
21609                spec.port_for_destination(entrada_ref.destination()),
21610                entrada_ref.port(),
21611                "port_for_destination(entrada.destination()) must equal \
21612                 entrada.port() — the two consumers of the per-:entrada \
21613                 L4-port axis (validator, per-destination resolver) both \
21614                 route through Entrada::port",
21615            );
21616        }
21617    }
21618
21619    #[test]
21620    fn wit_contract_source_returns_de_byte_equal_across_permutations() {
21621        // The canonical caller-Servico-scalar pin: [`WitContract::source`]
21622        // must return the `:contratos :de` field byte-for-byte, borrowed
21623        // from the typed slot's own [`String`] storage. Peer of the
21624        // sibling `destination_returns_entrada_para_byte_equal` pin on
21625        // the per-`:entrada` axis — same "the substrate-primitive
21626        // accessor must byte-equal the raw field access verbatim across
21627        // every author-declared value" discipline extended to the
21628        // per-`:contratos` caller arm. Pins against a future silent
21629        // detour that re-normalized the caller (an accidental
21630        // `.to_lowercase()` — every `:contratos :de` is validated as a
21631        // DNS-1123 label upstream via `validate_contrato_caixa`, so any
21632        // re-normalization is redundant + a drift surface between the
21633        // validator and the accessor), a namespace-prefix rewrite (an
21634        // accidental `format!("{namespace}/{de}")` per-CR fully-qualified
21635        // rewrite that didn't land on the peer axis), or a per-cluster
21636        // suffix stamp the operator authors on one consumer without the
21637        // other.
21638        for de in ["cart", "checkout", "catalog", "orders-v2"] {
21639            let c = WitContract {
21640                de: de.into(),
21641                para: "downstream".into(),
21642                wit: "wasi:http/proxy".into(),
21643                endpoint: Some("/lookup".into()),
21644                subject: None,
21645                slot: None,
21646            };
21647            assert_eq!(
21648                c.source(),
21649                de,
21650                "WitContract::source must return :contratos :de verbatim \
21651                 (got {:?}, expected {de:?})",
21652                c.source(),
21653            );
21654            assert_eq!(
21655                c.source(),
21656                c.de.as_str(),
21657                "WitContract::source must byte-equal the .de field access",
21658            );
21659        }
21660    }
21661
21662    #[test]
21663    fn wit_contract_source_borrows_from_de_storage() {
21664        // The borrow-not-copy pin: [`WitContract::source`] must return a
21665        // `&str` slice that borrows from the typed slot's own [`String`]
21666        // storage — same-address invariant with `c.de.as_str()`. Pins
21667        // against a future silent detour that allocated a fresh `String`
21668        // (`self.de.clone()` in the body would type-check but silently
21669        // drop the borrow, and every downstream consumer that assumed
21670        // the returned slice outlives `&self` would break on a stale-
21671        // reference use-after-free). Peer of the sibling
21672        // `destination_borrows_from_entrada_para_storage` on the
21673        // per-`:entrada` axis.
21674        let c = WitContract {
21675            de: "cart".into(),
21676            para: "catalog".into(),
21677            wit: "wasi:http/proxy".into(),
21678            endpoint: Some("/lookup".into()),
21679            subject: None,
21680            slot: None,
21681        };
21682        let src = c.source();
21683        let de_slice = c.de.as_str();
21684        assert_eq!(
21685            src.as_ptr(),
21686            de_slice.as_ptr(),
21687            "WitContract::source must borrow from the .de String's \
21688             backing storage — a fresh allocation here means the \
21689             accessor no longer names the substrate-primitive typed \
21690             dispatch and every downstream consumer would silently \
21691             carry a detached copy",
21692        );
21693        assert_eq!(
21694            src.len(),
21695            de_slice.len(),
21696            "WitContract::source and .de.as_str() must byte-equal in \
21697             length as well as in address",
21698        );
21699    }
21700
21701    #[test]
21702    fn wit_contract_destination_returns_para_byte_equal_across_permutations() {
21703        // The canonical callee-Servico-scalar pin: [`WitContract::destination`]
21704        // must return the `:contratos :para` field byte-for-byte,
21705        // borrowed from the typed slot's own [`String`] storage. Peer of
21706        // the sibling `destination_returns_entrada_para_byte_equal` on
21707        // the per-`:entrada` axis — both accessors name "the destination-
21708        // Servico byte-string" concept on their respective mesh-slot
21709        // atoms (per-ingress apex vs. per-typed-edge callee) and both
21710        // must project the underlying `.para` field verbatim so every
21711        // downstream renderer that composes them with peer accessors
21712        // (e.g. `spec.port_for_destination(c.destination())` at the CNP
21713        // per-edge L4 port emit site) reads the same byte-string the
21714        // author declared.
21715        for para in ["catalog", "payment", "orders", "inventory-v3"] {
21716            let c = WitContract {
21717                de: "cart".into(),
21718                para: para.into(),
21719                wit: "wasi:http/proxy".into(),
21720                endpoint: Some("/lookup".into()),
21721                subject: None,
21722                slot: None,
21723            };
21724            assert_eq!(
21725                c.destination(),
21726                para,
21727                "WitContract::destination must return :contratos :para \
21728                 verbatim (got {:?}, expected {para:?})",
21729                c.destination(),
21730            );
21731            assert_eq!(
21732                c.destination(),
21733                c.para.as_str(),
21734                "WitContract::destination must byte-equal the .para \
21735                 field access",
21736            );
21737        }
21738    }
21739
21740    #[test]
21741    fn wit_contract_destination_borrows_from_para_storage() {
21742        // The borrow-not-copy pin: [`WitContract::destination`] must
21743        // return a `&str` slice that borrows from the typed slot's own
21744        // [`String`] storage — same-address invariant with
21745        // `c.para.as_str()`. Peer of the sibling
21746        // `destination_borrows_from_entrada_para_storage` on the
21747        // per-`:entrada` axis.
21748        let c = WitContract {
21749            de: "cart".into(),
21750            para: "catalog".into(),
21751            wit: "wasi:http/proxy".into(),
21752            endpoint: Some("/lookup".into()),
21753            subject: None,
21754            slot: None,
21755        };
21756        let dest = c.destination();
21757        let para_slice = c.para.as_str();
21758        assert_eq!(
21759            dest.as_ptr(),
21760            para_slice.as_ptr(),
21761            "WitContract::destination must borrow from the .para \
21762             String's backing storage — a fresh allocation here means \
21763             the accessor no longer names the substrate-primitive typed \
21764             dispatch and every downstream consumer would silently \
21765             carry a detached copy",
21766        );
21767        assert_eq!(
21768            dest.len(),
21769            para_slice.len(),
21770            "WitContract::destination and .para.as_str() must byte-equal \
21771             in length as well as in address",
21772        );
21773    }
21774
21775    #[test]
21776    fn wit_contract_world_ref_returns_wit_byte_equal_across_permutations() {
21777        // The canonical per-`:contratos` WIT-world-reference scalar pin:
21778        // [`WitContract::world_ref`] must return the `:contratos :wit`
21779        // field byte-for-byte, borrowed from the typed slot's own
21780        // [`String`] storage. Sibling of the peer per-`:contratos`
21781        // [`WitContract::source`] / [`WitContract::destination`]
21782        // (7f0fd43), per-`:entrada` [`Entrada::hostname`] /
21783        // [`Entrada::destination`] (11f3dfe / 6db982c), per-`:membros`
21784        // [`Membro::nome`] / [`Membro::versao_requirement`] (4a32abf /
21785        // a40b0e3) pins on the mesh-slot-atom scalar-value axes — same
21786        // "the substrate-primitive accessor must byte-equal the raw
21787        // field access verbatim across every author-declared value"
21788        // discipline extended to the per-`:contratos` WIT-world arm.
21789        // Pins against a future silent detour that re-canonicalized the
21790        // WIT world reference (an accidental `.to_lowercase()` pass that
21791        // collapsed `WASI:HTTP/proxy` — every `:contratos :wit` past
21792        // [`WitContract::target`]'s [`crate::render::is_wit_world_ref`]
21793        // gate is already lowercase-prefixed so any re-normalization is
21794        // redundant + a drift surface between the validator and the
21795        // accessor), an M4-promotion-shape rewrite that formatted a
21796        // typed WIT-world enum through [`Display`] and silently drifted
21797        // the printer output from the source `caixa.lisp`, or a per-
21798        // cluster WIT-alias rewrite that didn't land on the peer field-
21799        // access sites. Five values sweep the shape-dispatch accept-set
21800        // the peer [`wit_shape_matches`] combinator admits (HTTP `wasi:`
21801        // / HTTP `http:` / PubSub `nats:` / PubSub `kafka:` / Store
21802        // `wasi:keyvalue/`).
21803        for (wit, endpoint, subject, slot) in [
21804            ("wasi:http/proxy", Some("/lookup"), None, None),
21805            ("http:proxy", Some("/health"), None, None),
21806            ("nats:pub-sub", None, Some("orders.paid"), None),
21807            ("kafka:events", None, Some("checkout-events"), None),
21808            ("wasi:keyvalue/store", None, None, Some("carts/{cart_id}")),
21809        ] {
21810            let c = WitContract {
21811                de: "cart".into(),
21812                para: "downstream".into(),
21813                wit: wit.into(),
21814                endpoint: endpoint.map(str::to_string),
21815                subject: subject.map(str::to_string),
21816                slot: slot.map(str::to_string),
21817            };
21818            assert_eq!(
21819                c.world_ref(),
21820                wit,
21821                "WitContract::world_ref must return :contratos :wit \
21822                 verbatim (got {:?}, expected {wit:?})",
21823                c.world_ref(),
21824            );
21825            assert_eq!(
21826                c.world_ref(),
21827                c.wit.as_str(),
21828                "WitContract::world_ref must byte-equal the .wit field \
21829                 access",
21830            );
21831        }
21832    }
21833
21834    #[test]
21835    fn wit_contract_world_ref_borrows_from_wit_storage() {
21836        // The borrow-not-copy pin: [`WitContract::world_ref`] must
21837        // return a `&str` slice that borrows from the typed slot's own
21838        // [`String`] storage — same-address invariant with
21839        // `c.wit.as_str()`. Pins against a future silent detour that
21840        // allocated a fresh `String` (`self.wit.clone()` in the body
21841        // would type-check but silently drop the borrow, and every
21842        // downstream consumer that assumed the returned slice outlives
21843        // `&self` would break on a stale-reference use-after-free — the
21844        // dedup-key `&str`-tuple at [`AplicacaoSpec::validate`]'s
21845        // duplicate-`:contratos` gate, the per-shape `wit_shape_is_*`
21846        // predicates' `&str` arg the peer [`is_http`][WitContract::is_http]
21847        // / [`is_pubsub`][WitContract::is_pubsub] /
21848        // [`is_store`][WitContract::is_store] methods route through —
21849        // each borrow from the WitContract's own storage and each would
21850        // silently misbehave if this accessor produced a detached copy).
21851        // Peer of the sibling per-`:contratos` [`WitContract::source`] /
21852        // [`WitContract::destination`] and per-`:entrada`
21853        // [`Entrada::destination`] / [`Entrada::hostname`] and
21854        // per-`:membros` [`Membro::nome`] / [`Membro::versao_requirement`]
21855        // borrow-invariant pins on the mesh-slot-atom scalar-value axes.
21856        let c = WitContract {
21857            de: "cart".into(),
21858            para: "catalog".into(),
21859            wit: "wasi:http/proxy".into(),
21860            endpoint: Some("/lookup".into()),
21861            subject: None,
21862            slot: None,
21863        };
21864        let world = c.world_ref();
21865        let wit_slice = c.wit.as_str();
21866        assert_eq!(
21867            world.as_ptr(),
21868            wit_slice.as_ptr(),
21869            "WitContract::world_ref must borrow from the .wit String's \
21870             backing storage — a fresh allocation here means the \
21871             accessor no longer names the substrate-primitive typed \
21872             dispatch and every downstream consumer would silently carry \
21873             a detached copy",
21874        );
21875        assert_eq!(
21876            world.len(),
21877            wit_slice.len(),
21878            "WitContract::world_ref and .wit.as_str() must byte-equal in \
21879             length as well as in address",
21880        );
21881    }
21882
21883    #[test]
21884    fn wit_contract_source_destination_world_ref_project_de_para_wit_triple() {
21885        // Sibling-triple invariant pin composing all three per-`:contratos`
21886        // substrate-primitive typed dispatches — [`WitContract::source`]
21887        // (7f0fd43), [`WitContract::destination`] (7f0fd43), and
21888        // [`WitContract::world_ref`] — at the joint
21889        // `(source(), destination(), world_ref())` call shape every
21890        // renderer that fans on per-edge caller-callee-shape identity
21891        // keys off. The invariant, evaluated per-contract:
21892        //
21893        //   (c.source(), c.destination(), c.world_ref())
21894        //   == (c.de.as_str(), c.para.as_str(), c.wit.as_str())
21895        //
21896        // Closes the last unlifted per-`:contratos` scalar axis — every
21897        // downstream consumer that reads the triple now routes through
21898        // exactly three typed dispatches on the substrate primitive,
21899        // not two typed + one open-coded field access. A future refactor
21900        // that silently split any one accessor's projection (an
21901        // accidental `world_ref()` M4-typed-WIT-enum `Display` re-
21902        // canonicalization that didn't reach the peer `source`/
21903        // `destination` arms, an accidental `source()` per-cluster
21904        // caller-alias rewrite that didn't land on the `world_ref` peer)
21905        // surfaces at caixa-core build time. Peer of the sibling per-
21906        // `:membros` `(nome(), versao_requirement())` (a40b0e3) and
21907        // per-`:entrada` `(hostname(), destination())` (6db982c /
21908        // 11f3dfe) pair invariants on the mesh-slot-atom scalar-value
21909        // axes, extended to the per-`:contratos` triple.
21910        for (de, para, wit, endpoint, subject, slot) in [
21911            (
21912                "cart",
21913                "catalog",
21914                "wasi:http/proxy",
21915                Some("/lookup"),
21916                None,
21917                None,
21918            ),
21919            (
21920                "checkout",
21921                "orders",
21922                "nats:pub-sub",
21923                None,
21924                Some("orders.paid"),
21925                None,
21926            ),
21927            (
21928                "cart",
21929                "kv",
21930                "wasi:keyvalue/store",
21931                None,
21932                None,
21933                Some("carts/{cart_id}"),
21934            ),
21935            (
21936                "orders-v2",
21937                "inventory-v3",
21938                "http:proxy",
21939                Some("/reserve"),
21940                None,
21941                None,
21942            ),
21943        ] {
21944            let c = WitContract {
21945                de: de.into(),
21946                para: para.into(),
21947                wit: wit.into(),
21948                endpoint: endpoint.map(str::to_string),
21949                subject: subject.map(str::to_string),
21950                slot: slot.map(str::to_string),
21951            };
21952            assert_eq!(
21953                (c.source(), c.destination(), c.world_ref()),
21954                (c.de.as_str(), c.para.as_str(), c.wit.as_str()),
21955                "(WitContract::source, ::destination, ::world_ref) must \
21956                 project (.de, .para, .wit) verbatim across every author-\
21957                 declared triple (got ({:?}, {:?}, {:?}), expected \
21958                 ({de:?}, {para:?}, {wit:?}))",
21959                c.source(),
21960                c.destination(),
21961                c.world_ref(),
21962            );
21963        }
21964    }
21965
21966    #[test]
21967    fn wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations() {
21968        // The canonical per-`:contratos` owned-form caller-callee-pair
21969        // pin: [`WitContract::edge_pair`] must return the
21970        // `(source(), destination())` tuple in owned form byte-for-byte,
21971        // projected through the lifted [`WitContract::source`] /
21972        // [`WitContract::destination`] scalar accessors. Pins the
21973        // composite-projection invariant on the per-`:contratos`
21974        // mesh-slot atom — every author-declared `(de, para)` pair must
21975        // round-trip verbatim through the substrate primitive's typed
21976        // dispatch, so the nine [`AplicacaoError`] diagnostic-
21977        // construction sites the accessor now feeds
21978        // ([`AplicacaoError::EmptyWit`],
21979        // [`AplicacaoError::ContratoEndpointEmpty`],
21980        // [`AplicacaoError::ContratoEndpointNotAbsolute`],
21981        // [`AplicacaoError::ContratoEndpointInvalid`],
21982        // [`AplicacaoError::ContratoSubjectEmpty`],
21983        // [`AplicacaoError::ContratoSubjectInvalid`],
21984        // [`AplicacaoError::ContratoSlotEmpty`],
21985        // [`AplicacaoError::ContratoSlotInvalid`],
21986        // [`AplicacaoError::ContratoDuplicate`]) all read the same
21987        // `(de, para)` label pair every author sees at the source
21988        // `caixa.lisp`. Pins against a future silent detour that swapped
21989        // the `.0` / `.1` arms (an accidental `(destination(),
21990        // source())` re-order in the body would silently invert every
21991        // downstream diagnostic's `de:` / `para:` label pair, silently
21992        // reversing the direction of every operator-facing typed error
21993        // arrow), a fresh-allocation shape drift (an accidental
21994        // `.to_string()` on one arm but not the other would leave the
21995        // owned/borrowed pair mismatched vs. the sibling `source()` /
21996        // `destination()` returns), or an M4 per-cluster caller/callee-
21997        // alias rewrite that landed on `source()` without reaching
21998        // `destination()` (or vice versa). Peer of the sibling per-
21999        // `:contratos` `(source, destination, world_ref)` triple
22000        // pin above on the mesh-slot-atom scalar-value axes, extended
22001        // to the owned-form pair-projection axis.
22002        for (de, para, wit, endpoint, subject, slot) in [
22003            (
22004                "cart",
22005                "catalog",
22006                "wasi:http/proxy",
22007                Some("/lookup"),
22008                None,
22009                None,
22010            ),
22011            (
22012                "checkout",
22013                "orders",
22014                "nats:pub-sub",
22015                None,
22016                Some("orders.paid"),
22017                None,
22018            ),
22019            (
22020                "cart",
22021                "kv",
22022                "wasi:keyvalue/store",
22023                None,
22024                None,
22025                Some("carts/{cart_id}"),
22026            ),
22027            (
22028                "orders-v2",
22029                "inventory-v3",
22030                "http:proxy",
22031                Some("/reserve"),
22032                None,
22033                None,
22034            ),
22035        ] {
22036            let c = WitContract {
22037                de: de.into(),
22038                para: para.into(),
22039                wit: wit.into(),
22040                endpoint: endpoint.map(str::to_string),
22041                subject: subject.map(str::to_string),
22042                slot: slot.map(str::to_string),
22043            };
22044            assert_eq!(
22045                c.edge_pair(),
22046                (de.to_string(), para.to_string()),
22047                "WitContract::edge_pair must return (:contratos :de, \
22048                 :contratos :para) as an owned tuple verbatim (got {:?}, \
22049                 expected ({de:?}, {para:?}))",
22050                c.edge_pair(),
22051            );
22052        }
22053    }
22054
22055    #[test]
22056    fn wit_contract_edge_pair_routes_through_source_destination_accessors() {
22057        // The composition pin: [`WitContract::edge_pair`] must return
22058        // exactly `(source().to_string(), destination().to_string())` —
22059        // the owned form of the sibling accessor pair — so any future
22060        // refactor that silently re-authored the caller-arm / callee-arm
22061        // projection to bypass the lifted scalar accessors (an accidental
22062        // `(self.de.clone(), self.para.clone())` regression back to the
22063        // raw field-access shape, an M4-typed-caller-enum `Display`
22064        // re-canonicalization on `source()` that didn't reach
22065        // `edge_pair()`, a per-cluster alias rewrite the operator lands
22066        // on `destination()` without reaching this composite projection)
22067        // trips at caixa-core build time. Pins the "typed dispatch
22068        // composes with typed dispatch, not with raw field access"
22069        // discipline every downstream diagnostic-construction site now
22070        // routes through — a `de:` / `para:` label pair whose
22071        // projection silently drifted off the substrate primitive's
22072        // scalar accessors would silently split the diagnostic's self-
22073        // locating signal from the source `caixa.lisp` author's view.
22074        // Peer of the sibling per-`:politicas` `is_empty` /
22075        // `validate_politicas` accessor-routing-pin family on the M3
22076        // mesh-slot family (18575, 18739, 18918, 19140, 19371).
22077        let c = WitContract {
22078            de: "cart".into(),
22079            para: "catalog".into(),
22080            wit: "wasi:http/proxy".into(),
22081            endpoint: Some("/lookup".into()),
22082            subject: None,
22083            slot: None,
22084        };
22085        assert_eq!(
22086            c.edge_pair(),
22087            (c.source().to_string(), c.destination().to_string()),
22088            "WitContract::edge_pair must compose exactly \
22089             (source().to_string(), destination().to_string()) — a \
22090             bypass of either sibling accessor here would silently \
22091             decouple the composite-projection axis from the \
22092             substrate-primitive scalar accessors every downstream \
22093             consumer routes through",
22094        );
22095    }
22096
22097    #[test]
22098    fn wit_contract_edge_triple_returns_source_destination_world_ref_owned_triple_across_permutations()
22099     {
22100        // The canonical per-`:contratos` owned-form
22101        // caller-callee-world-ref-triple pin:
22102        // [`WitContract::edge_triple`] must return the
22103        // `(source(), destination(), world_ref())` tuple in owned form
22104        // byte-for-byte, projected through the lifted
22105        // [`WitContract::source`] / [`WitContract::destination`] /
22106        // [`WitContract::world_ref`] scalar accessors. Pins the
22107        // composite-projection invariant on the per-`:contratos`
22108        // mesh-slot atom — every author-declared `(de, para, wit)`
22109        // triple must round-trip verbatim through the substrate
22110        // primitive's typed dispatch, so the nine
22111        // [`AplicacaoError`] diagnostic-construction sites the
22112        // accessor now feeds (the [`WitTarget`]-dispatch's eight
22113        // wrong-target / missing-target / invalid-wit / capability-
22114        // with-payload arms in [`WitContract::target`], plus the
22115        // paired duplicate-gate [`AplicacaoError::ContratoDuplicate`]
22116        // diagnostic constructor in [`AplicacaoSpec::validate`]) all
22117        // read the same `(de, para, wit)` triple every author sees at
22118        // the source `caixa.lisp`. Pins against a future silent
22119        // detour that swapped any two arms (an accidental `(destination(),
22120        // source(), world_ref())` re-order in the body would silently
22121        // invert every downstream diagnostic's `de:` / `para:` label
22122        // pair, silently reversing the direction of every operator-
22123        // facing typed error arrow), a fresh-allocation shape drift
22124        // (an accidental `.to_string()` skipped on one arm would leave
22125        // the owned/borrowed triple mismatched vs. the sibling
22126        // `source()` / `destination()` / `world_ref()` returns), or an
22127        // M4 per-cluster caller/callee-alias rewrite / per-CR world-ref
22128        // canonicalization pass that landed on one accessor without
22129        // reaching the peers. Peer of the sibling per-`:contratos`
22130        // caller-callee-pair
22131        // [`tests::wit_contract_edge_pair_returns_source_destination_owned_pair_across_permutations`]
22132        // pin on the mesh-slot-atom composite-projection axis,
22133        // extended to the triple-projection axis.
22134        for (de, para, wit, endpoint, subject, slot) in [
22135            (
22136                "cart",
22137                "catalog",
22138                "wasi:http/proxy",
22139                Some("/lookup"),
22140                None,
22141                None,
22142            ),
22143            (
22144                "checkout",
22145                "orders",
22146                "nats:pub-sub",
22147                None,
22148                Some("orders.paid"),
22149                None,
22150            ),
22151            (
22152                "cart",
22153                "kv",
22154                "wasi:keyvalue/store",
22155                None,
22156                None,
22157                Some("carts/{cart_id}"),
22158            ),
22159            (
22160                "orders-v2",
22161                "inventory-v3",
22162                "http:proxy",
22163                Some("/reserve"),
22164                None,
22165                None,
22166            ),
22167        ] {
22168            let c = WitContract {
22169                de: de.into(),
22170                para: para.into(),
22171                wit: wit.into(),
22172                endpoint: endpoint.map(str::to_string),
22173                subject: subject.map(str::to_string),
22174                slot: slot.map(str::to_string),
22175            };
22176            assert_eq!(
22177                c.edge_triple(),
22178                (de.to_string(), para.to_string(), wit.to_string()),
22179                "WitContract::edge_triple must return (:contratos :de, \
22180                 :contratos :para, :contratos :wit) as an owned triple \
22181                 verbatim (got {:?}, expected ({de:?}, {para:?}, {wit:?}))",
22182                c.edge_triple(),
22183            );
22184        }
22185    }
22186
22187    #[test]
22188    fn wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors() {
22189        // The composition pin: [`WitContract::edge_triple`] must return
22190        // exactly `(source().to_string(), destination().to_string(),
22191        // world_ref().to_string())` — the owned form of the sibling
22192        // scalar-accessor triple — so any future refactor that silently
22193        // re-authored one arm's projection to bypass the lifted scalar
22194        // accessors (an accidental `(self.de.clone(), self.para.clone(),
22195        // self.wit.clone())` regression back to the raw field-access
22196        // shape the internal `edge` closure and the ContratoDuplicate
22197        // diagnostic both carried before this lift landed, an
22198        // M4-typed-caller-enum `Display` re-canonicalization on
22199        // `source()` that didn't reach `edge_triple()`, a per-cluster
22200        // alias rewrite the operator lands on `destination()` /
22201        // `world_ref()` without reaching this composite projection)
22202        // trips at caixa-core build time. Pins the "typed dispatch
22203        // composes with typed dispatch, not with raw field access"
22204        // discipline every downstream diagnostic-construction site now
22205        // routes through — a `de:` / `para:` / `wit:` triple whose
22206        // projection silently drifted off the substrate primitive's
22207        // scalar accessors would silently split the diagnostic's self-
22208        // locating signal from the source `caixa.lisp` author's view.
22209        // Peer of the sibling per-`:contratos` edge_pair composition-
22210        // pin above on the mesh-slot-atom composite-projection axis.
22211        let c = WitContract {
22212            de: "cart".into(),
22213            para: "catalog".into(),
22214            wit: "wasi:http/proxy".into(),
22215            endpoint: Some("/lookup".into()),
22216            subject: None,
22217            slot: None,
22218        };
22219        assert_eq!(
22220            c.edge_triple(),
22221            (
22222                c.source().to_string(),
22223                c.destination().to_string(),
22224                c.world_ref().to_string(),
22225            ),
22226            "WitContract::edge_triple must compose exactly \
22227             (source().to_string(), destination().to_string(), \
22228             world_ref().to_string()) — a bypass of any sibling accessor \
22229             here would silently decouple the composite-projection axis \
22230             from the substrate-primitive scalar accessors every \
22231             downstream consumer routes through",
22232        );
22233    }
22234
22235    #[test]
22236    fn wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple() {
22237        // The canonical semantics-pin: [`WitContract::edge_triple`] must
22238        // project the full `(de, para, wit)` identity of a `:contratos`
22239        // edge — the sub-triple every triple-carrying
22240        // [`AplicacaoError::Contrato*`] diagnostic weaves into its
22241        // author-facing `de:` / `para:` / `wit:` fields (wrong-target,
22242        // missing-target, capability-with-payload, invalid-wit, and the
22243        // duplicate-gate). Rejects a drift in shape (an accidental
22244        // silent detour that returned a `(de, para)` pair or added an
22245        // extra field to the tuple, e.g. `(de, para, wit, endpoint)`,
22246        // would trip here because the return type would no longer
22247        // pattern-match the eight `let (de, para, wit) = edge();`
22248        // destructures the [`WitContract::target`] dispatch feeds off
22249        // + the paired duplicate-gate `let (de, para, wit) =
22250        // c.edge_triple();` destructure in
22251        // [`AplicacaoSpec::validate`]). Peer of the sibling per-
22252        // `:contratos` caller-callee-pair pin above extended to the
22253        // triple projection surface: closes the "one composite
22254        // accessor per typed diagnostic-construction sub-tuple"
22255        // discipline on the per-`:contratos` mesh-slot-atom axis.
22256        let c = WitContract {
22257            de: "checkout".into(),
22258            para: "orders".into(),
22259            wit: "nats:pub-sub".into(),
22260            endpoint: None,
22261            subject: Some("orders.paid".into()),
22262            slot: None,
22263        };
22264        let (de, para, wit) = c.edge_triple();
22265        assert_eq!(de, "checkout");
22266        assert_eq!(para, "orders");
22267        assert_eq!(wit, "nats:pub-sub");
22268    }
22269
22270    #[test]
22271    fn wit_contract_identity_routes_through_source_destination_world_ref_endpoint_subject_slot_accessors()
22272     {
22273        // The composition pin: [`WitContract::identity`] must return
22274        // exactly `(source(), destination(), world_ref(), endpoint(),
22275        // subject(), slot())` — the borrowed form of the six-scalar-
22276        // accessor identity axis. Any future refactor that silently
22277        // re-authored one arm's projection to bypass a scalar accessor
22278        // (a `self.de.as_str()` regression back to raw field access on
22279        // any of the three required arms, a `self.endpoint.as_deref()`
22280        // regression on any of the three optional arms, an M4 per-
22281        // cluster caller/callee-alias rewrite the operator lands on
22282        // `source()` / `destination()` without reaching this composite
22283        // projection) trips at caixa-core build time. Sweeps four
22284        // permutations of the WIT-shape × payload lattice — HTTP with
22285        // endpoint, pub-sub with subject, store with slot, payload-less
22286        // capability — so every payload arm is exercised. Peer of the
22287        // sibling per-`:contratos`
22288        // `wit_contract_edge_triple_routes_through_source_destination_world_ref_accessors`
22289        // composition pin on the mesh-slot-atom composite-projection
22290        // axis; extends the discipline from the (de, para, wit) prefix
22291        // onto the full-identity axis carrying the three payload arms.
22292        for (de, para, wit, endpoint, subject, slot) in [
22293            (
22294                "cart",
22295                "catalog",
22296                "wasi:http/proxy",
22297                Some("/lookup"),
22298                None,
22299                None,
22300            ),
22301            (
22302                "checkout",
22303                "orders",
22304                "nats:pub-sub",
22305                None,
22306                Some("orders.paid"),
22307                None,
22308            ),
22309            (
22310                "cart",
22311                "kv",
22312                "wasi:keyvalue/store",
22313                None,
22314                None,
22315                Some("carts/{cart_id}"),
22316            ),
22317            ("audit", "sink", "wasi:logging", None, None, None),
22318        ] {
22319            let c = WitContract {
22320                de: de.into(),
22321                para: para.into(),
22322                wit: wit.into(),
22323                endpoint: endpoint.map(str::to_owned),
22324                subject: subject.map(str::to_owned),
22325                slot: slot.map(str::to_owned),
22326            };
22327            assert_eq!(
22328                c.identity(),
22329                (
22330                    c.source(),
22331                    c.destination(),
22332                    c.world_ref(),
22333                    c.endpoint(),
22334                    c.subject(),
22335                    c.slot(),
22336                ),
22337                "WitContract::identity must compose exactly \
22338                 (source(), destination(), world_ref(), endpoint(), \
22339                 subject(), slot()) — a bypass of any sibling accessor \
22340                 here would silently decouple the identity-projection \
22341                 axis from the substrate-primitive scalar accessors \
22342                 every dedup-key consumer routes through",
22343            );
22344        }
22345    }
22346
22347    #[test]
22348    fn wit_contract_identity_projects_full_typed_edge_dedup_key_across_payload_shapes() {
22349        // The canonical semantics-pin: [`WitContract::identity`] must
22350        // project the six-axis (de, para, wit, endpoint, subject, slot)
22351        // dedup key the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22352        // gate keys off — two `WitContract`s that agree on all six axes
22353        // are the same typed edge declared twice, the graph-edge
22354        // analogue of duplicate `:membros` / `:placement :clusters` /
22355        // `:entrada :paths` entries. Rejects a shape drift (an
22356        // accidental silent detour that returned a prefix tuple or
22357        // added an extra field) by pattern-matching the six-arm shape.
22358        // Peer of the sibling per-`:contratos`
22359        // `wit_contract_edge_triple_projects_full_typed_edge_identity_owned_triple`
22360        // pin extended from the (de, para, wit) prefix onto the full
22361        // six-axis identity that the dedup key rides.
22362        let c = WitContract {
22363            de: "cart".into(),
22364            para: "catalog".into(),
22365            wit: "wasi:http/proxy".into(),
22366            endpoint: Some("/products/:id".into()),
22367            subject: None,
22368            slot: None,
22369        };
22370        let (de, para, wit, endpoint, subject, slot) = c.identity();
22371        assert_eq!(de, "cart");
22372        assert_eq!(para, "catalog");
22373        assert_eq!(wit, "wasi:http/proxy");
22374        assert_eq!(endpoint, Some("/products/:id"));
22375        assert_eq!(subject, None);
22376        assert_eq!(slot, None);
22377
22378        // Two byte-identical contracts must produce equal identities —
22379        // the dedup key's foundational invariant.
22380        let c2 = c.clone();
22381        assert_eq!(c.identity(), c2.identity());
22382
22383        // Any change on any of the six axes must break the identity —
22384        // sweeps by mutating one axis at a time.
22385        let mut mutated = c.clone();
22386        mutated.de = "search".into();
22387        assert_ne!(c.identity(), mutated.identity(), "de axis must partition");
22388        let mut mutated = c.clone();
22389        mutated.para = "warehouse".into();
22390        assert_ne!(c.identity(), mutated.identity(), "para axis must partition");
22391        let mut mutated = c.clone();
22392        mutated.wit = "http:legacy".into();
22393        assert_ne!(c.identity(), mutated.identity(), "wit axis must partition");
22394        let mut mutated = c.clone();
22395        mutated.endpoint = Some("/search".into());
22396        assert_ne!(
22397            c.identity(),
22398            mutated.identity(),
22399            "endpoint axis must partition"
22400        );
22401        let mut mutated = c.clone();
22402        mutated.subject = Some("orders.paid".into());
22403        assert_ne!(
22404            c.identity(),
22405            mutated.identity(),
22406            "subject axis must partition"
22407        );
22408        let mut mutated = c;
22409        mutated.slot = Some("carts/{id}".into());
22410        assert_ne!(mutated.identity().5, None, "slot axis must partition");
22411    }
22412
22413    #[test]
22414    fn wit_contract_is_self_loop_returns_true_on_matching_endpoints_across_permutations() {
22415        // The canonical per-`:contratos` structural-self-edge pin:
22416        // [`WitContract::is_self_loop`] must return `true` when the
22417        // `:de` and `:para` fields agree byte-for-byte, across every
22418        // WIT-shape variant the per-edge shape family carries. Pins
22419        // the shape-agnostic identity-space partition the
22420        // [`AplicacaoSpec::validate`] self-edge gate at
22421        // caixa-core/src/aplicacao.rs:5559 fires against — all four
22422        // [`WitTarget`] arms (HTTP / PubSub / Store / Capability) fall
22423        // under the same one predicate. Four permutations sweep the
22424        // accept-set: HTTP with endpoint, pub-sub with subject, KV
22425        // store with slot, and payload-less capability.
22426        for (nome, wit, endpoint, subject, slot) in [
22427            ("cart", "wasi:http/proxy", Some("/lookup"), None, None),
22428            ("checkout", "nats:pub-sub", None, Some("orders.paid"), None),
22429            (
22430                "kv",
22431                "wasi:keyvalue/store",
22432                None,
22433                None,
22434                Some("carts/{cart_id}"),
22435            ),
22436            ("audit", "wasi:logging", None, None, None),
22437        ] {
22438            let c = WitContract {
22439                de: nome.into(),
22440                para: nome.into(),
22441                wit: wit.into(),
22442                endpoint: endpoint.map(str::to_string),
22443                subject: subject.map(str::to_string),
22444                slot: slot.map(str::to_string),
22445            };
22446            assert!(
22447                c.is_self_loop(),
22448                "WitContract::is_self_loop must return true when \
22449                 :contratos :de == :contratos :para (got false on \
22450                 {nome:?} under {wit:?})",
22451            );
22452        }
22453    }
22454
22455    #[test]
22456    fn wit_contract_is_self_loop_returns_false_on_distinct_endpoints_across_permutations() {
22457        // The complement pin: [`WitContract::is_self_loop`] must return
22458        // `false` on every well-shaped inter-Servico contract (the
22459        // author-intended `:contratos` shape MESH-COMPOSITION §III.1
22460        // names — "Servico A calls Servico B" between two distinct
22461        // graph nodes). Pins against a future silent detour that
22462        // inverted the predicate (an accidental `!= ` swap for `==`
22463        // would silently reject every legitimate inter-Servico edge
22464        // and admit every self-edge — the exact inversion of the
22465        // author-intended shape). Four permutations sweep the same
22466        // WIT-shape accept-set the sibling positive-arm test carries.
22467        for (de, para, wit, endpoint, subject, slot) in [
22468            (
22469                "cart",
22470                "catalog",
22471                "wasi:http/proxy",
22472                Some("/lookup"),
22473                None,
22474                None,
22475            ),
22476            (
22477                "checkout",
22478                "orders",
22479                "nats:pub-sub",
22480                None,
22481                Some("orders.paid"),
22482                None,
22483            ),
22484            (
22485                "cart",
22486                "kv",
22487                "wasi:keyvalue/store",
22488                None,
22489                None,
22490                Some("carts/{cart_id}"),
22491            ),
22492            ("audit", "sink", "wasi:logging", None, None, None),
22493        ] {
22494            let c = WitContract {
22495                de: de.into(),
22496                para: para.into(),
22497                wit: wit.into(),
22498                endpoint: endpoint.map(str::to_string),
22499                subject: subject.map(str::to_string),
22500                slot: slot.map(str::to_string),
22501            };
22502            assert!(
22503                !c.is_self_loop(),
22504                "WitContract::is_self_loop must return false when \
22505                 :contratos :de differs from :contratos :para (got true \
22506                 on {de:?} → {para:?} under {wit:?})",
22507            );
22508        }
22509    }
22510
22511    #[test]
22512    fn wit_contract_is_self_loop_routes_through_source_destination_accessors() {
22513        // The composition pin: [`WitContract::is_self_loop`] must
22514        // resolve to exactly `self.source() == self.destination()` —
22515        // the equality probe of the sibling scalar-accessor pair — so
22516        // any future refactor that silently re-authored the predicate
22517        // to bypass the lifted scalar accessors (an accidental
22518        // `self.de == self.para` regression back to the raw field-
22519        // access shape, an M4-typed-caller-enum identity-comparison
22520        // rule that landed on `source()` without reaching
22521        // `destination()`, a per-cluster alias rewrite the operator
22522        // pins on `destination()` without reaching this predicate)
22523        // trips at caixa-core build time. Pins the "typed dispatch
22524        // composes with typed dispatch, not with raw field access"
22525        // discipline the sibling [`WitContract::edge_pair`] /
22526        // [`WitContract::edge_triple`] composite-projection accessors
22527        // already carry, extended onto the per-edge endpoint-equality
22528        // predicate axis. Positive and complement arms both fire.
22529        let self_edge = WitContract {
22530            de: "cart".into(),
22531            para: "cart".into(),
22532            wit: "wasi:http/proxy".into(),
22533            endpoint: Some("/lookup".into()),
22534            subject: None,
22535            slot: None,
22536        };
22537        assert_eq!(
22538            self_edge.is_self_loop(),
22539            self_edge.source() == self_edge.destination(),
22540            "WitContract::is_self_loop must compose exactly \
22541             `source() == destination()` — a bypass of either sibling \
22542             accessor here would silently decouple the endpoint-\
22543             equality predicate from the substrate-primitive scalar \
22544             accessors every downstream consumer routes through",
22545        );
22546        let inter_edge = WitContract {
22547            de: "cart".into(),
22548            para: "catalog".into(),
22549            wit: "wasi:http/proxy".into(),
22550            endpoint: Some("/lookup".into()),
22551            subject: None,
22552            slot: None,
22553        };
22554        assert_eq!(
22555            inter_edge.is_self_loop(),
22556            inter_edge.source() == inter_edge.destination(),
22557            "WitContract::is_self_loop must compose exactly \
22558             `source() == destination()` on the complement arm too",
22559        );
22560    }
22561
22562    #[test]
22563    fn wit_contract_target_wit_shape_gate_routes_through_world_ref_accessor() {
22564        // The composition pin: [`WitContract::target`]'s invalid-wit
22565        // value-shape gate must feed the reason string through the
22566        // lifted [`WitContract::world_ref`] scalar accessor — the same
22567        // typed dispatch on the substrate primitive every peer
22568        // per-`:contratos` payload-carrier extraction in the same
22569        // method body already routes through
22570        // ([`WitContract::endpoint`] on the HTTP-arm target extraction,
22571        // [`WitContract::subject`] on the pub-sub-arm target extraction,
22572        // [`WitContract::slot`] on the store-arm target extraction) and
22573        // every peer composite-projection accessor
22574        // ([`WitContract::edge_pair`], [`WitContract::edge_triple`],
22575        // [`WitContract::identity`]) already composes from. Any future
22576        // refactor that silently re-authored the gate to bypass the
22577        // lifted accessor (an accidental `&self.wit` regression back to
22578        // the raw field-access shape, an M4-typed-`WitWorld` `Display`
22579        // re-canonicalization on `world_ref()` that didn't reach this
22580        // gate, a per-CR lowercasing canonicalization pass the M4
22581        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer applies
22582        // per-tenant that lands on `world_ref()` without reaching this
22583        // gate) would silently split the invalid-wit diagnostic reason
22584        // from the substrate-primitive projection every downstream
22585        // consumer routes through. Same "typed dispatch composes with
22586        // typed dispatch, not with raw field access" discipline the
22587        // sibling
22588        // [`wit_contract_is_self_loop_routes_through_source_destination_accessors`]
22589        // pin already carries on the endpoint-equality predicate axis,
22590        // extended onto the invalid-wit value-shape gate axis inside
22591        // the same [`WitContract::target`] body. Closes the last
22592        // unlifted raw-field-access site inside `impl WitContract`.
22593        //
22594        // The fixture carries `:wit "WASI:HTTP/proxy"` — the canonical
22595        // uppercase-typo footgun the pre-c4213a4 shape silently demoted
22596        // to a capability-only edge; the value-shape gate rejects it
22597        // through [`crate::render::is_wit_world_ref`] on the substrate
22598        // primitive's ASCII-lowercase-only accept-set, with a
22599        // parser-shaped reason string the test asserts round-trips
22600        // byte-for-byte between the direct-dispatch call (through the
22601        // predicate on the accessor's projection) and the
22602        // [`WitContract::target`] gate's produced reason field.
22603        let c = WitContract {
22604            de: "cart".into(),
22605            para: "catalog".into(),
22606            wit: "WASI:HTTP/proxy".into(),
22607            endpoint: Some("/lookup".into()),
22608            subject: None,
22609            slot: None,
22610        };
22611        let err = c.target().unwrap_err();
22612        let AplicacaoError::ContratoWitInvalid {
22613            ref de,
22614            ref para,
22615            ref wit,
22616            ref reason,
22617        } = err
22618        else {
22619            panic!("expected ContratoWitInvalid, got {err:?}");
22620        };
22621        assert_eq!(de, "cart");
22622        assert_eq!(para, "catalog");
22623        assert_eq!(wit, "WASI:HTTP/proxy");
22624        let expected_reason = crate::render::is_wit_world_ref(c.world_ref()).unwrap_err();
22625        assert_eq!(
22626            *reason, expected_reason,
22627            "WitContract::target's invalid-wit value-shape gate reason \
22628             must compose exactly is_wit_world_ref(self.world_ref()) — \
22629             a bypass here (e.g. a raw `&self.wit` field-access \
22630             regression, or a divergent predicate on a different \
22631             projection) would silently decouple the invalid-wit \
22632             diagnostic's reason field from the substrate-primitive \
22633             scalar accessor every peer per-`:contratos` extraction in \
22634             the same method body already routes through",
22635        );
22636    }
22637
22638    #[test]
22639    fn wit_contract_is_self_loop_predicate_is_const_fn() {
22640        // Fail-before-pass-after pin on the [`WitContract::is_self_loop`]
22641        // caller-callee identity-space predicate's `const`-eval-surface
22642        // posture. The wrapper below dispatches through
22643        // [`WitContract::is_self_loop`] and is well-formed only when the
22644        // callee is itself `pub const fn` — any future accidental
22645        // downgrade to non-`const` fails the wrapper at caixa-core build
22646        // time with E0015 (`cannot call non-const method`), strictly
22647        // stronger than a runtime `assert!` and strictly stronger than a
22648        // module-scope `const _: () = assert!(…)` pin (the type's
22649        // `String` / `Option<String>` carriers rule out `const`-context
22650        // value construction; the `const fn` wrapper is the load-bearing
22651        // shape that side-steps the destructor-in-const restriction on
22652        // the value axis while still pinning the `const`-fn posture on
22653        // the callee — mirror of the sibling
22654        // [`wit_contract_pre_projection_accessor_family_is_const_fn`]
22655        // (279823b) and
22656        // [`wit_contract_identity_projection_accessor_is_const_fn`]
22657        // (1ab648c) pins' discipline verbatim on the peer scalar-
22658        // accessor and composite-projection surfaces). Closes the last
22659        // unlifted per-`:contratos` shape/identity predicate on the
22660        // const-eval surface — the peer WIT-shape-partition family
22661        // [`WitContract::is_http`] / [`WitContract::is_pubsub`] /
22662        // [`WitContract::is_store`] / [`WitContract::is_capability`]
22663        // already carried the `pub const fn` posture on the peer
22664        // WIT-world-ref classifier axis (d46420c / 84c2325 / 279823b);
22665        // this pin extends the same posture onto the caller-callee
22666        // identity-space partition. Sweeps every WIT-shape arm on both
22667        // the equal-endpoints (self-edge) and distinct-endpoints
22668        // (inter-edge) arms of the identity-space partition, plus one
22669        // same-length distinct-byte pair to pin the mid-loop `!=` arm
22670        // past the leading length-mismatch shortcut.
22671        const fn is_self_loop_via_const_fn(c: &WitContract) -> bool {
22672            c.is_self_loop()
22673        }
22674        let mk = |de: &str, para: &str, wit: &str| WitContract {
22675            de: de.into(),
22676            para: para.into(),
22677            wit: wit.into(),
22678            endpoint: None,
22679            subject: None,
22680            slot: None,
22681        };
22682        for (nome, wit) in [
22683            ("cart", "wasi:http/proxy"),
22684            ("checkout", "nats:pub-sub"),
22685            ("kv", "wasi:keyvalue/store"),
22686            ("audit", "wasi:logging"),
22687        ] {
22688            let self_edge = mk(nome, nome, wit);
22689            assert!(
22690                is_self_loop_via_const_fn(&self_edge),
22691                "self-edge {nome:?} under {wit:?}"
22692            );
22693            assert_eq!(
22694                is_self_loop_via_const_fn(&self_edge),
22695                self_edge.is_self_loop()
22696            );
22697        }
22698        for (de, para, wit) in [
22699            ("cart", "catalog", "wasi:http/proxy"),
22700            ("checkout", "orders", "nats:pub-sub"),
22701            ("cart", "kv", "wasi:keyvalue/store"),
22702            ("audit", "sink", "wasi:logging"),
22703        ] {
22704            let inter_edge = mk(de, para, wit);
22705            assert!(
22706                !is_self_loop_via_const_fn(&inter_edge),
22707                "inter-edge {de:?}→{para:?} under {wit:?}",
22708            );
22709            assert_eq!(
22710                is_self_loop_via_const_fn(&inter_edge),
22711                inter_edge.is_self_loop()
22712            );
22713        }
22714        // Same-length distinct-byte pair — pins the mid-loop `!=` arm
22715        // past the leading `a.len() != b.len()` shortcut so the const-fn
22716        // wrapper exercises every arm of the byte-slice equality loop.
22717        let same_len_pair = mk("cart", "kart", "wasi:http/proxy");
22718        assert!(
22719            !is_self_loop_via_const_fn(&same_len_pair),
22720            "same-length distinct-byte"
22721        );
22722        assert_eq!(
22723            is_self_loop_via_const_fn(&same_len_pair),
22724            same_len_pair.is_self_loop()
22725        );
22726    }
22727
22728    #[test]
22729    fn wit_contract_endpoint_returns_endpoint_option_byte_equal_across_permutations() {
22730        // The canonical per-`:contratos` HTTP-shaped `:endpoint`-scalar
22731        // pin: [`WitContract::endpoint`] must return the `:contratos
22732        // :endpoint` field byte-for-byte, borrowed from the typed slot's
22733        // own `Option<String>` storage. Peer of the sibling
22734        // per-`:placement` [`Placement::shard_key`] (7cd2a28) /
22735        // [`Placement::affinity`] (74ec2d3) accessor pins on the M3
22736        // mesh-slot `Option<String>` optional-scalar axes — same "the
22737        // substrate-primitive accessor must byte-equal the raw field
22738        // access verbatim across every author-declared value" discipline
22739        // extended to the per-`:contratos` HTTP-payload-carrier arm.
22740        // Pins against a future silent detour that re-canonicalized the
22741        // endpoint (an accidental percent-encoding pass that didn't
22742        // reach the peer field-access site at the dedup key, a per-CR
22743        // fully-qualified prefix rewrite the operator authors on one
22744        // consumer without the other, or an M4 typed-path-template
22745        // `Display` re-canonicalization that silently drifted the
22746        // printer output from the source `caixa.lisp`). Four values
22747        // sweep the accept-set the [`crate::render::is_gateway_api_http_path`]
22748        // gate upstream admits (short root-path, dashed, param-shaped,
22749        // deep-hierarchy).
22750        for endpoint in ["/lookup", "/api/v1/orders", "/products/:id", "/health/live"] {
22751            let c = WitContract {
22752                de: "cart".into(),
22753                para: "catalog".into(),
22754                wit: "wasi:http/proxy".into(),
22755                endpoint: Some(endpoint.into()),
22756                subject: None,
22757                slot: None,
22758            };
22759            assert_eq!(
22760                c.endpoint(),
22761                Some(endpoint),
22762                "WitContract::endpoint must return :contratos :endpoint \
22763                 verbatim (got {:?}, expected Some({endpoint:?}))",
22764                c.endpoint(),
22765            );
22766            assert_eq!(
22767                c.endpoint(),
22768                c.endpoint.as_deref(),
22769                "WitContract::endpoint must byte-equal the .endpoint \
22770                 field's `.as_deref()` projection",
22771            );
22772        }
22773    }
22774
22775    #[test]
22776    fn wit_contract_endpoint_none_when_field_is_none() {
22777        // The absent-`:endpoint` arm of the per-`:contratos` HTTP-shaped
22778        // payload-carrier accessor pin: when the typed slot is absent —
22779        // the canonical shape under a non-HTTP `:wit` world per the
22780        // [`WitContract::target`]-enforced shape ↔ target partition
22781        // ([`WitTarget::PubSub`] carries `:subject`, [`WitTarget::Store`]
22782        // carries `:slot`, [`WitTarget::Capability`] carries none) —
22783        // [`WitContract::endpoint`] must return `None`. Pins against a
22784        // future silent detour that projected the absent slot to a
22785        // `Some("")` empty-string default (the canonical `Option<String>`
22786        // → `String` collapse footgun the sibling M2
22787        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22788        // emptiness predicates already guard on the peer M2 typed-slot
22789        // surfaces), a `Some("None")` stringified-None round-trip, or a
22790        // `Some` arm whose contents were derived from a sibling slot (an
22791        // accidental fallback to the `:subject` / `:slot` payload that
22792        // read the pub-sub / store payload into the endpoint axis).
22793        // Three contracts sweep the accept-set every non-HTTP `:wit`
22794        // world lands on — pub-sub NATS, key/value, and payload-less
22795        // capability.
22796        for (wit, subject, slot) in [
22797            ("nats:pub-sub", Some("orders.paid"), None),
22798            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22799            ("wasi:cli/environment", None, None),
22800        ] {
22801            let c = WitContract {
22802                de: "cart".into(),
22803                para: "downstream".into(),
22804                wit: wit.into(),
22805                endpoint: None,
22806                subject: subject.map(str::to_string),
22807                slot: slot.map(str::to_string),
22808            };
22809            assert!(
22810                c.endpoint().is_none(),
22811                "WitContract::endpoint must return None when the typed \
22812                 slot is absent under :wit {wit:?} (got {:?})",
22813                c.endpoint(),
22814            );
22815            assert_eq!(
22816                c.endpoint(),
22817                c.endpoint.as_deref(),
22818                "WitContract::endpoint must byte-equal the .endpoint \
22819                 field's `.as_deref()` projection in the absent arm",
22820            );
22821        }
22822    }
22823
22824    #[test]
22825    fn wit_contract_endpoint_borrows_from_endpoint_storage() {
22826        // The borrow-not-copy pin: [`WitContract::endpoint`] must return
22827        // an `Option<&str>` whose `Some` arm borrows from the typed
22828        // slot's own [`String`] storage — same-address invariant with
22829        // `c.endpoint.as_deref().unwrap()`. Pins against a future silent
22830        // detour that allocated a fresh `String`
22831        // (`self.endpoint.clone().map(...)` in the body would type-check
22832        // but silently drop the borrow, and every downstream consumer
22833        // that assumed the returned slice outlives `&self` would break
22834        // on a stale-reference use-after-free — the [`WitContract::target`]
22835        // Http-arm payload extraction rebinds the returned `Option<&str>`
22836        // through `.ok_or_else(...)` and threads the `&str` payload into
22837        // [`WitTarget::Http { endpoint: &'a str }`], the
22838        // [`AplicacaoSpec::validate`] duplicate-`:contratos`
22839        // [`ContratoIdentity`] dedup key threads the returned
22840        // `Option<&str>` into the six-tuple's HTTP arm — each borrow
22841        // from the WitContract's own storage and each would silently
22842        // misbehave if this accessor produced a detached copy). Peer of
22843        // the sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
22844        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22845        // shaped optional-scalar axes — first extension of the
22846        // `Option<&str>` borrow-not-copy discipline onto the
22847        // per-`:contratos` HTTP-shaped payload-carrier axis.
22848        let c = WitContract {
22849            de: "cart".into(),
22850            para: "catalog".into(),
22851            wit: "wasi:http/proxy".into(),
22852            endpoint: Some("/lookup".into()),
22853            subject: None,
22854            slot: None,
22855        };
22856        let ep = c.endpoint().expect("Some arm");
22857        let storage_slice = c.endpoint.as_deref().expect("Some arm — storage side");
22858        assert_eq!(
22859            ep.as_ptr(),
22860            storage_slice.as_ptr(),
22861            "WitContract::endpoint must borrow from the .endpoint \
22862             String's backing storage — a fresh allocation here means \
22863             the accessor no longer names the substrate-primitive typed \
22864             dispatch and every downstream consumer would silently \
22865             carry a detached copy",
22866        );
22867        assert_eq!(
22868            ep.len(),
22869            storage_slice.len(),
22870            "WitContract::endpoint and .endpoint.as_deref() must byte-\
22871             equal in length as well as in address",
22872        );
22873    }
22874
22875    #[test]
22876    fn wit_contract_subject_returns_subject_option_byte_equal_across_permutations() {
22877        // The canonical per-`:contratos` pub-sub-shaped `:subject`-scalar
22878        // pin: [`WitContract::subject`] must return the `:contratos
22879        // :subject` field byte-for-byte, borrowed from the typed slot's
22880        // own `Option<String>` storage. Peer of the sibling per-`:contratos`
22881        // [`WitContract::endpoint`] (7020470) accessor pin on the M3
22882        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
22883        // optional-scalar axis — same "the substrate-primitive accessor
22884        // must byte-equal the raw field access verbatim across every
22885        // author-declared value" discipline extended to the pub-sub arm.
22886        // Pins against a future silent detour that re-canonicalized the
22887        // subject (an accidental `.to_lowercase()` normalization that
22888        // didn't reach the peer field-access site at the dedup key, a
22889        // per-CR fully-qualified prefix rewrite the operator authors on
22890        // one consumer without the other, or an M4 typed-subject-template
22891        // `Display` re-canonicalization that silently drifted the printer
22892        // output from the source `caixa.lisp`). Four values sweep the
22893        // NATS accept-set every pub-sub author-declared subject lands on
22894        // (flat token, dotted hierarchy, per-tenant prefix, wildcard).
22895        for subject in ["events", "orders.paid", "tenant-a.orders", "orders.>"] {
22896            let c = WitContract {
22897                de: "cart".into(),
22898                para: "notifier".into(),
22899                wit: "nats:pub-sub".into(),
22900                endpoint: None,
22901                subject: Some(subject.into()),
22902                slot: None,
22903            };
22904            assert_eq!(
22905                c.subject(),
22906                Some(subject),
22907                "WitContract::subject must return :contratos :subject \
22908                 verbatim (got {:?}, expected Some({subject:?}))",
22909                c.subject(),
22910            );
22911            assert_eq!(
22912                c.subject(),
22913                c.subject.as_deref(),
22914                "WitContract::subject must byte-equal the .subject \
22915                 field's `.as_deref()` projection",
22916            );
22917        }
22918    }
22919
22920    #[test]
22921    fn wit_contract_subject_none_when_field_is_none() {
22922        // The absent-`:subject` arm of the per-`:contratos` pub-sub-
22923        // shaped payload-carrier accessor pin: when the typed slot is
22924        // absent — the canonical shape under a non-pub-sub `:wit` world
22925        // per the [`WitContract::target`]-enforced shape ↔ target
22926        // partition ([`WitTarget::Http`] carries `:endpoint`,
22927        // [`WitTarget::Store`] carries `:slot`, [`WitTarget::Capability`]
22928        // carries none) — [`WitContract::subject`] must return `None`.
22929        // Pins against a future silent detour that projected the absent
22930        // slot to a `Some("")` empty-string default (the canonical
22931        // `Option<String>` → `String` collapse footgun the sibling M2
22932        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
22933        // emptiness predicates already guard on the peer M2 typed-slot
22934        // surfaces), a `Some("None")` stringified-None round-trip, or a
22935        // `Some` arm whose contents were derived from a sibling slot (an
22936        // accidental fallback to the `:endpoint` / `:slot` payload that
22937        // read the HTTP / store payload into the subject axis). Three
22938        // contracts sweep the accept-set every non-pub-sub `:wit` world
22939        // lands on — HTTP proxy, key/value store, and payload-less
22940        // capability.
22941        for (wit, endpoint, slot) in [
22942            ("wasi:http/proxy", Some("/lookup"), None),
22943            ("wasi:keyvalue/store", None, Some("carts/{cart_id}")),
22944            ("wasi:cli/environment", None, None),
22945        ] {
22946            let c = WitContract {
22947                de: "cart".into(),
22948                para: "downstream".into(),
22949                wit: wit.into(),
22950                endpoint: endpoint.map(str::to_string),
22951                subject: None,
22952                slot: slot.map(str::to_string),
22953            };
22954            assert!(
22955                c.subject().is_none(),
22956                "WitContract::subject must return None when the typed \
22957                 slot is absent under :wit {wit:?} (got {:?})",
22958                c.subject(),
22959            );
22960            assert_eq!(
22961                c.subject(),
22962                c.subject.as_deref(),
22963                "WitContract::subject must byte-equal the .subject \
22964                 field's `.as_deref()` projection in the absent arm",
22965            );
22966        }
22967    }
22968
22969    #[test]
22970    fn wit_contract_subject_borrows_from_subject_storage() {
22971        // The borrow-not-copy pin: [`WitContract::subject`] must return
22972        // an `Option<&str>` whose `Some` arm borrows from the typed
22973        // slot's own [`String`] storage — same-address invariant with
22974        // `c.subject.as_deref().unwrap()`. Pins against a future silent
22975        // detour that allocated a fresh `String`
22976        // (`self.subject.clone().map(...)` in the body would type-check
22977        // but silently drop the borrow, and every downstream consumer
22978        // that assumed the returned slice outlives `&self` would break
22979        // on a stale-reference use-after-free — the [`WitContract::target`]
22980        // PubSub-arm payload extraction rebinds the returned
22981        // `Option<&str>` through `.ok_or_else(...)` and threads the
22982        // `&str` payload into [`WitTarget::PubSub { subject: &'a str }`],
22983        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
22984        // [`ContratoIdentity`] dedup key threads the returned
22985        // `Option<&str>` into the six-tuple's pub-sub arm — each borrow
22986        // from the WitContract's own storage and each would silently
22987        // misbehave if this accessor produced a detached copy). Peer of
22988        // the sibling per-`:contratos` [`WitContract::endpoint`] (7020470)
22989        // borrow-invariant pin on the M3 mesh-slot `Option<String>`-
22990        // shaped optional-scalar axis — second extension of the
22991        // `Option<&str>` borrow-not-copy discipline onto the
22992        // per-`:contratos` payload-carrier family, this time on the
22993        // pub-sub arm.
22994        let c = WitContract {
22995            de: "cart".into(),
22996            para: "notifier".into(),
22997            wit: "nats:pub-sub".into(),
22998            endpoint: None,
22999            subject: Some("orders.paid".into()),
23000            slot: None,
23001        };
23002        let sub = c.subject().expect("Some arm");
23003        let storage_slice = c.subject.as_deref().expect("Some arm — storage side");
23004        assert_eq!(
23005            sub.as_ptr(),
23006            storage_slice.as_ptr(),
23007            "WitContract::subject must borrow from the .subject \
23008             String's backing storage — a fresh allocation here means \
23009             the accessor no longer names the substrate-primitive typed \
23010             dispatch and every downstream consumer would silently \
23011             carry a detached copy",
23012        );
23013        assert_eq!(
23014            sub.len(),
23015            storage_slice.len(),
23016            "WitContract::subject and .subject.as_deref() must byte-\
23017             equal in length as well as in address",
23018        );
23019    }
23020
23021    #[test]
23022    fn wit_contract_slot_returns_slot_option_byte_equal_across_permutations() {
23023        // The canonical per-`:contratos` key/value-store-shaped
23024        // `:slot`-scalar pin: [`WitContract::slot`] must return the
23025        // `:contratos :slot` field byte-for-byte, borrowed from the
23026        // typed slot's own `Option<String>` storage. Peer of the
23027        // sibling per-`:contratos` [`WitContract::endpoint`] (7020470) /
23028        // [`WitContract::subject`] (90de675) accessor pins on the M3
23029        // mesh-slot per-`:contratos` payload-carrier `Option<String>`
23030        // optional-scalar axis — same "the substrate-primitive
23031        // accessor must byte-equal the raw field access verbatim
23032        // across every author-declared value" discipline extended to
23033        // the store arm. Pins against a future silent detour that
23034        // re-canonicalized the slot template (an accidental
23035        // `.to_lowercase()` bucket-prefix normalization that didn't
23036        // reach the peer field-access site at the dedup key, a per-CR
23037        // fully-qualified prefix rewrite the operator authors on one
23038        // consumer without the other, or an M4 typed-key-template
23039        // `Display` re-canonicalization that silently drifted the
23040        // printer output from the source `caixa.lisp`). Four values
23041        // sweep the wasi:keyvalue accept-set every store-shaped
23042        // author-declared slot lands on (flat bucket, single-param
23043        // template, multi-param template, nested-hierarchy template).
23044        for slot in [
23045            "sessions",
23046            "carts/{cart_id}",
23047            "orders/{tenant}/{order_id}",
23048            "cache/tenant-a/orders/{id}",
23049        ] {
23050            let c = WitContract {
23051                de: "cart".into(),
23052                para: "kv".into(),
23053                wit: "wasi:keyvalue/store".into(),
23054                endpoint: None,
23055                subject: None,
23056                slot: Some(slot.into()),
23057            };
23058            assert_eq!(
23059                c.slot(),
23060                Some(slot),
23061                "WitContract::slot must return :contratos :slot \
23062                 verbatim (got {:?}, expected Some({slot:?}))",
23063                c.slot(),
23064            );
23065            assert_eq!(
23066                c.slot(),
23067                c.slot.as_deref(),
23068                "WitContract::slot must byte-equal the .slot field's \
23069                 `.as_deref()` projection",
23070            );
23071        }
23072    }
23073
23074    #[test]
23075    fn wit_contract_slot_none_when_field_is_none() {
23076        // The absent-`:slot` arm of the per-`:contratos` store-shaped
23077        // payload-carrier accessor pin: when the typed slot is absent —
23078        // the canonical shape under a non-store `:wit` world per the
23079        // [`WitContract::target`]-enforced shape ↔ target partition
23080        // ([`WitTarget::Http`] carries `:endpoint`, [`WitTarget::PubSub`]
23081        // carries `:subject`, [`WitTarget::Capability`] carries none) —
23082        // [`WitContract::slot`] must return `None`. Pins against a
23083        // future silent detour that projected the absent slot to a
23084        // `Some("")` empty-string default (the canonical
23085        // `Option<String>` → `String` collapse footgun the sibling M2
23086        // [`crate::LimitsSpec::is_empty`] / [`crate::BehaviorSpec::is_empty`]
23087        // emptiness predicates already guard on the peer M2 typed-slot
23088        // surfaces), a `Some("None")` stringified-None round-trip, or
23089        // a `Some` arm whose contents were derived from a sibling
23090        // slot (an accidental fallback to the `:endpoint` / `:subject`
23091        // payload that read the HTTP / pub-sub payload into the store
23092        // axis). Three contracts sweep the accept-set every non-store
23093        // `:wit` world lands on — HTTP proxy, pub-sub NATS, and
23094        // payload-less capability.
23095        for (wit, endpoint, subject) in [
23096            ("wasi:http/proxy", Some("/lookup"), None),
23097            ("nats:pub-sub", None, Some("orders.paid")),
23098            ("wasi:cli/environment", None, None),
23099        ] {
23100            let c = WitContract {
23101                de: "cart".into(),
23102                para: "downstream".into(),
23103                wit: wit.into(),
23104                endpoint: endpoint.map(str::to_string),
23105                subject: subject.map(str::to_string),
23106                slot: None,
23107            };
23108            assert!(
23109                c.slot().is_none(),
23110                "WitContract::slot must return None when the typed \
23111                 slot is absent under :wit {wit:?} (got {:?})",
23112                c.slot(),
23113            );
23114            assert_eq!(
23115                c.slot(),
23116                c.slot.as_deref(),
23117                "WitContract::slot must byte-equal the .slot field's \
23118                 `.as_deref()` projection in the absent arm",
23119            );
23120        }
23121    }
23122
23123    #[test]
23124    fn wit_contract_slot_borrows_from_slot_storage() {
23125        // The borrow-not-copy pin: [`WitContract::slot`] must return
23126        // an `Option<&str>` whose `Some` arm borrows from the typed
23127        // slot's own [`String`] storage — same-address invariant with
23128        // `c.slot.as_deref().unwrap()`. Pins against a future silent
23129        // detour that allocated a fresh `String`
23130        // (`self.slot.clone().map(...)` in the body would type-check
23131        // but silently drop the borrow, and every downstream consumer
23132        // that assumed the returned slice outlives `&self` would
23133        // break on a stale-reference use-after-free — the
23134        // [`WitContract::target`] Store-arm payload extraction rebinds
23135        // the returned `Option<&str>` through `.ok_or_else(...)` and
23136        // threads the `&str` payload into [`WitTarget::Store { slot: &'a str }`],
23137        // the [`AplicacaoSpec::validate`] duplicate-`:contratos`
23138        // [`ContratoIdentity`] dedup key threads the returned
23139        // `Option<&str>` into the six-tuple's store arm — each borrow
23140        // from the WitContract's own storage and each would silently
23141        // misbehave if this accessor produced a detached copy). Peer
23142        // of the sibling per-`:contratos` [`WitContract::endpoint`]
23143        // (7020470) / [`WitContract::subject`] (90de675)
23144        // borrow-invariant pins on the M3 mesh-slot `Option<String>`-
23145        // shaped optional-scalar axis — third and final extension of
23146        // the `Option<&str>` borrow-not-copy discipline onto the
23147        // per-`:contratos` payload-carrier family, this time on the
23148        // store arm.
23149        let c = WitContract {
23150            de: "cart".into(),
23151            para: "kv".into(),
23152            wit: "wasi:keyvalue/store".into(),
23153            endpoint: None,
23154            subject: None,
23155            slot: Some("carts/{cart_id}".into()),
23156        };
23157        let slot = c.slot().expect("Some arm");
23158        let storage_slice = c.slot.as_deref().expect("Some arm — storage side");
23159        assert_eq!(
23160            slot.as_ptr(),
23161            storage_slice.as_ptr(),
23162            "WitContract::slot must borrow from the .slot String's \
23163             backing storage — a fresh allocation here means the \
23164             accessor no longer names the substrate-primitive typed \
23165             dispatch and every downstream consumer would silently \
23166             carry a detached copy",
23167        );
23168        assert_eq!(
23169            slot.len(),
23170            storage_slice.len(),
23171            "WitContract::slot and .slot.as_deref() must byte-equal \
23172             in length as well as in address",
23173        );
23174    }
23175
23176    #[test]
23177    fn membro_nome_returns_caixa_byte_equal_across_permutations() {
23178        // The canonical per-`:membros` member-caixa `:nome`-scalar pin:
23179        // [`Membro::nome`] must return the `:membros :caixa` field
23180        // byte-for-byte, borrowed from the typed slot's own [`String`]
23181        // storage. Peer of the sibling per-`:contratos` [`WitContract::source`]
23182        // / [`WitContract::destination`] (7f0fd43) and per-`:entrada`
23183        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
23184        // slot-atom scalar-value axes — same "the substrate-primitive
23185        // accessor must byte-equal the raw field access verbatim across
23186        // every author-declared value" discipline extended to the
23187        // per-`:membros` member-identity arm. Pins against a future
23188        // silent detour that re-normalized the member identity (an
23189        // accidental `.to_lowercase()` — every `:membros :caixa` is
23190        // validated as a DNS-1123 label upstream via
23191        // [`validate_membro_caixa`], so any re-normalization is
23192        // redundant + a drift surface between the validator and the
23193        // accessor), a namespace-prefix rewrite (an accidental
23194        // `format!("{namespace}/{caixa}")` per-CR fully-qualified
23195        // rewrite that didn't land on the peer axes), or a per-cluster
23196        // alias stamp the operator authors on one consumer without the
23197        // other. Four values sweep the accept-set the DNS-1123 gate
23198        // upstream admits (short single-word / dashed / v-suffixed
23199        // member names).
23200        for name in ["cart", "checkout", "catalog", "orders-v2"] {
23201            let m = Membro {
23202                caixa: name.into(),
23203                versao: "^0.1".into(),
23204            };
23205            assert_eq!(
23206                m.nome(),
23207                name,
23208                "Membro::nome must return :membros :caixa verbatim \
23209                 (got {:?}, expected {name:?})",
23210                m.nome(),
23211            );
23212            assert_eq!(
23213                m.nome(),
23214                m.caixa.as_str(),
23215                "Membro::nome must byte-equal the .caixa field access",
23216            );
23217        }
23218    }
23219
23220    #[test]
23221    fn membro_nome_borrows_from_caixa_storage() {
23222        // The borrow-not-copy pin: [`Membro::nome`] must return a `&str`
23223        // slice that borrows from the typed slot's own [`String`]
23224        // storage — same-address invariant with `m.caixa.as_str()`. Pins
23225        // against a future silent detour that allocated a fresh `String`
23226        // (`self.caixa.clone()` in the body would type-check but
23227        // silently drop the borrow, and every downstream consumer that
23228        // assumed the returned slice outlives `&self` would break on a
23229        // stale-reference use-after-free — the `HashSet<&str>` collector
23230        // at [`AplicacaoSpec::validate`]'s `names` seed, the
23231        // `BTreeMap<&str, BTreeSet<&str>>` adjacency map at
23232        // [`AplicacaoSpec::detect_sync_cycles`], the
23233        // [`crate::render::insert_first_seen`] dedup key at
23234        // [`AplicacaoSpec::validate_membros`] — each borrow from the
23235        // Membro's own storage and each would silently misbehave if
23236        // this accessor produced a detached copy). Peer of the sibling
23237        // per-`:contratos` [`WitContract::source`] /
23238        // [`WitContract::destination`] and per-`:entrada`
23239        // [`Entrada::destination`] borrow-invariant pins on the mesh-
23240        // slot-atom scalar-value axes.
23241        let m = Membro {
23242            caixa: "checkout".into(),
23243            versao: "^0.1".into(),
23244        };
23245        let name = m.nome();
23246        let caixa_slice = m.caixa.as_str();
23247        assert_eq!(
23248            name.as_ptr(),
23249            caixa_slice.as_ptr(),
23250            "Membro::nome must borrow from the .caixa String's backing \
23251             storage — a fresh allocation here means the accessor no \
23252             longer names the substrate-primitive typed dispatch and \
23253             every downstream consumer would silently carry a detached \
23254             copy",
23255        );
23256        assert_eq!(
23257            name.len(),
23258            caixa_slice.len(),
23259            "Membro::nome and .caixa.as_str() must byte-equal in length \
23260             as well as in address",
23261        );
23262    }
23263
23264    #[test]
23265    fn membro_versao_requirement_returns_versao_byte_equal_across_permutations() {
23266        // The canonical per-`:membros` member-`:versao`-scalar pin:
23267        // [`Membro::versao_requirement`] must return the
23268        // `:membros :versao` field byte-for-byte, borrowed from the typed
23269        // slot's own [`String`] storage. Sibling of the peer
23270        // `membro_nome_returns_caixa_byte_equal_across_permutations`
23271        // (4a32abf) pin on the per-`:membros` member-caixa `:nome` scalar
23272        // — same "the substrate-primitive accessor must byte-equal the
23273        // raw field access verbatim across every author-declared value"
23274        // discipline extended to the per-`:membros` member-`:versao`
23275        // requirement-string arm. Pins against a future silent detour
23276        // that re-canonicalized the requirement (an accidental
23277        // `.to_string()` via [`parse_requirement`] → [`Display`] round-
23278        // trip that collapsed `"^0.1"` to `">=0.1, <0.2"` and silently
23279        // drifted the printer output away from the source `caixa.lisp`,
23280        // an accidental whitespace trim on `"^ 0.1"` that no consumer
23281        // ever produced from the field-access side, an accidental
23282        // per-cluster lacre-projected concrete-version rewrite that
23283        // didn't land on the peer field-access sites). Five values sweep
23284        // the accept-set the shared
23285        // [`crate::render::require_valid_versao_requirement`] gate
23286        // admits (caret / tilde / exact / wildcard / bare-major).
23287        for req in ["^0.1", "~0.1.2", "0.1.0", "*", "^1"] {
23288            let m = Membro {
23289                caixa: "cart".into(),
23290                versao: req.into(),
23291            };
23292            assert_eq!(
23293                m.versao_requirement(),
23294                req,
23295                "Membro::versao_requirement must return :membros :versao \
23296                 verbatim (got {:?}, expected {req:?})",
23297                m.versao_requirement(),
23298            );
23299            assert_eq!(
23300                m.versao_requirement(),
23301                m.versao.as_str(),
23302                "Membro::versao_requirement must byte-equal the .versao \
23303                 field access",
23304            );
23305        }
23306    }
23307
23308    #[test]
23309    fn membro_versao_requirement_borrows_from_versao_storage() {
23310        // The borrow-not-copy pin: [`Membro::versao_requirement`] must
23311        // return a `&str` slice that borrows from the typed slot's own
23312        // [`String`] storage — same-address invariant with
23313        // `m.versao.as_str()`. Pins against a future silent detour that
23314        // allocated a fresh `String` (`self.versao.clone()` in the body
23315        // would type-check but silently drop the borrow, and every
23316        // downstream consumer that assumed the returned slice outlives
23317        // `&self` would break on a stale-reference use-after-free). Peer
23318        // of the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
23319        // per-`:contratos` [`WitContract::source`] /
23320        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
23321        // [`Entrada::destination`] (6db982c) borrow-invariant pins on
23322        // the mesh-slot-atom scalar-value axes.
23323        let m = Membro {
23324            caixa: "checkout".into(),
23325            versao: "^0.1".into(),
23326        };
23327        let req = m.versao_requirement();
23328        let versao_slice = m.versao.as_str();
23329        assert_eq!(
23330            req.as_ptr(),
23331            versao_slice.as_ptr(),
23332            "Membro::versao_requirement must borrow from the .versao \
23333             String's backing storage — a fresh allocation here means \
23334             the accessor no longer names the substrate-primitive typed \
23335             dispatch and every downstream consumer would silently carry \
23336             a detached copy",
23337        );
23338        assert_eq!(
23339            req.len(),
23340            versao_slice.len(),
23341            "Membro::versao_requirement and .versao.as_str() must byte-\
23342             equal in length as well as in address",
23343        );
23344    }
23345
23346    #[test]
23347    fn membro_nome_and_versao_requirement_project_caixa_and_versao_pair() {
23348        // Sibling-pair invariant pin composing both per-`:membros`
23349        // substrate-primitive typed dispatches — [`Membro::nome`]
23350        // (4a32abf) and [`Membro::versao_requirement`] — at the joint
23351        // `(nome(), versao_requirement())` call shape every renderer
23352        // that fans on per-member identity + version pin keys off. The
23353        // invariant, evaluated per-member:
23354        //
23355        //   (m.nome(), m.versao_requirement()) == (m.caixa.as_str(), m.versao.as_str())
23356        //
23357        // Closes the last unlifted per-`:membros` scalar axis — every
23358        // downstream consumer that reads the pair now routes through
23359        // exactly two typed dispatches on the substrate primitive, not
23360        // one typed + one open-coded field access. A future refactor
23361        // that silently split either accessor's projection (an
23362        // accidental `nome()` namespace-prefix rewrite that didn't
23363        // reach the peer, an accidental `versao_requirement()` lacre-
23364        // projected concrete-version rewrite that didn't land on the
23365        // `nome()` peer) surfaces at caixa-core build time. Peer of the
23366        // sibling per-`:entrada` `(hostname(), destination())` and
23367        // per-`:contratos` `(source(), destination())` pair invariants
23368        // on the mesh-slot-atom scalar-value axes.
23369        for (caixa, versao) in [
23370            ("cart", "^0.1"),
23371            ("checkout", "~0.1.2"),
23372            ("catalog", "0.1.0"),
23373            ("orders-v2", "*"),
23374        ] {
23375            let m = Membro {
23376                caixa: caixa.into(),
23377                versao: versao.into(),
23378            };
23379            assert_eq!(
23380                (m.nome(), m.versao_requirement()),
23381                (m.caixa.as_str(), m.versao.as_str()),
23382                "(Membro::nome, Membro::versao_requirement) must project \
23383                 (.caixa, .versao) verbatim across every author-declared \
23384                 pair (got ({:?}, {:?}), expected ({caixa:?}, {versao:?}))",
23385                m.nome(),
23386                m.versao_requirement(),
23387            );
23388        }
23389    }
23390
23391    #[test]
23392    fn validate_membros_empty_gate_routes_through_nome_accessor() {
23393        // Composition pin: [`AplicacaoSpec::validate_membros`]'s
23394        // `MembroCaixaEmpty` refusal-arm must key off [`Membro::nome`],
23395        // not the raw `.caixa` field access. Structurally: setting
23396        // ONLY the `.caixa` field to `""` on an otherwise-well-formed
23397        // `:membros` entry must (1) trip the `MembroCaixaEmpty` gate
23398        // and (2) produce a `m.nome()` byte-equal to `m.caixa.as_str()`
23399        // (i.e. the empty string) — so the emptiness predicate the
23400        // refusal arm reaches under is the accessor-projected value,
23401        // not a peer field that would silently drift under a future
23402        // accessor-side rewrite.
23403        //
23404        // Pins against a future silent detour that (a) re-derived the
23405        // emptiness gate off `self.caixa.is_empty()` in `validate_membros`
23406        // instead of `self.nome().is_empty()`, silently disagreeing with
23407        // every peer consumer (the `validate_membro_caixa(m.nome())`
23408        // call one line below, the dedup-key `insert_first_seen(&mut
23409        // seen, m.nome(), …)` two lines below, the emit-side per-
23410        // `programs[]` entry-`name:` at caixa-mesh/src/lib.rs:133),
23411        // (b) accessor-side introduced a per-tenant alias arm the
23412        // caller was unaware of, silently rewriting an author-declared
23413        // `:caixa "checkout"` to `""` — the raw-field-access gate
23414        // would fail-open while the accessor-routed peer consumers
23415        // would fail-closed, splitting the diagnostic from the actual
23416        // failure surface.
23417        //
23418        // Peer of the sibling
23419        // [`mesh_policy_is_empty_mtls_required_arm_routes_through_accessor`]
23420        // (c0110f1) composition pin — same "the shape-gate predicate
23421        // must route through the substrate-primitive typed dispatch"
23422        // discipline extended onto the per-`:membros` empty-`:caixa`
23423        // refusal-arm axis. Closes the last unlifted `.caixa` production-
23424        // code read site on `Membro` — after this converge every
23425        // caixa-core `.caixa` field access outside the accessor's own
23426        // body is either a test-side field-setter (in-module tests
23427        // constructing invalid-shape inputs) or a doc-comment reference.
23428        let mut s = three_member_spec();
23429        s.membros[1].caixa = String::new();
23430        assert!(
23431            s.membros[1].nome().is_empty(),
23432            "Membro::nome must byte-equal the .caixa field access — an \
23433             accessor-side detour that no longer projects the raw field \
23434             would silently split this drift-detection test from the \
23435             validate() refusal arm",
23436        );
23437        assert_eq!(
23438            s.membros[1].nome(),
23439            s.membros[1].caixa.as_str(),
23440            "Membro::nome and .caixa.as_str() must byte-equal on an \
23441             empty-`:caixa` entry — the emptiness gate keys off the \
23442             accessor by construction",
23443        );
23444        assert_eq!(
23445            s.validate().unwrap_err(),
23446            AplicacaoError::MembroCaixaEmpty,
23447            "validate_membros' emptiness gate must fire MembroCaixaEmpty \
23448             on an entry whose accessor-projected `nome()` is empty",
23449        );
23450    }
23451
23452    #[test]
23453    fn placement_shard_key_returns_shard_key_option_byte_equal_across_permutations() {
23454        // The canonical per-`:placement` Akka-cluster-sharding
23455        // `:shard-key`-scalar pin: [`Placement::shard_key`] must return
23456        // the `:placement :shard-key` field byte-for-byte, borrowed
23457        // from the typed slot's own `Option<String>` storage. Peer of
23458        // the sibling per-`:membros` [`Membro::nome`] (4a32abf) and
23459        // per-`:contratos` [`WitContract::source`] /
23460        // [`WitContract::destination`] (7f0fd43) and per-`:entrada`
23461        // [`Entrada::destination`] (6db982c) accessor pins on the mesh-
23462        // slot-atom scalar-value axes — same "the substrate-primitive
23463        // accessor must byte-equal the raw field access verbatim across
23464        // every author-declared value" discipline extended to the
23465        // per-`:placement` Akka-cluster-sharding key extractor arm.
23466        // Pins against a future silent detour that re-normalized the
23467        // key (an accidental `.to_lowercase()` — every non-empty
23468        // `:shard-key` is validated as a printable-ASCII single-token
23469        // reference upstream via [`validate_placement_shard_key`], so
23470        // any re-normalization is redundant + a drift surface between
23471        // the validator and the accessor), a per-cluster alias rewrite
23472        // the operator authors on one consumer without the other, or an
23473        // accidental variable-prefix strip (`$tenantId` → `tenantId`)
23474        // that didn't land on the peer field-access sites. Four values
23475        // sweep the accept-set the shape gate admits — bare identifier,
23476        // `$`-prefixed variable, dotted path, `${}`-quoted variable —
23477        // the four canonical Akka-style entity-id extractor shapes the
23478        // future M4 cluster-sharding reconciler hashes.
23479        for key in ["tenantId", "$tenantId", "metadata.tenantId", "${tenant}"] {
23480            let p = Placement {
23481                estrategia: PlacementStrategy::Sharded,
23482                clusters: vec!["rio".into()],
23483                affinity: None,
23484                shard_key: Some(key.into()),
23485            };
23486            assert_eq!(
23487                p.shard_key(),
23488                Some(key),
23489                "Placement::shard_key must return :placement :shard-key \
23490                 verbatim (got {:?}, expected Some({key:?}))",
23491                p.shard_key(),
23492            );
23493            assert_eq!(
23494                p.shard_key(),
23495                p.shard_key.as_deref(),
23496                "Placement::shard_key must byte-equal the .shard_key \
23497                 field's `.as_deref()` projection",
23498            );
23499        }
23500    }
23501
23502    #[test]
23503    fn placement_shard_key_none_when_field_is_none() {
23504        // The absent-`:shard-key` arm of the per-`:placement`
23505        // Akka-cluster-sharding accessor pin: when the typed slot is
23506        // absent — the canonical shape under `:estrategia Replicated` /
23507        // `SingleNode` per the [`AplicacaoSpec::validate_placement`]-
23508        // enforced `shard_key.is_some() == matches!(estrategia,
23509        // Sharded)` partition — [`Placement::shard_key`] must return
23510        // `None`. Pins against a future silent detour that projected
23511        // the absent slot to a `Some("")` empty-string default (the
23512        // canonical `Option<String>` → `String` collapse footgun the
23513        // sibling M2 [`crate::LimitsSpec::is_empty`] /
23514        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
23515        // already guard on the peer M2 typed-slot surfaces), a
23516        // `Some("None")` stringified-None round-trip, or a `Some` arm
23517        // whose contents were derived from a sibling slot (an
23518        // accidental fallback to `estrategia.as_str()` that read the
23519        // strategy discriminator into the key axis). Two placements
23520        // sweep the accept-set every `validate`-passing non-`Sharded`
23521        // shape lands on — `Replicated` (Erlang/OTP distributed-app
23522        // takeover) and `SingleNode` (single-node hosting).
23523        for estrategia in [PlacementStrategy::Replicated, PlacementStrategy::SingleNode] {
23524            let p = Placement {
23525                estrategia,
23526                clusters: vec!["rio".into()],
23527                affinity: None,
23528                shard_key: None,
23529            };
23530            assert!(
23531                p.shard_key().is_none(),
23532                "Placement::shard_key must return None when the typed \
23533                 slot is absent under :estrategia {estrategia:?} (got {:?})",
23534                p.shard_key(),
23535            );
23536            assert_eq!(
23537                p.shard_key(),
23538                p.shard_key.as_deref(),
23539                "Placement::shard_key must byte-equal the .shard_key \
23540                 field's `.as_deref()` projection in the absent arm",
23541            );
23542        }
23543    }
23544
23545    #[test]
23546    fn placement_shard_key_borrows_from_shard_key_storage() {
23547        // The borrow-not-copy pin: [`Placement::shard_key`] must return
23548        // an `Option<&str>` whose `Some` arm borrows from the typed
23549        // slot's own [`String`] storage — same-address invariant with
23550        // `p.shard_key.as_deref().unwrap()`. Pins against a future
23551        // silent detour that allocated a fresh `String`
23552        // (`self.shard_key.clone().map(...)` in the body would type-
23553        // check but silently drop the borrow, and every downstream
23554        // consumer that assumed the returned slice outlives `&self`
23555        // would break on a stale-reference use-after-free — the
23556        // [`AplicacaoSpec::validate_placement`] `Sharded`-arm shape
23557        // gate's `Some(k)`-bound match arm reads `k: &str` under the
23558        // accessor's return type and would silently misbehave if this
23559        // accessor produced a detached copy). Peer of the sibling
23560        // per-`:membros` [`Membro::nome`] (4a32abf), per-`:contratos`
23561        // [`WitContract::source`] / [`WitContract::destination`]
23562        // (7f0fd43), and per-`:entrada` [`Entrada::destination`]
23563        // (6db982c) borrow-invariant pins on the mesh-slot-atom
23564        // scalar-value axes — first extension of the discipline onto
23565        // an `Option<String>`-shaped optional-scalar axis.
23566        let p = Placement {
23567            estrategia: PlacementStrategy::Sharded,
23568            clusters: vec!["rio".into()],
23569            affinity: None,
23570            shard_key: Some("tenantId".into()),
23571        };
23572        let key = p.shard_key().expect("Some arm");
23573        let storage_slice = p.shard_key.as_deref().expect("Some arm — storage side");
23574        assert_eq!(
23575            key.as_ptr(),
23576            storage_slice.as_ptr(),
23577            "Placement::shard_key must borrow from the .shard_key \
23578             String's backing storage — a fresh allocation here means \
23579             the accessor no longer names the substrate-primitive typed \
23580             dispatch and every downstream consumer would silently \
23581             carry a detached copy",
23582        );
23583        assert_eq!(
23584            key.len(),
23585            storage_slice.len(),
23586            "Placement::shard_key and .shard_key.as_deref() must byte-\
23587             equal in length as well as in address",
23588        );
23589    }
23590
23591    #[test]
23592    fn placement_affinity_returns_affinity_option_byte_equal_across_permutations() {
23593        // The canonical per-`:placement` M3-Adaptive-compression-hint
23594        // scalar pin: [`Placement::affinity`] must return the
23595        // `:placement :affinity` field byte-for-byte, borrowed from the
23596        // typed slot's own `Option<String>` storage. Peer of the sibling
23597        // per-`:placement` [`Placement::shard_key`] (7cd2a28) accessor
23598        // pin on the sibling `Option<&str>` optional-scalar axis — same
23599        // "the substrate-primitive accessor must byte-equal the raw
23600        // field access verbatim across every author-declared value"
23601        // discipline extended to the peer per-`:placement` M3-Adaptive-
23602        // compression-hint arm. Pins against a future silent detour
23603        // that re-normalized the hint (an accidental `.to_lowercase()`
23604        // — every `:affinity` is already validated as a DNS-1123 label
23605        // upstream via [`validate_placement_affinity`], so any re-
23606        // normalization is redundant + a drift surface between the
23607        // validator and the accessor), a per-cluster alias rewrite the
23608        // operator authors on one consumer without the other, or an
23609        // accidental hint-family collapse (`low-latency` → `latency`
23610        // that dropped the qualifier prefix). Four values sweep the
23611        // MESH-COMPOSITION §II.4 vocabulary the accept-set names — the
23612        // canonical adaptive-compression-weight biases the future M4
23613        // placement engine reads.
23614        for hint in [
23615            "data-locality",
23616            "low-latency",
23617            "high-throughput",
23618            "cost-optimized",
23619        ] {
23620            let p = Placement {
23621                estrategia: PlacementStrategy::Replicated,
23622                clusters: vec!["rio".into()],
23623                affinity: Some(hint.into()),
23624                shard_key: None,
23625            };
23626            assert_eq!(
23627                p.affinity(),
23628                Some(hint),
23629                "Placement::affinity must return :placement :affinity \
23630                 verbatim (got {:?}, expected Some({hint:?}))",
23631                p.affinity(),
23632            );
23633            assert_eq!(
23634                p.affinity(),
23635                p.affinity.as_deref(),
23636                "Placement::affinity must byte-equal the .affinity \
23637                 field's `.as_deref()` projection",
23638            );
23639        }
23640    }
23641
23642    #[test]
23643    fn placement_affinity_none_when_field_is_none() {
23644        // The absent-`:affinity` arm of the per-`:placement`
23645        // M3-Adaptive-compression-hint accessor pin: when the typed
23646        // slot is absent — the canonical shape of an Aplicacao that
23647        // leaves the compression weighting up to the placement engine's
23648        // cluster-default arm — [`Placement::affinity`] must return
23649        // `None`. Pins against a future silent detour that projected
23650        // the absent slot to a `Some("")` empty-string default (the
23651        // canonical `Option<String>` → `String` collapse footgun the
23652        // sibling M2 [`crate::LimitsSpec::is_empty`] /
23653        // [`crate::BehaviorSpec::is_empty`] emptiness predicates
23654        // already guard on the peer M2 typed-slot surfaces), a
23655        // `Some("None")` stringified-None round-trip, a `Some` arm
23656        // whose contents were derived from a sibling slot (an
23657        // accidental fallback to `estrategia.as_str()` that read the
23658        // strategy discriminator into the hint axis), or a
23659        // `Some("default")` implicit-default that would silently biases
23660        // the routing without the author having written one. Three
23661        // placements sweep the accept-set every `validate`-passing
23662        // `:affinity None` shape lands on — one per PlacementStrategy
23663        // discriminator arm (`SingleNode`, `Replicated`, `Sharded`
23664        // with a shard-key), since `:affinity` is orthogonal to
23665        // `:estrategia` in the typed grammar.
23666        for (estrategia, shard_key) in [
23667            (PlacementStrategy::SingleNode, None),
23668            (PlacementStrategy::Replicated, None),
23669            (PlacementStrategy::Sharded, Some("tenantId".to_string())),
23670        ] {
23671            let p = Placement {
23672                estrategia,
23673                clusters: vec!["rio".into()],
23674                affinity: None,
23675                shard_key,
23676            };
23677            assert!(
23678                p.affinity().is_none(),
23679                "Placement::affinity must return None when the typed \
23680                 slot is absent under :estrategia {estrategia:?} (got {:?})",
23681                p.affinity(),
23682            );
23683            assert_eq!(
23684                p.affinity(),
23685                p.affinity.as_deref(),
23686                "Placement::affinity must byte-equal the .affinity \
23687                 field's `.as_deref()` projection in the absent arm",
23688            );
23689        }
23690    }
23691
23692    #[test]
23693    fn placement_affinity_borrows_from_affinity_storage() {
23694        // The borrow-not-copy pin: [`Placement::affinity`] must return
23695        // an `Option<&str>` whose `Some` arm borrows from the typed
23696        // slot's own [`String`] storage — same-address invariant with
23697        // `p.affinity.as_deref().unwrap()`. Pins against a future
23698        // silent detour that allocated a fresh `String`
23699        // (`self.affinity.clone().map(...)` in the body would type-
23700        // check but silently drop the borrow, and every downstream
23701        // consumer that assumed the returned slice outlives `&self`
23702        // would break on a stale-reference use-after-free — the
23703        // [`AplicacaoSpec::validate_placement`] per-hint value-shape
23704        // gate reads the accessor's `&str` return through the
23705        // [`validate_placement_affinity`] `&str` parameter and would
23706        // silently misbehave if this accessor produced a detached
23707        // copy). Peer of the sibling per-`:placement`
23708        // [`Placement::shard_key`] (7cd2a28) borrow-invariant pin on
23709        // the M3 mesh-slot-atom `Option<String>` optional-scalar axis —
23710        // extends the discipline onto the sibling per-`:placement`
23711        // M3-Adaptive-compression-hint arm.
23712        let p = Placement {
23713            estrategia: PlacementStrategy::Replicated,
23714            clusters: vec!["rio".into()],
23715            affinity: Some("data-locality".into()),
23716            shard_key: None,
23717        };
23718        let hint = p.affinity().expect("Some arm");
23719        let storage_slice = p.affinity.as_deref().expect("Some arm — storage side");
23720        assert_eq!(
23721            hint.as_ptr(),
23722            storage_slice.as_ptr(),
23723            "Placement::affinity must borrow from the .affinity \
23724             String's backing storage — a fresh allocation here means \
23725             the accessor no longer names the substrate-primitive typed \
23726             dispatch and every downstream consumer would silently \
23727             carry a detached copy",
23728        );
23729        assert_eq!(
23730            hint.len(),
23731            storage_slice.len(),
23732            "Placement::affinity and .affinity.as_deref() must byte-\
23733             equal in length as well as in address",
23734        );
23735    }
23736
23737    #[test]
23738    fn placement_estrategia_returns_estrategia_verbatim_across_permutations() {
23739        // The canonical per-`:placement` distribution-strategy-scalar
23740        // pin: [`Placement::estrategia`] must return the `:placement
23741        // :estrategia` field verbatim as a [`PlacementStrategy`],
23742        // `Copy`-projected from the typed slot's own `PlacementStrategy`
23743        // storage across every variant in the closed accept-set
23744        // (`SingleNode` — Erlang/OTP distributed-app takeover;
23745        // `Replicated` — active-active across every named cluster;
23746        // `Sharded` — Akka-style hash-keyed entity distribution). Pins
23747        // against a future silent detour that re-derived the strategy
23748        // from a peer axis (an accidental fallback to
23749        // `if shard_key.is_some() { Sharded } else { Replicated }`
23750        // collapse that read the shard-key axis into the strategy
23751        // discriminator), a variant remap the operator authors on one
23752        // consumer without the other, or a stale-derive detour that
23753        // substituted [`PlacementStrategy::default`] when the field
23754        // held any explicit variant (which would silently collapse the
23755        // distinction between "author explicitly declared `:estrategia
23756        // Replicated`" and "author omitted the slot and inherited the
23757        // default" the future per-cluster override slot depends on).
23758        // Peer of the sibling per-`:entrada` `port_returns_entrada_port_verbatim_across_permutations`
23759        // pin on the `Copy`-return `u16` scalar axis — same "the
23760        // substrate-primitive accessor must byte-equal the raw field
23761        // access verbatim across every author-declared value" discipline
23762        // extended onto the per-`:placement` distribution-strategy
23763        // `Copy`-composite-enum scalar axis.
23764        for estrategia in [
23765            PlacementStrategy::SingleNode,
23766            PlacementStrategy::Replicated,
23767            PlacementStrategy::Sharded,
23768        ] {
23769            // Route the paired `:shard-key` fixture-builder through the
23770            // typed cross-slot invariant predicate
23771            // [`PlacementStrategy::requires_shard_key`] rather than the
23772            // [`gen_platform::IsVariant`]-derived [`PlacementStrategy::is_sharded`]
23773            // arm-identity predicate — same discipline the sibling
23774            // `placement_strategy_variants_round_trip` fixture builder now
23775            // reads through.
23776            let shard_key = estrategia
23777                .requires_shard_key()
23778                .then(|| "tenantId".to_string());
23779            let p = Placement {
23780                estrategia,
23781                clusters: vec!["rio".into()],
23782                affinity: None,
23783                shard_key,
23784            };
23785            assert_eq!(
23786                p.estrategia(),
23787                estrategia,
23788                "Placement::estrategia must return :placement :estrategia \
23789                 verbatim (got {:?}, expected {estrategia:?})",
23790                p.estrategia(),
23791            );
23792            assert_eq!(
23793                p.estrategia(),
23794                p.estrategia,
23795                "Placement::estrategia accessor and .estrategia field \
23796                 access must byte-equal — the accessor is the substrate-\
23797                 primitive typed dispatch every downstream distribution-\
23798                 strategy consumer must route through",
23799            );
23800        }
23801    }
23802
23803    #[test]
23804    fn validate_placement_reads_through_lifted_estrategia_accessor() {
23805        // Three-consumer coherence pin: the
23806        // [`AplicacaoSpec::validate_placement`]
23807        // [`AplicacaoError::PlacementWithoutClusters`] error carrier's
23808        // `estrategia:` field (which reads through
23809        // [`Placement::estrategia`] to name the strategy the empty
23810        // `:clusters` list was declared against), the same method's
23811        // `Sharded ↔ non-Sharded` `match` partition dispatch (which
23812        // reads through [`Placement::estrategia`] to fan across the
23813        // shape-gate cascades), and the non-`Sharded`-arm
23814        // [`AplicacaoError::ShardKeyOnNonSharded`] error carrier's
23815        // `estrategia:` field (which reads through
23816        // [`Placement::estrategia`] to name the strategy the declared-
23817        // but-inert `:shard-key` was authored under) must all key off
23818        // the lifted accessor, so any future rebrand on the typed
23819        // slot's reader shape lands at exactly one place. Pins the
23820        // three-site coherence by exercising each error surface end-
23821        // to-end and asserting the surfaced `estrategia:` field byte-
23822        // equals the accessor's return. Peer of the sibling per-
23823        // `:entrada` `validate_entrada_port_floor_gate_reads_through_lifted_port_accessor`
23824        // pin on the M3 mesh-slot `Copy`-return scalar axis.
23825
23826        // Arm 1: empty `:clusters` list surfaces `PlacementWithoutClusters`,
23827        // whose `estrategia:` field must byte-equal the accessor's return
23828        // for every variant in the closed accept-set.
23829        for estrategia in [
23830            PlacementStrategy::SingleNode,
23831            PlacementStrategy::Replicated,
23832            PlacementStrategy::Sharded,
23833        ] {
23834            let mut spec = three_member_spec();
23835            spec.placement.estrategia = estrategia;
23836            spec.placement.clusters = Vec::new();
23837            // Route the paired `:shard-key` spec-mutator through the typed
23838            // cross-slot invariant predicate
23839            // [`PlacementStrategy::requires_shard_key`] rather than the
23840            // [`gen_platform::IsVariant`]-derived
23841            // [`PlacementStrategy::is_sharded`] arm-identity predicate —
23842            // same discipline the sibling
23843            // `placement_strategy_variants_round_trip` and
23844            // `estrategia_returns_placement_estrategia_verbatim_across_permutations`
23845            // fixture builders now read through.
23846            spec.placement.shard_key = estrategia
23847                .requires_shard_key()
23848                .then(|| "tenantId".to_string());
23849            let err = spec.validate().unwrap_err();
23850            match err {
23851                AplicacaoError::PlacementWithoutClusters { estrategia: e } => {
23852                    assert_eq!(
23853                        e,
23854                        spec.placement.estrategia(),
23855                        "PlacementWithoutClusters.estrategia must byte-equal \
23856                         Placement::estrategia() — the error carrier reads \
23857                         through the lifted accessor",
23858                    );
23859                }
23860                other => panic!(
23861                    "expected PlacementWithoutClusters, got {other:?} for \
23862                     estrategia={estrategia:?}"
23863                ),
23864            }
23865        }
23866
23867        // Arm 2: `:shard-key` authored on a non-`Sharded` strategy
23868        // surfaces `ShardKeyOnNonSharded`, whose `estrategia:` field
23869        // must byte-equal the accessor's return for both non-`Sharded`
23870        // strategies.
23871        for estrategia in [PlacementStrategy::SingleNode, PlacementStrategy::Replicated] {
23872            let mut spec = three_member_spec();
23873            spec.placement.estrategia = estrategia;
23874            spec.placement.shard_key = Some("tenantId".into());
23875            let err = spec.validate().unwrap_err();
23876            match err {
23877                AplicacaoError::ShardKeyOnNonSharded { estrategia: e, .. } => {
23878                    assert_eq!(
23879                        e,
23880                        spec.placement.estrategia(),
23881                        "ShardKeyOnNonSharded.estrategia must byte-equal \
23882                         Placement::estrategia() — the non-Sharded-arm \
23883                         refusal reads through the lifted accessor",
23884                    );
23885                }
23886                other => panic!(
23887                    "expected ShardKeyOnNonSharded, got {other:?} for \
23888                     estrategia={estrategia:?}"
23889                ),
23890            }
23891        }
23892    }
23893
23894    // ── per-`:placement` `:clusters` typed-accessor coherence pins ──────────
23895    //
23896    // The [`Placement::clusters`] accessor lift is the second slice-return
23897    // (`&[T]`) accessor on any typed slot — sibling to the seed M2
23898    // [`crate::SupervisorSpec::children`] (bc92bce) accessor on the peer
23899    // per-`:supervisor` static-child-list `Vec`-carry axis. The two pins
23900    // below cover (1) the accessor's byte-equal projection against the raw
23901    // field access across the empty / singleton / cohort fixtures the
23902    // [`AplicacaoSpec::validate_placement`] pre-flight `.is_empty()` probe
23903    // and the per-cluster validate loop fan between, and (2) the two-
23904    // consumer coherence of the paired pre-flight refusal probe and the
23905    // per-cluster validate loop routing through the accessor on both arms.
23906
23907    #[test]
23908    fn placement_clusters_returns_clusters_slice_byte_equal_across_permutations() {
23909        // The canonical per-`:placement` cluster-pool-scalar-shape pin:
23910        // [`Placement::clusters`] must return the `:placement :clusters`
23911        // typed `Vec<String>` verbatim as a `&[String]` slice-view over
23912        // the same backing buffer the raw `self.clusters.as_slice()`
23913        // field access borrows from, byte-equal across every
23914        // representative fixture in the accept-set — the empty slice
23915        // (the pre-validation sentinel every
23916        // [`AplicacaoError::PlacementWithoutClusters`] refusal keys off),
23917        // the singleton slice (the minimal `SingleNode`-shape cohort),
23918        // and multi-entry cohorts (the peer `Replicated` / `Sharded`
23919        // multi-cluster shapes MESH-COMPOSITION §II.1 / §II.4 declare).
23920        //
23921        // Pins against a future silent detour that returned
23922        // `&Vec<String>` (which would type-check but leak the storage-
23923        // side `Vec`'s grow/push/reserve surface no consumer of the
23924        // typed view reaches for), a fresh-allocated `Vec<String>` copy
23925        // (which would type-check via a coercion but silently break
23926        // every downstream caller that relied on the slice sharing the
23927        // backing buffer's identity), or an out-of-order or length-
23928        // drifted projection (which would silently split the paired
23929        // pre-flight `.is_empty()` refusal probe's input from the per-
23930        // cluster validate loop's traversal input).
23931        //
23932        // Peer of the sibling M2
23933        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
23934        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
23935        // `:supervisor` static-child-list axis, extended onto the M3
23936        // per-`:placement` distribution-target-list `Vec`-carry axis.
23937        let fixtures: Vec<Vec<String>> = vec![
23938            Vec::new(),
23939            vec!["rio".into()],
23940            vec!["rio".into(), "mar".into()],
23941            vec!["rio".into(), "mar".into(), "plo".into()],
23942        ];
23943        for clusters in fixtures {
23944            let p = Placement {
23945                clusters: clusters.clone(),
23946                ..Placement::default()
23947            };
23948            assert_eq!(
23949                p.clusters(),
23950                clusters.as_slice(),
23951                "Placement::clusters must return :placement :clusters \
23952                 verbatim (got {:?}, expected {:?})",
23953                p.clusters(),
23954                clusters.as_slice(),
23955            );
23956            assert_eq!(
23957                p.clusters(),
23958                p.clusters.as_slice(),
23959                "Placement::clusters accessor and .clusters.as_slice() \
23960                 field access must byte-equal — the accessor is the \
23961                 substrate-primitive typed dispatch every downstream \
23962                 cluster-pool consumer must route through",
23963            );
23964            assert_eq!(
23965                p.clusters().len(),
23966                p.clusters.len(),
23967                "Placement::clusters().len() must byte-equal \
23968                 self.clusters.len() — a length-drift would silently \
23969                 split the paired pre-flight `.is_empty()` refusal \
23970                 probe input from the per-cluster validate loop's \
23971                 traversal input",
23972            );
23973        }
23974    }
23975
23976    #[test]
23977    fn validate_placement_reads_through_lifted_clusters_accessor() {
23978        // Two-consumer coherence pin: the
23979        // [`AplicacaoSpec::validate_placement`] pre-flight
23980        // `self.placement.clusters().is_empty()` refusal probe (which
23981        // must trip [`AplicacaoError::PlacementWithoutClusters`] when
23982        // the accessor projects the empty slice) and the per-cluster
23983        // validate loop's `for c in self.placement.clusters()`
23984        // traversal (which must reach every entry in the same order
23985        // the accessor projects, so both the per-entry value-shape
23986        // gate that trips [`AplicacaoError::PlacementClusterInvalid`]
23987        // and the duplicate-detection HashSet insert that trips
23988        // [`AplicacaoError::PlacementClusterDuplicate`] key off the
23989        // accessor's projection) must both key off the lifted
23990        // accessor, so any future rebrand on the typed slot's reader
23991        // shape lands at exactly one place. Pins the two-site
23992        // coherence by exercising each production consumer end-to-end:
23993        // (1) the `PlacementWithoutClusters` refusal under the empty
23994        // slice, (2) the `PlacementClusterInvalid` refusal fires on
23995        // the second entry of a two-cluster cohort whose head is
23996        // valid but tail is not (which requires the loop to reach the
23997        // second entry through the accessor), and (3) the
23998        // `PlacementClusterDuplicate` refusal fires on the second
23999        // entry of a two-cluster cohort that shares a name (which
24000        // requires the loop to reach both entries — a first-entry-only
24001        // projection would silently pass since the dedup HashSet has
24002        // room for the first insert).
24003        //
24004        // Peer of the sibling M2
24005        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
24006        // (bc92bce) coherence pin on the per-`:supervisor` static-
24007        // child-list axis, extended onto the M3 per-`:placement`
24008        // distribution-target-list `Vec`-carry axis.
24009
24010        // (1) Pre-flight `.is_empty()` probe: the empty slice must
24011        // trip `PlacementWithoutClusters`.
24012        let mut spec = three_member_spec();
24013        spec.placement.clusters = Vec::new();
24014        match spec.validate().unwrap_err() {
24015            AplicacaoError::PlacementWithoutClusters { .. } => {}
24016            other => panic!("expected PlacementWithoutClusters, got {other:?}"),
24017        }
24018        assert!(
24019            spec.placement.clusters().is_empty(),
24020            "the pre-flight refusal input must be the empty slice per \
24021             the accessor's projection",
24022        );
24023
24024        // (2) Per-cluster validate loop: a two-cluster cohort with an
24025        // invalid tail entry must trip `PlacementClusterInvalid` on
24026        // the tail — the loop must reach the second entry through
24027        // the accessor.
24028        let mut spec = three_member_spec();
24029        spec.placement.clusters = vec!["rio".into(), "BAD_CLUSTER".into()];
24030        match spec.validate().unwrap_err() {
24031            AplicacaoError::PlacementClusterInvalid { cluster, .. } => {
24032                assert_eq!(
24033                    cluster, "BAD_CLUSTER",
24034                    "PlacementClusterInvalid.cluster must carry the \
24035                     tail entry the loop reached through the accessor",
24036                );
24037            }
24038            other => panic!("expected PlacementClusterInvalid, got {other:?}"),
24039        }
24040        assert_eq!(
24041            spec.placement.clusters().len(),
24042            2,
24043            "the per-cluster validate loop's traversal input must be \
24044             a two-element slice per the accessor's projection",
24045        );
24046
24047        // (3) Per-cluster validate loop: a two-cluster cohort that
24048        // shares a name must trip `PlacementClusterDuplicate` on the
24049        // second entry — the loop must reach both entries through the
24050        // accessor for the dedup HashSet's second insert to collide.
24051        let mut spec = three_member_spec();
24052        spec.placement.clusters = vec!["rio".into(), "rio".into()];
24053        match spec.validate().unwrap_err() {
24054            AplicacaoError::PlacementClusterDuplicate { cluster } => {
24055                assert_eq!(
24056                    cluster, "rio",
24057                    "PlacementClusterDuplicate.cluster must carry the \
24058                     shared cluster name verbatim",
24059                );
24060            }
24061            other => panic!("expected PlacementClusterDuplicate, got {other:?}"),
24062        }
24063        assert_eq!(
24064            spec.placement.clusters().len(),
24065            2,
24066            "the per-cluster validate loop's traversal input must be \
24067             a two-element slice per the accessor's projection",
24068        );
24069    }
24070
24071    #[test]
24072    fn aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations() {
24073        // The canonical per-`:membros` member-list-slice-shape pin:
24074        // [`AplicacaoSpec::membros`] must return the `:membros` typed
24075        // `Vec<Membro>` verbatim as a `&[Membro]` slice-view over the
24076        // same backing buffer the raw `self.membros.as_slice()` field
24077        // access borrows from, byte-equal across every representative
24078        // fixture in the accept-set — the empty slice (the pre-
24079        // validation sentinel every [`AplicacaoError::NoMembros`]
24080        // refusal keys off), the singleton slice (the minimal one-
24081        // Servico Aplicacao shape), and multi-entry cohorts (the peer
24082        // multi-Servico shapes MESH-COMPOSITION §III.1 declares as the
24083        // load-bearing identity of the application graph).
24084        //
24085        // Pins against a future silent detour that returned
24086        // `&Vec<Membro>` (which would type-check but leak the storage-
24087        // side `Vec`'s grow/push/reserve surface no consumer of the
24088        // typed view reaches for), a fresh-allocated `Vec<Membro>` copy
24089        // (which would type-check via a coercion but silently break
24090        // every downstream caller that relied on the slice sharing the
24091        // backing buffer's identity), or an out-of-order or length-
24092        // drifted projection (which would silently split the paired
24093        // `HashSet<&str>` name-set seed's collect input from the
24094        // pre-flight `.is_empty()` refusal probe's input from the per-
24095        // member validate loop's traversal input from the
24096        // programs.yaml emitter's per-entry fan-out loop's input from
24097        // the `feira app graph` per-member print traversal's input).
24098        //
24099        // Peer of the sibling M2
24100        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
24101        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
24102        // `:supervisor` static-child-list axis and the sibling M3
24103        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
24104        // (a6e18d7) `&[String]` byte-equal pin on the per-
24105        // `:placement` distribution-target-list axis — extends the
24106        // slice-return-accessor byte-equal-projection discipline onto
24107        // the outermost M3 mesh-slot type's per-Aplicacao member-list
24108        // `Vec`-carry axis.
24109        let fixtures: Vec<Vec<Membro>> = vec![
24110            Vec::new(),
24111            vec![membro("catalog", "^0.1")],
24112            vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24113            vec![
24114                membro("catalog", "^0.1"),
24115                membro("cart", "^0.1"),
24116                membro("payment", "^0.2"),
24117            ],
24118        ];
24119        for membros in fixtures {
24120            let s = AplicacaoSpec {
24121                membros: membros.clone(),
24122                contratos: Vec::new(),
24123                politicas: MeshPolicy::default(),
24124                placement: Placement::default(),
24125                entrada: None,
24126            };
24127            assert_eq!(
24128                s.membros(),
24129                membros.as_slice(),
24130                "AplicacaoSpec::membros must return :membros verbatim \
24131                 (got {:?}, expected {:?})",
24132                s.membros(),
24133                membros.as_slice(),
24134            );
24135            assert_eq!(
24136                s.membros(),
24137                s.membros.as_slice(),
24138                "AplicacaoSpec::membros accessor and .membros.as_slice() \
24139                 field access must byte-equal — the accessor is the \
24140                 substrate-primitive typed dispatch every downstream \
24141                 member-list consumer must route through",
24142            );
24143            assert_eq!(
24144                s.membros().len(),
24145                s.membros.len(),
24146                "AplicacaoSpec::membros().len() must byte-equal \
24147                 self.membros.len() — a length-drift would silently \
24148                 split the paired `HashSet<&str>` name-set seed's \
24149                 collect input from the pre-flight `.is_empty()` \
24150                 refusal probe input from the per-member validate \
24151                 loop's traversal input",
24152            );
24153        }
24154    }
24155
24156    #[test]
24157    fn validate_reads_through_lifted_membros_accessor() {
24158        // Three-consumer coherence pin: the
24159        // [`AplicacaoSpec::validate_membros`] pre-flight
24160        // `self.membros().is_empty()` refusal probe (which must trip
24161        // [`AplicacaoError::NoMembros`] when the accessor projects the
24162        // empty slice), the same method's per-member validate loop's
24163        // `for m in self.membros()` traversal (which must reach every
24164        // entry in the same order the accessor projects, so both the
24165        // per-entry empty-`:caixa` gate that trips
24166        // [`AplicacaoError::MembroCaixaEmpty`] and the duplicate-
24167        // detection `insert_first_seen` that trips
24168        // [`AplicacaoError::MembroDuplicate`] key off the accessor's
24169        // projection), and the peer [`AplicacaoSpec::validate`]'s
24170        // `HashSet<&str>` name-set seed's
24171        // `self.membros().iter().map(Membro::nome).collect()` collect
24172        // input (which every `:contratos` `:de` / `:para` membership
24173        // lookup rejects an unknown name against) must all three key
24174        // off the lifted accessor, so any future rebrand on the typed
24175        // slot's reader shape lands at exactly one place. Pins the
24176        // three-site coherence by exercising each production consumer
24177        // end-to-end: (1) the `NoMembros` refusal under the empty
24178        // slice, (2) the `MembroCaixaEmpty` refusal fires on the
24179        // second entry of a two-member cohort whose head is valid but
24180        // tail has an empty `:caixa` (which requires the loop to
24181        // reach the second entry through the accessor), and (3) the
24182        // `MembroDuplicate` refusal fires on the second entry of a
24183        // two-member cohort that shares a `:caixa` name (which
24184        // requires the loop to reach both entries through the
24185        // accessor for the dedup HashSet's second insert to collide).
24186        //
24187        // Peer of the sibling M2
24188        // [`crate::supervisor::tests::validate_reads_through_lifted_children_accessor`]
24189        // (bc92bce) coherence pin on the per-`:supervisor` static-
24190        // child-list axis and the sibling M3
24191        // `validate_placement_reads_through_lifted_clusters_accessor`
24192        // (a6e18d7) coherence pin on the per-`:placement` distribution-
24193        // target-list axis — extends the slice-return-accessor
24194        // multi-consumer coherence discipline onto the outermost M3
24195        // mesh-slot type's per-Aplicacao member-list `Vec`-carry axis.
24196
24197        // (1) Pre-flight `.is_empty()` probe: the empty slice must
24198        // trip `NoMembros`.
24199        let mut spec = three_member_spec();
24200        spec.membros = Vec::new();
24201        assert_eq!(spec.validate().unwrap_err(), AplicacaoError::NoMembros);
24202        assert!(
24203            spec.membros().is_empty(),
24204            "the pre-flight refusal input must be the empty slice per \
24205             the accessor's projection",
24206        );
24207
24208        // (2) Per-member validate loop: a two-member cohort with an
24209        // empty-`:caixa` tail entry must trip `MembroCaixaEmpty` on
24210        // the tail — the loop must reach the second entry through
24211        // the accessor.
24212        let mut spec = three_member_spec();
24213        spec.membros = vec![membro("catalog", "^0.1"), membro("", "^0.1")];
24214        assert_eq!(
24215            spec.validate().unwrap_err(),
24216            AplicacaoError::MembroCaixaEmpty,
24217        );
24218        assert_eq!(
24219            spec.membros().len(),
24220            2,
24221            "the per-member validate loop's traversal input must be \
24222             a two-element slice per the accessor's projection",
24223        );
24224
24225        // (3) Per-member validate loop: a two-member cohort that
24226        // shares a `:caixa` name must trip `MembroDuplicate` on the
24227        // second entry — the loop must reach both entries through the
24228        // accessor for the dedup HashSet's second insert to collide.
24229        let mut spec = three_member_spec();
24230        spec.membros = vec![membro("catalog", "^0.1"), membro("catalog", "^0.2")];
24231        match spec.validate().unwrap_err() {
24232            AplicacaoError::MembroDuplicate { caixa } => {
24233                assert_eq!(
24234                    caixa, "catalog",
24235                    "MembroDuplicate.caixa must carry the shared \
24236                     member name verbatim",
24237                );
24238            }
24239            other => panic!("expected MembroDuplicate, got {other:?}"),
24240        }
24241        assert_eq!(
24242            spec.membros().len(),
24243            2,
24244            "the per-member validate loop's traversal input must be \
24245             a two-element slice per the accessor's projection",
24246        );
24247    }
24248
24249    #[test]
24250    fn aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations() {
24251        // The canonical per-`:contratos` contract-list-slice-shape pin:
24252        // [`AplicacaoSpec::contratos`] must return the `:contratos`
24253        // typed `Vec<WitContract>` verbatim as a `&[WitContract]`
24254        // slice-view over the same backing buffer the raw
24255        // `self.contratos.as_slice()` field access borrows from, byte-
24256        // equal across every representative fixture in the accept-set —
24257        // the empty slice (the pre-validation "internal-only mesh" shape
24258        // an Aplicacao whose members exchange no typed edges renders
24259        // through), the singleton slice (the minimal one-edge Aplicacao
24260        // shape), and multi-entry cohorts (the peer multi-edge shapes
24261        // MESH-COMPOSITION §III.1 declares as the load-bearing edge-set
24262        // of the application graph).
24263        //
24264        // Pins against a future silent detour that returned
24265        // `&Vec<WitContract>` (which would type-check but leak the
24266        // storage-side `Vec`'s grow/push/reserve surface no consumer of
24267        // the typed view reaches for), a fresh-allocated
24268        // `Vec<WitContract>` copy (which would type-check via a coercion
24269        // but silently break every downstream caller that relied on the
24270        // slice sharing the backing buffer's identity), or an out-of-
24271        // order or length-drifted projection (which would silently split
24272        // the paired `AplicacaoSpec::validate` per-edge dedup HashSet
24273        // seed's traversal input from the `detect_sync_cycles` per-edge
24274        // adjacency-list seed's traversal input from the
24275        // `caixa_mesh::cilium_network_policies` per-`(:de, :para)`
24276        // BTreeMap grouping loop's traversal input from the
24277        // `feira app graph` per-contract print traversal's input).
24278        //
24279        // Peer of the immediately-adjacent sibling M3
24280        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
24281        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
24282        // node-list axis, the sibling M3
24283        // `placement_clusters_returns_clusters_slice_byte_equal_across_permutations`
24284        // (a6e18d7) `&[String]` byte-equal pin on the per-`:placement`
24285        // distribution-target-list axis, and the sibling M2
24286        // `supervisor_spec_children_returns_children_slice_byte_equal_across_permutations`
24287        // (bc92bce) `&[ChildSpec]` byte-equal pin on the per-
24288        // `:supervisor` static-child-list axis — extends the slice-
24289        // return-accessor byte-equal-projection discipline onto the
24290        // outermost M3 mesh-slot type's per-Aplicacao contract-list
24291        // `Vec`-carry axis, closing the last unlifted per-
24292        // `AplicacaoSpec` `Vec`-carry axis.
24293        let fixtures: Vec<Vec<WitContract>> = vec![
24294            Vec::new(),
24295            vec![contract_http("cart", "catalog", "/products/:id")],
24296            vec![
24297                contract_http("cart", "catalog", "/products/:id"),
24298                contract_http("cart", "payment", "/charge"),
24299            ],
24300            vec![
24301                contract_http("cart", "catalog", "/products/:id"),
24302                contract_http("cart", "payment", "/charge"),
24303                contract_http("payment", "catalog", "/audit"),
24304            ],
24305        ];
24306        for contratos in fixtures {
24307            let s = AplicacaoSpec {
24308                membros: vec![
24309                    membro("catalog", "^0.1"),
24310                    membro("cart", "^0.1"),
24311                    membro("payment", "^0.2"),
24312                ],
24313                contratos: contratos.clone(),
24314                politicas: MeshPolicy::default(),
24315                placement: Placement::default(),
24316                entrada: None,
24317            };
24318            assert_eq!(
24319                s.contratos(),
24320                contratos.as_slice(),
24321                "AplicacaoSpec::contratos must return :contratos verbatim \
24322                 (got {:?}, expected {:?})",
24323                s.contratos(),
24324                contratos.as_slice(),
24325            );
24326            assert_eq!(
24327                s.contratos(),
24328                s.contratos.as_slice(),
24329                "AplicacaoSpec::contratos accessor and \
24330                 .contratos.as_slice() field access must byte-equal — \
24331                 the accessor is the substrate-primitive typed dispatch \
24332                 every downstream contract-list consumer must route \
24333                 through",
24334            );
24335            assert_eq!(
24336                s.contratos().len(),
24337                s.contratos.len(),
24338                "AplicacaoSpec::contratos().len() must byte-equal \
24339                 self.contratos.len() — a length-drift would silently \
24340                 split the paired per-edge validate-loop's traversal \
24341                 input from the sync-cycle adjacency-list seed's \
24342                 traversal input from the cilium_network_policies \
24343                 per-`(:de, :para)` BTreeMap grouping loop's traversal \
24344                 input from the `feira app graph` per-contract print \
24345                 traversal's input",
24346            );
24347        }
24348    }
24349
24350    #[test]
24351    fn validate_reads_through_lifted_contratos_accessor() {
24352        // Three-consumer coherence pin: the [`AplicacaoSpec::validate`]
24353        // per-`:contratos` validate-loop's `for c in self.contratos()`
24354        // traversal (which must reach every entry in the same order the
24355        // accessor projects, so both the per-entry
24356        // [`AplicacaoError::ContratoMemberMissing`] membership-lookup
24357        // gate and the per-entry [`AplicacaoError::ContratoDuplicate`]
24358        // dedup `HashSet` insert key off the accessor's projection),
24359        // the peer [`AplicacaoSpec::detect_sync_cycles`]'s
24360        // `for c in self.contratos()` adjacency-list seed (which drives
24361        // the sync-subgraph deadlock-detection gate via
24362        // [`AplicacaoError::SyncCycle`]), and the peer
24363        // [`caixa_mesh::cilium_network_policies`]'s
24364        // `for c in spec.contratos()` per-`(:de, :para)` BTreeMap
24365        // grouping loop (which drives the per-CNP fan-out) must all
24366        // three key off the lifted accessor, so any future rebrand on
24367        // the typed slot's reader shape lands at exactly one place. Pins
24368        // the three-site coherence by exercising the two caixa-core
24369        // production consumers end-to-end: (1) the empty-`:contratos`
24370        // slice must validate without a per-edge diagnostic (the
24371        // per-edge loop is a no-op under the empty projection), (2) the
24372        // `ContratoMemberMissing` refusal fires on the second entry of a
24373        // two-edge cohort whose head references a valid member but tail
24374        // references a phantom name (which requires the loop to reach
24375        // the second entry through the accessor), and (3) the
24376        // `SyncCycle` refusal fires on a self-referential two-edge
24377        // cohort through the sync-cycle detector's peer projection
24378        // (which requires the detector to iterate the accessor's
24379        // projection to add the back-edge to its adjacency list).
24380        //
24381        // Peer of the sibling M3
24382        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24383        // three-consumer coherence pin on the per-`:membros` node-list
24384        // axis and the sibling M3
24385        // `validate_placement_reads_through_lifted_clusters_accessor`
24386        // (a6e18d7) coherence pin on the per-`:placement` distribution-
24387        // target-list axis — extends the slice-return-accessor multi-
24388        // consumer coherence discipline onto the outermost M3 mesh-slot
24389        // type's per-Aplicacao contract-list `Vec`-carry axis.
24390
24391        // (1) Empty-`:contratos` slice: the per-edge loop is a no-op
24392        // and no per-edge diagnostic surfaces. Validate succeeds on
24393        // the well-formed `:membros` head.
24394        let mut spec = three_member_spec();
24395        spec.contratos = Vec::new();
24396        assert!(
24397            spec.validate().is_ok(),
24398            "empty :contratos must validate — the per-edge loop is a \
24399             no-op under the accessor's empty projection",
24400        );
24401        assert!(
24402            spec.contratos().is_empty(),
24403            "the per-edge validate loop's traversal input must be the \
24404             empty slice per the accessor's projection",
24405        );
24406
24407        // (2) Per-edge validate loop: a two-edge cohort whose tail
24408        // references a phantom `:para` member must trip
24409        // `ContratoMemberMissing` on the tail — the loop must reach
24410        // the second entry through the accessor for the membership
24411        // lookup to fail on the phantom name.
24412        let mut spec = three_member_spec();
24413        spec.contratos = vec![
24414            contract_http("cart", "catalog", "/products/:id"),
24415            contract_http("cart", "phantom", "/x"),
24416        ];
24417        let err = spec.validate().unwrap_err();
24418        assert!(
24419            matches!(
24420                err,
24421                AplicacaoError::ContratoMemberMissing { ref caixa }
24422                    if caixa == "phantom"
24423            ),
24424            "expected ContratoMemberMissing{{caixa:\"phantom\"}}, got {err:?}",
24425        );
24426        assert_eq!(
24427            spec.contratos().len(),
24428            2,
24429            "the per-edge validate loop's traversal input must be \
24430             a two-element slice per the accessor's projection",
24431        );
24432
24433        // (3) Sync-cycle detector: a two-edge synchronous cohort
24434        // whose second edge closes the sync-subgraph back onto the
24435        // first must trip [`AplicacaoError::ContratoCycle`] — the
24436        // detector must iterate the accessor's projection to add
24437        // both edges to its adjacency list, so a length-drift on
24438        // the accessor's projection would silently disagree with
24439        // the sync-cycle detector on which edge closes the loop.
24440        // Peer projection to the `validate` per-edge loop above:
24441        // the sync-cycle detector routes through the same lifted
24442        // accessor, so a rebrand of the reader shape lands at one
24443        // place. Uses a two-edge cohort (cart → catalog → cart)
24444        // because the per-edge `ContratoSelfLoop` gate fires before
24445        // the sync-cycle detector on a single self-referential edge
24446        // (`cart → cart`) — the cycle-detector's input must be a
24447        // multi-edge cohort for its per-edge traversal input to be
24448        // observably wider than the per-edge validate loop's input.
24449        let mut spec = three_member_spec();
24450        spec.contratos = vec![
24451            contract_http("cart", "catalog", "/products/:id"),
24452            contract_http("catalog", "cart", "/callback"),
24453        ];
24454        let err = spec.validate().unwrap_err();
24455        assert!(
24456            matches!(err, AplicacaoError::ContratoCycle { .. }),
24457            "expected ContratoCycle from the sync-cycle detector on a \
24458             two-edge back-edge cohort, got {err:?}",
24459        );
24460        assert_eq!(
24461            spec.contratos().len(),
24462            2,
24463            "the sync-cycle detector's traversal input must be a \
24464             two-element slice per the accessor's projection",
24465        );
24466    }
24467
24468    #[test]
24469    fn aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations() {
24470        // The canonical per-`:politicas` outer-composite-reference-shape
24471        // pin: [`AplicacaoSpec::politicas`] must return the `:politicas`
24472        // typed `MeshPolicy` verbatim as a `&MeshPolicy` reference over
24473        // the same backing storage the raw `&self.politicas` field
24474        // access borrows from, byte-equal across every representative
24475        // fixture in the accept-set — the default `MeshPolicy` (the
24476        // author-empty "no policy on any axis" shape whose
24477        // [`MeshPolicy::is_empty`] evaluates `true`), the singleton
24478        // shapes carrying one axis at a time
24479        // (`{mtls_required, timeout, retries, circuit_breaker,
24480        // rate_limit}` — the minimal five-axis fan-out over the
24481        // per-axis lifted accessor family every downstream mesh-artifact
24482        // emitter dispatches on), and the multi-axis composite (the
24483        // canonical `three_member_spec` fixture's `{timeout, retries,
24484        // mtls_required}` triple — the load-bearing shape every
24485        // Aplicacao-scoped fixture in this suite constructs).
24486        //
24487        // Pins against a future silent detour that returned a fresh-
24488        // cloned `MeshPolicy` copy (which would type-check via a `Clone`
24489        // impl but silently break every downstream caller that relied
24490        // on the reference sharing the composite's backing identity), a
24491        // reference to an operator-resolved overlay (the future
24492        // per-cluster `:politicas-overrides` slot MESH-COMPOSITION §V
24493        // acknowledges — its resolution must land at exactly this
24494        // accessor body, not silently divert the raw slot away from a
24495        // second consumer), or an axis-shuffled projection (a future
24496        // detour that swapped `timeout` and `retries` through the
24497        // accessor would silently split the paired `validate_politicas`
24498        // per-axis bracket-dispatch's traversal input from the peer
24499        // `caixa_mesh::gateway_routes` HTTPRoute timeout+retry overlay
24500        // emitter's fan-out input from the peer
24501        // `caixa_mesh::cilium_network_policies` per-CNP mTLS-mode
24502        // overlay emitter's fan-out input).
24503        //
24504        // Peer of the sibling M3
24505        // `aplicacao_spec_membros_returns_membros_slice_byte_equal_across_permutations`
24506        // (6c77e36) `&[Membro]` byte-equal pin on the per-`:membros`
24507        // node-list `Vec`-carry axis and the sibling M3
24508        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_across_permutations`
24509        // (0dcc926) `&[WitContract]` byte-equal pin on the per-
24510        // `:contratos` edge-list `Vec`-carry axis — extends the outer-
24511        // accessor byte-equal-projection discipline onto the outermost
24512        // M3 mesh-slot type's per-Aplicacao mesh-policy composite-
24513        // reference axis, the first `&Composite`-return accessor on the
24514        // outer [`AplicacaoSpec`] type.
24515        let fixtures: Vec<MeshPolicy> = vec![
24516            MeshPolicy::default(),
24517            MeshPolicy {
24518                mtls_required: Some(true),
24519                ..MeshPolicy::default()
24520            },
24521            MeshPolicy {
24522                mtls_required: Some(false),
24523                ..MeshPolicy::default()
24524            },
24525            MeshPolicy {
24526                timeout: Some(Duration::from_secs(30)),
24527                ..MeshPolicy::default()
24528            },
24529            MeshPolicy {
24530                retries: Some(3),
24531                ..MeshPolicy::default()
24532            },
24533            MeshPolicy {
24534                circuit_breaker: Some(CircuitBreaker {
24535                    max_failures: 5,
24536                    window: Duration::from_secs(30),
24537                }),
24538                ..MeshPolicy::default()
24539            },
24540            MeshPolicy {
24541                rate_limit: Some(RateLimit {
24542                    rate: 100,
24543                    window: Duration::from_secs(1),
24544                }),
24545                ..MeshPolicy::default()
24546            },
24547            MeshPolicy {
24548                timeout: Some(Duration::from_secs(30)),
24549                retries: Some(3),
24550                mtls_required: Some(true),
24551                ..MeshPolicy::default()
24552            },
24553        ];
24554        for politicas in fixtures {
24555            let s = AplicacaoSpec {
24556                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24557                contratos: Vec::new(),
24558                politicas: politicas.clone(),
24559                placement: Placement::default(),
24560                entrada: None,
24561            };
24562            assert_eq!(
24563                *s.politicas(),
24564                politicas,
24565                "AplicacaoSpec::politicas must return :politicas verbatim \
24566                 (got {:?}, expected {:?})",
24567                s.politicas(),
24568                politicas,
24569            );
24570            assert!(
24571                std::ptr::eq(s.politicas(), &s.politicas),
24572                "AplicacaoSpec::politicas accessor and &self.politicas \
24573                 field access must borrow the same backing storage — \
24574                 the accessor is the substrate-primitive typed dispatch \
24575                 every downstream mesh-policy composite consumer must \
24576                 route through, and a reference-identity split would \
24577                 silently break every consumer that relied on the \
24578                 borrow sharing the composite's storage",
24579            );
24580            assert_eq!(
24581                s.politicas().is_empty(),
24582                s.politicas.is_empty(),
24583                "AplicacaoSpec::politicas().is_empty() must byte-equal \
24584                 self.politicas.is_empty() — an emptiness-drift would \
24585                 silently split the paired `validate_politicas` \
24586                 per-axis bracket-dispatch's seed from the peer \
24587                 caixa-mesh CNP mTLS-overlay emitter's key from the \
24588                 peer caixa-mesh HTTPRoute timeout+retry overlay \
24589                 emitter's key",
24590            );
24591        }
24592    }
24593
24594    #[test]
24595    fn validate_politicas_reads_through_lifted_politicas_accessor() {
24596        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
24597        // per-axis bracket-dispatch seed (`let p = self.politicas();`,
24598        // followed by the per-axis fan-out `p.timeout()` /
24599        // `p.retries()` / `p.circuit_breaker()` / `p.rate_limit()` on
24600        // the lifted axis-level accessor family) must key off the
24601        // lifted outer accessor, so any future rebrand on the typed
24602        // slot's outer-composite reader shape lands at exactly one
24603        // place. Pins the multi-axis coherence by exercising each
24604        // per-axis refusal end-to-end: (1) `PolicyTimeoutZero` fires on
24605        // a `Some(Duration::ZERO)` timeout under the outer accessor's
24606        // reference projection, (2) `PolicyRetriesZero` fires on a
24607        // `Some(0)` retries under the same projection, and (3) an
24608        // empty [`MeshPolicy::default`] passes `validate_politicas` —
24609        // the outer accessor's reference-projection reaches every
24610        // per-axis branch without silently short-circuiting any.
24611        //
24612        // Peer of the sibling M3
24613        // [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24614        // three-consumer coherence pin on the per-`:membros` node-list
24615        // axis and the sibling M3
24616        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24617        // three-consumer coherence pin on the per-`:contratos`
24618        // edge-list axis — extends the multi-consumer coherence
24619        // discipline onto the outermost M3 mesh-slot type's per-
24620        // Aplicacao mesh-policy composite-reference axis, the first
24621        // `&Composite`-return accessor on the outer [`AplicacaoSpec`]
24622        // type.
24623
24624        // (1) `PolicyTimeoutZero` refusal under the outer accessor's
24625        // reference projection: a `Some(Duration::ZERO)` timeout must
24626        // trip the zero-floor gate. The bracket-dispatch's first arm
24627        // reads `p.timeout()` on the reference returned by the outer
24628        // accessor.
24629        let mut spec = three_member_spec();
24630        spec.politicas.timeout = Some(Duration::ZERO);
24631        spec.politicas.retries = None;
24632        spec.politicas.circuit_breaker = None;
24633        spec.politicas.rate_limit = None;
24634        assert_eq!(
24635            spec.validate().unwrap_err(),
24636            AplicacaoError::PolicyTimeoutZero,
24637        );
24638        assert!(
24639            std::ptr::eq(spec.politicas(), &spec.politicas),
24640            "the `validate_politicas` per-axis bracket-dispatch's \
24641             traversal input must be the same backing composite the \
24642             accessor's reference projection borrows from",
24643        );
24644
24645        // (2) `PolicyRetriesZero` refusal under the outer accessor's
24646        // reference projection: a `Some(0)` retries must trip the
24647        // zero-floor gate. The bracket-dispatch's second arm reads
24648        // `p.retries()` on the reference returned by the outer accessor.
24649        let mut spec = three_member_spec();
24650        spec.politicas.timeout = None;
24651        spec.politicas.retries = Some(0);
24652        spec.politicas.circuit_breaker = None;
24653        spec.politicas.rate_limit = None;
24654        assert_eq!(
24655            spec.validate().unwrap_err(),
24656            AplicacaoError::PolicyRetriesZero,
24657        );
24658
24659        // (3) Empty `MeshPolicy::default()` passes `validate_politicas`
24660        // — every per-axis arm short-circuits on `None`, so the outer
24661        // accessor's reference projection reaches the fall-through
24662        // `Ok(())` without any per-axis refusal firing.
24663        let mut spec = three_member_spec();
24664        spec.politicas = MeshPolicy::default();
24665        assert!(
24666            spec.validate().is_ok(),
24667            "an empty `MeshPolicy` must pass `validate_politicas` — \
24668             every per-axis arm short-circuits on `None` under the \
24669             outer accessor's reference projection",
24670        );
24671        assert!(
24672            spec.politicas().is_empty(),
24673            "the outer accessor's reference projection must be the \
24674             empty composite per the `MeshPolicy::default()` fixture",
24675        );
24676    }
24677
24678    #[test]
24679    #[allow(clippy::too_many_lines)]
24680    fn validate_politicas_timeout_and_retries_arms_route_through_lifted_axis_accessors() {
24681        // Per-axis coherence pin: the [`AplicacaoSpec::validate_politicas`]
24682        // per-axis bracket-dispatch's `:timeout` and `:retries` arms
24683        // must both key off the lifted axis-level accessors
24684        // ([`MeshPolicy::timeout`] / [`MeshPolicy::retries`]), matching
24685        // the peer `:circuit-breaker` / `:rate-limit` arms already
24686        // routing through [`MeshPolicy::circuit_breaker`] /
24687        // [`MeshPolicy::rate_limit`] — a uniform "one typed dispatch
24688        // per axis on the substrate primitive" shape at the fan-out
24689        // (four axes, four accessors, no raw-field-access site
24690        // anywhere on the bracket-dispatch). Pins the per-axis
24691        // coherence at the accept-set boundaries the bracket carves:
24692        //   1. accessor byte-equal to raw field on every representative
24693        //      accept-set value (`None`, sub-cap, at-cap, past-cap
24694        //      sentinel) — a future accessor drift that no longer
24695        //      shipped the raw slot verbatim would surface here,
24696        //   2. `PolicyTimeoutZero` refusal fires on `Some(Duration::ZERO)`
24697        //      routed through the accessor's projection, proving the
24698        //      first arm reads through the accessor rather than a
24699        //      silent-detour peer-axis field access,
24700        //   3. `PolicyRetriesZero` refusal fires on `Some(0)` routed
24701        //      through the accessor's projection, proving the second
24702        //      arm reads through the accessor,
24703        //   4. an at-cap `Some(POLICY_RETRIES_MAX)` retries value
24704        //      passes validate under the accessor projection (paired
24705        //      with a `Some(POLICY_TIMEOUT_MAX)` at-cap timeout on the
24706        //      sibling axis), pinning the upper-boundary accept-arm
24707        //      also routes through the accessor.
24708        //
24709        // Peer of the sibling M3
24710        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
24711        // outer-composite-reference coherence pin (which asserts the
24712        // `let p = self.politicas()` seed); extends the discipline onto
24713        // the per-axis fan-out layer that consumes the seed's
24714        // reference. Same shape as
24715        // [`validate_reads_through_lifted_contratos_accessor`] (0dcc926)
24716        // and [`validate_reads_through_lifted_membros_accessor`] (6c77e36)
24717        // apply on the per-`AplicacaoSpec` `Vec`-carry axes, extended
24718        // onto the per-`MeshPolicy` `Option<Copy-T>`-carry axes.
24719
24720        // (1) Accessor byte-equal to raw field on the `:timeout` axis
24721        // across the accept-set boundaries the bracket dispatch's
24722        // three-arm gate carves out
24723        // ([`crate::render::require_positive_canonical_bounded_duration`]
24724        // — zero-floor + canonical-form + upper-cap).
24725        for timeout in [
24726            None,
24727            Some(Duration::ZERO),
24728            Some(Duration::from_millis(1)),
24729            Some(POLICY_TIMEOUT_MAX),
24730        ] {
24731            let p = MeshPolicy {
24732                timeout,
24733                ..MeshPolicy::default()
24734            };
24735            assert_eq!(
24736                p.timeout(),
24737                p.timeout,
24738                "MeshPolicy::timeout accessor must byte-equal the raw \
24739                 .timeout field across every accept-set boundary the \
24740                 validate_politicas :timeout arm carves out — a drift \
24741                 here would silently split the validate bracket's arm \
24742                 from the peer caixa-mesh HTTPRoute timeout-overlay \
24743                 emitter's read",
24744            );
24745        }
24746
24747        // (2) Accessor byte-equal to raw field on the `:retries` axis
24748        // across the accept-set boundaries the bracket dispatch's
24749        // two-arm gate carves out
24750        // ([`crate::render::require_positive_bounded_u32`] — zero-floor
24751        // + upper-cap).
24752        for retries in [
24753            None,
24754            Some(0u32),
24755            Some(1u32),
24756            Some(POLICY_RETRIES_MAX),
24757            Some(POLICY_RETRIES_MAX + 1),
24758            Some(u32::MAX),
24759        ] {
24760            let p = MeshPolicy {
24761                retries,
24762                ..MeshPolicy::default()
24763            };
24764            assert_eq!(
24765                p.retries(),
24766                p.retries,
24767                "MeshPolicy::retries accessor must byte-equal the raw \
24768                 .retries field across every accept-set boundary the \
24769                 validate_politicas :retries arm carves out — a drift \
24770                 here would silently split the validate bracket's arm \
24771                 from the peer caixa-mesh HTTPRoute retry-overlay \
24772                 emitter's read",
24773            );
24774        }
24775
24776        // (3) `PolicyTimeoutZero` fires on the accessor-projected
24777        // zero-floor boundary. A silent detour that no longer read
24778        // through `p.timeout()` (a peer-axis field read, an accidental
24779        // Option::and-then chain that collapsed the None arm to Some,
24780        // an accessor rebrand that clamped the return through the
24781        // upper cap) would fail to refuse here.
24782        let mut spec = three_member_spec();
24783        spec.politicas.timeout = Some(Duration::ZERO);
24784        spec.politicas.retries = None;
24785        spec.politicas.circuit_breaker = None;
24786        spec.politicas.rate_limit = None;
24787        assert_eq!(
24788            spec.politicas().timeout(),
24789            Some(Duration::ZERO),
24790            "the accessor projection must reflect the fixture's \
24791             `Some(Duration::ZERO)` :timeout verbatim",
24792        );
24793        assert_eq!(
24794            spec.validate().unwrap_err(),
24795            AplicacaoError::PolicyTimeoutZero,
24796            "the validate_politicas :timeout zero-floor arm must fire \
24797             through the lifted accessor's projection — a silent \
24798             detour to a peer-axis field would fail to refuse",
24799        );
24800
24801        // (4) `PolicyRetriesZero` fires on the accessor-projected
24802        // zero-floor boundary on the sibling `:retries` axis.
24803        let mut spec = three_member_spec();
24804        spec.politicas.timeout = None;
24805        spec.politicas.retries = Some(0);
24806        spec.politicas.circuit_breaker = None;
24807        spec.politicas.rate_limit = None;
24808        assert_eq!(
24809            spec.politicas().retries(),
24810            Some(0),
24811            "the accessor projection must reflect the fixture's \
24812             `Some(0)` :retries verbatim",
24813        );
24814        assert_eq!(
24815            spec.validate().unwrap_err(),
24816            AplicacaoError::PolicyRetriesZero,
24817            "the validate_politicas :retries zero-floor arm must fire \
24818             through the lifted accessor's projection — a silent \
24819             detour to a peer-axis field would fail to refuse",
24820        );
24821
24822        // (5) At-cap accept-arm on both axes: a `Some(POLICY_TIMEOUT_MAX)`
24823        // timeout paired with a `Some(POLICY_RETRIES_MAX)` retries
24824        // must pass validate under the accessor projection — pins the
24825        // upper-boundary accept-arm also routes through the lifted
24826        // accessor (a drift that clamped or short-circuited at the
24827        // upper boundary would fail the whole-spec validate here).
24828        let mut spec = three_member_spec();
24829        spec.politicas.timeout = Some(POLICY_TIMEOUT_MAX);
24830        spec.politicas.retries = Some(POLICY_RETRIES_MAX);
24831        spec.politicas.circuit_breaker = None;
24832        spec.politicas.rate_limit = None;
24833        assert_eq!(
24834            spec.politicas().timeout(),
24835            Some(POLICY_TIMEOUT_MAX),
24836            "the accessor projection must reflect the fixture's \
24837             at-cap :timeout verbatim",
24838        );
24839        assert_eq!(
24840            spec.politicas().retries(),
24841            Some(POLICY_RETRIES_MAX),
24842            "the accessor projection must reflect the fixture's \
24843             at-cap :retries verbatim",
24844        );
24845        assert!(
24846            spec.validate().is_ok(),
24847            "at-cap :timeout + :retries must pass validate under the \
24848             accessor projection — the upper-boundary accept-arm on \
24849             both axes routes through the lifted accessor",
24850        );
24851    }
24852
24853    #[test]
24854    fn aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations() {
24855        // The canonical per-`:placement` outer-composite-reference-shape
24856        // pin: [`AplicacaoSpec::placement`] must return the `:placement`
24857        // typed `Placement` verbatim as a `&Placement` reference over the
24858        // same backing storage the raw `&self.placement` field access
24859        // borrows from, byte-equal across every representative fixture in
24860        // the accept-set — the default `Placement` (the substrate seed
24861        // shape whose [`PlacementStrategy::default`] evaluates to
24862        // `SingleNode` with an empty `:clusters` pool and both
24863        // optional-scalar axes `None`), and every canonical strategy /
24864        // cluster-pool / optional-scalar combination the
24865        // [`AplicacaoSpec::validate_placement`] gate accepts (each of the
24866        // three [`PlacementStrategy`] variants — `SingleNode`,
24867        // `Replicated`, `Sharded` — cross-projected with a non-empty
24868        // `:clusters` pool and, on the `Sharded` arm, a non-empty
24869        // `:shard-key`; a `:affinity`-carrying `Replicated` fixture; the
24870        // canonical `three_member_spec` `Replicated` fixture's
24871        // `{Replicated, ["rio", "mar"], "data-locality", None}` composite).
24872        //
24873        // Pins against a future silent detour that returned a fresh-
24874        // cloned `Placement` copy (which would type-check via a `Clone`
24875        // impl but silently break every downstream caller that relied on
24876        // the reference sharing the composite's backing identity), a
24877        // reference to an operator-resolved overlay (the future per-
24878        // cluster `:placement-overrides` slot MESH-COMPOSITION §V
24879        // acknowledges — its resolution must land at exactly this
24880        // accessor body, not silently divert the raw slot away from a
24881        // second consumer), or an axis-shuffled projection (a future
24882        // detour that swapped `clusters` and `affinity` through the
24883        // accessor would silently split the paired `validate_placement`
24884        // per-axis bracket-dispatch's traversal input from the peer
24885        // `caixa_mesh::programs_for_aplicacao` per-Aplicacao
24886        // programs.yaml distribution-annotation emitter's fan-out input
24887        // from the peer `feira app graph` per-Aplicacao print line's
24888        // input).
24889        //
24890        // Peer of the sibling M3
24891        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
24892        // (534dc21) `&MeshPolicy` byte-equal pin on the per-`:politicas`
24893        // outer mesh-policy composite-reference axis, and of the sibling
24894        // slice-return `aplicacao_spec_membros_returns_membros_slice_
24895        // byte_equal_across_permutations` (6c77e36) `&[Membro]` +
24896        // `aplicacao_spec_contratos_returns_contratos_slice_byte_equal_
24897        // across_permutations` (0dcc926) `&[WitContract]` pins — extends
24898        // the outer-accessor byte-equal-projection discipline onto the
24899        // outermost M3 mesh-slot type's per-Aplicacao distribution
24900        // composite-reference axis, the second `&Composite`-return
24901        // accessor on the outer [`AplicacaoSpec`] type.
24902        let fixtures: Vec<Placement> = vec![
24903            Placement::default(),
24904            Placement {
24905                estrategia: PlacementStrategy::SingleNode,
24906                clusters: vec!["rio".into()],
24907                affinity: None,
24908                shard_key: None,
24909            },
24910            Placement {
24911                estrategia: PlacementStrategy::Replicated,
24912                clusters: vec!["rio".into(), "mar".into()],
24913                affinity: None,
24914                shard_key: None,
24915            },
24916            Placement {
24917                estrategia: PlacementStrategy::Replicated,
24918                clusters: vec!["rio".into(), "mar".into()],
24919                affinity: Some("data-locality".into()),
24920                shard_key: None,
24921            },
24922            Placement {
24923                estrategia: PlacementStrategy::Sharded,
24924                clusters: vec!["rio".into(), "mar".into()],
24925                affinity: None,
24926                shard_key: Some("tenantId".into()),
24927            },
24928            Placement {
24929                estrategia: PlacementStrategy::Sharded,
24930                clusters: vec!["rio".into(), "mar".into(), "sol".into()],
24931                affinity: Some("low-latency".into()),
24932                shard_key: Some("metadata.tenantId".into()),
24933            },
24934        ];
24935        for placement in fixtures {
24936            let s = AplicacaoSpec {
24937                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
24938                contratos: Vec::new(),
24939                politicas: MeshPolicy::default(),
24940                placement: placement.clone(),
24941                entrada: None,
24942            };
24943            assert_eq!(
24944                *s.placement(),
24945                placement,
24946                "AplicacaoSpec::placement must return :placement verbatim \
24947                 (got {:?}, expected {:?})",
24948                s.placement(),
24949                placement,
24950            );
24951            assert!(
24952                std::ptr::eq(s.placement(), &s.placement),
24953                "AplicacaoSpec::placement accessor and &self.placement \
24954                 field access must borrow the same backing storage — the \
24955                 accessor is the substrate-primitive typed dispatch every \
24956                 downstream distribution-composite consumer must route \
24957                 through, and a reference-identity split would silently \
24958                 break every consumer that relied on the borrow sharing \
24959                 the composite's storage",
24960            );
24961            assert_eq!(
24962                s.placement().estrategia(),
24963                s.placement.estrategia,
24964                "AplicacaoSpec::placement().estrategia() must byte-equal \
24965                 self.placement.estrategia — a strategy-drift would \
24966                 silently split the paired `validate_placement` \
24967                 `Sharded` ↔ non-`Sharded` partition scrutinee from the \
24968                 peer caixa-mesh programs.yaml `placement.estrategia` \
24969                 emitter's key from the peer `feira app graph` printer's \
24970                 strategy label",
24971            );
24972            assert_eq!(
24973                s.placement().clusters(),
24974                s.placement.clusters.as_slice(),
24975                "AplicacaoSpec::placement().clusters() must byte-equal \
24976                 self.placement.clusters — a cluster-pool drift would \
24977                 silently split the paired `validate_placement` \
24978                 pre-flight `.is_empty()` refusal probe's traversal from \
24979                 the peer caixa-mesh programs.yaml `placement.clusters` \
24980                 emitter's fan-out from the peer `feira app graph` \
24981                 printer's cluster list",
24982            );
24983        }
24984    }
24985
24986    #[test]
24987    fn validate_placement_reads_through_lifted_placement_accessor() {
24988        // Multi-axis coherence pin: the [`AplicacaoSpec::validate_placement`]
24989        // per-axis bracket-dispatch seed (`let p = self.placement();`,
24990        // followed by the per-axis fan-out `p.clusters()` /
24991        // `p.estrategia()` / `p.affinity()` / `p.shard_key()` on the
24992        // lifted axis-level accessor family) must key off the lifted
24993        // outer accessor, so any future rebrand on the typed slot's
24994        // outer-composite reader shape lands at exactly one place. Pins
24995        // the multi-axis coherence by exercising each per-axis refusal
24996        // end-to-end: (1) `PlacementWithoutClusters` fires on an empty
24997        // `:clusters` pool under the outer accessor's reference
24998        // projection, (2) `ShardedWithoutKey` fires on a `Sharded`
24999        // strategy with a `None` `:shard-key` under the same projection,
25000        // (3) `ShardKeyOnNonSharded` fires on a non-`Sharded` strategy
25001        // with a `Some` `:shard-key` under the same projection, and
25002        // (4) the canonical `three_member_spec` `Replicated` fixture
25003        // passes `validate_placement` under the outer accessor's
25004        // reference projection — the accessor's reference-projection
25005        // reaches every per-axis branch (cluster-pool refusal, `Sharded`
25006        // ↔ non-`Sharded` partition scrutinee, `:shard-key` shape gate)
25007        // without silently short-circuiting any.
25008        //
25009        // Peer of the sibling M3
25010        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
25011        // (534dc21) multi-axis coherence pin on the per-`:politicas`
25012        // outer mesh-policy composite-reference axis — extends the
25013        // multi-consumer coherence discipline onto the outermost M3
25014        // mesh-slot type's per-Aplicacao distribution composite-
25015        // reference axis, the second `&Composite`-return accessor on
25016        // the outer [`AplicacaoSpec`] type.
25017
25018        // (1) `PlacementWithoutClusters` refusal under the outer
25019        // accessor's reference projection: an empty `:clusters` pool
25020        // must trip the pre-flight refusal probe. The bracket-dispatch's
25021        // first arm reads `p.clusters()` on the reference returned by
25022        // the outer accessor.
25023        let mut spec = three_member_spec();
25024        spec.placement.clusters = Vec::new();
25025        assert_eq!(
25026            spec.validate().unwrap_err(),
25027            AplicacaoError::PlacementWithoutClusters {
25028                estrategia: PlacementStrategy::Replicated,
25029            },
25030        );
25031        assert!(
25032            std::ptr::eq(spec.placement(), &spec.placement),
25033            "the `validate_placement` per-axis bracket-dispatch's \
25034             traversal input must be the same backing composite the \
25035             accessor's reference projection borrows from",
25036        );
25037
25038        // (2) `ShardedWithoutKey` refusal under the outer accessor's
25039        // reference projection: a `Sharded` strategy with a `None`
25040        // `:shard-key` must trip the `Sharded`-arm shape-gate cascade.
25041        // The bracket-dispatch's third arm reads `p.estrategia()` for
25042        // the match scrutinee then `p.shard_key()` for the cascade
25043        // scrutinee, both on the reference returned by the outer
25044        // accessor.
25045        let mut spec = three_member_spec();
25046        spec.placement.estrategia = PlacementStrategy::Sharded;
25047        spec.placement.shard_key = None;
25048        assert_eq!(
25049            spec.validate().unwrap_err(),
25050            AplicacaoError::ShardedWithoutKey,
25051        );
25052
25053        // (3) `ShardKeyOnNonSharded` refusal under the outer accessor's
25054        // reference projection: a non-`Sharded` strategy with a `Some`
25055        // `:shard-key` must trip the declared-but-inert refusal. The
25056        // bracket-dispatch's non-`Sharded` arm reads `p.shard_key()`
25057        // + `p.estrategia()` for the diagnostic on the reference
25058        // returned by the outer accessor.
25059        let mut spec = three_member_spec();
25060        spec.placement.estrategia = PlacementStrategy::Replicated;
25061        spec.placement.shard_key = Some("tenantId".into());
25062        assert_eq!(
25063            spec.validate().unwrap_err(),
25064            AplicacaoError::ShardKeyOnNonSharded {
25065                estrategia: PlacementStrategy::Replicated,
25066                shard_key: "tenantId".into(),
25067            },
25068        );
25069
25070        // (4) Canonical `three_member_spec` `Replicated` fixture passes
25071        // `validate_placement` — every per-axis arm reaches the fall-
25072        // through `Ok(())` without any per-axis refusal firing under the
25073        // outer accessor's reference projection.
25074        let spec = three_member_spec();
25075        assert!(
25076            spec.validate().is_ok(),
25077            "the canonical Replicated placement fixture must pass \
25078             `validate_placement` — every per-axis arm short-circuits on \
25079             valid input under the outer accessor's reference projection",
25080        );
25081        assert_eq!(
25082            spec.placement().estrategia(),
25083            PlacementStrategy::Replicated,
25084            "the outer accessor's reference projection must be the \
25085             canonical Replicated fixture's strategy",
25086        );
25087        assert_eq!(
25088            spec.placement().clusters(),
25089            &["rio", "mar"],
25090            "the outer accessor's reference projection must be the \
25091             canonical Replicated fixture's cluster pool",
25092        );
25093    }
25094
25095    #[test]
25096    fn aplicacao_spec_entrada_returns_entrada_option_ref_byte_equal_across_permutations() {
25097        // The canonical per-`:entrada` outer-composite-optional-
25098        // reference-shape pin: [`AplicacaoSpec::entrada`] must return
25099        // the `:entrada` typed `Option<Entrada>` verbatim as an
25100        // `Option<&Entrada>` reference over the same backing storage
25101        // the raw `self.entrada.as_ref()` field access borrows from,
25102        // byte-equal across every representative fixture in the
25103        // accept-set — the author-omitted `None` shape (the
25104        // "internal-only mesh" partition every downstream external-
25105        // gateway emitter treats as "emit nothing"), the minimal
25106        // singleton `:entrada` composite (host + destination + empty
25107        // paths + default port), the paths-carrying composite (the
25108        // canonical `three_member_spec` fixture's ["/api" "/health"]
25109        // path-list shape every HTTPRoute per-rule fan-out emitter
25110        // reads), and the non-default port composite (the canonical
25111        // custom-port shape the port-fallback resolver reads).
25112        //
25113        // Pins against a future silent detour that returned a fresh-
25114        // cloned `Entrada` copy (which would type-check via a `Clone`
25115        // impl but silently break every downstream caller that
25116        // relied on the reference sharing the composite's backing
25117        // identity), a reference to an operator-resolved overlay
25118        // (the future per-cluster `:entrada-overrides` slot the
25119        // MESH-COMPOSITION §V federation roadmap acknowledges — its
25120        // resolution must land at exactly this accessor body, not
25121        // silently divert the raw slot away from a second consumer),
25122        // a `None` → `Some(Entrada::default)` cluster-default
25123        // projection (which would collapse the load-bearing
25124        // "author-omitted `:entrada` ⇒ internal-only mesh" partition
25125        // the peer `gateway_routes` early-return + `feira app graph`
25126        // internal-only-mesh partition both read), or an axis-
25127        // shuffled projection (a future detour that swapped
25128        // `host` and `para` through the accessor would silently
25129        // split the paired `validate` per-`:entrada` shape-and-
25130        // membership gate's traversal input from the peer
25131        // `caixa_mesh::gateway_routes` Gateway + HTTPRoute emitter's
25132        // fan-out input from the peer `feira app graph` external-
25133        // gateway summary line).
25134        //
25135        // Peer of the sibling M3
25136        // `aplicacao_spec_politicas_returns_politicas_ref_byte_equal_across_permutations`
25137        // (534dc21) `&MeshPolicy` byte-equal pin on the per-
25138        // `:politicas` outer mesh-policy composite-reference axis
25139        // and of the sibling M3
25140        // `aplicacao_spec_placement_returns_placement_ref_byte_equal_across_permutations`
25141        // (9abb8f0) `&Placement` byte-equal pin on the per-
25142        // `:placement` outer distribution-composite composite-
25143        // reference axis — extends the outer-accessor byte-equal-
25144        // projection discipline onto the last unlifted outermost M3
25145        // mesh-slot type's per-Aplicacao external-gateway composite-
25146        // reference axis, the third and final `&Composite`-return
25147        // accessor on the outer [`AplicacaoSpec`] type.
25148        let fixtures: Vec<Option<Entrada>> = vec![
25149            None,
25150            Some(Entrada {
25151                host: "checkout.quero.cloud".into(),
25152                para: "cart".into(),
25153                paths: Vec::new(),
25154                port: DEFAULT_SERVICO_PORT,
25155            }),
25156            Some(Entrada {
25157                host: "checkout.quero.cloud".into(),
25158                para: "cart".into(),
25159                paths: vec!["/api".into(), "/health".into()],
25160                port: DEFAULT_SERVICO_PORT,
25161            }),
25162            Some(Entrada {
25163                host: "checkout.quero.cloud".into(),
25164                para: "cart".into(),
25165                paths: vec!["/api".into()],
25166                port: 9443,
25167            }),
25168        ];
25169        for entrada in fixtures {
25170            let s = AplicacaoSpec {
25171                membros: vec![membro("catalog", "^0.1"), membro("cart", "^0.1")],
25172                contratos: Vec::new(),
25173                politicas: MeshPolicy::default(),
25174                placement: Placement::default(),
25175                entrada: entrada.clone(),
25176            };
25177            assert_eq!(
25178                s.entrada(),
25179                entrada.as_ref(),
25180                "AplicacaoSpec::entrada must return :entrada verbatim \
25181                 (got {:?}, expected {:?})",
25182                s.entrada(),
25183                entrada.as_ref(),
25184            );
25185            match (s.entrada(), s.entrada.as_ref()) {
25186                (Some(a), Some(b)) => assert!(
25187                    std::ptr::eq(a, b),
25188                    "AplicacaoSpec::entrada accessor and \
25189                     self.entrada.as_ref() field access must borrow \
25190                     the same backing storage — the accessor is the \
25191                     substrate-primitive typed dispatch every \
25192                     downstream external-gateway composite consumer \
25193                     must route through, and a reference-identity \
25194                     split would silently break every consumer that \
25195                     relied on the borrow sharing the composite's \
25196                     storage",
25197                ),
25198                (None, None) => {}
25199                _ => panic!(
25200                    "AplicacaoSpec::entrada presence bit must byte-\
25201                     equal self.entrada.is_some() — a presence-bit \
25202                     drift would silently split the paired `validate` \
25203                     per-`:entrada` shape-and-membership gate's \
25204                     traversal head from the peer \
25205                     caixa-mesh gateway_routes early-return partition \
25206                     from the peer `feira app graph` internal-only-\
25207                     mesh partition",
25208                ),
25209            }
25210            assert_eq!(
25211                s.entrada().is_some(),
25212                s.entrada.is_some(),
25213                "AplicacaoSpec::entrada().is_some() must byte-equal \
25214                 self.entrada.is_some() — a presence-bit drift would \
25215                 silently split every downstream `Option<&Entrada>` \
25216                 consumer's partition on the internal-only-mesh arm",
25217            );
25218        }
25219    }
25220
25221    #[test]
25222    fn validate_reads_through_lifted_entrada_accessor() {
25223        // Multi-consumer coherence pin: the [`AplicacaoSpec::validate`]
25224        // per-`:entrada` shape-and-membership gate (`if let Some(e) =
25225        // self.entrada() { … }`, followed by the per-axis fan-out
25226        // `validate_entrada_para(&e.para)` /
25227        // `EntradaMemberMissing` membership lookup /
25228        // `EmptyEntradaHost` / `validate_entrada_host(&e.host)` /
25229        // per-`e.paths` `validate_entrada_path` traversal) must key
25230        // off the lifted outer accessor, so any future rebrand on
25231        // the typed slot's outer-composite reader shape lands at
25232        // exactly one place. Pins the multi-axis coherence by
25233        // exercising each per-axis refusal end-to-end: (1) the
25234        // author-omitted `None` shape short-circuits past every
25235        // per-`:entrada` refusal (the internal-only mesh partition
25236        // the accessor's `None` arm names), (2) `EntradaMemberMissing`
25237        // fires on a well-shaped but phantom `:para` under the outer
25238        // accessor's reference projection, and (3) the canonical
25239        // `three_member_spec` `:entrada` fixture passes `validate`
25240        // under the outer accessor's reference projection.
25241        //
25242        // Peer of the sibling M3
25243        // [`validate_politicas_reads_through_lifted_politicas_accessor`]
25244        // (534dc21) multi-axis coherence pin on the per-`:politicas`
25245        // outer mesh-policy composite-reference axis and the sibling
25246        // M3
25247        // [`validate_placement_reads_through_lifted_placement_accessor`]
25248        // (9abb8f0) multi-axis coherence pin on the per-`:placement`
25249        // outer distribution-composite composite-reference axis —
25250        // extends the multi-consumer coherence discipline onto the
25251        // last unlifted outermost M3 mesh-slot type's per-Aplicacao
25252        // external-gateway composite-reference axis, the third and
25253        // final `&Composite`-return accessor on the outer
25254        // [`AplicacaoSpec`] type.
25255
25256        // (1) `None` :entrada — the internal-only-mesh partition
25257        // short-circuits past every per-`:entrada` refusal. The outer
25258        // accessor's reference projection reaches the fall-through
25259        // `Ok(())` on the `None` arm without any per-axis refusal
25260        // firing.
25261        let mut spec = three_member_spec();
25262        spec.entrada = None;
25263        assert!(
25264            spec.validate().is_ok(),
25265            "an author-omitted `:entrada` must pass `validate` — the \
25266             internal-only-mesh partition short-circuits past every \
25267             per-`:entrada` refusal under the outer accessor's \
25268             reference projection",
25269        );
25270        assert!(
25271            spec.entrada().is_none(),
25272            "the outer accessor's reference projection must name the \
25273             internal-only-mesh partition per the `None` fixture",
25274        );
25275
25276        // (2) `EntradaMemberMissing` refusal under the outer accessor's
25277        // reference projection: a well-shaped but phantom `:para` must
25278        // trip the membership-lookup refusal. The gate's second arm
25279        // reads `e.para` on the reference returned by the outer
25280        // accessor.
25281        let mut spec = three_member_spec();
25282        if let Some(e) = spec.entrada.as_mut() {
25283            e.para = "phantom".into();
25284        }
25285        assert_eq!(
25286            spec.validate().unwrap_err(),
25287            AplicacaoError::EntradaMemberMissing {
25288                para: "phantom".into(),
25289            },
25290        );
25291        match (spec.entrada(), spec.entrada.as_ref()) {
25292            (Some(a), Some(b)) => assert!(
25293                std::ptr::eq(a, b),
25294                "the `validate` per-`:entrada` gate's traversal head \
25295                 must be the same backing composite the accessor's \
25296                 reference projection borrows from",
25297            ),
25298            _ => panic!("fixture must carry Some(:entrada)"),
25299        }
25300
25301        // (3) Canonical `three_member_spec` `:entrada` fixture passes
25302        // `validate` — every per-axis arm reaches the fall-through
25303        // `Ok(())` without any per-axis refusal firing under the
25304        // outer accessor's reference projection.
25305        let spec = three_member_spec();
25306        assert!(
25307            spec.validate().is_ok(),
25308            "the canonical `:entrada` fixture must pass `validate` — \
25309             every per-axis arm short-circuits on valid input under \
25310             the outer accessor's reference projection",
25311        );
25312        assert!(
25313            spec.entrada().is_some(),
25314            "the outer accessor's reference projection must be the \
25315             canonical `:entrada` fixture's composite",
25316        );
25317    }
25318
25319    #[test]
25320    fn port_for_destination_reads_through_lifted_entrada_accessor() {
25321        // Peer coherence pin: the
25322        // [`AplicacaoSpec::port_for_destination`] per-destination
25323        // L4-port fallback resolver's composite-projection seed
25324        // (`self.entrada().filter(…).map_or(…)`) must key off the
25325        // lifted outer accessor. Pins the coherence by exercising
25326        // the resolver end-to-end: (1) the `None` `:entrada` shape
25327        // falls through to `DEFAULT_SERVICO_PORT` under the outer
25328        // accessor's reference projection, (2) a non-matching
25329        // destination falls through to `DEFAULT_SERVICO_PORT` under
25330        // the outer accessor's reference projection, and (3) the
25331        // matching destination resolves to the `:entrada :port`
25332        // value under the outer accessor's reference projection.
25333        //
25334        // Peer of the sibling
25335        // [`validate_reads_through_lifted_entrada_accessor`] multi-
25336        // consumer coherence pin on the same per-`:entrada` outer-
25337        // composite axis — extends the multi-consumer coherence
25338        // discipline onto the second per-`:entrada` production
25339        // consumer, the L4-port fallback resolver.
25340
25341        // (1) `None` :entrada — the resolver's `filter(…).map_or(…)`
25342        // seed falls through to `DEFAULT_SERVICO_PORT` on the `None`
25343        // arm under the outer accessor's reference projection.
25344        let mut spec = three_member_spec();
25345        spec.entrada = None;
25346        assert_eq!(
25347            spec.port_for_destination("cart"),
25348            DEFAULT_SERVICO_PORT,
25349            "the port-fallback resolver must fall through to \
25350             DEFAULT_SERVICO_PORT on an author-omitted `:entrada` \
25351             under the outer accessor's reference projection",
25352        );
25353
25354        // (2) Non-matching destination — the resolver's `filter(…)`
25355        // arm rejects a mismatched destination and falls through
25356        // to `DEFAULT_SERVICO_PORT` under the outer accessor's
25357        // reference projection.
25358        let mut spec = three_member_spec();
25359        if let Some(e) = spec.entrada.as_mut() {
25360            e.para = "cart".into();
25361            e.port = 9443;
25362        }
25363        assert_eq!(
25364            spec.port_for_destination("catalog"),
25365            DEFAULT_SERVICO_PORT,
25366            "the port-fallback resolver must fall through to \
25367             DEFAULT_SERVICO_PORT on a non-matching destination \
25368             under the outer accessor's reference projection",
25369        );
25370
25371        // (3) Matching destination — the resolver's `map_or(…)` arm
25372        // returns the `:entrada :port` value under the outer
25373        // accessor's reference projection.
25374        let mut spec = three_member_spec();
25375        if let Some(e) = spec.entrada.as_mut() {
25376            e.para = "cart".into();
25377            e.port = 9443;
25378        }
25379        assert_eq!(
25380            spec.port_for_destination("cart"),
25381            9443,
25382            "the port-fallback resolver must return the \
25383             `:entrada :port` value on a matching destination \
25384             under the outer accessor's reference projection",
25385        );
25386    }
25387
25388    #[test]
25389    fn mesh_policy_mtls_required_returns_mtls_required_option_byte_equal_across_permutations() {
25390        // The canonical per-`:politicas` `:mtls-required` mTLS-
25391        // enforcement-toggle scalar pin: [`MeshPolicy::mtls_required`]
25392        // must return the `:politicas :mtls-required` typed bool
25393        // verbatim as an `Option<bool>`, byte-equal to the raw field
25394        // access across every value in the three-way accept-set —
25395        // `None` (cluster default applies), `Some(true)` (mTLS
25396        // handshake enforced — the sandboxing-by-default arm the
25397        // MeshPolicy's docstring names), `Some(false)` (handshake
25398        // skipped — the explicit debug-edge opt-out).
25399        //
25400        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
25401        // (7cd2a28) accessor pin on the `Option<&str>` optional-scalar
25402        // axis, extended to the peer per-`:politicas` `Option<Copy-T>`
25403        // shape — first `Option<Copy-T>`-return accessor on the M3
25404        // mesh-slot family. Pins against a future silent detour that
25405        // re-derived the toggle from a peer axis (an accidental
25406        // `.circuit_breaker.is_some()` collapse that assumed mTLS on
25407        // whenever a breaker is set), a `None` → `Some(false)` cluster-
25408        // default projection (the canonical `Option<bool>` → `bool`
25409        // collapse footgun the surrounding `is_empty()` predicate
25410        // guards on the peer emptiness axis), or a `Some(true)` /
25411        // `Some(false)` variant swap that landed on one consumer
25412        // without the other.
25413        for required in [None, Some(true), Some(false)] {
25414            let p = MeshPolicy {
25415                mtls_required: required,
25416                ..MeshPolicy::default()
25417            };
25418            assert_eq!(
25419                p.mtls_required(),
25420                required,
25421                "MeshPolicy::mtls_required must return :politicas \
25422                 :mtls-required verbatim (got {:?}, expected {required:?})",
25423                p.mtls_required(),
25424            );
25425            assert_eq!(
25426                p.mtls_required(),
25427                p.mtls_required,
25428                "MeshPolicy::mtls_required must byte-equal the raw \
25429                 .mtls_required field access across every value in the \
25430                 three-way accept-set",
25431            );
25432        }
25433    }
25434
25435    #[test]
25436    fn mesh_policy_is_empty_mtls_required_arm_routes_through_accessor() {
25437        // Composition pin: [`MeshPolicy::is_empty`]'s `mtls_required`
25438        // arm must key off [`MeshPolicy::mtls_required`], not the raw
25439        // `.mtls_required` field access. Structurally: toggling ONLY
25440        // the `mtls_required` slot on an otherwise-default MeshPolicy
25441        // must flip `is_empty()` from `true` (all-`None`) to `false`
25442        // (one axis carries a value); the flip must be observed for
25443        // both `Some(true)` and `Some(false)` since the emptiness
25444        // semantic reads "any axis carries a value" — not "any axis
25445        // carries a truthy value" — the same non-collapsing shape the
25446        // sibling M2 [`crate::LimitsSpec::is_empty`] /
25447        // [`crate::BehaviorSpec::is_empty`] predicates carry on their
25448        // peer `Option<T>`-typed slot surfaces.
25449        //
25450        // Pins against a future silent detour that re-derived the
25451        // emptiness predicate off a peer axis (an accidental
25452        // `.rate_limit.is_none()`-only chain that dropped the
25453        // `mtls_required` arm entirely), a `mtls_required == Some(_)`
25454        // collapse to a truthy-only check (which would silently
25455        // classify `Some(false)` as empty), or an accessor-side
25456        // detour that no longer names the substrate-primitive typed
25457        // dispatch (an accidental `self.mtls_required.unwrap_or(false)
25458        // == false` fallback in the accessor that would silently
25459        // classify both `None` and `Some(false)` as the same value).
25460        //
25461        // Peer of the sibling per-`:placement` [`Placement::shard_key`]
25462        // (7cd2a28) accessor-composition pin on the sibling optional-
25463        // scalar axis — same "the emptiness / shape-gate predicate
25464        // must route through the substrate-primitive typed dispatch"
25465        // discipline extended onto the peer per-`:politicas` emptiness
25466        // predicate.
25467        let empty = MeshPolicy::default();
25468        assert!(
25469            empty.is_empty(),
25470            "MeshPolicy::default() must be is_empty() — every axis \
25471             defaults to None",
25472        );
25473        for required in [Some(true), Some(false)] {
25474            let p = MeshPolicy {
25475                mtls_required: required,
25476                ..MeshPolicy::default()
25477            };
25478            assert!(
25479                !p.is_empty(),
25480                "MeshPolicy::is_empty must return false when \
25481                 :mtls-required is {required:?} — the emptiness \
25482                 predicate reads \"any axis carries a value\", not \
25483                 \"any axis carries a truthy value\"",
25484            );
25485            assert_eq!(
25486                p.mtls_required().is_none(),
25487                p.is_empty(),
25488                "when :mtls-required is the only set axis, \
25489                 is_empty() must equal mtls_required().is_none() — \
25490                 the accessor and the emptiness predicate must \
25491                 route through the same substrate-primitive typed \
25492                 dispatch on the :mtls-required arm",
25493            );
25494        }
25495    }
25496
25497    #[test]
25498    fn mesh_policy_mtls_required_projects_option_bool_by_copy() {
25499        // The by-copy pin: [`MeshPolicy::mtls_required`] returns
25500        // `Option<bool>` by copy — `Option<bool>` is `Copy` and the
25501        // accessor must return by value, not by reference. Peer of the
25502        // sibling per-`:placement` [`Placement::shard_key`] (7cd2a28)
25503        // borrow-invariant pin on the sibling `Option<String>` slot,
25504        // but extended onto the peer `Option<bool>` copy-invariant
25505        // shape — the accessor's returned `Option<bool>` must outlive
25506        // `&self` (multiple calls must return equal values from a
25507        // dropped-`&self` copy, since the returned Option carries no
25508        // borrow), and calling the accessor twice on the same
25509        // MeshPolicy must yield the same `Option<bool>` verbatim
25510        // (idempotent, no side effects on `&self`).
25511        //
25512        // Pins against a future silent detour that returned
25513        // `Option<&bool>` (which would type-check but silently break
25514        // every downstream caller — [`single_field_overlay`]'s first
25515        // parameter is `Option<T: Clone>`, and `&bool` would fold to a
25516        // detached copy at the call site), an accidental
25517        // `Option::as_ref()` projection (`self.mtls_required.as_ref()`
25518        // would also type-check but return `Option<&bool>`), or a
25519        // one-arm-only accessor that reads `Some(*b)` in the Some arm
25520        // but reads a fresh Default::default() in the None arm.
25521        for required in [None, Some(true), Some(false)] {
25522            let p = MeshPolicy {
25523                mtls_required: required,
25524                ..MeshPolicy::default()
25525            };
25526            let first = p.mtls_required();
25527            let second = p.mtls_required();
25528            assert_eq!(
25529                first, second,
25530                "MeshPolicy::mtls_required must be idempotent — two \
25531                 successive calls on the same &self must return the \
25532                 same Option<bool>",
25533            );
25534            assert_eq!(
25535                first, required,
25536                "MeshPolicy::mtls_required must return :politicas \
25537                 :mtls-required verbatim by copy — got {first:?}, \
25538                 expected {required:?}",
25539            );
25540        }
25541    }
25542
25543    #[test]
25544    fn mesh_policy_retries_returns_retries_option_byte_equal_across_permutations() {
25545        // The canonical per-`:politicas` `:retries` transient-failure-
25546        // retry-budget scalar pin: [`MeshPolicy::retries`] must return
25547        // the `:politicas :retries` typed `u32` verbatim as an
25548        // `Option<u32>`, byte-equal to the raw field access across every
25549        // representative value in the accept-set — `None` (cluster
25550        // default applies — typically "no retries beyond a single
25551        // dispatch attempt" the caixa-mesh `retry_overlay` builder
25552        // documents), `Some(1)` (the lower boundary of the
25553        // `1..=POLICY_RETRIES_MAX` accept-set the surrounding
25554        // `AplicacaoSpec::validate_politicas` gate carves out on the
25555        // sibling `PolicyRetriesZero` refusal), `Some(POLICY_RETRIES_MAX)`
25556        // (the upper boundary the same gate carves out on the sibling
25557        // `PolicyRetriesOverMax` refusal), and `Some(u32::MAX)` (a
25558        // past-the-guard sentinel that pins the accessor doesn't perform
25559        // a silent bounds-collapse at the return path).
25560        //
25561        // Sibling of the peer per-`:politicas`
25562        // [`MeshPolicy::mtls_required`] (c0110f1) accessor pin on the
25563        // sibling `Option<Copy-T>` optional-scalar axis, extended to the
25564        // peer per-`:politicas` `Option<u32>` shape — second
25565        // `Option<Copy-T>`-return accessor on the M3 mesh-slot family.
25566        // Pins against a future silent detour that re-derived the retry
25567        // cap from a peer axis (an accidental `.circuit_breaker
25568        // .as_ref().map(|b| b.max_failures)` collapse that read the
25569        // breaker's max-failure count as a retry budget), a
25570        // `None → Some(0)` cluster-default projection (which would
25571        // silently re-introduce the `PolicyRetriesZero` refusal case at
25572        // the emit boundary), or a bounds-collapsing accessor that
25573        // clamped the return through `POLICY_RETRIES_MAX` (the
25574        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
25575        // must ship the raw slot verbatim so a validate-time gate
25576        // regression surfaces at the emit boundary rather than being
25577        // silently absorbed).
25578        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
25579            let p = MeshPolicy {
25580                retries,
25581                ..MeshPolicy::default()
25582            };
25583            assert_eq!(
25584                p.retries(),
25585                retries,
25586                "MeshPolicy::retries must return :politicas :retries \
25587                 verbatim (got {:?}, expected {retries:?})",
25588                p.retries(),
25589            );
25590            assert_eq!(
25591                p.retries(),
25592                p.retries,
25593                "MeshPolicy::retries must byte-equal the raw .retries \
25594                 field access across every value in the accept-set",
25595            );
25596        }
25597    }
25598
25599    #[test]
25600    fn mesh_policy_is_empty_retries_arm_routes_through_accessor() {
25601        // Composition pin: [`MeshPolicy::is_empty`]'s `retries` arm
25602        // must key off [`MeshPolicy::retries`], not the raw `.retries`
25603        // field access. Structurally: toggling ONLY the `retries` slot
25604        // on an otherwise-default MeshPolicy must flip `is_empty()`
25605        // from `true` (all-`None`) to `false` (one axis carries a
25606        // value); the flip must be observed for every value in the
25607        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25608        // gate accepts (`Some(1)`, `Some(POLICY_RETRIES_MAX)`), since
25609        // the emptiness semantic reads "any axis carries a value" —
25610        // not "any axis carries a value the validate gate accepts" —
25611        // the same non-collapsing shape the peer M2
25612        // [`crate::LimitsSpec::is_empty`] /
25613        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25614        //
25615        // Pins against a future silent detour that re-derived the
25616        // emptiness predicate off a peer axis (an accidental
25617        // `.rate_limit.is_none()`-only chain that dropped the
25618        // `retries` arm entirely), a `retries == Some(_)` collapse
25619        // that key-off a validate-gate-clamped bounds check (which
25620        // would silently classify a past-the-guard `Some(u32::MAX)`
25621        // as empty because it fails the `1..=POLICY_RETRIES_MAX`
25622        // check), or an accessor-side detour that no longer names the
25623        // substrate-primitive typed dispatch.
25624        //
25625        // Sibling of the peer per-`:politicas`
25626        // [`MeshPolicy::mtls_required`] (c0110f1) accessor-composition
25627        // pin on the sibling `Option<Copy-T>` optional-scalar axis —
25628        // same "the emptiness predicate must route through the
25629        // substrate-primitive typed dispatch" discipline extended onto
25630        // the peer per-`:politicas` `Option<u32>` axis.
25631        let empty = MeshPolicy::default();
25632        assert!(
25633            empty.is_empty(),
25634            "MeshPolicy::default() must be is_empty() — every axis \
25635             defaults to None",
25636        );
25637        for retries in [Some(1u32), Some(POLICY_RETRIES_MAX)] {
25638            let p = MeshPolicy {
25639                retries,
25640                ..MeshPolicy::default()
25641            };
25642            assert!(
25643                !p.is_empty(),
25644                "MeshPolicy::is_empty must return false when \
25645                 :retries is {retries:?} — the emptiness \
25646                 predicate reads \"any axis carries a value\", not \
25647                 \"any axis carries a value the validate gate \
25648                 accepts\"",
25649            );
25650            assert_eq!(
25651                p.retries().is_none(),
25652                p.is_empty(),
25653                "when :retries is the only set axis, is_empty() \
25654                 must equal retries().is_none() — the accessor and \
25655                 the emptiness predicate must route through the same \
25656                 substrate-primitive typed dispatch on the :retries \
25657                 arm",
25658            );
25659        }
25660    }
25661
25662    #[test]
25663    fn mesh_policy_retries_projects_option_u32_by_copy() {
25664        // The by-copy pin: [`MeshPolicy::retries`] returns
25665        // `Option<u32>` by copy — `Option<u32>` is `Copy` and the
25666        // accessor must return by value, not by reference. Sibling of
25667        // the peer per-`:politicas` [`MeshPolicy::mtls_required`]
25668        // (c0110f1) by-copy pin on the peer `Option<bool>` slot,
25669        // extended onto the sibling `Option<u32>` copy-invariant
25670        // shape — the accessor's returned `Option<u32>` must outlive
25671        // `&self` (multiple calls must return equal values from a
25672        // dropped-`&self` copy, since the returned Option carries no
25673        // borrow), and calling the accessor twice on the same
25674        // MeshPolicy must yield the same `Option<u32>` verbatim
25675        // (idempotent, no side effects on `&self`).
25676        //
25677        // Pins against a future silent detour that returned
25678        // `Option<&u32>` (which would type-check but silently break
25679        // every downstream caller — [`crate::render::single_field_overlay`]'s
25680        // first parameter is `Option<T: Clone>`, and `&u32` would
25681        // fold to a detached copy at the call site), an accidental
25682        // `Option::as_ref()` projection (`self.retries.as_ref()` would
25683        // also type-check but return `Option<&u32>`), or a one-arm-
25684        // only accessor that reads `Some(*n)` in the Some arm but
25685        // reads a fresh `Default::default()` (`0_u32`) in the None
25686        // arm.
25687        for retries in [None, Some(1u32), Some(POLICY_RETRIES_MAX), Some(u32::MAX)] {
25688            let p = MeshPolicy {
25689                retries,
25690                ..MeshPolicy::default()
25691            };
25692            let first = p.retries();
25693            let second = p.retries();
25694            assert_eq!(
25695                first, second,
25696                "MeshPolicy::retries must be idempotent — two \
25697                 successive calls on the same &self must return the \
25698                 same Option<u32>",
25699            );
25700            assert_eq!(
25701                first, retries,
25702                "MeshPolicy::retries must return :politicas :retries \
25703                 verbatim by copy — got {first:?}, expected {retries:?}",
25704            );
25705        }
25706    }
25707
25708    #[test]
25709    fn mesh_policy_timeout_returns_timeout_option_byte_equal_across_permutations() {
25710        // The canonical per-`:politicas` `:timeout` Gateway-API-mesh
25711        // per-call-deadline scalar pin: [`MeshPolicy::timeout`] must
25712        // return the `:politicas :timeout` typed [`Duration`] verbatim
25713        // as an `Option<Duration>`, byte-equal to the raw field access
25714        // across every representative value in the accept-set — `None`
25715        // (cluster default applies — typically the gateway class's
25716        // implementation-side per-request wall-clock cap the caixa-mesh
25717        // `timeout_overlay` builder documents), `Some(Duration::from_millis(1))`
25718        // (the lower boundary of the `1ms..=POLICY_TIMEOUT_MAX` accept-
25719        // set the surrounding `AplicacaoSpec::validate_politicas` gate
25720        // carves out on the sibling `PolicyTimeoutZero` /
25721        // `PolicyTimeoutNotCanonical` refusals), `Some(POLICY_TIMEOUT_MAX)`
25722        // (the upper boundary the same gate carves out on the sibling
25723        // `PolicyTimeoutExceedsCap` refusal), `Some(Duration::ZERO)`
25724        // (a past-the-guard sentinel that pins the accessor doesn't
25725        // perform a silent bounds-collapse into `None` on the zero-
25726        // Duration arm — validate rejects zero but the accessor must
25727        // ship the raw slot verbatim), and `Some(Duration::MAX)` (a
25728        // past-the-guard sentinel that pins the accessor doesn't
25729        // perform a silent bounds-collapse at the return path).
25730        //
25731        // Sibling of the peer per-`:politicas`
25732        // [`MeshPolicy::retries`] (bdfb399) accessor pin on the sibling
25733        // `Option<u32>` optional-scalar axis and the peer per-
25734        // `:politicas` [`MeshPolicy::mtls_required`] (c0110f1) accessor
25735        // pin on the sibling `Option<bool>` optional-scalar axis,
25736        // extended onto the peer per-`:politicas` `Option<Duration>`
25737        // shape — third `Option<Copy-T>`-return accessor on the M3
25738        // mesh-slot family. Pins against a future silent detour that
25739        // re-derived the per-call cap from a peer axis (an accidental
25740        // `.circuit_breaker.as_ref().map(|b| b.window)` collapse that
25741        // read the breaker's rolling-window duration as a per-call
25742        // deadline), a `None → Some(Duration::MAX)` cluster-default
25743        // projection (which would silently re-introduce the
25744        // MESH-COMPOSITION §V CSE-invariant-violating "no infinite
25745        // blocking" arm at the emit boundary), or a bounds-collapsing
25746        // accessor that clamped the return through `POLICY_TIMEOUT_MAX`
25747        // (the `AplicacaoSpec::validate` gate owns the bounds; the
25748        // accessor must ship the raw slot verbatim so a validate-time
25749        // gate regression surfaces at the emit boundary rather than
25750        // being silently absorbed).
25751        for timeout in [
25752            None,
25753            Some(Duration::from_millis(1)),
25754            Some(POLICY_TIMEOUT_MAX),
25755            Some(Duration::ZERO),
25756            Some(Duration::MAX),
25757        ] {
25758            let p = MeshPolicy {
25759                timeout,
25760                ..MeshPolicy::default()
25761            };
25762            assert_eq!(
25763                p.timeout(),
25764                timeout,
25765                "MeshPolicy::timeout must return :politicas :timeout \
25766                 verbatim (got {:?}, expected {timeout:?})",
25767                p.timeout(),
25768            );
25769            assert_eq!(
25770                p.timeout(),
25771                p.timeout,
25772                "MeshPolicy::timeout must byte-equal the raw .timeout \
25773                 field access across every value in the accept-set",
25774            );
25775        }
25776    }
25777
25778    #[test]
25779    fn mesh_policy_is_empty_timeout_arm_routes_through_accessor() {
25780        // Composition pin: [`MeshPolicy::is_empty`]'s `timeout` arm
25781        // must key off [`MeshPolicy::timeout`], not the raw `.timeout`
25782        // field access. Structurally: toggling ONLY the `timeout` slot
25783        // on an otherwise-default MeshPolicy must flip `is_empty()`
25784        // from `true` (all-`None`) to `false` (one axis carries a
25785        // value); the flip must be observed for every value in the
25786        // accept-set the surrounding `AplicacaoSpec::validate_politicas`
25787        // gate accepts (`Some(Duration::from_millis(1))`,
25788        // `Some(POLICY_TIMEOUT_MAX)`), since the emptiness semantic
25789        // reads "any axis carries a value" — not "any axis carries a
25790        // value the validate gate accepts" — the same non-collapsing
25791        // shape the peer M2 [`crate::LimitsSpec::is_empty`] /
25792        // [`crate::BehaviorSpec::is_empty`] predicates carry.
25793        //
25794        // Pins against a future silent detour that re-derived the
25795        // emptiness predicate off a peer axis (an accidental
25796        // `.rate_limit.is_none()`-only chain that dropped the
25797        // `timeout` arm entirely), a `timeout == Some(_)` collapse
25798        // that key-off a validate-gate-clamped bounds check (which
25799        // would silently classify a past-the-guard `Some(Duration::MAX)`
25800        // as empty because it fails the `1ms..=POLICY_TIMEOUT_MAX`
25801        // check), or an accessor-side detour that no longer names the
25802        // substrate-primitive typed dispatch.
25803        //
25804        // Sibling of the peer per-`:politicas`
25805        // [`MeshPolicy::retries`] (bdfb399) accessor-composition pin on
25806        // the sibling `Option<u32>` optional-scalar axis and the peer
25807        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25808        // accessor-composition pin on the sibling `Option<bool>`
25809        // optional-scalar axis — same "the emptiness predicate must
25810        // route through the substrate-primitive typed dispatch"
25811        // discipline extended onto the peer per-`:politicas`
25812        // `Option<Duration>` axis.
25813        let empty = MeshPolicy::default();
25814        assert!(
25815            empty.is_empty(),
25816            "MeshPolicy::default() must be is_empty() — every axis \
25817             defaults to None",
25818        );
25819        for timeout in [Some(Duration::from_millis(1)), Some(POLICY_TIMEOUT_MAX)] {
25820            let p = MeshPolicy {
25821                timeout,
25822                ..MeshPolicy::default()
25823            };
25824            assert!(
25825                !p.is_empty(),
25826                "MeshPolicy::is_empty must return false when \
25827                 :timeout is {timeout:?} — the emptiness \
25828                 predicate reads \"any axis carries a value\", not \
25829                 \"any axis carries a value the validate gate \
25830                 accepts\"",
25831            );
25832            assert_eq!(
25833                p.timeout().is_none(),
25834                p.is_empty(),
25835                "when :timeout is the only set axis, is_empty() \
25836                 must equal timeout().is_none() — the accessor and \
25837                 the emptiness predicate must route through the same \
25838                 substrate-primitive typed dispatch on the :timeout \
25839                 arm",
25840            );
25841        }
25842    }
25843
25844    #[test]
25845    fn mesh_policy_timeout_projects_option_duration_by_copy() {
25846        // The by-copy pin: [`MeshPolicy::timeout`] returns
25847        // `Option<Duration>` by copy — `Option<Duration>` is `Copy`
25848        // and the accessor must return by value, not by reference.
25849        // Sibling of the peer per-`:politicas`
25850        // [`MeshPolicy::retries`] (bdfb399) by-copy pin on the
25851        // sibling `Option<u32>` optional-scalar axis and the peer
25852        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1)
25853        // by-copy pin on the sibling `Option<bool>` optional-scalar
25854        // axis, extended onto the peer per-`:politicas`
25855        // `Option<Duration>` copy-invariant shape — the accessor's
25856        // returned `Option<Duration>` must outlive `&self` (multiple
25857        // calls must return equal values from a dropped-`&self`
25858        // copy, since the returned Option carries no borrow), and
25859        // calling the accessor twice on the same MeshPolicy must
25860        // yield the same `Option<Duration>` verbatim (idempotent, no
25861        // side effects on `&self`).
25862        //
25863        // Pins against a future silent detour that returned
25864        // `Option<&Duration>` (which would type-check but silently
25865        // break every downstream caller — [`crate::render::single_field_overlay`]'s
25866        // first parameter is `Option<T: Clone>`, and `&Duration`
25867        // would fold to a detached copy at the call site), an
25868        // accidental `Option::as_ref()` projection
25869        // (`self.timeout.as_ref()` would also type-check but return
25870        // `Option<&Duration>`), or a one-arm-only accessor that
25871        // reads `Some(*d)` in the Some arm but reads a fresh
25872        // `Default::default()` (`Duration::ZERO`) in the None arm
25873        // (which would silently re-classify every unset `:timeout`
25874        // as the `PolicyTimeoutZero`-refused zero-Duration value at
25875        // the accessor boundary).
25876        for timeout in [
25877            None,
25878            Some(Duration::from_millis(1)),
25879            Some(POLICY_TIMEOUT_MAX),
25880            Some(Duration::ZERO),
25881            Some(Duration::MAX),
25882        ] {
25883            let p = MeshPolicy {
25884                timeout,
25885                ..MeshPolicy::default()
25886            };
25887            let first = p.timeout();
25888            let second = p.timeout();
25889            assert_eq!(
25890                first, second,
25891                "MeshPolicy::timeout must be idempotent — two \
25892                 successive calls on the same &self must return the \
25893                 same Option<Duration>",
25894            );
25895            assert_eq!(
25896                first, timeout,
25897                "MeshPolicy::timeout must return :politicas :timeout \
25898                 verbatim by copy — got {first:?}, expected {timeout:?}",
25899            );
25900        }
25901    }
25902
25903    #[test]
25904    fn mesh_policy_rate_limit_returns_rate_limit_option_byte_equal_across_permutations() {
25905        // The canonical per-`:politicas` `:rate-limit` Envoy-
25906        // `local_rate_limit`-mesh token-bucket-declaration scalar pin:
25907        // [`MeshPolicy::rate_limit`] must return the `:politicas
25908        // :rate-limit` typed [`RateLimit`] verbatim as an
25909        // `Option<RateLimit>`, byte-equal to the raw field access
25910        // across every representative value in the accept-set — `None`
25911        // (cluster default applies — no per-Aplicacao rate declaration,
25912        // the gateway-class per-listener default arm the future caixa-
25913        // mesh `local_rate_limit_overlay` emitter documents),
25914        // `Some(RateLimit { rate: 1, window: Duration::from_secs(1) })`
25915        // (the lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` rate
25916        // accept-set the surrounding
25917        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
25918        // sibling `PolicyRateLimitZero` refusal, paired with the
25919        // canonical-window "1 second" arm of the three-unit
25920        // `{"s", "m", "h"}` [`is_canonical_rate_limit_window`] bijection),
25921        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: Duration::from_secs(3600) })`
25922        // (the upper boundary the same gate carves out on the sibling
25923        // `PolicyRateLimitExceedsCap` refusal, paired with the
25924        // canonical-window "1 hour" arm), `Some(RateLimit { rate: 0, window: Duration::ZERO })`
25925        // (a past-the-guard sentinel that pins the accessor doesn't
25926        // perform a silent bounds-collapse into `None` on the
25927        // zero-rate/zero-window arm — validate rejects zero but the
25928        // accessor must ship the raw slot verbatim so a validate-time
25929        // gate regression surfaces at the emit boundary rather than
25930        // being silently absorbed), and
25931        // `Some(RateLimit { rate: u32::MAX, window: Duration::MAX })`
25932        // (a past-the-guard sentinel that pins the accessor doesn't
25933        // perform a silent bounds-collapse at the return path).
25934        //
25935        // First `Option<Copy-composite-T>`-return accessor pin on the
25936        // M3 mesh-slot family (peer of the sibling per-`:politicas`
25937        // [`MeshPolicy::mtls_required`] c0110f1 `Option<bool>` /
25938        // [`MeshPolicy::retries`] bdfb399 `Option<u32>` /
25939        // [`MeshPolicy::timeout`] 7073d0f `Option<Duration>` primitive-
25940        // Copy accessor pins, extended onto the peer per-`:politicas`
25941        // composite-`Copy` shape — [`RateLimit`] is `#[derive(Copy)]`
25942        // and the accessor returns by value). Pins against a future
25943        // silent detour that re-derived the rate declaration from a
25944        // peer axis (an accidental
25945        // `.circuit_breaker.as_ref().map(|b| RateLimit { rate: b.max_failures, window: b.window })`
25946        // collapse that read the breaker's trip threshold + rolling
25947        // window as a rate declaration), a `None → Some(default())`
25948        // cluster-default projection (which would silently re-
25949        // introduce a "cluster default is 0/s" arm the emit boundary
25950        // would take as "declared but inert" — the canonical
25951        // declared-but-inert footgun the sibling
25952        // [`POLICY_RATE_LIMIT_MAX`] cap arm closes on the peer
25953        // amplification-shape axis), a bounds-collapsing accessor
25954        // that clamped `rl.rate` through [`POLICY_RATE_LIMIT_MAX`] or
25955        // clamped `rl.window` through [`is_canonical_rate_limit_window`]
25956        // (the [`AplicacaoSpec::validate`] gate owns the bounds; the
25957        // accessor must ship the raw slot verbatim), or a
25958        // by-reference detour (`Option<&RateLimit>`) that broke every
25959        // downstream consumer keying off `Option<RateLimit>` by-copy.
25960        for rl in [
25961            None,
25962            Some(RateLimit {
25963                rate: 1,
25964                window: Duration::from_secs(1),
25965            }),
25966            Some(RateLimit {
25967                rate: POLICY_RATE_LIMIT_MAX,
25968                window: Duration::from_secs(3600),
25969            }),
25970            Some(RateLimit {
25971                rate: 0,
25972                window: Duration::ZERO,
25973            }),
25974            Some(RateLimit {
25975                rate: u32::MAX,
25976                window: Duration::MAX,
25977            }),
25978        ] {
25979            let p = MeshPolicy {
25980                rate_limit: rl,
25981                ..MeshPolicy::default()
25982            };
25983            assert_eq!(
25984                p.rate_limit(),
25985                rl,
25986                "MeshPolicy::rate_limit must return :politicas :rate-limit \
25987                 verbatim (got {:?}, expected {rl:?})",
25988                p.rate_limit(),
25989            );
25990            assert_eq!(
25991                p.rate_limit(),
25992                p.rate_limit,
25993                "MeshPolicy::rate_limit must byte-equal the raw \
25994                 .rate_limit field access across every value in the \
25995                 accept-set",
25996            );
25997        }
25998    }
25999
26000    #[test]
26001    fn mesh_policy_is_empty_rate_limit_arm_routes_through_accessor() {
26002        // Composition pin: [`MeshPolicy::is_empty`]'s `rate_limit` arm
26003        // must key off [`MeshPolicy::rate_limit`], not the raw
26004        // `.rate_limit` field access. Structurally: toggling ONLY the
26005        // `rate_limit` slot on an otherwise-default MeshPolicy must
26006        // flip `is_empty()` from `true` (all-`None`) to `false` (one
26007        // axis carries a value); the flip must be observed for every
26008        // representative value in the accept-set the surrounding
26009        // [`AplicacaoSpec::validate_politicas`] gate accepts
26010        // (`Some(RateLimit { rate: 1, window: 1s })`,
26011        // `Some(RateLimit { rate: POLICY_RATE_LIMIT_MAX, window: 1h })`),
26012        // since the emptiness semantic reads "any axis carries a
26013        // value" — not "any axis carries a value the validate gate
26014        // accepts" — the same non-collapsing shape the peer M2
26015        // [`crate::LimitsSpec::is_empty`] /
26016        // [`crate::BehaviorSpec::is_empty`] predicates carry.
26017        //
26018        // Pins against a future silent detour that re-derived the
26019        // emptiness predicate off a peer axis (an accidental
26020        // `.timeout.is_none()`-only chain that dropped the
26021        // `rate_limit` arm entirely — the last unlifted inline field
26022        // access on `is_empty` before this lift), a `rate_limit ==
26023        // Some(_)` collapse that key-off a validate-gate-clamped
26024        // bounds check (which would silently classify a past-the-
26025        // guard `Some(RateLimit { rate: 0, window: 0s })` as empty
26026        // because it fails the value-shape gate), or an accessor-
26027        // side detour that no longer names the substrate-primitive
26028        // typed dispatch.
26029        //
26030        // Fourth "the emptiness predicate must route through the
26031        // substrate-primitive typed dispatch" composition pin on the
26032        // M3 mesh-slot family — closes the last unlifted composition
26033        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
26034        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
26035        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
26036        // 7073d0f is_empty-composition pins on the sibling primitive-
26037        // Copy axes, extended onto the peer per-`:politicas`
26038        // composite-Copy `Option<RateLimit>` axis).
26039        let empty = MeshPolicy::default();
26040        assert!(
26041            empty.is_empty(),
26042            "MeshPolicy::default() must be is_empty() — every axis \
26043             defaults to None",
26044        );
26045        for rl in [
26046            RateLimit {
26047                rate: 1,
26048                window: Duration::from_secs(1),
26049            },
26050            RateLimit {
26051                rate: POLICY_RATE_LIMIT_MAX,
26052                window: Duration::from_secs(3600),
26053            },
26054        ] {
26055            let p = MeshPolicy {
26056                rate_limit: Some(rl),
26057                ..MeshPolicy::default()
26058            };
26059            assert!(
26060                !p.is_empty(),
26061                "MeshPolicy::is_empty must return false when \
26062                 :rate-limit is {rl:?} — the emptiness predicate \
26063                 reads \"any axis carries a value\", not \"any axis \
26064                 carries a value the validate gate accepts\"",
26065            );
26066            assert_eq!(
26067                p.rate_limit().is_none(),
26068                p.is_empty(),
26069                "when :rate-limit is the only set axis, is_empty() \
26070                 must equal rate_limit().is_none() — the accessor \
26071                 and the emptiness predicate must route through the \
26072                 same substrate-primitive typed dispatch on the \
26073                 :rate-limit arm",
26074            );
26075        }
26076    }
26077
26078    #[test]
26079    fn validate_politicas_rate_limit_zero_rate_arm_routes_through_accessor() {
26080        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26081        // `:rate-limit` value-shape gate must key off
26082        // [`MeshPolicy::rate_limit`], not the raw `&p.rate_limit`
26083        // field bind. Structurally: a `MeshPolicy` whose only set
26084        // axis is a `Some(RateLimit { rate: 0, .. })` must surface
26085        // the `PolicyRateLimitZero` refusal exactly, and the same
26086        // MeshPolicy with the rate at the canonical lower boundary
26087        // `Some(RateLimit { rate: 1, window: 1s })` must pass validate.
26088        // The pair jointly pins the accessor + validate-gate
26089        // composition: any future silent detour that had the accessor
26090        // omit the `Some(RateLimit { rate: 0, .. })` arm (a
26091        // `.rate_limit().filter(|rl| rl.rate > 0)` collapse) would
26092        // silently absorb the `PolicyRateLimitZero` refusal at the
26093        // accessor boundary — the composition pin catches that at
26094        // caixa-core build time.
26095        //
26096        // Sibling of the peer [`validate_politicas`]
26097        // `:mtls-required` / `:retries` / `:timeout` composition pins
26098        // on the sibling primitive-Copy optional-scalar axes — same
26099        // "the validate / shape-gate predicate must route through the
26100        // substrate-primitive typed dispatch" discipline extended
26101        // onto the peer per-`:politicas` composite-Copy
26102        // `Option<RateLimit>` axis. Second composition-with-accessor
26103        // pin on the M3 mesh-slot `Option<RateLimit>` arm alongside
26104        // the [`MeshPolicy::is_empty`] rate-limit-arm pin above.
26105        let mut spec = three_member_spec();
26106        spec.politicas = MeshPolicy {
26107            rate_limit: Some(RateLimit {
26108                rate: 0,
26109                window: Duration::from_secs(1),
26110            }),
26111            ..MeshPolicy::default()
26112        };
26113        assert!(
26114            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
26115            "validate_politicas must reject rate == 0 with \
26116             PolicyRateLimitZero — the accessor and the validate gate \
26117             must route through the same substrate-primitive typed \
26118             dispatch on the :rate-limit zero-floor arm",
26119        );
26120        spec.politicas = MeshPolicy {
26121            rate_limit: Some(RateLimit {
26122                rate: 1,
26123                window: Duration::from_secs(1),
26124            }),
26125            ..MeshPolicy::default()
26126        };
26127        assert!(
26128            spec.validate().is_ok(),
26129            "validate_politicas must accept rate == 1 (the canonical \
26130             lower boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-\
26131             set) with a canonical 1s window",
26132        );
26133    }
26134
26135    #[test]
26136    fn mesh_policy_circuit_breaker_returns_circuit_breaker_option_byte_equal_across_permutations() {
26137        // The canonical per-`:politicas` `:circuit-breaker` Envoy-
26138        // `outlier_detection`-mesh consecutive-failure-ejection scalar
26139        // pin: [`MeshPolicy::circuit_breaker`] must return the
26140        // `:politicas :circuit-breaker` typed [`CircuitBreaker`]
26141        // verbatim as an `Option<CircuitBreaker>`, byte-equal to the
26142        // raw field access across every representative value in the
26143        // accept-set — `None` (cluster default applies — no
26144        // per-Aplicacao breaker declaration, the gateway-class per-
26145        // listener default arm the future caixa-mesh
26146        // `outlier_detection_overlay` emitter documents),
26147        // `Some(CircuitBreaker { max_failures: 1, window: Duration::from_millis(1) })`
26148        // (the lower boundary of the accept-set the surrounding
26149        // [`AplicacaoSpec::validate_politicas`] gate carves out on the
26150        // sibling `PolicyBreakerZeroFailures` / `PolicyBreakerZeroWindow`
26151        // refusals),
26152        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`
26153        // (the upper boundary the same gate carves out on the sibling
26154        // `PolicyBreakerMaxFailuresExceedsCap` /
26155        // `PolicyBreakerWindowExceedsCap` refusals),
26156        // `Some(CircuitBreaker { max_failures: 0, window: Duration::ZERO })`
26157        // (a past-the-guard sentinel that pins the accessor doesn't
26158        // perform a silent bounds-collapse into `None` on the
26159        // zero-failures/zero-window arm — validate rejects zero but
26160        // the accessor must ship the raw slot verbatim so a validate-
26161        // time gate regression surfaces at the emit boundary rather
26162        // than being silently absorbed), and
26163        // `Some(CircuitBreaker { max_failures: u32::MAX, window: Duration::MAX })`
26164        // (a past-the-guard sentinel that pins the accessor doesn't
26165        // perform a silent bounds-collapse at the return path).
26166        //
26167        // Second `Option<Copy-composite-T>`-return accessor pin on the
26168        // M3 mesh-slot family (peer of the sibling per-`:politicas`
26169        // [`MeshPolicy::rate_limit`] 21a6c3b `Option<RateLimit>`
26170        // composite-Copy accessor pin, and of the sibling per-
26171        // `:politicas` [`MeshPolicy::timeout`] 7073d0f /
26172        // [`MeshPolicy::retries`] bdfb399 /
26173        // [`MeshPolicy::mtls_required`] c0110f1 primitive-Copy
26174        // accessor pins). Pins against a future silent detour that
26175        // re-derived the breaker declaration from a peer axis (an
26176        // accidental `.rate_limit.map(|rl| CircuitBreaker { max_failures: rl.rate, window: rl.window })`
26177        // collapse that read the rate-limit's bucket capacity + refill
26178        // period as a breaker declaration), a `None → Some(default())`
26179        // cluster-default projection (which would silently re-
26180        // introduce the `PolicyBreakerZeroFailures` /
26181        // `PolicyBreakerZeroWindow` refusal cases at the emit
26182        // boundary), a bounds-collapsing accessor that clamped
26183        // `cb.max_failures` through
26184        // [`POLICY_BREAKER_MAX_FAILURES_MAX`] or clamped `cb.window`
26185        // through [`POLICY_BREAKER_WINDOW_MAX`] (the
26186        // [`AplicacaoSpec::validate`] gate owns the bounds; the
26187        // accessor must ship the raw slot verbatim), or a
26188        // by-reference detour (`Option<&CircuitBreaker>`) that broke
26189        // every downstream consumer keying off `Option<CircuitBreaker>`
26190        // by-copy.
26191        for cb in [
26192            None,
26193            Some(CircuitBreaker {
26194                max_failures: 1,
26195                window: Duration::from_millis(1),
26196            }),
26197            Some(CircuitBreaker {
26198                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
26199                window: POLICY_BREAKER_WINDOW_MAX,
26200            }),
26201            Some(CircuitBreaker {
26202                max_failures: 0,
26203                window: Duration::ZERO,
26204            }),
26205            Some(CircuitBreaker {
26206                max_failures: u32::MAX,
26207                window: Duration::MAX,
26208            }),
26209        ] {
26210            let p = MeshPolicy {
26211                circuit_breaker: cb,
26212                ..MeshPolicy::default()
26213            };
26214            assert_eq!(
26215                p.circuit_breaker(),
26216                cb,
26217                "MeshPolicy::circuit_breaker must return :politicas \
26218                 :circuit-breaker verbatim (got {:?}, expected {cb:?})",
26219                p.circuit_breaker(),
26220            );
26221            assert_eq!(
26222                p.circuit_breaker(),
26223                p.circuit_breaker,
26224                "MeshPolicy::circuit_breaker must byte-equal the raw \
26225                 .circuit_breaker field access across every value in \
26226                 the accept-set",
26227            );
26228        }
26229    }
26230
26231    #[test]
26232    fn mesh_policy_is_empty_circuit_breaker_arm_routes_through_accessor() {
26233        // Composition pin: [`MeshPolicy::is_empty`]'s `circuit_breaker`
26234        // arm must key off [`MeshPolicy::circuit_breaker`], not the raw
26235        // `.circuit_breaker` field access. Structurally: toggling ONLY
26236        // the `circuit_breaker` slot on an otherwise-default MeshPolicy
26237        // must flip `is_empty()` from `true` (all-`None`) to `false`
26238        // (one axis carries a value); the flip must be observed for
26239        // every representative value in the accept-set the surrounding
26240        // [`AplicacaoSpec::validate_politicas`] gate accepts
26241        // (`Some(CircuitBreaker { max_failures: 1, window: 1ms })`,
26242        // `Some(CircuitBreaker { max_failures: POLICY_BREAKER_MAX_FAILURES_MAX, window: POLICY_BREAKER_WINDOW_MAX })`),
26243        // since the emptiness semantic reads "any axis carries a
26244        // value" — not "any axis carries a value the validate gate
26245        // accepts" — the same non-collapsing shape the peer M2
26246        // [`crate::LimitsSpec::is_empty`] /
26247        // [`crate::BehaviorSpec::is_empty`] predicates carry.
26248        //
26249        // Pins against a future silent detour that re-derived the
26250        // emptiness predicate off a peer axis (an accidental
26251        // `.rate_limit.is_none()`-only chain that dropped the
26252        // `circuit_breaker` arm entirely — the last unlifted inline
26253        // field access on `is_empty` before this lift), a
26254        // `circuit_breaker == Some(_)` collapse that key-off a
26255        // validate-gate-clamped bounds check (which would silently
26256        // classify a past-the-guard `Some(CircuitBreaker { max_failures:
26257        // 0, window: 0s })` as empty because it fails the value-shape
26258        // gate), or an accessor-side detour that no longer names the
26259        // substrate-primitive typed dispatch.
26260        //
26261        // Fifth "the emptiness predicate must route through the
26262        // substrate-primitive typed dispatch" composition pin on the
26263        // M3 mesh-slot family — closes the last unlifted composition
26264        // arm on [`MeshPolicy::is_empty`] (peer of the sibling
26265        // per-`:politicas` [`MeshPolicy::mtls_required`] c0110f1 /
26266        // [`MeshPolicy::retries`] bdfb399 / [`MeshPolicy::timeout`]
26267        // 7073d0f / [`MeshPolicy::rate_limit`] 21a6c3b is_empty-
26268        // composition pins on the sibling primitive-Copy + composite-
26269        // Copy axes, extended onto the peer per-`:politicas`
26270        // composite-Copy `Option<CircuitBreaker>` axis).
26271        let empty = MeshPolicy::default();
26272        assert!(
26273            empty.is_empty(),
26274            "MeshPolicy::default() must be is_empty() — every axis \
26275             defaults to None",
26276        );
26277        for cb in [
26278            CircuitBreaker {
26279                max_failures: 1,
26280                window: Duration::from_millis(1),
26281            },
26282            CircuitBreaker {
26283                max_failures: POLICY_BREAKER_MAX_FAILURES_MAX,
26284                window: POLICY_BREAKER_WINDOW_MAX,
26285            },
26286        ] {
26287            let p = MeshPolicy {
26288                circuit_breaker: Some(cb),
26289                ..MeshPolicy::default()
26290            };
26291            assert!(
26292                !p.is_empty(),
26293                "MeshPolicy::is_empty must return false when \
26294                 :circuit-breaker is {cb:?} — the emptiness predicate \
26295                 reads \"any axis carries a value\", not \"any axis \
26296                 carries a value the validate gate accepts\"",
26297            );
26298            assert_eq!(
26299                p.circuit_breaker().is_none(),
26300                p.is_empty(),
26301                "when :circuit-breaker is the only set axis, \
26302                 is_empty() must equal circuit_breaker().is_none() — \
26303                 the accessor and the emptiness predicate must route \
26304                 through the same substrate-primitive typed dispatch \
26305                 on the :circuit-breaker arm",
26306            );
26307        }
26308    }
26309
26310    #[test]
26311    fn validate_politicas_circuit_breaker_arm_routes_through_accessor() {
26312        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26313        // `:circuit-breaker` value-shape gate must key off
26314        // [`MeshPolicy::circuit_breaker`], not the raw
26315        // `&p.circuit_breaker` field bind. Structurally: a `MeshPolicy`
26316        // whose only set axis is a `Some(CircuitBreaker { max_failures:
26317        // 0, .. })` must surface the `PolicyBreakerZeroFailures`
26318        // refusal exactly, and the same MeshPolicy with the breaker at
26319        // the canonical lower boundary
26320        // `Some(CircuitBreaker { max_failures: 1, window: 1ms })` must
26321        // pass validate. The pair jointly pins the accessor +
26322        // validate-gate composition: any future silent detour that had
26323        // the accessor omit the `Some(CircuitBreaker { max_failures:
26324        // 0, .. })` arm (a
26325        // `.circuit_breaker().filter(|cb| cb.max_failures > 0)`
26326        // collapse) would silently absorb the
26327        // `PolicyBreakerZeroFailures` refusal at the accessor
26328        // boundary — the composition pin catches that at caixa-core
26329        // build time.
26330        //
26331        // Sibling of the peer [`validate_politicas`]
26332        // `:mtls-required` / `:retries` / `:timeout` / `:rate-limit`
26333        // composition pins on the sibling primitive-Copy + composite-
26334        // Copy optional-scalar axes — same "the validate / shape-gate
26335        // predicate must route through the substrate-primitive typed
26336        // dispatch" discipline extended onto the peer per-`:politicas`
26337        // composite-Copy `Option<CircuitBreaker>` axis. Second
26338        // composition-with-accessor pin on the M3 mesh-slot
26339        // `Option<CircuitBreaker>` arm alongside the
26340        // [`MeshPolicy::is_empty`] circuit-breaker-arm pin above.
26341        let mut spec = three_member_spec();
26342        spec.politicas = MeshPolicy {
26343            circuit_breaker: Some(CircuitBreaker {
26344                max_failures: 0,
26345                window: Duration::from_millis(1),
26346            }),
26347            ..MeshPolicy::default()
26348        };
26349        assert!(
26350            matches!(
26351                spec.validate(),
26352                Err(AplicacaoError::PolicyBreakerZeroFailures)
26353            ),
26354            "validate_politicas must reject max_failures == 0 with \
26355             PolicyBreakerZeroFailures — the accessor and the validate \
26356             gate must route through the same substrate-primitive \
26357             typed dispatch on the :circuit-breaker zero-floor arm",
26358        );
26359        spec.politicas = MeshPolicy {
26360            circuit_breaker: Some(CircuitBreaker {
26361                max_failures: 1,
26362                window: Duration::from_millis(1),
26363            }),
26364            ..MeshPolicy::default()
26365        };
26366        assert!(
26367            spec.validate().is_ok(),
26368            "validate_politicas must accept a CircuitBreaker at the \
26369             canonical lower boundary (max_failures = 1, window = \
26370             1ms) — the accessor and the validate gate must route \
26371             through the same substrate-primitive typed dispatch on \
26372             the :circuit-breaker arm",
26373        );
26374    }
26375
26376    #[test]
26377    fn circuit_breaker_max_failures_returns_max_failures_u32_byte_equal_across_permutations() {
26378        // The canonical per-`:politicas :circuit-breaker` `:max-failures`
26379        // Envoy-outlier-detection trip-threshold scalar pin:
26380        // [`CircuitBreaker::max_failures`] must return the
26381        // `:politicas :circuit-breaker :max-failures` typed `u32`
26382        // verbatim, byte-equal to the raw field access across every
26383        // representative value in the accept-set — `1` (the lower
26384        // boundary of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-
26385        // set the surrounding [`AplicacaoSpec::validate_politicas`] gate
26386        // carves out on the sibling `PolicyBreakerZeroFailures` refusal),
26387        // `POLICY_BREAKER_MAX_FAILURES_MAX` (the upper boundary the same
26388        // gate carves out on the sibling `PolicyBreakerMaxFailuresExceedsCap`
26389        // refusal), `0` (a past-the-guard sentinel that pins the accessor
26390        // doesn't perform a silent bounds-collapse into `1` on the zero
26391        // arm — validate rejects zero but the accessor must ship the
26392        // raw slot verbatim so a validate-time gate regression surfaces
26393        // at the emit boundary rather than being silently absorbed),
26394        // `u32::MAX` (a past-the-guard sentinel that pins the accessor
26395        // doesn't perform a silent bounds-collapse through
26396        // `POLICY_BREAKER_MAX_FAILURES_MAX` at the return path).
26397        //
26398        // First sub-struct required-scalar accessor pin on the M3
26399        // mesh-slot family — sibling in shape to the peer per-`:membros`
26400        // [`Membro::nome`] (4a32abf) / [`Membro::versao_requirement`]
26401        // (a40b0e3) required-`String`-carry accessor pins and the peer
26402        // per-`:contratos` [`WitContract::source`] /
26403        // [`WitContract::destination`] (7f0fd43) required-`String`-carry
26404        // accessor pins, extended onto the peer per-`CircuitBreaker`
26405        // required-`u32` scalar-value axis. Pins against a future silent
26406        // detour that re-derived the trip threshold from a peer axis (an
26407        // accidental `self.window.as_secs() as u32` collapse that read
26408        // the breaker's rolling-window duration as a failure count), a
26409        // `0 → 1` cluster-default projection (which would silently absorb
26410        // the `PolicyBreakerZeroFailures` refusal case at the accessor
26411        // boundary), or a bounds-collapsing accessor that clamped the
26412        // return through `POLICY_BREAKER_MAX_FAILURES_MAX` (the
26413        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
26414        // must ship the raw slot verbatim).
26415        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
26416            let cb = CircuitBreaker {
26417                max_failures,
26418                window: Duration::from_secs(60),
26419            };
26420            assert_eq!(
26421                cb.max_failures(),
26422                max_failures,
26423                "CircuitBreaker::max_failures must return :politicas \
26424                 :circuit-breaker :max-failures verbatim (got {}, \
26425                 expected {max_failures})",
26426                cb.max_failures(),
26427            );
26428            assert_eq!(
26429                cb.max_failures(),
26430                cb.max_failures,
26431                "CircuitBreaker::max_failures must byte-equal the raw \
26432                 .max_failures field access across every value in the \
26433                 u32 accept-set",
26434            );
26435        }
26436    }
26437
26438    #[test]
26439    fn validate_politicas_max_failures_zero_floor_arm_routes_through_accessor() {
26440        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26441        // `:circuit-breaker :max-failures` zero-floor arm must key off
26442        // [`CircuitBreaker::max_failures`], not the raw `.max_failures`
26443        // field access. Structurally: a `CircuitBreaker { max_failures:
26444        // 0, .. }` embedded in a `:politicas :circuit-breaker` slot must
26445        // surface the `PolicyBreakerZeroFailures` refusal exactly, and a
26446        // `CircuitBreaker { max_failures: 1, .. }` (the lower boundary
26447        // of the `1..=POLICY_BREAKER_MAX_FAILURES_MAX` accept-set) must
26448        // pass validate. The pair jointly pins the accessor +
26449        // validate-gate composition: any future silent detour that had
26450        // the accessor return a fresh `1` on the zero arm (a
26451        // `.max_failures().max(1)` collapse) would silently absorb the
26452        // `PolicyBreakerZeroFailures` refusal at the accessor boundary
26453        // and the validate gate would accept a struct-literal
26454        // `CircuitBreaker { max_failures: 0, .. }` — the composition pin
26455        // catches that at caixa-core build time.
26456        //
26457        // Peer of the sibling per-`:politicas`
26458        // [`MeshPolicy::mtls_required`] (c0110f1) /
26459        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
26460        // (7073d0f) accessor-composition pins on the sibling optional-
26461        // scalar axes — same "the validate / shape-gate predicate must
26462        // route through the substrate-primitive typed dispatch"
26463        // discipline extended onto the peer per-`CircuitBreaker`
26464        // required-scalar composition axis.
26465        let mut spec = three_member_spec();
26466        spec.politicas = MeshPolicy {
26467            circuit_breaker: Some(CircuitBreaker {
26468                max_failures: 0,
26469                window: Duration::from_secs(60),
26470            }),
26471            ..MeshPolicy::default()
26472        };
26473        assert!(
26474            matches!(
26475                spec.validate(),
26476                Err(AplicacaoError::PolicyBreakerZeroFailures)
26477            ),
26478            "validate_politicas must reject max_failures == 0 with \
26479             PolicyBreakerZeroFailures — the accessor and the validate \
26480             gate must route through the same substrate-primitive typed \
26481             dispatch on the :max-failures zero-floor arm",
26482        );
26483        spec.politicas = MeshPolicy {
26484            circuit_breaker: Some(CircuitBreaker {
26485                max_failures: 1,
26486                window: Duration::from_secs(60),
26487            }),
26488            ..MeshPolicy::default()
26489        };
26490        assert!(
26491            spec.validate().is_ok(),
26492            "validate_politicas must accept max_failures == 1 (the \
26493             lower boundary of the 1..=POLICY_BREAKER_MAX_FAILURES_MAX \
26494             accept-set)",
26495        );
26496    }
26497
26498    #[test]
26499    fn circuit_breaker_max_failures_projects_u32_by_copy() {
26500        // The by-copy pin: [`CircuitBreaker::max_failures`] returns
26501        // `u32` by copy — `u32` is `Copy` and the accessor must return
26502        // by value, not by reference. Peer of the sibling
26503        // per-`:politicas` [`MeshPolicy::mtls_required`] (c0110f1) /
26504        // [`MeshPolicy::retries`] (bdfb399) / [`MeshPolicy::timeout`]
26505        // (7073d0f) by-copy pins on the sibling `Option<Copy-T>`
26506        // optional-scalar axes, extended onto the peer
26507        // per-`CircuitBreaker` required-`u32` copy-invariant shape —
26508        // the accessor's returned `u32` must outlive `&self` (multiple
26509        // calls must return equal values from a dropped-`&self` copy,
26510        // since the returned scalar carries no borrow), and calling
26511        // the accessor twice on the same CircuitBreaker must yield the
26512        // same `u32` verbatim (idempotent, no side effects on `&self`).
26513        //
26514        // Pins against a future silent detour that returned `&u32`
26515        // (which would type-check but silently break every downstream
26516        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
26517        // first parameter is `u32`, and `&u32` would fold to a detached
26518        // copy at the call site with a `*` deref the sibling accessors
26519        // don't need), an accidental `.max_failures.wrapping_add(0)`
26520        // detour that returned a fresh copy through an arithmetic
26521        // no-op (breaking a future `const fn` regression), or a
26522        // one-arm-only accessor that returned a saturating value on
26523        // some sentinel input (breaking the pass-through invariant the
26524        // sibling required-scalar accessors carry).
26525        for max_failures in [1u32, POLICY_BREAKER_MAX_FAILURES_MAX, 0, u32::MAX] {
26526            let cb = CircuitBreaker {
26527                max_failures,
26528                window: Duration::from_secs(60),
26529            };
26530            let first = cb.max_failures();
26531            let second = cb.max_failures();
26532            assert_eq!(
26533                first, second,
26534                "CircuitBreaker::max_failures must be idempotent — two \
26535                 successive calls on the same &self must return the \
26536                 same u32",
26537            );
26538            assert_eq!(
26539                first, max_failures,
26540                "CircuitBreaker::max_failures must return :politicas \
26541                 :circuit-breaker :max-failures verbatim by copy — \
26542                 got {first}, expected {max_failures}",
26543            );
26544        }
26545    }
26546
26547    #[test]
26548    fn circuit_breaker_window_returns_window_duration_byte_equal_across_permutations() {
26549        // The canonical per-`:politicas :circuit-breaker` `:window`
26550        // Envoy-outlier-detection rolling-observation-interval scalar
26551        // pin: [`CircuitBreaker::window`] must return the
26552        // `:politicas :circuit-breaker :window` typed `Duration`
26553        // verbatim, byte-equal to the raw field access across every
26554        // representative value in the accept-set — `Duration::from_millis(1)`
26555        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
26556        // accept-set the surrounding [`AplicacaoSpec::validate_politicas`]
26557        // gate carves out on the sibling `PolicyBreakerZeroWindow`
26558        // refusal), `POLICY_BREAKER_WINDOW_MAX` (the upper boundary the
26559        // same gate carves out on the sibling
26560        // `PolicyBreakerWindowExceedsCap` refusal),
26561        // `Duration::ZERO` (a past-the-guard sentinel that pins the
26562        // accessor doesn't perform a silent bounds-collapse into
26563        // `Duration::from_millis(1)` on the zero arm — validate rejects
26564        // zero but the accessor must ship the raw slot verbatim so a
26565        // validate-time gate regression surfaces at the emit boundary
26566        // rather than being silently absorbed),
26567        // `Duration::from_secs(86_400)` (a past-the-guard sentinel — 24h,
26568        // far above the 1h cap — that pins the accessor doesn't perform
26569        // a silent bounds-collapse through `POLICY_BREAKER_WINDOW_MAX`
26570        // at the return path).
26571        //
26572        // Second sub-struct required-scalar accessor pin on the M3
26573        // mesh-slot family — sibling in shape to the just-landed
26574        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
26575        // (3a74062) required-`u32` accessor pin on the peer
26576        // per-`CircuitBreaker` required-axis, extended onto the
26577        // per-sub-struct required-`Duration` axis. Pins against a
26578        // future silent detour that re-derived the observation window
26579        // from a peer axis (an accidental
26580        // `Duration::from_secs(self.max_failures as u64)` collapse that
26581        // read the breaker's trip count as an observation-interval
26582        // duration), a `Duration::ZERO → Duration::from_millis(1)`
26583        // cluster-default projection (which would silently absorb the
26584        // `PolicyBreakerZeroWindow` refusal case at the accessor
26585        // boundary), or a bounds-collapsing accessor that clamped the
26586        // return through `POLICY_BREAKER_WINDOW_MAX` (the
26587        // `AplicacaoSpec::validate` gate owns the bounds; the accessor
26588        // must ship the raw slot verbatim).
26589        for window in [
26590            Duration::from_millis(1),
26591            POLICY_BREAKER_WINDOW_MAX,
26592            Duration::ZERO,
26593            Duration::from_secs(86_400),
26594        ] {
26595            let cb = CircuitBreaker {
26596                max_failures: 5,
26597                window,
26598            };
26599            assert_eq!(
26600                cb.window(),
26601                window,
26602                "CircuitBreaker::window must return :politicas \
26603                 :circuit-breaker :window verbatim (got {:?}, \
26604                 expected {window:?})",
26605                cb.window(),
26606            );
26607            assert_eq!(
26608                cb.window(),
26609                cb.window,
26610                "CircuitBreaker::window must byte-equal the raw \
26611                 .window field access across every value in the \
26612                 Duration accept-set",
26613            );
26614        }
26615    }
26616
26617    #[test]
26618    fn validate_politicas_window_zero_floor_arm_routes_through_accessor() {
26619        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
26620        // `:circuit-breaker :window` zero-floor arm must key off
26621        // [`CircuitBreaker::window`], not the raw `.window` field
26622        // access. Structurally: a `CircuitBreaker { window:
26623        // Duration::ZERO, .. }` embedded in a
26624        // `:politicas :circuit-breaker` slot must surface the
26625        // `PolicyBreakerZeroWindow` refusal exactly, and a
26626        // `CircuitBreaker { window: Duration::from_millis(1), .. }`
26627        // (the lower boundary of the `1ms..=POLICY_BREAKER_WINDOW_MAX`
26628        // accept-set) must pass validate. The pair jointly pins the
26629        // accessor + validate-gate composition: any future silent
26630        // detour that had the accessor return a fresh
26631        // `Duration::from_millis(1)` on the zero arm (a
26632        // `.window().max(Duration::from_millis(1))` collapse) would
26633        // silently absorb the `PolicyBreakerZeroWindow` refusal at the
26634        // accessor boundary and the validate gate would accept a
26635        // struct-literal `CircuitBreaker { window: Duration::ZERO, .. }`
26636        // — the composition pin catches that at caixa-core build time.
26637        //
26638        // Peer of the sibling per-`CircuitBreaker`
26639        // [`CircuitBreaker::max_failures`] (3a74062) accessor-composition
26640        // pin on the peer required-scalar `:max-failures` axis — same
26641        // "the validate / shape-gate predicate must route through the
26642        // substrate-primitive typed dispatch" discipline extended onto
26643        // the peer per-`CircuitBreaker` required-`Duration` composition
26644        // axis.
26645        let mut spec = three_member_spec();
26646        spec.politicas = MeshPolicy {
26647            circuit_breaker: Some(CircuitBreaker {
26648                max_failures: 5,
26649                window: Duration::ZERO,
26650            }),
26651            ..MeshPolicy::default()
26652        };
26653        assert!(
26654            matches!(
26655                spec.validate(),
26656                Err(AplicacaoError::PolicyBreakerZeroWindow)
26657            ),
26658            "validate_politicas must reject window == Duration::ZERO \
26659             with PolicyBreakerZeroWindow — the accessor and the \
26660             validate gate must route through the same substrate-\
26661             primitive typed dispatch on the :window zero-floor arm",
26662        );
26663        spec.politicas = MeshPolicy {
26664            circuit_breaker: Some(CircuitBreaker {
26665                max_failures: 5,
26666                window: Duration::from_millis(1),
26667            }),
26668            ..MeshPolicy::default()
26669        };
26670        assert!(
26671            spec.validate().is_ok(),
26672            "validate_politicas must accept window == \
26673             Duration::from_millis(1) (the lower boundary of the \
26674             1ms..=POLICY_BREAKER_WINDOW_MAX accept-set)",
26675        );
26676    }
26677
26678    #[test]
26679    fn circuit_breaker_window_projects_duration_by_copy() {
26680        // The by-copy pin: [`CircuitBreaker::window`] returns
26681        // `Duration` by copy — `Duration` is `Copy` and the accessor
26682        // must return by value, not by reference. Peer of the sibling
26683        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`]
26684        // (3a74062) by-copy pin on the peer required-scalar
26685        // `:max-failures` axis, extended onto the peer
26686        // per-`CircuitBreaker` required-`Duration` copy-invariant shape
26687        // — the accessor's returned `Duration` must outlive `&self`
26688        // (multiple calls must return equal values from a
26689        // dropped-`&self` copy, since the returned scalar carries no
26690        // borrow), and calling the accessor twice on the same
26691        // CircuitBreaker must yield the same `Duration` verbatim
26692        // (idempotent, no side effects on `&self`).
26693        //
26694        // Pins against a future silent detour that returned
26695        // `&Duration` (which would type-check but silently break every
26696        // downstream `Duration`-by-value consumer —
26697        // [`crate::render::require_positive_canonical_bounded_duration`]'s
26698        // first parameter is `Duration`, and `&Duration` would fold to
26699        // a detached copy at the call site with a `*` deref the sibling
26700        // accessors don't need), an accidental `.window + Duration::ZERO`
26701        // detour that returned a fresh copy through an arithmetic
26702        // no-op (breaking a future `const fn` regression), or a
26703        // one-arm-only accessor that returned a saturating value on
26704        // some sentinel input (breaking the pass-through invariant the
26705        // sibling required-scalar accessors carry).
26706        for window in [
26707            Duration::from_millis(1),
26708            POLICY_BREAKER_WINDOW_MAX,
26709            Duration::ZERO,
26710            Duration::from_secs(86_400),
26711        ] {
26712            let cb = CircuitBreaker {
26713                max_failures: 5,
26714                window,
26715            };
26716            let first = cb.window();
26717            let second = cb.window();
26718            assert_eq!(
26719                first, second,
26720                "CircuitBreaker::window must be idempotent — two \
26721                 successive calls on the same &self must return the \
26722                 same Duration",
26723            );
26724            assert_eq!(
26725                first, window,
26726                "CircuitBreaker::window must return :politicas \
26727                 :circuit-breaker :window verbatim by copy — \
26728                 got {first:?}, expected {window:?}",
26729            );
26730        }
26731    }
26732
26733    #[test]
26734    fn port_for_destination_at_contract_destination_returns_entrada_port_when_para_matches() {
26735        // Apex-identity pair-invariant pin composing both substrate-
26736        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
26737        // and [`WitContract::destination`] — at the emit-side call shape
26738        // every per-`(:de, :para)` CNP L4 port reader now takes. The
26739        // invariant, evaluated per-edge:
26740        //
26741        //   spec.port_for_destination(c.destination()) == expected_port
26742        //
26743        // where `expected_port` is `entrada.port` when
26744        // `c.destination() == entrada.destination()` and
26745        // `DEFAULT_SERVICO_PORT` otherwise. Peer of the sibling
26746        // `port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations`
26747        // pin on the per-`:entrada` axis — that pin encodes the apex
26748        // ingress L4 identity via `entrada.destination()`; this pin
26749        // encodes the per-edge L4 identity via `c.destination()`, and
26750        // both compose on the same substrate-primitive resolver so a
26751        // future refactor that silently split either accessor's apex
26752        // behavior surfaces at caixa-core build time.
26753        let mut spec = three_member_spec();
26754        if let Some(e) = spec.entrada.as_mut() {
26755            e.para = "cart".into();
26756            e.port = 8443;
26757        }
26758        let apex_contract = WitContract {
26759            de: "checkout".into(),
26760            para: "cart".into(),
26761            wit: "wasi:http/proxy".into(),
26762            endpoint: Some("/hello".into()),
26763            subject: None,
26764            slot: None,
26765        };
26766        assert_eq!(
26767            spec.port_for_destination(apex_contract.destination()),
26768            8443,
26769            "`spec.port_for_destination(c.destination())` must equal \
26770             `entrada.port` when the contract callee names the ingress \
26771             apex — the CNP per-edge L4 port and the HTTPRoute apex \
26772             backendRef port share this substrate-primitive resolver.",
26773        );
26774        let non_apex_contract = WitContract {
26775            de: "cart".into(),
26776            para: "payment".into(),
26777            wit: "wasi:http/proxy".into(),
26778            endpoint: Some("/charge".into()),
26779            subject: None,
26780            slot: None,
26781        };
26782        assert_eq!(
26783            spec.port_for_destination(non_apex_contract.destination()),
26784            DEFAULT_SERVICO_PORT,
26785            "`spec.port_for_destination(c.destination())` must fall back \
26786             to the substrate-canonical port floor when the contract \
26787             callee is not the ingress apex — the resolver's non-apex \
26788             arm reaches for [`DEFAULT_SERVICO_PORT`] by construction.",
26789        );
26790    }
26791
26792    #[test]
26793    fn membro_key_consts_are_lower_camel_case_shape() {
26794        // Shape-pin: every `MEMBRO_KEY_*` const must be a
26795        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
26796        // `kebab-case` hyphens, no leading colon, no `PascalCase`
26797        // leading capital, no whitespace / dots) — the canonical shape
26798        // the `#[serde(rename_all = "camelCase")]` derive produces on
26799        // [`Membro`]. A future flip to a non-camelCase attribute at
26800        // the derive surfaces both here (this test fails on the
26801        // stale-constant shape) and at
26802        // `membro_serde_keys_match_lifted_membro_key_consts` (that test
26803        // fails on the mismatch between const and derive). Peer with
26804        // `supervisor_key_consts_are_lower_camel_case_shape` (40cc4e5)
26805        // on the sibling `SupervisorSpec` top-level axis.
26806        for key in [crate::MEMBRO_KEY_CAIXA, crate::MEMBRO_KEY_VERSAO] {
26807            assert!(
26808                !key.is_empty(),
26809                "MEMBRO_KEY_* must be non-empty (got {key:?})"
26810            );
26811            let first = key.chars().next().unwrap();
26812            assert!(
26813                first.is_ascii_lowercase(),
26814                "MEMBRO_KEY_* must lead with an ASCII-lowercase byte \
26815                 (got {key:?}, leads with {first:?})",
26816            );
26817            assert!(
26818                key.chars().all(|c| c.is_ascii_alphanumeric()),
26819                "MEMBRO_KEY_* must be ASCII-alphanumeric only \
26820                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
26821            );
26822        }
26823    }
26824
26825    // ── drift-detection: serde-derive-to-CONTRATO_KEY_* identity ─────────
26826
26827    #[test]
26828    fn wit_contract_serde_keys_match_lifted_contrato_key_consts() {
26829        // Load-bearing invariant: the three `CONTRATO_KEY_*` consts
26830        // ([`crate::CONTRATO_KEY_DE`] / [`crate::CONTRATO_KEY_PARA`] /
26831        // [`crate::CONTRATO_KEY_WIT`]) name the exact camelCase JSON
26832        // keys the `#[serde(rename_all = "camelCase")]` attribute on
26833        // [`WitContract`] emits for the required-triad. The three
26834        // sibling payload-arm keys already pin under
26835        // [`WitTarget::HTTP_FIELD_NAME`] / `PUBSUB_FIELD_NAME` /
26836        // `STORE_FIELD_NAME` — pin all six alongside so a future
26837        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
26838        // verbatim-field-name flip at the derive attribute (any of which
26839        // would silently break every downstream JSON consumer that
26840        // reaches for one of the six via `Value::get(...)`) surfaces
26841        // here as a build-time test failure at `aplicacao.rs`, not as an
26842        // apply-time `.get(<stale-canonical-const>)` returning `None`
26843        // far from the derive-attr drift's commit. Peer with the sibling
26844        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
26845        // pin on the M3 `:membros` per-entry axis — same discipline the
26846        // `Membro` per-entry lift established, extended here to the
26847        // sibling M3 `WitContract` per-`:contratos` entry axis, the last
26848        // M3 mesh-slot atom top-level `#[serde(rename_all = "camelCase")]`
26849        // axis on the Aplicacao surface without a lifted serde-key peer.
26850        let c = WitContract {
26851            de: "cart".into(),
26852            para: "catalog".into(),
26853            wit: "wasi:http/proxy".into(),
26854            endpoint: Some("/lookup".into()),
26855            subject: None,
26856            slot: None,
26857        };
26858        let json = serde_json::to_string(&c).unwrap();
26859        for key in [
26860            crate::CONTRATO_KEY_DE,
26861            crate::CONTRATO_KEY_PARA,
26862            crate::CONTRATO_KEY_WIT,
26863            WitTarget::HTTP_FIELD_NAME,
26864        ] {
26865            let quoted = format!("\"{key}\"");
26866            assert!(
26867                json.contains(&quoted),
26868                "serialized WitContract must carry the lifted \
26869                 CONTRATO_KEY_* / WitTarget::*_FIELD_NAME byte-sequence \
26870                 {quoted} verbatim in the JSON emission (got: {json})",
26871            );
26872        }
26873
26874        // Pin the two remaining payload-arm keys by round-tripping a
26875        // `WitContract` under each payload-shape (pub-sub, store) — the
26876        // required-triad appears on every emission but the payload arms
26877        // only surface when their `Option<String>` field is `Some`.
26878        let pubsub = WitContract {
26879            de: "cart".into(),
26880            para: "events".into(),
26881            wit: "nats:pub-sub".into(),
26882            endpoint: None,
26883            subject: Some("orders.placed".into()),
26884            slot: None,
26885        };
26886        let pubsub_json = serde_json::to_string(&pubsub).unwrap();
26887        let pubsub_quoted = format!("\"{}\"", WitTarget::PUBSUB_FIELD_NAME);
26888        assert!(
26889            pubsub_json.contains(&pubsub_quoted),
26890            "serialized pub-sub WitContract must carry the lifted \
26891             WitTarget::PUBSUB_FIELD_NAME byte-sequence {pubsub_quoted} \
26892             verbatim in the JSON emission (got: {pubsub_json})",
26893        );
26894        let store = WitContract {
26895            de: "cart".into(),
26896            para: "sessions".into(),
26897            wit: "wasi:keyvalue/store".into(),
26898            endpoint: None,
26899            subject: None,
26900            slot: Some("cart/$id".into()),
26901        };
26902        let store_json = serde_json::to_string(&store).unwrap();
26903        let store_quoted = format!("\"{}\"", WitTarget::STORE_FIELD_NAME);
26904        assert!(
26905            store_json.contains(&store_quoted),
26906            "serialized store WitContract must carry the lifted \
26907             WitTarget::STORE_FIELD_NAME byte-sequence {store_quoted} \
26908             verbatim in the JSON emission (got: {store_json})",
26909        );
26910    }
26911
26912    #[test]
26913    fn contrato_key_consts_are_pairwise_distinct() {
26914        // Cross-axis drift-detection pin: a future collapse of the six
26915        // canonical [`WitContract`] per-entry byte-strings onto the same
26916        // value (e.g. an accidental copy-paste flip of
26917        // [`crate::CONTRATO_KEY_WIT`] to also read `"de"`, or a
26918        // rebrand of [`WitTarget::STORE_FIELD_NAME`] to match the
26919        // sibling [`WitTarget::HTTP_FIELD_NAME`]) would silently reroute
26920        // every downstream probe on one axis onto the sibling axis's
26921        // overlay entry and pass every propagation-probe test that
26922        // expected only the stale axis's value. Peer of the sibling
26923        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0) —
26924        // widened here to the six-way axis the `WitContract`
26925        // required-triad + `WitTarget` payload-triad jointly cover.
26926        let all = [
26927            crate::CONTRATO_KEY_DE,
26928            crate::CONTRATO_KEY_PARA,
26929            crate::CONTRATO_KEY_WIT,
26930            WitTarget::HTTP_FIELD_NAME,
26931            WitTarget::PUBSUB_FIELD_NAME,
26932            WitTarget::STORE_FIELD_NAME,
26933        ];
26934        for (i, a) in all.iter().enumerate() {
26935            for b in all.iter().skip(i + 1) {
26936                assert_ne!(
26937                    a, b,
26938                    "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME consts \
26939                     must be pairwise-distinct canonical byte-sequences \
26940                     — got `{a}` == `{b}`",
26941                );
26942            }
26943        }
26944    }
26945
26946    #[test]
26947    fn contrato_key_consts_are_lower_camel_case_shape() {
26948        // Shape-pin: every `CONTRATO_KEY_*` (and every peer
26949        // `WitTarget::*_FIELD_NAME`) const must be a lowerCamelCase
26950        // byte-sequence (no `snake_case` underscores, no `kebab-case`
26951        // hyphens, no leading colon, no `PascalCase` leading capital, no
26952        // whitespace / dots) — the canonical shape the
26953        // `#[serde(rename_all = "camelCase")]` derive produces on
26954        // [`WitContract`]. A future flip to a non-camelCase attribute at
26955        // the derive surfaces both here (this test fails on the
26956        // stale-constant shape) and at
26957        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
26958        // (that test fails on the mismatch between const and derive).
26959        // Peer with `membro_key_consts_are_lower_camel_case_shape`
26960        // (ce80ca0) on the sibling `Membro` per-entry axis.
26961        for key in [
26962            crate::CONTRATO_KEY_DE,
26963            crate::CONTRATO_KEY_PARA,
26964            crate::CONTRATO_KEY_WIT,
26965            WitTarget::HTTP_FIELD_NAME,
26966            WitTarget::PUBSUB_FIELD_NAME,
26967            WitTarget::STORE_FIELD_NAME,
26968        ] {
26969            assert!(
26970                !key.is_empty(),
26971                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26972                 non-empty (got {key:?})"
26973            );
26974            let first = key.chars().next().unwrap();
26975            assert!(
26976                first.is_ascii_lowercase(),
26977                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must lead \
26978                 with an ASCII-lowercase byte (got {key:?}, leads with \
26979                 {first:?})",
26980            );
26981            assert!(
26982                key.chars().all(|c| c.is_ascii_alphanumeric()),
26983                "CONTRATO_KEY_* / WitTarget::*_FIELD_NAME must be \
26984                 ASCII-alphanumeric only — no `_` / `-` / `:` / `.` / \
26985                 whitespace (got {key:?})",
26986            );
26987        }
26988    }
26989
26990    // ── drift-detection: serde-derive-to-ENTRADA_KEY_* identity ──────────
26991
26992    #[test]
26993    fn entrada_serde_keys_match_lifted_entrada_key_consts() {
26994        // Load-bearing invariant: the four `ENTRADA_KEY_*` consts
26995        // ([`crate::ENTRADA_KEY_HOST`] / [`crate::ENTRADA_KEY_PARA`] /
26996        // [`crate::ENTRADA_KEY_PATHS`] / [`crate::ENTRADA_KEY_PORT`])
26997        // name the exact camelCase JSON keys the
26998        // `#[serde(rename_all = "camelCase")]` attribute on
26999        // [`Entrada`] emits. Serialize a fully-populated `Entrada` and
27000        // pin that each canonical byte-sequence appears verbatim in the
27001        // JSON — a future accidental `rename_all = "snake_case"` /
27002        // `"kebab-case"` / verbatim-field-name flip at the derive
27003        // attribute (any of which would silently break every downstream
27004        // JSON consumer that reaches for one of the four consts via
27005        // `Value::get(...)` — the [`caixa_mesh`] Gateway/HTTPRoute
27006        // emitter's per-Aplicacao hostname/paths/port projection, the
27007        // future `app-operator` reconciler's per-Aplicacao ingress
27008        // bind, the future `mesh.pleme.io/v1alpha1/Aplicacao` CR
27009        // materializer's admission-time cross-check) surfaces here as
27010        // a build-time test failure at `aplicacao.rs`, not as an
27011        // apply-time `.get(<stale-canonical-const>)` returning `None`
27012        // far from the derive-attr drift's commit. Peer with the
27013        // sibling
27014        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
27015        // (ca463a4) and
27016        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
27017        // pins on the M3 collection-slot atom axes — same discipline
27018        // both collection-slot lifts established, extended here to the
27019        // singleton `:entrada` mesh-slot atom axis, the last M3
27020        // typed-struct top-level `#[serde(rename_all = "camelCase")]`
27021        // axis on the Aplicacao surface without a lifted serde-key
27022        // peer.
27023        let e = Entrada {
27024            host: "checkout.quero.cloud".into(),
27025            para: "cart".into(),
27026            paths: vec!["/cart".into()],
27027            port: 8080,
27028        };
27029        let json = serde_json::to_string(&e).unwrap();
27030        for key in [
27031            crate::ENTRADA_KEY_HOST,
27032            crate::ENTRADA_KEY_PARA,
27033            crate::ENTRADA_KEY_PATHS,
27034            crate::ENTRADA_KEY_PORT,
27035        ] {
27036            let quoted = format!("\"{key}\"");
27037            assert!(
27038                json.contains(&quoted),
27039                "serialized Entrada must carry the lifted ENTRADA_KEY_* \
27040                 byte-sequence {quoted} verbatim in the JSON emission \
27041                 (got: {json})",
27042            );
27043        }
27044    }
27045
27046    #[test]
27047    fn entrada_key_consts_are_pairwise_distinct() {
27048        // Cross-axis drift-detection pin: a future collapse of the four
27049        // canonical [`Entrada`] singleton byte-strings onto the same
27050        // value (e.g. an accidental copy-paste flip of
27051        // [`crate::ENTRADA_KEY_PARA`] to also read `"host"`) would
27052        // silently reroute every downstream probe on one axis onto the
27053        // sibling axis's overlay entry and pass every propagation-probe
27054        // test that expected only the stale axis's value — the
27055        // Gateway/HTTPRoute emitter would read the hostname string
27056        // where the destination-Servico name was expected (or vice
27057        // versa), the admission-webhook cross-check would compare the
27058        // wrong pair of values, and the resulting Gateway resource
27059        // would either be admitted with garbage or rejected at the
27060        // controller far from the rebrand commit's source. Peer of the
27061        // sibling four-way distinct pin on the `SUPERVISOR_KEY_*`
27062        // tetrad (40cc4e5), the two-way distinct pin on the
27063        // `MEMBRO_KEY_*` pair (ce80ca0), and the six-way distinct pin
27064        // on the `CONTRATO_KEY_*` triad + `WitTarget::*_FIELD_NAME`
27065        // triad (ca463a4).
27066        let all = [
27067            crate::ENTRADA_KEY_HOST,
27068            crate::ENTRADA_KEY_PARA,
27069            crate::ENTRADA_KEY_PATHS,
27070            crate::ENTRADA_KEY_PORT,
27071        ];
27072        for (i, a) in all.iter().enumerate() {
27073            for b in all.iter().skip(i + 1) {
27074                assert_ne!(
27075                    a, b,
27076                    "ENTRADA_KEY_* consts must be pairwise-distinct \
27077                     canonical byte-sequences — got `{a}` == `{b}`",
27078                );
27079            }
27080        }
27081    }
27082
27083    #[test]
27084    fn entrada_key_consts_are_lower_camel_case_shape() {
27085        // Shape-pin: every `ENTRADA_KEY_*` const must be a
27086        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27087        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27088        // leading capital, no whitespace / dots) — the canonical shape
27089        // the `#[serde(rename_all = "camelCase")]` derive produces on
27090        // [`Entrada`]. A future flip to a non-camelCase attribute at
27091        // the derive surfaces both here (this test fails on the
27092        // stale-constant shape) and at
27093        // `entrada_serde_keys_match_lifted_entrada_key_consts` (that
27094        // test fails on the mismatch between const and derive). Peer
27095        // with `membro_key_consts_are_lower_camel_case_shape` (ce80ca0)
27096        // and `contrato_key_consts_are_lower_camel_case_shape`
27097        // (ca463a4) on the sibling M3 per-`:membros` and per-`:contratos`
27098        // entry axes.
27099        for key in [
27100            crate::ENTRADA_KEY_HOST,
27101            crate::ENTRADA_KEY_PARA,
27102            crate::ENTRADA_KEY_PATHS,
27103            crate::ENTRADA_KEY_PORT,
27104        ] {
27105            assert!(
27106                !key.is_empty(),
27107                "ENTRADA_KEY_* must be non-empty (got {key:?})"
27108            );
27109            let first = key.chars().next().unwrap();
27110            assert!(
27111                first.is_ascii_lowercase(),
27112                "ENTRADA_KEY_* must lead with an ASCII-lowercase byte \
27113                 (got {key:?}, leads with {first:?})",
27114            );
27115            assert!(
27116                key.chars().all(|c| c.is_ascii_alphanumeric()),
27117                "ENTRADA_KEY_* must be ASCII-alphanumeric only \
27118                 — no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27119            );
27120        }
27121    }
27122
27123    // ── drift-detection: serde-derive-to-POLITICAS_KEY_* identity ────────
27124
27125    #[test]
27126    fn mesh_policy_serde_keys_match_lifted_politicas_key_consts() {
27127        // Load-bearing invariant: the five `POLITICAS_KEY_*` consts
27128        // ([`crate::POLITICAS_KEY_TIMEOUT`] /
27129        // [`crate::POLITICAS_KEY_RETRIES`] /
27130        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] /
27131        // [`crate::POLITICAS_KEY_MTLS_REQUIRED`] /
27132        // [`crate::POLITICAS_KEY_RATE_LIMIT`]) name the exact camelCase
27133        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute
27134        // on [`MeshPolicy`] emits. Three of the five axes
27135        // (`circuit_breaker` → `circuitBreaker`, `mtls_required` →
27136        // `mtlsRequired`, `rate_limit` → `rateLimit`) are non-trivial
27137        // camelCase transforms — the derive-attribute is load-bearing
27138        // on those, unlike the sibling `Entrada` / `Membro` /
27139        // `WitContract` structs whose fields are all lowercase-single-
27140        // word and where the derive is a no-op on every axis.
27141        // Serialize a fully-populated [`MeshPolicy`] (every axis
27142        // `Some(…)` so `skip_serializing_if = "Option::is_none"` fires
27143        // on none of the five slots) and pin that each canonical
27144        // byte-sequence appears verbatim in the JSON — a future
27145        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
27146        // verbatim-field-name flip at the derive attribute (any of
27147        // which would silently break every downstream JSON consumer
27148        // that reaches for one of the five consts via
27149        // `Value::get(...)` — the future M4 per-edge `:politicas`
27150        // overlay projection onto Cilium `L7Rules` and Gateway API
27151        // `HTTPRoute` backend timeouts, the future
27152        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
27153        // admission-time mesh-policy cross-check, the future
27154        // `feira lint` per-`:politicas` bound-check gate) surfaces here
27155        // as a build-time test failure at `aplicacao.rs`, not as an
27156        // apply-time `.get(<stale-canonical-const>)` returning `None`
27157        // far from the derive-attr drift's commit. Peer with the
27158        // sibling `entrada_serde_keys_match_lifted_entrada_key_consts`
27159        // (a3d6162), `wit_contract_serde_keys_match_lifted_contrato_key_consts`
27160        // (ca463a4), and `membro_serde_keys_match_lifted_membro_key_consts`
27161        // (ce80ca0) pins on the M3 collection-slot / singleton-slot
27162        // atom axes — same discipline every M3 sibling lift
27163        // established, extended here to the singleton `:politicas`
27164        // mesh-slot atom axis, closing the last M3 typed-struct
27165        // top-level `#[serde(rename_all = "camelCase")]` axis on the
27166        // Aplicacao surface without a lifted serde-key peer.
27167        let p = MeshPolicy {
27168            timeout: Some(Duration::from_secs(30)),
27169            retries: Some(3),
27170            circuit_breaker: Some(CircuitBreaker {
27171                max_failures: 5,
27172                window: Duration::from_secs(60),
27173            }),
27174            mtls_required: Some(true),
27175            rate_limit: Some(RateLimit {
27176                rate: 100,
27177                window: Duration::from_secs(1),
27178            }),
27179        };
27180        let json = serde_json::to_string(&p).unwrap();
27181        for key in [
27182            crate::POLITICAS_KEY_TIMEOUT,
27183            crate::POLITICAS_KEY_RETRIES,
27184            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
27185            crate::POLITICAS_KEY_MTLS_REQUIRED,
27186            crate::POLITICAS_KEY_RATE_LIMIT,
27187        ] {
27188            let quoted = format!("\"{key}\"");
27189            assert!(
27190                json.contains(&quoted),
27191                "serialized MeshPolicy must carry the lifted \
27192                 POLITICAS_KEY_* byte-sequence {quoted} verbatim in the \
27193                 JSON emission (got: {json})",
27194            );
27195        }
27196    }
27197
27198    #[test]
27199    fn politicas_key_consts_are_pairwise_distinct() {
27200        // Cross-axis drift-detection pin: a future collapse of the five
27201        // canonical [`MeshPolicy`] singleton byte-strings onto the same
27202        // value (e.g. an accidental copy-paste flip of
27203        // [`crate::POLITICAS_KEY_RETRIES`] to also read `"timeout"`)
27204        // would silently reroute every downstream probe on one axis
27205        // onto the sibling axis's overlay entry and pass every
27206        // propagation-probe test that expected only the stale axis's
27207        // value — the M4 per-edge `:politicas` overlay projection would
27208        // read the retry-count string where the timeout duration was
27209        // expected (or vice versa), the CR materializer's admission
27210        // cross-check would compare the wrong pair of values, and the
27211        // resulting mesh reconciler would either bind the wrong axis
27212        // or reject the resource at reconcile far from the rebrand
27213        // commit's source. Peer of the sibling four-way distinct pin
27214        // on the `SUPERVISOR_KEY_*` tetrad (40cc4e5), the four-way
27215        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
27216        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0),
27217        // and the six-way distinct pin on the `CONTRATO_KEY_*` triad +
27218        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
27219        let all = [
27220            crate::POLITICAS_KEY_TIMEOUT,
27221            crate::POLITICAS_KEY_RETRIES,
27222            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
27223            crate::POLITICAS_KEY_MTLS_REQUIRED,
27224            crate::POLITICAS_KEY_RATE_LIMIT,
27225        ];
27226        for (i, a) in all.iter().enumerate() {
27227            for b in all.iter().skip(i + 1) {
27228                assert_ne!(
27229                    a, b,
27230                    "POLITICAS_KEY_* consts must be pairwise-distinct \
27231                     canonical byte-sequences — got `{a}` == `{b}`",
27232                );
27233            }
27234        }
27235    }
27236
27237    #[test]
27238    fn politicas_key_consts_are_lower_camel_case_shape() {
27239        // Shape-pin: every `POLITICAS_KEY_*` const must be a
27240        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27241        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27242        // leading capital, no whitespace / dots) — the canonical shape
27243        // the `#[serde(rename_all = "camelCase")]` derive produces on
27244        // [`MeshPolicy`]. A future flip to a non-camelCase attribute
27245        // at the derive surfaces both here (this test fails on the
27246        // stale-constant shape) and at
27247        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
27248        // (that test fails on the mismatch between const and derive).
27249        // Peer with `entrada_key_consts_are_lower_camel_case_shape`
27250        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27251        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27252        // (ca463a4) on the sibling M3 typed-struct axes.
27253        for key in [
27254            crate::POLITICAS_KEY_TIMEOUT,
27255            crate::POLITICAS_KEY_RETRIES,
27256            crate::POLITICAS_KEY_CIRCUIT_BREAKER,
27257            crate::POLITICAS_KEY_MTLS_REQUIRED,
27258            crate::POLITICAS_KEY_RATE_LIMIT,
27259        ] {
27260            assert!(
27261                !key.is_empty(),
27262                "POLITICAS_KEY_* must be non-empty (got {key:?})"
27263            );
27264            let first = key.chars().next().unwrap();
27265            assert!(
27266                first.is_ascii_lowercase(),
27267                "POLITICAS_KEY_* must lead with an ASCII-lowercase \
27268                 byte (got {key:?}, leads with {first:?})",
27269            );
27270            assert!(
27271                key.chars().all(|c| c.is_ascii_alphanumeric()),
27272                "POLITICAS_KEY_* must be ASCII-alphanumeric only — \
27273                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27274            );
27275        }
27276    }
27277
27278    // ── drift-detection: serde-derive-to-CIRCUIT_BREAKER_KEY_* identity ──
27279
27280    #[test]
27281    fn circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts() {
27282        // Load-bearing invariant: the two `CIRCUIT_BREAKER_KEY_*` consts
27283        // ([`crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES`] /
27284        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`]) name the exact camelCase
27285        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
27286        // [`CircuitBreaker`] emits inside the
27287        // [`crate::POLITICAS_KEY_CIRCUIT_BREAKER`] sub-block. One of the
27288        // two axes (`max_failures` → `maxFailures`) is a non-trivial
27289        // camelCase transform — the derive-attribute is load-bearing on
27290        // that axis, unlike the sibling `window` field where the derive
27291        // is a no-op. Serialize a fully-populated [`CircuitBreaker`] and
27292        // pin that each canonical byte-sequence appears verbatim in the
27293        // JSON — a future accidental `rename_all = "snake_case"` /
27294        // `"kebab-case"` / verbatim-field-name flip at the derive
27295        // attribute (any of which would silently break every downstream
27296        // JSON consumer that reaches for one of the two consts via
27297        // `Value::get(POLITICAS_KEY_CIRCUIT_BREAKER).and_then(|v|
27298        // v.get(CIRCUIT_BREAKER_KEY_MAX_FAILURES))` — the future M4
27299        // per-edge `:politicas` overlay projection onto the mesh's
27300        // per-backend consecutive-failure-counter tripping threshold, the
27301        // future `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
27302        // admission-time breaker cross-check, the future `feira lint`
27303        // per-`:politicas :circuit-breaker` bound-check gate) surfaces
27304        // here as a build-time test failure at `aplicacao.rs`, not as an
27305        // apply-time `.get(<stale-canonical-const>)` returning `None`
27306        // far from the derive-attr drift's commit. Peer with the sibling
27307        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
27308        // (b55cca7) parent-axis pin — that test pins the outer
27309        // sub-block key the derive on [`MeshPolicy`] emits, this test
27310        // pins the inner keys the derive on the payload type emits, so
27311        // the two together lock the whole [`MeshPolicy`] breaker-tuning
27312        // shape end-to-end at build time.
27313        let cb = CircuitBreaker {
27314            max_failures: 5,
27315            window: Duration::from_secs(60),
27316        };
27317        let json = serde_json::to_string(&cb).unwrap();
27318        for key in [
27319            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27320            crate::CIRCUIT_BREAKER_KEY_WINDOW,
27321        ] {
27322            let quoted = format!("\"{key}\"");
27323            assert!(
27324                json.contains(&quoted),
27325                "serialized CircuitBreaker must carry the lifted \
27326                 CIRCUIT_BREAKER_KEY_* byte-sequence {quoted} verbatim \
27327                 in the JSON emission (got: {json})",
27328            );
27329        }
27330    }
27331
27332    #[test]
27333    fn circuit_breaker_key_consts_are_pairwise_distinct() {
27334        // Cross-axis drift-detection pin: a future collapse of the two
27335        // canonical [`CircuitBreaker`] sub-block byte-strings onto the
27336        // same value (e.g. an accidental copy-paste flip of
27337        // [`crate::CIRCUIT_BREAKER_KEY_WINDOW`] to also read
27338        // `"maxFailures"`) would silently reroute every downstream
27339        // probe on one axis onto the sibling axis's overlay entry and
27340        // pass every propagation-probe test that expected only the
27341        // stale axis's value — the M4 per-edge `:politicas` overlay
27342        // projection would read the failure-count where the window
27343        // duration was expected (or vice versa), the CR materializer's
27344        // admission cross-check would compare the wrong pair of values,
27345        // and the resulting mesh reconciler would either bind the wrong
27346        // axis or reject the resource at reconcile far from the rebrand
27347        // commit's source. Peer of the sibling five-way distinct pin on
27348        // the `POLITICAS_KEY_*` pentad (b55cca7), the four-way distinct
27349        // pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the two-way
27350        // distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and the
27351        // six-way distinct pin on the `CONTRATO_KEY_*` triad +
27352        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
27353        let all = [
27354            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27355            crate::CIRCUIT_BREAKER_KEY_WINDOW,
27356        ];
27357        for (i, a) in all.iter().enumerate() {
27358            for b in all.iter().skip(i + 1) {
27359                assert_ne!(
27360                    a, b,
27361                    "CIRCUIT_BREAKER_KEY_* consts must be pairwise-distinct \
27362                     canonical byte-sequences — got `{a}` == `{b}`",
27363                );
27364            }
27365        }
27366    }
27367
27368    #[test]
27369    fn circuit_breaker_key_consts_are_lower_camel_case_shape() {
27370        // Shape-pin: every `CIRCUIT_BREAKER_KEY_*` const must be a
27371        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27372        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27373        // leading capital, no whitespace / dots) — the canonical shape
27374        // the `#[serde(rename_all = "camelCase")]` derive produces on
27375        // [`CircuitBreaker`]. A future flip to a non-camelCase attribute
27376        // at the derive surfaces both here (this test fails on the
27377        // stale-constant shape) and at
27378        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
27379        // (that test fails on the mismatch between const and derive).
27380        // Peer with `politicas_key_consts_are_lower_camel_case_shape`
27381        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
27382        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27383        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27384        // (ca463a4) on the sibling M3 typed-struct axes.
27385        for key in [
27386            crate::CIRCUIT_BREAKER_KEY_MAX_FAILURES,
27387            crate::CIRCUIT_BREAKER_KEY_WINDOW,
27388        ] {
27389            assert!(
27390                !key.is_empty(),
27391                "CIRCUIT_BREAKER_KEY_* must be non-empty (got {key:?})"
27392            );
27393            let first = key.chars().next().unwrap();
27394            assert!(
27395                first.is_ascii_lowercase(),
27396                "CIRCUIT_BREAKER_KEY_* must lead with an ASCII-lowercase \
27397                 byte (got {key:?}, leads with {first:?})",
27398            );
27399            assert!(
27400                key.chars().all(|c| c.is_ascii_alphanumeric()),
27401                "CIRCUIT_BREAKER_KEY_* must be ASCII-alphanumeric only — \
27402                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27403            );
27404        }
27405    }
27406
27407    // ── drift-detection: serde-derive-to-M3_PLACEMENT_KEY_* identity ─────
27408
27409    #[test]
27410    fn placement_serde_keys_match_lifted_m3_placement_key_consts() {
27411        // Load-bearing invariant: the four `M3_PLACEMENT_KEY_*` consts
27412        // ([`crate::M3_PLACEMENT_KEY_ESTRATEGIA`] /
27413        // [`crate::M3_PLACEMENT_KEY_CLUSTERS`] /
27414        // [`crate::M3_PLACEMENT_KEY_AFFINITY`] /
27415        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`]) name the exact camelCase
27416        // JSON keys the `#[serde(rename_all = "camelCase")]` attribute on
27417        // [`Placement`] emits. One of the four axes (`shard_key` →
27418        // `shardKey`) is a non-trivial camelCase transform — the
27419        // derive-attribute is load-bearing on that axis, unlike the
27420        // sibling `estrategia` / `clusters` / `affinity` axes whose
27421        // source-side field names carry no `_` and where the derive is a
27422        // no-op. Serialize a fully-populated [`Placement`] (both
27423        // `Option`-carrying axes `Some(_)` so
27424        // `skip_serializing_if = "Option::is_none"` fires on neither of
27425        // the two optional slots) and pin that each canonical
27426        // byte-sequence appears verbatim in the JSON — a future
27427        // accidental `rename_all = "snake_case"` / `"kebab-case"` /
27428        // verbatim-field-name flip at the derive attribute (any of which
27429        // would silently break every downstream consumer that reaches
27430        // for one of the four consts via
27431        // `Value::get(M3_KEY_PLACEMENT).and_then(|v|
27432        // v.get(M3_PLACEMENT_KEY_*))` — the `lareira-fleet-programs`
27433        // aggregator's per-cluster fanout filter keying off
27434        // `placement.clusters`, the M3 shard-pool dispatch materializer
27435        // keying off `placement.shardKey`, the M3 Adaptive compression
27436        // pass weighting off `placement.affinity`, every downstream
27437        // dispatcher branching on `placement.estrategia`, the future
27438        // `mesh.pleme.io/v1alpha1/Aplicacao` CR materializer's
27439        // admission-time placement cross-check, the future `feira lint`
27440        // per-`:placement` bound-check gate) surfaces here as a
27441        // build-time test failure at `aplicacao.rs`, not as an
27442        // apply-time `.get(<stale-canonical-const>)` returning `None`
27443        // far from the derive-attr drift's commit. Peer with the sibling
27444        // `mesh_policy_serde_keys_match_lifted_politicas_key_consts`
27445        // (b55cca7),
27446        // `circuit_breaker_serde_keys_match_lifted_circuit_breaker_key_consts`
27447        // (468e959),
27448        // `entrada_serde_keys_match_lifted_entrada_key_consts` (a3d6162),
27449        // `wit_contract_serde_keys_match_lifted_contrato_key_consts`
27450        // (ca463a4), and
27451        // `membro_serde_keys_match_lifted_membro_key_consts` (ce80ca0)
27452        // pins on the M3 collection-slot / singleton-slot atom axes —
27453        // closes the last M3 typed-struct top-level
27454        // `#[serde(rename_all = "camelCase")]` axis on the Aplicacao
27455        // surface without a drift-detection pin.
27456        let p = Placement {
27457            estrategia: PlacementStrategy::Sharded,
27458            clusters: vec!["rio".into(), "mar".into()],
27459            affinity: Some("data-locality".into()),
27460            shard_key: Some("$tenantId".into()),
27461        };
27462        let json = serde_json::to_string(&p).unwrap();
27463        for key in [
27464            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27465            crate::M3_PLACEMENT_KEY_CLUSTERS,
27466            crate::M3_PLACEMENT_KEY_AFFINITY,
27467            crate::M3_PLACEMENT_KEY_SHARD_KEY,
27468        ] {
27469            let quoted = format!("\"{key}\"");
27470            assert!(
27471                json.contains(&quoted),
27472                "serialized Placement must carry the lifted \
27473                 M3_PLACEMENT_KEY_* byte-sequence {quoted} verbatim in \
27474                 the JSON emission (got: {json})",
27475            );
27476        }
27477    }
27478
27479    #[test]
27480    fn m3_placement_key_consts_are_pairwise_distinct() {
27481        // Cross-axis drift-detection pin: a future collapse of the four
27482        // canonical [`Placement`] sub-block byte-strings onto the same
27483        // value (e.g. an accidental copy-paste flip of
27484        // [`crate::M3_PLACEMENT_KEY_SHARD_KEY`] to also read
27485        // `"affinity"`) would silently reroute every downstream probe on
27486        // one axis onto the sibling axis's overlay entry and pass every
27487        // propagation-probe test that expected only the stale axis's
27488        // value — the M3 shard-pool dispatch materializer would read the
27489        // affinity placement-hint where the shard-selection template was
27490        // expected (or vice versa), the M3 Adaptive compression pass's
27491        // cross-check would compare the wrong pair of values, and the
27492        // resulting placement engine would either bind the wrong axis or
27493        // reject the resource at reconcile far from the rebrand commit's
27494        // source. Peer of the sibling two-way distinct pin on the
27495        // `CIRCUIT_BREAKER_KEY_*` pair (468e959), the five-way distinct
27496        // pin on the `POLITICAS_KEY_*` pentad (b55cca7), the four-way
27497        // distinct pin on the `ENTRADA_KEY_*` tetrad (a3d6162), the
27498        // two-way distinct pin on the `MEMBRO_KEY_*` pair (ce80ca0), and
27499        // the six-way distinct pin on the `CONTRATO_KEY_*` triad +
27500        // `WitTarget::*_FIELD_NAME` triad (ca463a4).
27501        let all = [
27502            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27503            crate::M3_PLACEMENT_KEY_CLUSTERS,
27504            crate::M3_PLACEMENT_KEY_AFFINITY,
27505            crate::M3_PLACEMENT_KEY_SHARD_KEY,
27506        ];
27507        for (i, a) in all.iter().enumerate() {
27508            for b in all.iter().skip(i + 1) {
27509                assert_ne!(
27510                    a, b,
27511                    "M3_PLACEMENT_KEY_* consts must be pairwise-distinct \
27512                     canonical byte-sequences — got `{a}` == `{b}`",
27513                );
27514            }
27515        }
27516    }
27517
27518    #[test]
27519    fn m3_placement_key_consts_are_lower_camel_case_shape() {
27520        // Shape-pin: every `M3_PLACEMENT_KEY_*` const must be a
27521        // lowerCamelCase byte-sequence (no `snake_case` underscores, no
27522        // `kebab-case` hyphens, no leading colon, no `PascalCase`
27523        // leading capital, no whitespace / dots) — the canonical shape
27524        // the `#[serde(rename_all = "camelCase")]` derive produces on
27525        // [`Placement`]. A future flip to a non-camelCase attribute at
27526        // the derive surfaces both here (this test fails on the stale-
27527        // constant shape) and at
27528        // `placement_serde_keys_match_lifted_m3_placement_key_consts`
27529        // (that test fails on the mismatch between const and derive).
27530        // Peer with `circuit_breaker_key_consts_are_lower_camel_case_shape`
27531        // (468e959), `politicas_key_consts_are_lower_camel_case_shape`
27532        // (b55cca7), `entrada_key_consts_are_lower_camel_case_shape`
27533        // (a3d6162), `membro_key_consts_are_lower_camel_case_shape`
27534        // (ce80ca0), and `contrato_key_consts_are_lower_camel_case_shape`
27535        // (ca463a4) on the sibling M3 typed-struct axes.
27536        for key in [
27537            crate::M3_PLACEMENT_KEY_ESTRATEGIA,
27538            crate::M3_PLACEMENT_KEY_CLUSTERS,
27539            crate::M3_PLACEMENT_KEY_AFFINITY,
27540            crate::M3_PLACEMENT_KEY_SHARD_KEY,
27541        ] {
27542            assert!(
27543                !key.is_empty(),
27544                "M3_PLACEMENT_KEY_* must be non-empty (got {key:?})"
27545            );
27546            let first = key.chars().next().unwrap();
27547            assert!(
27548                first.is_ascii_lowercase(),
27549                "M3_PLACEMENT_KEY_* must lead with an ASCII-lowercase \
27550                 byte (got {key:?}, leads with {first:?})",
27551            );
27552            assert!(
27553                key.chars().all(|c| c.is_ascii_alphanumeric()),
27554                "M3_PLACEMENT_KEY_* must be ASCII-alphanumeric only — \
27555                 no `_` / `-` / `:` / `.` / whitespace (got {key:?})",
27556            );
27557        }
27558    }
27559
27560    // ── AplicacaoSpec::port_for_destination — the substrate-canonical
27561    //    destination-facing L4 port resolver every per-Aplicacao renderer
27562    //    reaching for a per-destination Servico TCP port axis routes
27563    //    through. The four pin tests below fix the four-way accept-set
27564    //    the resolver must always honor: (:entrada-para-matches,
27565    //    :entrada-para-mismatches, :entrada-none-so-fallback,
27566    //    :entrada-port-non-default-honored) — drift on any arm surfaces
27567    //    at caixa-core build time rather than at cluster-apply time.
27568
27569    #[test]
27570    fn port_for_destination_returns_entrada_port_when_para_matches_destination() {
27571        // The typed `:entrada` block's `:para "cart"` matches the
27572        // queried destination, so the resolver returns the author-
27573        // declared `:port` scalar verbatim — the canonical "the
27574        // destination Servico IS the ingress apex, honor the typed
27575        // listener port" arm of the port-resolution dispatch.
27576        let mut spec = three_member_spec();
27577        if let Some(e) = spec.entrada.as_mut() {
27578            e.para = "cart".into();
27579            e.port = 9090;
27580        }
27581        assert_eq!(
27582            spec.port_for_destination("cart"),
27583            9090,
27584            "port_for_destination(entrada.para) must return entrada.port \
27585             verbatim, not the DEFAULT_SERVICO_PORT fallback"
27586        );
27587    }
27588
27589    #[test]
27590    fn port_for_destination_falls_back_to_default_servico_port_when_para_mismatches() {
27591        // The typed `:entrada` block names `:para "cart"`, but the
27592        // queried destination is `"payment"` — a Servico that
27593        // participates in the mesh graph but is not the ingress apex.
27594        // The resolver falls back to the lifted DEFAULT_SERVICO_PORT
27595        // canonical port floor, closing the "non-apex destination reads
27596        // the substrate default" arm. Same fixture the peer
27597        // `cnp_l4_fallback_port_routes_through_lifted_default_servico_port`
27598        // pin at caixa-mesh exercises through the CNP emit-side path;
27599        // this pin exercises the shared underlying resolver directly.
27600        let spec = three_member_spec();
27601        assert_eq!(
27602            spec.port_for_destination("payment"),
27603            DEFAULT_SERVICO_PORT,
27604            "port_for_destination(non-apex-destination) must route \
27605             through the lifted DEFAULT_SERVICO_PORT canonical port floor"
27606        );
27607    }
27608
27609    #[test]
27610    fn port_for_destination_falls_back_to_default_servico_port_when_entrada_none() {
27611        // Internal-only Aplicacao — no `:entrada` block declared. Every
27612        // per-destination port query falls back to the lifted
27613        // DEFAULT_SERVICO_PORT canonical floor. The arm exists because
27614        // the Aplicacao surface admits `:entrada None` (internal mesh
27615        // with no external gateway); every downstream renderer's per-
27616        // destination port axis must still resolve to a well-defined
27617        // scalar even without an ingress apex.
27618        let mut spec = three_member_spec();
27619        spec.entrada = None;
27620        assert_eq!(
27621            spec.port_for_destination("cart"),
27622            DEFAULT_SERVICO_PORT,
27623            "port_for_destination on an internal-only Aplicacao must \
27624             fall back to the lifted DEFAULT_SERVICO_PORT floor for \
27625             every destination"
27626        );
27627        assert_eq!(
27628            spec.port_for_destination("payment"),
27629            DEFAULT_SERVICO_PORT,
27630            "port_for_destination on an internal-only Aplicacao must \
27631             fall back uniformly across every destination — the fallback \
27632             is not entrada-shape-conditional"
27633        );
27634    }
27635
27636    #[test]
27637    fn port_for_destination_honors_non_default_entrada_port_verbatim() {
27638        // Structural pin against a hypothetical future refactor that
27639        // reconciled `entrada.port` against `DEFAULT_SERVICO_PORT` at
27640        // the resolver (a "normalize to the default when the author's
27641        // port matches the substrate default" collapse) — that would
27642        // break renderer sites that carry meaning on the emitted port
27643        // value beyond bare equality (a future per-cluster listener-
27644        // audit that keys off the author-declared port, not the
27645        // resolved-with-fallback port). Pin that a non-default
27646        // entrada.port is returned verbatim so drift here surfaces at
27647        // caixa-core build time.
27648        let mut spec = three_member_spec();
27649        if let Some(e) = spec.entrada.as_mut() {
27650            e.para = "cart".into();
27651            e.port = 8443;
27652        }
27653        assert_ne!(
27654            8443, DEFAULT_SERVICO_PORT,
27655            "test fixture must probe a port distinct from \
27656             DEFAULT_SERVICO_PORT to exercise the honor-verbatim arm"
27657        );
27658        assert_eq!(
27659            spec.port_for_destination("cart"),
27660            8443,
27661            "port_for_destination(entrada.para) must return entrada.port \
27662             verbatim, even when the port differs from DEFAULT_SERVICO_PORT"
27663        );
27664    }
27665
27666    #[test]
27667    fn port_for_destination_at_entrada_destination_returns_entrada_port_across_permutations() {
27668        // Apex-identity pair-invariant pin composing both substrate-
27669        // primitive typed dispatches — [`AplicacaoSpec::port_for_destination`]
27670        // and [`Entrada::destination`] — at the emit-side call shape
27671        // every per-Aplicacao renderer's ingress-apex L4 port reader
27672        // now takes. The invariant:
27673        //
27674        //   spec.port_for_destination(entrada.destination()) == entrada.port
27675        //
27676        // holds by construction under today's single-destination
27677        // `:entrada` slot (`destination()` returns `entrada.para`, and
27678        // the resolver's apex arm matches `para == destination` and
27679        // returns `entrada.port`), and every downstream consumer that
27680        // composes the two accessors at the ingress apex — the
27681        // `caixa_mesh::gateway_routes` HTTPRoute per-rule
27682        // `backendRefs[0].port` emit-site path, the peer future M4 CR
27683        // materializer's admission-webhook that promotes the scalar to
27684        // a per-CR override overlay, every future per-Aplicacao snapshot
27685        // renderer's apex-facing L4 port reader — reaches through the
27686        // same composition. Pin the identity across four permutations
27687        // (`:para` × `:port` including a non-default port to exercise
27688        // the honor-verbatim arm and a non-cart `:para` to exercise
27689        // destination-agnostic identity) so a future refactor that
27690        // silently split either accessor's apex behavior surfaces at
27691        // caixa-core build time — a subtle `destination()` renaming
27692        // that returned `entrada.host.as_str()` instead of
27693        // `entrada.para.as_str()` would blow this pin loudly, closing
27694        // the last quiet failure mode the two lifts admit in composition.
27695        //
27696        // Peer discipline with the sibling caixa-mesh cross-crate pin
27697        // [`caixa_mesh::tests::httproute_backend_ref_port_and_cnp_l4_port_share_port_for_destination_resolver_at_emit_site`]
27698        // on the two-renderer pair-invariant axis; this pin encodes the
27699        // same two-consumer coherence rule at the substrate-primitive
27700        // level so the invariant survives even if every renderer is
27701        // deleted.
27702        for (para, port) in [
27703            ("cart", DEFAULT_SERVICO_PORT),
27704            ("cart", 8443u16),
27705            ("payment", 9090u16),
27706            ("catalog", 443u16),
27707        ] {
27708            let mut spec = three_member_spec();
27709            if let Some(e) = spec.entrada.as_mut() {
27710                e.para = para.into();
27711                e.port = port;
27712            }
27713            let expected_port = spec
27714                .entrada()
27715                .expect("three_member_spec carries a typed `:entrada` block")
27716                .port();
27717            let composed_port = {
27718                let entrada = spec.entrada().expect("entrada present");
27719                spec.port_for_destination(entrada.destination())
27720            };
27721            assert_eq!(
27722                composed_port, expected_port,
27723                "`spec.port_for_destination(entrada.destination())` must \
27724                 equal `entrada.port` under today's single-destination \
27725                 `:entrada` slot — this is the apex-identity contract \
27726                 every downstream ingress-apex L4 port reader relies on. \
27727                 Input :entrada :para: {para:?}, :entrada :port: {port}"
27728            );
27729        }
27730    }
27731
27732    #[test]
27733    fn port_for_destination_apex_arm_routes_through_destination_accessor() {
27734        // Composition pin: [`AplicacaoSpec::port_for_destination`]'s
27735        // per-`:entrada` apex-arm membership probe must key off
27736        // [`Entrada::destination`], not the raw `.para` field access.
27737        // Structurally: setting ONLY the `:entrada :para` field to a
27738        // fresh non-cart destination on an otherwise-well-formed
27739        // Aplicacao must (1) leave `e.destination()` byte-equal to
27740        // `e.para.as_str()` (the accessor is byte-projective by
27741        // definition), and (2) cause the resolver's apex arm to fire
27742        // and return `entrada.port` at exactly that new destination
27743        // while every other destination string falls through to
27744        // [`DEFAULT_SERVICO_PORT`] under the accessor-projected
27745        // membership check. Pins against a future silent detour that
27746        // (a) re-derived the apex-arm membership probe off
27747        // `e.para == destination` in `port_for_destination` instead of
27748        // `e.destination() == destination`, silently disagreeing with
27749        // the two peer `caixa-mesh` per-`(HTTPRoute, CNP)` emit-site
27750        // consumers (`entrada.destination()` at
27751        // caixa-mesh/src/lib.rs:3173, `c.destination()` at
27752        // caixa-mesh/src/lib.rs:2739) that already reach through the
27753        // accessor, (b) accessor-side introduced a per-tenant alias
27754        // arm the caller was unaware of, silently rewriting an
27755        // author-declared `:para "cart"` value to a canary-aliased
27756        // form — the raw-field-access resolver would fall through to
27757        // `DEFAULT_SERVICO_PORT` matching the un-aliased destination
27758        // while the peer emit-site consumers landed on the aliased
27759        // destination, splitting the ingress-apex L4 port at
27760        // cluster-apply time.
27761        //
27762        // Peer of the sibling
27763        // [`validate_membros_empty_gate_routes_through_nome_accessor`]
27764        // (d0de220) composition pin on the per-`:membros` refusal-arm
27765        // axis — same "the shape-gate predicate must route through the
27766        // substrate-primitive typed dispatch" discipline extended onto
27767        // the per-`:entrada` apex-arm membership-probe axis. Closes
27768        // the last unlifted `.para` production-code read site on
27769        // `Entrada` in `caixa-core` — after this converge every
27770        // `caixa-core` `.para` field access outside the accessor's own
27771        // body and outside the `WitContract` per-`:contratos` sibling
27772        // axis is either a test-side field-setter or a doc-comment
27773        // reference.
27774        for (para, port) in [("cart", 8080u16), ("payment", 9090u16), ("catalog", 443u16)] {
27775            let mut spec = three_member_spec();
27776            if let Some(e) = spec.entrada.as_mut() {
27777                e.para = para.into();
27778                e.port = port;
27779            }
27780            let e = spec
27781                .entrada
27782                .as_ref()
27783                .expect("three_member_spec carries a typed `:entrada` block");
27784            assert_eq!(
27785                e.destination(),
27786                e.para.as_str(),
27787                "Entrada::destination must byte-equal the .para field \
27788                 access — an accessor-side detour that no longer \
27789                 projects the raw field would silently split this \
27790                 drift-detection test from the port_for_destination \
27791                 apex-arm membership probe",
27792            );
27793            assert_eq!(
27794                spec.port_for_destination(para),
27795                port,
27796                "port_for_destination must key off the accessor-projected \
27797                 destination and return `entrada.port` on the apex arm — \
27798                 input :entrada :para: {para:?}, :entrada :port: {port}",
27799            );
27800            assert_eq!(
27801                spec.port_for_destination("ghost-destination-never-a-member"),
27802                DEFAULT_SERVICO_PORT,
27803                "port_for_destination must fall through to \
27804                 DEFAULT_SERVICO_PORT on a non-matching destination \
27805                 under the accessor-projected membership check — input \
27806                 :entrada :para: {para:?}, :entrada :port: {port}",
27807            );
27808        }
27809    }
27810
27811    #[test]
27812    fn rate_limit_rate_returns_rate_u32_byte_equal_across_permutations() {
27813        // The canonical per-`:politicas :rate-limit` `:rate`
27814        // Envoy-local-rate-limit-mesh token-bucket-capacity scalar pin:
27815        // [`RateLimit::rate`] must return the `:politicas :rate-limit`
27816        // typed `u32` verbatim, byte-equal to the raw field access
27817        // across every representative value in the accept-set — `1` (the
27818        // lower boundary of the `1..=POLICY_RATE_LIMIT_MAX` accept-set
27819        // the surrounding [`AplicacaoSpec::validate_politicas`] gate
27820        // carves out on the sibling `PolicyRateLimitZero` refusal),
27821        // `POLICY_RATE_LIMIT_MAX` (the upper boundary the same gate
27822        // carves out on the sibling `PolicyRateLimitExceedsCap` refusal),
27823        // `0` (a past-the-guard sentinel that pins the accessor doesn't
27824        // perform a silent bounds-collapse into `1` on the zero arm —
27825        // validate rejects zero but the accessor must ship the raw slot
27826        // verbatim so a validate-time gate regression surfaces at the
27827        // emit boundary rather than being silently absorbed), `u32::MAX`
27828        // (a past-the-guard sentinel that pins the accessor doesn't
27829        // perform a silent bounds-collapse through
27830        // `POLICY_RATE_LIMIT_MAX` at the return path).
27831        //
27832        // First sub-struct required-scalar accessor pin on the
27833        // `RateLimit` axis — sibling in shape to the peer
27834        // per-`CircuitBreaker` [`CircuitBreaker::max_failures`] (3a74062)
27835        // required-`u32` accessor pin on the peer per-sub-struct
27836        // required-axis. Pins against a future silent detour that
27837        // re-derived the token capacity from a peer axis (an accidental
27838        // `self.window.as_secs() as u32` collapse that read the
27839        // rate-limit window duration as a token count), a `0 → 1`
27840        // cluster-default projection (which would silently absorb the
27841        // `PolicyRateLimitZero` refusal case at the accessor boundary),
27842        // or a bounds-collapsing accessor that clamped the return
27843        // through `POLICY_RATE_LIMIT_MAX` (the `AplicacaoSpec::validate`
27844        // gate owns the bounds; the accessor must ship the raw slot
27845        // verbatim).
27846        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27847            let rl = RateLimit {
27848                rate,
27849                window: Duration::from_secs(1),
27850            };
27851            assert_eq!(
27852                rl.rate(),
27853                rate,
27854                "RateLimit::rate must return :politicas :rate-limit :rate \
27855                 verbatim (got {}, expected {rate})",
27856                rl.rate(),
27857            );
27858            assert_eq!(
27859                rl.rate(),
27860                rl.rate,
27861                "RateLimit::rate must byte-equal the raw .rate field \
27862                 access across every value in the u32 accept-set",
27863            );
27864        }
27865    }
27866
27867    #[test]
27868    fn validate_politicas_rate_zero_floor_arm_routes_through_accessor() {
27869        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
27870        // `:rate-limit :rate` zero-floor arm must key off
27871        // [`RateLimit::rate`], not the raw `.rate` field access.
27872        // Structurally: a `RateLimit { rate: 0, window:
27873        // Duration::from_secs(1) }` embedded in a `:politicas
27874        // :rate-limit` slot must surface the `PolicyRateLimitZero`
27875        // refusal exactly, and a `RateLimit { rate: 1, window:
27876        // Duration::from_secs(1) }` (the lower boundary of the
27877        // `1..=POLICY_RATE_LIMIT_MAX` accept-set) must pass validate.
27878        // The pair jointly pins the accessor + validate-gate composition:
27879        // any future silent detour that had the accessor return a fresh
27880        // `1` on the zero arm (a `.rate().max(1)` collapse) would
27881        // silently absorb the `PolicyRateLimitZero` refusal at the
27882        // accessor boundary and the validate gate would accept a
27883        // struct-literal `RateLimit { rate: 0, .. }` — the composition
27884        // pin catches that at caixa-core build time.
27885        //
27886        // Peer of the sibling per-`CircuitBreaker`
27887        // [`CircuitBreaker::max_failures`] (3a74062) /
27888        // [`CircuitBreaker::window`] (373957f) accessor-composition
27889        // pins on the peer required-scalar axes — same "the validate /
27890        // shape-gate predicate must route through the substrate-primitive
27891        // typed dispatch" discipline extended onto the peer
27892        // per-`RateLimit` required-`u32` composition axis.
27893        let mut spec = three_member_spec();
27894        spec.politicas = MeshPolicy {
27895            rate_limit: Some(RateLimit {
27896                rate: 0,
27897                window: Duration::from_secs(1),
27898            }),
27899            ..MeshPolicy::default()
27900        };
27901        assert!(
27902            matches!(spec.validate(), Err(AplicacaoError::PolicyRateLimitZero)),
27903            "validate_politicas must reject rate == 0 with \
27904             PolicyRateLimitZero — the accessor and the validate gate \
27905             must route through the same substrate-primitive typed \
27906             dispatch on the :rate zero-floor arm",
27907        );
27908        spec.politicas = MeshPolicy {
27909            rate_limit: Some(RateLimit {
27910                rate: 1,
27911                window: Duration::from_secs(1),
27912            }),
27913            ..MeshPolicy::default()
27914        };
27915        assert!(
27916            spec.validate().is_ok(),
27917            "validate_politicas must accept rate == 1 (the lower \
27918             boundary of the 1..=POLICY_RATE_LIMIT_MAX accept-set)",
27919        );
27920    }
27921
27922    #[test]
27923    fn rate_limit_rate_projects_u32_by_copy() {
27924        // The by-copy pin: [`RateLimit::rate`] returns `u32` by copy —
27925        // `u32` is `Copy` and the accessor must return by value, not by
27926        // reference. Peer of the sibling per-`CircuitBreaker`
27927        // [`CircuitBreaker::max_failures`] (3a74062) by-copy pin on the
27928        // peer required-scalar `:max-failures` axis, extended onto the
27929        // peer per-`RateLimit` required-`u32` copy-invariant shape —
27930        // the accessor's returned `u32` must outlive `&self` (multiple
27931        // calls must return equal values from a dropped-`&self` copy,
27932        // since the returned scalar carries no borrow), and calling the
27933        // accessor twice on the same RateLimit must yield the same
27934        // `u32` verbatim (idempotent, no side effects on `&self`).
27935        //
27936        // Pins against a future silent detour that returned `&u32`
27937        // (which would type-check but silently break every downstream
27938        // arithmetic consumer — [`crate::render::require_positive_bounded_u32`]'s
27939        // first parameter is `u32`, and `&u32` would fold to a detached
27940        // copy at the call site with a `*` deref the sibling accessors
27941        // don't need), an accidental `.rate.wrapping_add(0)` detour that
27942        // returned a fresh copy through an arithmetic no-op (breaking a
27943        // future `const fn` regression), or a one-arm-only accessor
27944        // that returned a saturating value on some sentinel input
27945        // (breaking the pass-through invariant the sibling required-
27946        // scalar accessors carry).
27947        for rate in [1u32, POLICY_RATE_LIMIT_MAX, 0, u32::MAX] {
27948            let rl = RateLimit {
27949                rate,
27950                window: Duration::from_secs(1),
27951            };
27952            let first = rl.rate();
27953            let second = rl.rate();
27954            assert_eq!(
27955                first, second,
27956                "RateLimit::rate must be idempotent — two successive \
27957                 calls on the same &self must return the same u32",
27958            );
27959            assert_eq!(
27960                first, rate,
27961                "RateLimit::rate must return :politicas :rate-limit :rate \
27962                 verbatim by copy — got {first}, expected {rate}",
27963            );
27964        }
27965    }
27966
27967    #[test]
27968    fn rate_limit_window_returns_window_duration_byte_equal_across_permutations() {
27969        // The canonical per-`:politicas :rate-limit` `:window`
27970        // Envoy-local-rate-limit-mesh token-bucket-refill-period scalar
27971        // pin: [`RateLimit::window`] must return the
27972        // `:politicas :rate-limit :window` typed `Duration` verbatim,
27973        // byte-equal to the raw field access across every
27974        // representative value in the accept-set — `Duration::from_secs(1)`
27975        // (the `"s"` canonical window, the lower row of
27976        // [`RATE_LIMIT_UNIT_TABLE`] the surrounding
27977        // [`AplicacaoSpec::validate_politicas`] gate accepts via
27978        // [`is_canonical_rate_limit_window`]),
27979        // `Duration::from_secs(60)` (the `"m"` canonical window, the
27980        // middle row), `Duration::from_secs(3600)` (the `"h"` canonical
27981        // window, the upper row), `Duration::ZERO` (a past-the-guard
27982        // sentinel that pins the accessor doesn't perform a silent
27983        // bounds-collapse into `Duration::from_secs(1)` on the zero
27984        // arm — validate rejects an off-set window through
27985        // `PolicyRateLimitWindowNotCanonical` but the accessor must
27986        // ship the raw slot verbatim so a validate-time gate
27987        // regression surfaces at the emit boundary rather than being
27988        // silently absorbed), `Duration::from_millis(500)` (a
27989        // sub-canonical past-the-guard sentinel that pins the accessor
27990        // doesn't silently normalize a non-canonical fractional
27991        // magnitude onto the nearest canonical row).
27992        //
27993        // Second sub-struct required-scalar accessor pin on the
27994        // `RateLimit` axis — sibling in shape to the just-landed
27995        // per-`RateLimit` [`RateLimit::rate`] (7f81a60) required-`u32`
27996        // accessor pin on the peer per-sub-struct required-axis,
27997        // extended onto the per-`RateLimit` required-`Duration` axis.
27998        // Pins against a future silent detour that re-derived the
27999        // refill period from a peer axis (an accidental
28000        // `Duration::from_secs(self.rate as u64)` collapse that read
28001        // the rate-limit token capacity as a refill-interval
28002        // duration), a `Duration::ZERO → Duration::from_secs(1)`
28003        // canonical-default projection (which would silently absorb
28004        // the `PolicyRateLimitWindowNotCanonical` refusal case at the
28005        // accessor boundary), or a canonical-set-collapsing accessor
28006        // that clamped the return through [`rate_limit_window_unit`]
28007        // (the `AplicacaoSpec::validate` gate owns the canonical-set
28008        // membership; the accessor must ship the raw slot verbatim).
28009        for window in [
28010            Duration::from_secs(1),
28011            Duration::from_secs(60),
28012            Duration::from_secs(3600),
28013            Duration::ZERO,
28014            Duration::from_millis(500),
28015        ] {
28016            let rl = RateLimit { rate: 100, window };
28017            assert_eq!(
28018                rl.window(),
28019                window,
28020                "RateLimit::window must return :politicas :rate-limit :window \
28021                 verbatim (got {:?}, expected {window:?})",
28022                rl.window(),
28023            );
28024            assert_eq!(
28025                rl.window(),
28026                rl.window,
28027                "RateLimit::window must byte-equal the raw .window field \
28028                 access across every value in the Duration accept-set",
28029            );
28030        }
28031    }
28032
28033    #[test]
28034    fn validate_politicas_rate_limit_window_canonical_arm_routes_through_accessor() {
28035        // Composition pin: [`AplicacaoSpec::validate_politicas`]'s
28036        // `:rate-limit :window` canonical-set arm must key off
28037        // [`RateLimit::window`], not the raw `.window` field access.
28038        // Structurally: a `RateLimit { window: Duration::from_millis(500),
28039        // .. }` embedded in a `:politicas :rate-limit` slot must
28040        // surface the `PolicyRateLimitWindowNotCanonical` refusal
28041        // exactly (with the sub-canonical `Duration::from_millis(500)`
28042        // magnitude carried through verbatim), and a `RateLimit
28043        // { window: Duration::from_secs(1), .. }` (the lower row of
28044        // the `RATE_LIMIT_UNIT_TABLE` accept-set) must pass validate.
28045        // The pair jointly pins the accessor + validate-gate
28046        // composition: any future silent detour that had the accessor
28047        // normalize the off-set window to the nearest canonical row
28048        // (a `.window().max(Duration::from_secs(1))` collapse, or a
28049        // `rate_limit_window_unit(.window()).map_or(Duration::from_secs(1), …)`
28050        // collapse) would silently absorb the
28051        // `PolicyRateLimitWindowNotCanonical` refusal at the accessor
28052        // boundary — including a drift in the error's `window` payload
28053        // (the emit-side diagnostic reader keys off the offending
28054        // magnitude verbatim, so a normalization at the accessor
28055        // boundary would silently pin the wrong magnitude in the
28056        // refusal). The composition pin catches that at caixa-core
28057        // build time.
28058        //
28059        // Peer of the sibling per-`RateLimit` [`RateLimit::rate`]
28060        // (7f81a60) accessor-composition pin on the peer required-
28061        // scalar `:rate` axis — same "the validate / shape-gate
28062        // predicate must route through the substrate-primitive typed
28063        // dispatch, and the error payload must project through the
28064        // same accessor" discipline extended onto the peer
28065        // per-`RateLimit` required-`Duration` composition axis.
28066        let mut spec = three_member_spec();
28067        spec.politicas = MeshPolicy {
28068            rate_limit: Some(RateLimit {
28069                rate: 100,
28070                window: Duration::from_millis(500),
28071            }),
28072            ..MeshPolicy::default()
28073        };
28074        match spec.validate() {
28075            Err(AplicacaoError::PolicyRateLimitWindowNotCanonical { window }) => {
28076                assert_eq!(
28077                    window,
28078                    Duration::from_millis(500),
28079                    "PolicyRateLimitWindowNotCanonical must carry the \
28080                     offending :window magnitude verbatim through the \
28081                     accessor — got {window:?}, expected 500ms",
28082                );
28083            }
28084            other => panic!(
28085                "validate_politicas must reject non-canonical :window \
28086                 with PolicyRateLimitWindowNotCanonical — the accessor \
28087                 and the validate gate must route through the same \
28088                 substrate-primitive typed dispatch on the :window \
28089                 canonical-set arm; got {other:?}",
28090            ),
28091        }
28092        spec.politicas = MeshPolicy {
28093            rate_limit: Some(RateLimit {
28094                rate: 100,
28095                window: Duration::from_secs(1),
28096            }),
28097            ..MeshPolicy::default()
28098        };
28099        assert!(
28100            spec.validate().is_ok(),
28101            "validate_politicas must accept window == Duration::from_secs(1) \
28102             (the lower row of the RATE_LIMIT_UNIT_TABLE accept-set)",
28103        );
28104    }
28105
28106    #[test]
28107    fn rate_limit_window_projects_duration_by_copy() {
28108        // The by-copy pin: [`RateLimit::window`] returns `Duration`
28109        // by copy — `Duration` is `Copy` and the accessor must return
28110        // by value, not by reference. Peer of the sibling per-`RateLimit`
28111        // [`RateLimit::rate`] (7f81a60) by-copy pin on the peer
28112        // required-scalar `:rate` axis, extended onto the peer
28113        // per-`RateLimit` required-`Duration` copy-invariant shape —
28114        // the accessor's returned `Duration` must outlive `&self`
28115        // (multiple calls must return equal values from a
28116        // dropped-`&self` copy, since the returned scalar carries no
28117        // borrow), and calling the accessor twice on the same
28118        // RateLimit must yield the same `Duration` verbatim
28119        // (idempotent, no side effects on `&self`).
28120        //
28121        // Pins against a future silent detour that returned
28122        // `&Duration` (which would type-check but silently break every
28123        // downstream `Duration`-by-value consumer —
28124        // [`is_canonical_rate_limit_window`]'s first parameter is
28125        // `Duration`, and `&Duration` would fold to a detached copy at
28126        // the call site with a `*` deref the sibling accessors don't
28127        // need), an accidental `.window + Duration::ZERO` detour that
28128        // returned a fresh copy through an arithmetic no-op (breaking
28129        // a future `const fn` regression), or a one-arm-only accessor
28130        // that returned a canonical fallback on some sentinel input
28131        // (breaking the pass-through invariant the sibling required-
28132        // scalar accessors carry).
28133        for window in [
28134            Duration::from_secs(1),
28135            Duration::from_secs(60),
28136            Duration::from_secs(3600),
28137            Duration::ZERO,
28138            Duration::from_millis(500),
28139        ] {
28140            let rl = RateLimit { rate: 100, window };
28141            let first = rl.window();
28142            let second = rl.window();
28143            assert_eq!(
28144                first, second,
28145                "RateLimit::window must be idempotent — two successive \
28146                 calls on the same &self must return the same Duration",
28147            );
28148            assert_eq!(
28149                first, window,
28150                "RateLimit::window must return :politicas :rate-limit :window \
28151                 verbatim by copy — got {first:?}, expected {window:?}",
28152            );
28153        }
28154    }
28155
28156    #[test]
28157    fn placement_estrategia_default_pins_m3_canonical_value() {
28158        // Pin [`PLACEMENT_ESTRATEGIA_DEFAULT`] at
28159        // [`PlacementStrategy::Replicated`] — MESH-COMPOSITION §II.2's
28160        // active-active-across-every-named-cluster arm, the closest
28161        // canonical M3 production reference the substrate carries and
28162        // the arm the caixa-mesh `programs.yaml` fan-out already keys off
28163        // for every un-`:placement`-declared Aplicacao. Pinning the arm
28164        // here surfaces a future rebrand of the M3-canonical
28165        // distribution default (a widening to `Sharded` once the
28166        // substrate discovers hash-keyed distribution as the more
28167        // common production shape, a tightening to `SingleNode` for
28168        // stateful Erlang/OTP distributed-app-takeover semantics
28169        // MESH-COMPOSITION §II.1 names, a per-cluster overlay the
28170        // operator pins through a future `:placement-overrides` slot)
28171        // as a deliberate test edit, not a silent contract migration.
28172        // Peer of the sibling M2 per-supervisor value pins
28173        // [`crate::supervisor::tests::supervisor_estrategia_default_pins_otp_canonical_value`]
28174        // /
28175        // [`crate::supervisor::tests::supervisor_child_restart_default_pins_otp_canonical_value`]
28176        // extended onto the M3 mesh-primitive-defining `:placement
28177        // :estrategia` axis.
28178        assert_eq!(PLACEMENT_ESTRATEGIA_DEFAULT, PlacementStrategy::Replicated);
28179    }
28180
28181    #[test]
28182    fn placement_strategy_default_routes_through_lifted_default() {
28183        // Composition pin: the [`Default for PlacementStrategy`] impl's
28184        // return arm must route through the substrate-canonical
28185        // [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const` rather than
28186        // a raw `Self::Replicated` arm. Prior to the lift the impl
28187        // carried an inline `Self::Replicated` arm with no compile-time
28188        // link back to the shared M3-canonical `Replicated` arm the
28189        // paired [`Default for Placement`] impl's struct-literal
28190        // `estrategia` field, the serde-side `#[serde(default)]` on
28191        // [`Placement::estrategia`] that resolves an author-omitted
28192        // wire-form `:placement :estrategia` scalar through the impl,
28193        // and the [`crate::manifest::Caixa::aplicacao_view`] fold's
28194        // `.unwrap_or_default()` `Option<Placement>` collapse arm (which
28195        // routes through [`Placement::default`] which routes through the
28196        // strategy default) all key off — so a future rebrand of the
28197        // M3-canonical distribution default would have had to be threaded
28198        // through the `Default` impl and the three peer routes in
28199        // lockstep or the four consumers would silently split. Byte-
28200        // parity against the lifted constant closes the split. Peer of
28201        // the sibling
28202        // [`crate::supervisor::tests::restart_strategy_default_routes_through_lifted_default`]
28203        // /
28204        // [`crate::supervisor::tests::restart_policy_default_routes_through_lifted_default`]
28205        // composition pins on the M2 per-supervisor axes.
28206        assert_eq!(PlacementStrategy::default(), PLACEMENT_ESTRATEGIA_DEFAULT);
28207    }
28208
28209    #[test]
28210    fn placement_default_estrategia_routes_through_lifted_default() {
28211        // Composition pin: the [`Default for Placement`] impl's
28212        // struct-literal `estrategia` field must route through the
28213        // substrate-canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed
28214        // `pub const` (either directly, or via the [`PlacementStrategy::default`]
28215        // impl that the sibling
28216        // `placement_strategy_default_routes_through_lifted_default` pin
28217        // already routes onto the constant). Structurally: every
28218        // `Placement::default()` call must yield an `estrategia` field
28219        // byte-equal to the lifted constant so the two paired defaults —
28220        // the [`Default for PlacementStrategy`] impl arm and the
28221        // struct-literal default arm here — cannot silently split on any
28222        // future M3-canonical distribution-default rebrand. Peer of the
28223        // sibling M2
28224        // [`crate::supervisor::tests::supervisor_spec_default_estrategia_routes_through_lifted_default`]
28225        // byte-parity pin on the [`Default for SupervisorSpec`]
28226        // struct-literal `estrategia` field extended onto the M3
28227        // mesh-primitive-defining slot family.
28228        assert_eq!(
28229            Placement::default().estrategia,
28230            PLACEMENT_ESTRATEGIA_DEFAULT,
28231        );
28232    }
28233
28234    #[test]
28235    fn placement_serde_default_estrategia_routes_through_lifted_default() {
28236        // Composition pin: the serde-side `#[serde(default)]` on
28237        // [`Placement::estrategia`] — the wire-format author-omitted
28238        // `:placement :estrategia` arm — must resolve onto the substrate-
28239        // canonical [`PLACEMENT_ESTRATEGIA_DEFAULT`] typed `pub const`
28240        // (via the [`Default for PlacementStrategy`] impl the sibling
28241        // `placement_strategy_default_routes_through_lifted_default` pin
28242        // already routes onto the constant). Structurally: a `Placement`
28243        // deserialized from a payload that omits the `estrategia` key
28244        // must yield an `estrategia` field byte-equal to the lifted
28245        // constant, so the wire-format author-omitted arm and the
28246        // [`PlacementStrategy::default`] impl arm cannot silently split
28247        // on any future M3-canonical distribution-default rebrand. Peer
28248        // of the sibling M2
28249        // [`crate::supervisor::tests::child_spec_serde_default_restart_routes_through_lifted_default`]
28250        // byte-parity pin on the wire-format author-omitted `:children
28251        // :restart` scalar extended onto the M3 mesh-primitive-defining
28252        // slot family.
28253        let omitted: Placement = serde_json::from_str("{}")
28254            .expect("Placement must deserialize with the estrategia key omitted");
28255        assert_eq!(
28256            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
28257            "an author-omitted :placement :estrategia slot must degrade onto \
28258             the PLACEMENT_ESTRATEGIA_DEFAULT typed pub const (got \
28259             {:?}, expected {:?})",
28260            omitted.estrategia, PLACEMENT_ESTRATEGIA_DEFAULT,
28261        );
28262    }
28263}